Ejemplo n.º 1
0
    def test_from_to_dict(self):
        link, created = Link.objects.get_or_create(link="https://tj.org")
        self.assertTrue(created)
        self.assertIsNotNone(link.id)

        journal, created = Journal.objects.get_or_create(name="Test Journal")
        journal.links.add(link)
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)
        self.assertEquals(
            {"name": "Test Journal", "links": [{"url": "https://tj.org"}]},
            journal.to_dict(),
        )
        self.assertEquals(
            (journal, False),
            Journal.from_dict(
                {"name": "Test Journal", "links": [{"url": "https://tj.org"}]}
            ),
        )
        self.assertEquals((journal, False), Journal.from_dict({"name": "Test Journal"}))

        journal, created = Journal.objects.get_or_create(name="Random Journal")
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)
        self.assertEquals({"name": "Random Journal", "links": None}, journal.to_dict())
        self.assertEquals(
            (journal, False),
            Journal.from_dict({"name": "Random Journal", "links": None}),
        )
        self.assertEquals(
            (journal, False), Journal.from_dict({"name": "Random Journal"})
        )
Ejemplo n.º 2
0
    def create(self, request):
        permission_classes = [AllowAny]
        print(request.data['title'])
        print(request.data['content'])

        if not request.data['title'] or not request.data['content']:
            return Response({'message': 'title or content cannot be null'},
                            status.HTTP_400_BAD_REQUEST)

        newJournal = Journal(title=request.data['title'],
                             content=request.data['content'])
        newJournal.save()

        serializer = JournalSerializer(newJournal)
        return Response(serializer.data, status.HTTP_201_CREATED)


# @api_view(['GET'])
# def getAllJournals(request):
#     print(request.user)
#     journals = Journal.objects.all()
#     serializer = JournalSerializer(journals)

#     if len(journals) == 0:
#         return Response([])
#     else:
#         return Response(serializer.data)

# @api_view(['POST'])
# def addJournal(request):
#         print(request.title)
#         print(request.content)
#         return Response([])
Ejemplo n.º 3
0
def initialize_journal(request):
    f = open(os.path.join(settings.EFS_ROOT, 'log.txt'), 'w') #DELETE THIS
    sub = request.user.subscriber
    if sub.total_entries == 0:
        try:
            met = Metrics.objects.get(current=True)
            met.log_journal_entry()
        except:
            pass #never fail user request because of a metrics error
        try:
            creds = None
            # The file token.pickle stores the user's access and refresh tokens, and is
            # created automatically when the authorization flow completes for the first
            # time.
            if os.path.exists(os.path.join(settings.EFS_ROOT, str(sub.id) + 'token.pickle')):
                with open(os.path.join(settings.EFS_ROOT, str(sub.id) + 'token.pickle'), 'rb') as token:
                    creds = pickle.load(token)
            # If there are no (valid) credentials available, let the user log in.
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        os.path.join(settings.EFS_ROOT, 'credentials.json'),
                        ['https://www.googleapis.com/auth/documents'])
                    flow.redirect_uri = flow._OOB_REDIRECT_URI
                    flow.fetch_token(code=request.POST["auth_code"])
                    creds = flow.credentials
                # Save the credentials for the next run
                with open(os.path.join(settings.EFS_ROOT, str(sub.id) + 'token.pickle'), 'wb') as token:
                    pickle.dump(creds, token)
            service = build('docs', 'v1', credentials=creds)
        except:
            return render(request, 'initialize_journal_prompt.html', {"googleError": True})
        names = ["SMSJournal"]
        for name in names:
            try:
                journal = sub.journal_set.get(name=process_journal_name(name))
                write_to_gdoc(journal.google_docs_id, "Welcome to SMSJournal! You can make journal entries to this file by sending messages to the SMSJournal phone number, (970)-507-7992. To send an entry to a different journal, just add a tag like @ideas and we'll find or create the journal \"ideas\" in your Google Drive.", service)
            except:
                doc = service.documents().create(body={"title": name}).execute()
                write_to_gdoc(doc["documentId"], "Welcome to SMSJournal! You can make journal entries to this file by sending messages to the SMSJournal phone number, (970)-507-7992. To send an entry to a different journal, just add a tag like @ideas and we'll find or create the journal \"ideas\" in your Google Drive.", service)
                journal = Journal(subscriber=sub,
                                  name=process_journal_name(name),
                                  google_docs_id=doc["documentId"])
                journal.save()
            sub.last_entry = timezone.now()
            sub.total_entries = sub.total_entries + 1
            sub.save()
            client = boto3.client('pinpoint', 'us-east-1')
            pinpoint_id = settings.AWS_PINPOINT_PROJECT_ID
            client.send_messages(ApplicationId=pinpoint_id,
                                 MessageRequest={'Context': {},
                                                 'Addresses': {sub.phone: {"ChannelType": "SMS"}},
                                                 'MessageConfiguration': {
                                                 'SMSMessage': {'Body': 'Welcome to SMSJournal! This is the phone number where you can send your journal entries. Please save this number to your contacts as SMSJournal for easy access.',
                                                                'OriginationNumber': "+19705077992",
                                                                'MessageType': 'TRANSACTIONAL'}}})
    return HttpResponseRedirect('/account/')
Ejemplo n.º 4
0
    def test_get(self):
        journal, created = Journal.from_dict({"name": "Science Journal"})
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)

        journal2 = Journal.get("Science Journal")
        self.assertIsNotNone(journal2)
        self.assertEquals(journal, journal2)

        journal2 = Journal.get("science")
        self.assertIsNotNone(journal2)
        self.assertEquals(journal, journal2)

        journal2 = Journal.get(str(journal.id))
        self.assertIsNotNone(journal2)
        self.assertEquals(journal, journal2)
Ejemplo n.º 5
0
    def test_print(self):
        journal, created = Journal.from_dict({"name": "Science Journal"})
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)

        with StringIO() as cout:
            journal.print(cout)
            self.assertEquals(
                "Field                            Value                              "
                + "                                \n=================================="
                + "==================================================================\n"
                + "Id                               1                                  "
                + "                                \n__________________________________"
                + "__________________________________________________________________\n"
                + "Name                             Science Journal                    "
                + "                                \n__________________________________"
                + "__________________________________________________________________\n"
                + "Links                                                               "
                + "                                \n__________________________________"
                + "__________________________________________________________________\n"
                + "Papers                                                              "
                + "                                \n__________________________________"
                + "__________________________________________________________________\n",
                cout.getvalue(),
            )
Ejemplo n.º 6
0
    def test_search(self):
        journal, created = Journal.from_dict({"name": "Science Journal"})
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)

        journal, created = Journal.from_dict({"name": "Nature Journal"})
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)

        journal, created = Journal.from_dict({"name": "Math science"})
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)

        self.assertEquals(3, Journal.objects.all().count())
        self.assertEquals(2, Journal.search("journal").count())
        self.assertEquals(2, Journal.search("science").count())
def get_characters_next_journal_credit(character):
    chosen_attendance = None
    is_downtime = False
    attendances_without_game_journals = character.game_attendance_set \
        .filter(relevant_game__end_time__isnull=False, journal__isnull=True) \
        .order_by("relevant_game__end_time") \
        .all()
    for attendance in attendances_without_game_journals:
        if attendance.is_confirmed and (
                attendance.relevant_game.is_finished()
                or attendance.relevant_game.is_recorded()):
            chosen_attendance = attendance
    if not chosen_attendance:
        completed_attendances = character.completed_games_rev_sort()
        for attendance in completed_attendances:
            downtime_journal = Journal.objects.filter(
                game_attendance=attendance, is_downtime=True).first()
            if not downtime_journal:
                chosen_attendance = attendance
                is_downtime = True
    if chosen_attendance:
        reward_is_improvement = Journal.get_num_journals_until_improvement(
            character) <= 1 and not is_downtime
        return {
            "attendance": chosen_attendance,
            "is_downtime": is_downtime,
            "reward_is_improvement": reward_is_improvement
        }
    else:
        return None
Ejemplo n.º 8
0
    def test_save(self):
        journal = Journal(name="Science Journal")
        journal.save()
        self.assertIsNotNone(journal.id)
        self.assertEquals("science-journal", journal.slug)

        journal = Journal(name="Random Math Journal")
        journal.save()
        self.assertIsNotNone(journal.id)
        self.assertEquals("random-math-journal", journal.slug)
Ejemplo n.º 9
0
    def test_get_or_create(self):
        journal, created = Journal.from_dict({"name": "Science Journal"})
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)
        self.assertEquals(1, Journal.objects.count())

        journal2 = Journal.get_or_create("Science Journal")
        self.assertIsNotNone(journal2)
        self.assertEquals(journal, journal2)
        self.assertEquals(1, Journal.objects.count())

        journal2 = Journal.get_or_create(str(journal.id))
        self.assertIsNotNone(journal2)
        self.assertEquals(journal, journal2)
        self.assertEquals(1, Journal.objects.count())

        journal2 = Journal.get_or_create("IT Journal")
        self.assertIsNotNone(journal2)
        self.assertNotEquals(journal, journal2)
        self.assertEquals(2, Journal.objects.count())
Ejemplo n.º 10
0
    def edit(self: T, field: str, value: Union[str, datetime.date], *args,
             **kwargs):
        """Change field by given value."""
        fields = [
            "title",
            "author",
            "publishing_date",
            "publishing-date",
            "journal",
            "volume",
            "language",
            "file",
            "link",
            "bibtex",
        ]
        assert field in fields

        if field == "title":
            self.title = value
        elif field == "author" and isinstance(value, str):
            author = Person.get_or_create(value)
            if self.authors.filter(pk=author.pk).exists():
                self.authors.remove(author)
            else:
                self.authors.add(author)
        elif field == "publishing_date" or field == "publishing-date":
            self.publishing_date = value
        elif field == "journal" and isinstance(value, str):
            self.journal = Journal.get_or_create(value)
        elif field == "volume":
            self.volume = value
        elif field == "bibtex":
            self.bibtex = value
        elif field == "language" and isinstance(value, str):
            language = Language.get_or_create(value)
            if self.languages.filter(pk=language.pk).exists():
                self.languages.remove(language)
            else:
                self.languages.add(language)
        elif field == "link" and isinstance(value, str):
            link = Link.get_or_create(value)
            if self.links.filter(pk=link.pk).exists():
                self.links.remove(link)
            else:
                self.links.add(link)
        elif field == "file":
            file, created = File.from_dict({"path": value})
            if self.files.filter(pk=file.pk).exists():
                self.files.remove(file)
                file.delete()
            else:
                self.files.add(file)
        self.save(*args, **kwargs)
Ejemplo n.º 11
0
    def test_delete(self):
        journals, created = Journal.from_dict({"name": "Science Journal"})
        self.assertTrue(created)
        self.assertIsNotNone(journals.id)

        deleted = journals.delete()
        self.assertIsNone(journals.id)
        self.assertEquals((1, {"journals.Journal": 1}), deleted)

        journals, created = Journal.from_dict(
            {"name": "Nature Science Journal", "links": [{"url": "https://nsj.org"}]}
        )
        self.assertTrue(created)
        self.assertIsNotNone(journals.id)

        deleted = journals.delete()
        self.assertIsNone(journals.id)
        self.assertEquals(
            (3, {"journals.Journal": 1, "journals.Journal_links": 1, "links.Link": 1}),
            deleted,
        )
Ejemplo n.º 12
0
 def __make_journal(self,
                    title="title",
                    content=None,
                    writer=None,
                    game_attendance=None,
                    edit_date=timezone.now(),
                    is_downtime=False,
                    is_valid=False,
                    is_deleted=False,
                    contains_spoilers=True):
     journal = Journal(title=title,
                       content=content,
                       writer=writer,
                       game_attendance=game_attendance,
                       edit_date=edit_date,
                       is_downtime=is_downtime,
                       is_valid=is_valid,
                       is_deleted=is_deleted,
                       contains_spoilers=contains_spoilers)
     journal.save()
     return journal
Ejemplo n.º 13
0
    def from_dict(cls: Type[T], data: Dict) -> Tuple[T, bool]:
        """Create from dict.

        Returns True if was crated, i. e. was not found in the DB.
        """
        defaults: Dict = {}
        if "journal" in data and data["journal"]:
            defaults["journal"] = Journal.from_dict(data["journal"])[0]
        if "volume" in data and data["volume"]:
            defaults["volume"] = data["volume"]
        if "publishing_date" in data and data["publishing_date"]:
            defaults["publishing_date"] = datetime.datetime.strptime(
                data["publishing_date"], "%Y-%m-%d").date()
        if "bibtex" in data and data["bibtex"]:
            defaults["bibtex"] = data["bibtex"]

        paper, created = Paper.objects.get_or_create(title=data["title"],
                                                     defaults=defaults)

        if "authors" in data and data["authors"]:
            for i in data["authors"]:
                paper.authors.add(Person.from_dict(i)[0])
        if "languages" in data and data["languages"]:
            for i in data["languages"]:
                paper.languages.add(Language.from_dict(i)[0])
        if "links" in data and data["links"]:
            for i in data["links"]:
                paper.links.add(Link.from_dict(i)[0])

        if "acquisitions" in data and data["acquisitions"]:
            for i in data["acquisitions"]:
                Acquisition.from_dict(i, paper)
        if "files" in data and data["files"]:
            for i in data["files"]:
                File.from_dict(i, paper)
        if "reads" in data and data["reads"]:
            for i in data["reads"]:
                Read.from_dict(i, paper)
        paper.save()
        return paper, created
Ejemplo n.º 14
0
    def test_from_to_dict(self):
        author1, created = Person.from_dict({"name": "John Doe"})
        self.assertTrue(created)
        self.assertIsNotNone(author1.id)

        author2, created = Person.from_dict({"name": "Jane Doe"})
        self.assertTrue(created)
        self.assertIsNotNone(author2.id)

        journal, created = Journal.from_dict({"name": "Science Journal"})
        self.assertTrue(created)
        self.assertIsNotNone(journal.id)

        paper, created = Paper.objects.get_or_create(
            title="Random new stuff", journal=journal, volume="1/2021"
        )
        paper.authors.add(author1)
        paper.authors.add(author2)
        self.assertTrue(created)
        self.assertIsNotNone(paper.id)
        self.assertEquals(
            {
                "title": "Random new stuff",
                "authors": [
                    {"name": "Jane Doe", "links": None},
                    {"name": "John Doe", "links": None},
                ],
                "journal": {"name": "Science Journal", "links": None},
                "volume": "1/2021",
                "publishing_date": None,
                "languages": None,
                "files": None,
                "bibtex": None,
                "links": None,
                "acquisitions": None,
                "reads": None,
            },
            paper.to_dict(),
        )
        self.assertEquals(
            (paper, False),
            Paper.from_dict(
                {
                    "title": "Random new stuff",
                    "authors": [
                        {"name": "Jane Doe", "links": None},
                        {"name": "John Doe", "links": None},
                    ],
                    "journal": {"name": "Science Journal", "links": None},
                    "volume": "1/2021",
                    "publishing_date": None,
                    "languages": None,
                    "files": None,
                    "bibtex": None,
                    "links": None,
                    "acquisitions": None,
                    "reads": None,
                }
            ),
        )
        self.assertEquals(
            (paper, False),
            Paper.from_dict(
                {
                    "title": "Random new stuff",
                    "authors": [
                        {"name": "Jane Doe"},
                        {"name": "John Doe"},
                    ],
                    "journal": {"name": "Science Journal"},
                    "volume": "1/2021",
                }
            ),
        )

        language, created = Language.from_dict({"name": "Englisch"})
        self.assertTrue(created)
        self.assertIsNotNone(language.id)

        link, created = Link.from_dict({"url": "https://example.com"})
        self.assertTrue(created)
        self.assertIsNotNone(link.id)

        paper, created = Paper.objects.get_or_create(
            title="Random Science stuff",
            publishing_date=datetime.strptime("2021-01-01", "%Y-%m-%d").date(),
            journal=journal,
            volume="2/2021",
        )
        paper.authors.add(author1)
        paper.authors.add(author2)
        paper.languages.add(language)
        paper.links.add(link)
        self.assertTrue(created)
        self.assertIsNotNone(paper.id)

        acquisition, created = Acquisition.from_dict(
            {"date": "2021-01-02", "price": 10}, paper
        )
        self.assertTrue(created)
        self.assertIsNotNone(acquisition.id)

        read, created = Read.from_dict(
            {"started": "2021-01-02", "finished": "2021-01-03"}, paper
        )
        self.assertTrue(created)
        self.assertIsNotNone(read.id)

        self.assertEquals(
            {
                "title": "Random Science stuff",
                "authors": [
                    {"name": "Jane Doe", "links": None},
                    {"name": "John Doe", "links": None},
                ],
                "journal": {"name": "Science Journal", "links": None},
                "volume": "2/2021",
                "publishing_date": "2021-01-01",
                "languages": [{"name": "Englisch"}],
                "files": None,
                "bibtex": None,
                "links": [{"url": "https://example.com"}],
                "acquisitions": [{"date": "2021-01-02", "price": 10.0}],
                "reads": [{"started": "2021-01-02", "finished": "2021-01-03"}],
            },
            paper.to_dict(),
        )
        self.assertEquals(
            (paper, False),
            Paper.from_dict(
                {
                    "title": "Random Science stuff",
                    "authors": [
                        {"name": "Jane Doe", "links": None},
                        {"name": "John Doe", "links": None},
                    ],
                    "journal": {"name": "Science Journal", "links": None},
                    "volume": "2/2021",
                    "publishing_date": "2021-01-01",
                    "languages": [{"name": "Englisch"}],
                    "files": None,
                    "bibtex": None,
                    "links": [{"url": "https://example.com"}],
                    "acquisitions": [{"date": "2021-01-02", "price": 10.0}],
                    "reads": [{"started": "2021-01-02", "finished": "2021-01-03"}],
                }
            ),
        )
        self.assertEquals(
            (paper, False),
            Paper.from_dict(
                {
                    "title": "Random Science stuff",
                    "authors": [
                        {"name": "Jane Doe"},
                        {"name": "John Doe"},
                    ],
                    "journal": {"name": "Science Journal"},
                    "volume": "2/2021",
                    "publishing_date": "2021-01-01",
                    "languages": [{"name": "Englisch"}],
                    "links": [{"url": "https://example.com"}],
                    "acquisitions": [{"date": "2021-01-02", "price": 10.0}],
                    "reads": [{"started": "2021-01-02", "finished": "2021-01-03"}],
                }
            ),
        )

        with NamedTemporaryFile() as f:
            f.write(b"Lorem ipsum dolorem")

            file, created = File.from_dict({"path": f.name})
            self.assertTrue(created)
            self.assertIsNotNone(file.id)
            self.assertEquals(
                os.path.basename(f.name), os.path.basename(file.file.name)
            )

            paper, created = Paper.objects.get_or_create(
                title="Boring Science stuff",
                publishing_date=datetime.strptime("2021-02-01", "%Y-%m-%d").date(),
                journal=journal,
                volume="2/2021",
            )
            paper.authors.add(author1)
            paper.authors.add(author2)
            paper.languages.add(language)
            paper.links.add(link)
            paper.files.add(file)
            paper.save()
            self.assertTrue(created)
            self.assertIsNotNone(paper.id)
            self.assertEquals(
                {
                    "title": "Boring Science stuff",
                    "authors": [
                        {"name": "Jane Doe", "links": None},
                        {"name": "John Doe", "links": None},
                    ],
                    "journal": {"name": "Science Journal", "links": None},
                    "volume": "2/2021",
                    "publishing_date": "2021-02-01",
                    "languages": [{"name": "Englisch"}],
                    "bibtex": None,
                    "links": [{"url": "https://example.com"}],
                    "files": [
                        {
                            "path": os.path.join(
                                settings.MEDIA_ROOT,
                                "papers",
                                str(paper.pk),
                                os.path.basename(f.name),
                            )
                        }
                    ],
                    "acquisitions": None,
                    "reads": None,
                },
                paper.to_dict(),
            )
Ejemplo n.º 15
0
def _paper(args: Namespace, file: TextIO = sys.stdout):
    paper: Optional[Paper] = None
    if args.subparser == "acquisition":
        paper = Paper.get(args.paper)
        acquisition: Optional[Acquisition] = None
        if args.acquisition_subparser == "add" and paper:
            acquisition, created = Acquisition.from_dict(
                {
                    "date": args.date,
                    "price": args.price
                }, paper)
            if created:
                stdout.write(
                    _('Successfully added acquisition with id "%(pk)d".') %
                    {"pk": acquisition.pk},
                    "=",
                    file=file,
                )
            else:
                stdout.write(
                    _('The acquisition already exists with id "%(pk)d".') %
                    {"pk": acquisition.pk},
                    "",
                    file=file,
                )
            acquisition.print(file)
        elif args.acquisition_subparser == "delete" and paper:
            acquisition = Acquisition.get(args.acquisition, papers=paper)
            if acquisition:
                acquisition.delete(acquisition)
                stdout.write(
                    _('Successfully deleted acquisition with id "%(pk)d".') %
                    {"pk": acquisition.pk},
                    "",
                    file=file,
                )
            else:
                stdout.write(_("No acquisition found."), "", file=file)
        elif args.acquisition_subparser == "edit" and paper:
            acquisition = Acquisition.get(args.acquisition, papers=paper)
            if acquisition:
                acquisition.edit(args.field, args.value)
                stdout.write(
                    _('Successfully edited acquisition with id "%(pk)d".') %
                    {"pk": acquisition.pk},
                    "=",
                    file=file,
                )
                acquisition.print(file)
            else:
                stdout.write(["No acquisition found."], "", file=file)
        else:
            stdout.write(_("No paper found."), "", file=file)
    elif args.subparser == "add":
        paper, created = Paper.from_dict({
            "title":
            args.title,
            "authors":
            [Person.get_or_create(author).to_dict() for author in args.author],
            "publishing_date":
            args.publishing_date,
            "journal":
            Journal.get_or_create(args.journal).to_dict()
            if args.journal else None,
            "volume":
            args.volume,
            "languages": [
                Language.get_or_create(language).to_dict()
                for language in args.language
            ],
            "links":
            [Link.get_or_create(link).to_dict() for link in args.link],
            "files": [{
                "path": file
            } for file in args.file],
        })
        if created:
            stdout.write(
                _('Successfully added paper "%(title)s" with id "%(pk)d".') % {
                    "title": paper.title,
                    "pk": paper.pk
                },
                "=",
                file=file,
            )
        else:
            stdout.write(
                _('The paper "%(title)s" already exists with id "%(pk)d".') % {
                    "title": paper.title,
                    "pk": paper.pk
                },
                "",
                file=file,
            )
        paper.print(file)
    elif args.subparser == "delete":
        paper = Paper.get(args.paper)
        if paper:
            paper.delete()
            stdout.write(
                _('Successfully deleted paper with id "%(title)s".') %
                {"title": paper.title},
                "",
                file=file,
            )
        else:
            stdout.write(_("No paper found."), "", file=file)
    elif args.subparser == "edit":
        paper = Paper.get(args.paper)
        if paper:
            paper.edit(args.edit_subparser, args.value)
            stdout.write(
                _('Successfully edited paper "%(title)s" with id "%(pk)d".') %
                {
                    "title": paper.title,
                    "pk": paper.pk
                },
                "",
                file=file,
            )
            paper.print(file)
        else:
            stdout.write(_("No paper found."), "", file=file)
    elif args.subparser == "info":
        paper = Paper.get(args.paper)
        if paper:
            paper.print(file)
        else:
            stdout.write(_("No paper found."), "", file=file)
    elif args.subparser == "list":
        if args.search:
            papers = Paper.search(args.search)
        elif args.shelf:
            papers = Paper.by_shelf(args.shelf)
        else:
            papers = Paper.objects.all()
        stdout.write(
            [_("Id"), _("Name"), _("Journal"),
             _("Volume")],
            "=",
            [0.05, 0.7, 0.85],
            file=file,
        )
        for i, has_next in lookahead(papers):
            stdout.write(
                [i.pk, i.name, i.journal.name, i.volume],
                "_" if has_next else "=",
                [0.05, 0.7, 0.85],
                file=file,
            )
    elif args.subparser == "open":
        paper = Paper.get(args.paper)
        if paper:
            paper_file = paper.files.get(pk=args.file)
            path = settings.MEDIA_ROOT / paper_file.file.path
            if sys.platform == "linux":
                os.system(f'xdg-open "{path}"')
            else:
                os.system(f'open "{path}"')
        else:
            stdout.write(_("No paper found."), "", file=file)
    elif args.subparser == "parse":
        for paper, created in Paper.from_bibfile(args.bibfile, args.file):
            if created:
                stdout.write(
                    _('Successfully added paper "%(title)s" with id "%(pk)d".')
                    % {
                        "title": paper.title,
                        "pk": paper.pk
                    },
                    file=file,
                )
                if args.acquisition:
                    acquisition, created = Acquisition.from_dict(
                        {"date": datetime.date.today()}, paper)
                    if created:
                        stdout.write(
                            _('Successfully added acquisition with id "%(pk)d".'
                              ) % {"pk": acquisition.pk},
                            "=",
                            file=file,
                        )
                    else:
                        stdout.write(
                            _('The acquisition already exists with id "%(pk)d".'
                              ) % {"pk": acquisition.pk},
                            "=",
                            file=file,
                        )
            else:
                stdout.write(
                    _('The paper "%(title)s" already exists with id "%(pk)d".')
                    % {
                        "title": paper.title,
                        "pk": paper.pk
                    },
                    "=",
                    file=file,
                )
            paper.print(file)
    elif args.subparser == "read":
        paper = Paper.get(args.paper)
        read: Optional[Read] = None
        if args.read_subparser == "add" and paper:
            read, created = Read.from_dict(
                {
                    "started": args.started,
                    "finished": args.finished
                }, paper)
            if created:
                stdout.write(
                    _('Successfully added read with id "%(pk)d".') %
                    {"pk": read.pk},
                    "=",
                    file=file,
                )
            else:
                stdout.write(
                    _('The read already exists with id "%(pk)d".') %
                    {"pk": read.pk},
                    "",
                    file=file,
                )
            read.print(file)
        elif args.read_subparser == "delete" and paper:
            read = Read.get(args.read, papers=paper)
            if read:
                read.delete()
                stdout.write(
                    _('Successfully deleted read with id "%(pk)d".') %
                    {"pk": read.pk},
                    "",
                    file=file,
                )
            else:
                stdout.write(_("No read found."), "", file=file)
        elif args.read_subparser == "edit" and paper:
            read = Read.get(args.read, papers=paper)
            if read:
                read.edit(args.field, args.value)
                stdout.write(
                    _('Successfully edited read with id "%(pk)d".') %
                    {"pk": read.pk},
                    "=",
                    file=file,
                )
                read.info(file)
            else:
                stdout.write(_("No read found."), "", file=file)
        else:
            stdout.write(_("No paper found."), "", file=file)
Ejemplo n.º 16
0
def _journal(args: Namespace, file: TextIO = sys.stdout):
    journal: Optional[Journal] = None
    if args.subparser == "add":
        journal, created = Journal.from_dict({
            "name":
            args.name,
            "links":
            [Link.get_or_create(link).to_dict() for link in args.link],
        })
        if created:
            stdout.write(
                _('Successfully added journal "%(name)s" with id "%(pk)d".') %
                {
                    "name": journal.name,
                    "pk": journal.pk
                },
                "=",
                file=file,
            )
            journal.print(file)
        else:
            stdout.write(
                _('The journal "%(name)s" already exists with id "%(pk)d", aborting...'
                  ) % {
                      "name": journal.name,
                      "pk": journal.pk
                  },
                "",
                file=file,
            )
    elif args.subparser == "delete":
        journal = Journal.get(args.journal)
        if journal:
            journal.delete()
            stdout.write(
                _('Successfully deleted journal with id "%(pk)d".') %
                {"pk": journal.pk},
                "",
                file=file,
            )
        else:
            stdout.write(_("No journal found."), "", file=file)
    elif args.subparser == "edit":
        journal = Journal.get(args.journal)
        if journal:
            journal.edit(args.field, args.value)
            stdout.write(
                _('Successfully edited journal "%(name)s" with id "%(pk)d".') %
                {
                    "name": journal.name,
                    "pk": journal.pk
                },
                "",
                file=file,
            )
            journal.print(file)
        else:
            stdout.write(_("No journal found."), "", file=file)
    elif args.subparser == "info":
        journal = Journal.get(args.journal)
        if journal:
            journal.info(file)
        else:
            stdout.write([_("No journal found.")], "")
    elif args.subparser == "list":
        if args.search:
            journals = Journal.search(args.search)
        else:
            journals = Journal.objects.all()
        stdout.write(
            [_("Id"), _("Name"), _("Number of papers")],
            "=", [0.05, 0.8],
            file=file)
        for i, has_next in lookahead(journals):
            stdout.write(
                [i.id, i.name, i.papers.count()],
                "_" if has_next else "=",
                [0.05, 0.8],
                file=file,
            )