Exemplo n.º 1
0
    def from_dict(cls: Type[T], data: Dict, book: Book) -> Tuple[T, bool]:
        """Create from dict.

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

        edition, created = cls.objects.get_or_create(
            book=book,
            alternate_title=data["alternate_title"]
            if "alternate_title" in data else None,
            isbn=data["isbn"] if "isbn" in data else None,
            publishing_date=data["publishing_date"]
            if "publishing_date" in data else None,
            defaults=defaults,
        )

        if "cover_image" in data and data["cover_image"]:
            edition.cover_image.save(
                os.path.basename(data["cover_image"]),
                DJFile(open(data["cover_image"], "rb")),
            )
        if "languages" in data and data["languages"]:
            for i in data["languages"]:
                edition.languages.add(Language.from_dict(i)[0])
        if "links" in data and data["links"]:
            for i in data["links"]:
                edition.links.add(Link.from_dict(i)[0])
        if "persons" in data and data["persons"]:
            for i in data["persons"]:
                edition.persons.add(Person.from_dict(i)[0])

        if "acquisitions" in data and data["acquisitions"]:
            for i in data["acquisitions"]:
                Acquisition.from_dict(i, edition)
        if "files" in data and data["files"]:
            for i in data["files"]:
                File.from_dict(i, edition)
        if "reads" in data and data["reads"]:
            for i in data["reads"]:
                Read.from_dict(i, edition)
        edition.save()
        return edition, created
Exemplo n.º 2
0
    def test_delete(self):
        for obj in [self.edition, self.issue, self.paper]:
            read, created = Read.from_dict({"date": "2021-01-01"}, obj)
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)

            deleted = read.delete()
            self.assertIsNone(read.pk)
            self.assertEquals((1, {"shelves.Read": 1}), deleted)
Exemplo n.º 3
0
    def from_dict(cls: Type[T], data: Dict, magazine: Magazine) -> Tuple[T, bool]:
        """Create from dict.

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

        issue, created = cls.objects.get_or_create(
            issue=data["issue"], magazine=magazine, defaults=defaults
        )

        if "cover_image" in data and data["cover_image"]:
            issue.cover_image.save(
                os.path.basename(data["cover_image"]),
                DJFile(open(data["cover_image"], "rb")),
            )
        if "languages" in data and data["languages"]:
            for i in data["languages"]:
                if type(i) == dict:
                    issue.languages.add(Language.from_dict(i)[0])
                else:
                    issue.languages.add(Language.get_or_create(i))
        if "links" in data and data["links"]:
            for i in data["links"]:
                issue.links.add(Link.from_dict(i)[0])

        if "acquisitions" in data and data["acquisitions"]:
            for i in data["acquisitions"]:
                Acquisition.from_dict(i, issue)
        if "files" in data and data["files"]:
            for i in data["files"]:
                File.from_dict(i, issue)
        if "reads" in data and data["reads"]:
            for i in data["reads"]:
                Read.from_dict(i, issue)
        issue.save()
        return issue, created
Exemplo n.º 4
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
Exemplo n.º 5
0
    def test_edit(self):
        for obj in [self.edition, self.issue, self.paper]:
            read, created = Read.from_dict({"started": "2021-01-01"}, obj)
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)

            self.assertEquals(None, read.finished)
            read.edit("finished",
                      datetime.strptime("2021-02-01", "%Y-%m-%d").date())
            self.assertEquals(
                datetime.strptime("2021-02-01", "%Y-%m-%d").date(),
                read.finished)

            self.assertEquals(
                datetime.strptime("2021-01-01", "%Y-%m-%d").date(),
                read.started)
            read.edit("started",
                      datetime.strptime("2021-02-10", "%Y-%m-%d").date())
            self.assertEquals(
                datetime.strptime("2021-02-10", "%Y-%m-%d").date(),
                read.started)
Exemplo n.º 6
0
def _magazine(args: Namespace, file: TextIO = sys.stdout):
    magazine: Optional[Magazine] = None
    if args.subparser == "add":
        magazine, created = Magazine.from_dict({
            "name":
            args.name,
            "feed":
            Link.get_or_create(args.feed).to_dict() if args.feed else None,
            "links":
            [Link.get_or_create(link).to_dict() for link in args.link],
        })
        if created:
            stdout.write(
                _('Successfully added magazine "%(name)s" with id "%(pk)d".') %
                {
                    "name": magazine.name,
                    "pk": magazine.pk
                },
                "=",
                file=file,
            )
        else:
            stdout.write(
                _('The magazine "%(name)s" already exists with id "%(pk)d", ' +
                  "aborting...") % {
                      "name": magazine.name,
                      "pk": magazine.pk
                  },
                "",
                file=file,
            )
        magazine.print(file)
    elif args.subparser == "delete":
        magazine = Magazine.get(args.magazine)
        if magazine:
            magazine.delete()
            stdout.write(
                _('Successfully deleted magazine "%(name)s".') %
                {"name": magazine.name},
                "",
                file=file,
            )
        else:
            stdout.write(_("No magazine found."), "", file=file)
    elif args.subparser == "edit":
        magazine = Magazine.get(args.magazine)
        if magazine:
            magazine.edit(args.field, args.value)
            stdout.write(
                _('Successfully edited magazine "%(name)s" with id "%(pk)d".')
                % {
                    "name": magazine.name,
                    "pk": magazine.pk
                },
                "",
                file=file,
            )
        else:
            stdout.write(_("No magazine found."), "", file=file)
    elif args.subparser == "info":
        magazine = Magazine.get(args.magazine)
        if magazine:
            magazine.print(file)
        else:
            stdout.write(_("No magazine found."), "", file=file)
    elif args.subparser == "issue":
        magazine = Magazine.get(args.magazine)
        acquisition: Optional[Acquisition] = None
        if magazine:
            if args.issue_subparser == "acquisition" and magazine:
                issue = Issue.get(args.issue, magazine)
                if args.acquisition_subparser == "add" and issue:
                    acquisition, created = Acquisition.from_dict(
                        {
                            "date": args.date,
                            "price": args.price
                        }, issue)
                    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 issue:
                    acquisition = Acquisition.get(args.acquisition,
                                                  issues=issue)
                    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 issue:
                    acquisition = Acquisition.get(args.acquisition,
                                                  issues=issue)
                    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 issue found."), "", file=file)
            elif args.issue_subparser == "add" and magazine:
                issue, created = Issue.from_dict(
                    {
                        "issue":
                        args.issue,
                        "publishing_date":
                        args.publishing_date,
                        "cover":
                        args.cover,
                        "languages":
                        args.language,
                        "links": [
                            Link.get_or_create(link).to_dict()
                            for link in args.link
                        ],
                        "files": [{
                            "path": file
                        } for file in args.file],
                    },
                    magazine,
                )
                if created:
                    stdout.write(
                        _('Successfully added issue "%(issue)s" with id "%(pk)d".'
                          ) % {
                              "issue": issue.issue,
                              "pk": issue.pk
                          },
                        "=",
                        file=file,
                    )
                else:
                    stdout.write(
                        _('The issue "%(issue)s" already exists with id "%(pk)d".'
                          ) % {
                              "issue": issue.issue,
                              "pk": issue.pk
                          },
                        "",
                        file=file,
                    )
                issue.print(file)
            elif args.subparser == "delete" and magazine:
                issue = Issue.get(args.issue)
                if issue:
                    issue.delete()
                    stdout.write(
                        _('Successfully deleted issue with id "%(pk)s".') %
                        {"pk": issue.pk},
                        "",
                        file=file,
                    )
                else:
                    stdout.write(_("No issue found."), "", file=file)
            elif args.issue_subparser == "edit" and magazine:
                issue = Issue.get(args.issue, magazine)
                if issue:
                    issue.edit(args.edit_subparser, args.value)
                    stdout.write(
                        _('Successfully edited issue "%(issue)s" with id "%(pk)d".'
                          ) % {
                              "issue": issue.issue,
                              "pk": issue.pk
                          },
                        "",
                        file=file,
                    )
                    issue.print(file)
                else:
                    stdout.write(_("No issue found."), "", file=file)
            elif args.issue_subparser == "info" and magazine:
                issue = Issue.get(args.issue, magazine)
                if issue:
                    issue.print(file)
                else:
                    stdout.write(_("No issue found."), "", file=file)
            elif args.issue_subparser == "list" and magazine:
                if args.search:
                    issues = Issue.search(args.search)
                elif args.shelf:
                    issues = Issue.by_shelf(args.shelf)
                else:
                    issues = Issue.objects.filter(magazine=magazine)
                stdout.write(
                    [_("Id"),
                     _("Magazine"),
                     _("Issue"),
                     _("Publishing date")],
                    "=",
                    [0.05, 0.40, 0.85],
                    file=file,
                )
                for i, has_next in lookahead(issues):
                    stdout.write(
                        [i.pk, i.magazine.name, i.issue, i.publishing_date],
                        "_" if has_next else "=",
                        [0.05, 0.40, 0.85],
                        file=file,
                    )
            elif args.issue_subparser == "open" and magazine:
                issue = Issue.get(args.issue, magazine)
                if issue:
                    issue_file = issue.files.get(pk=args.file)
                    path = settings.MEDIA_ROOT / issue_file.file.path
                    if sys.platform == "linux":
                        os.system(f'xdg-open "{path}"')
                    else:
                        os.system(f'open "{path}"')
                else:
                    stdout.write(_("No issue found."), "", file=file)
            elif args.issue_subparser == "read" and magazine:
                issue = Issue.get(args.issue, magazine)
                read: Optional[Read] = None
                if args.read_subparser == "add" and issue:
                    read, created = Read.from_dict(
                        {
                            "started": args.started,
                            "finished": args.finished
                        }, issue)
                    if created:
                        stdout.write(
                            _('Successfully added read with id "%(pk)s".') %
                            {"pk": read.pk},
                            "=",
                            file=file,
                        )
                    else:
                        stdout.write(
                            _('The read already exists with id "%(pk)s".') %
                            {"pk": read.pk},
                            "",
                            file=file,
                        )
                    read.print(file)
                elif args.read_subparser == "delete" and issue:
                    read = Read.get(args.read, issues=issue)
                    if read:
                        read.delete()
                        stdout.write(
                            _('Successfully deleted read with id "%(pk)s".') %
                            {"pk": read.pk},
                            "",
                            file=file,
                        )
                    else:
                        stdout.write(_("No read found."), "", file=file)
                elif args.read_subparser == "edit" and issue:
                    read = Read.get(args.read, issues=issue)
                    if read:
                        read.edit(args.field, args.value)
                        stdout.write(
                            _('Successfully edited read with id "%(pk)s".') %
                            {"pk": read.pk},
                            "=",
                            file=file,
                        )
                        read.info(file)
                    else:
                        stdout.write(_("No read found."), "", file=file)
                else:
                    stdout.write(_("No issue found."), "", file=file)
        else:
            stdout.write(_("No magazine found."), "", file=file)
    elif args.subparser == "list":
        if args.search:
            magazines = Magazine.search(args.search)
        else:
            magazines = Magazine.objects.all()

        stdout.write(
            [_("Id"), _("Name"), _("Number of issues")],
            "=",
            [0.05, 0.8],
            file=file,
        )
        for i, has_next in lookahead(magazines):
            stdout.write(
                [i.pk, i.name, i.issues.count()],
                "_" if has_next else "=",
                [0.05, 0.8],
                file=file,
            )
Exemplo n.º 7
0
    def test_save(self):
        for obj in [self.edition, self.issue, self.paper]:
            read = Read(content_object=obj,
                        started="2021-01-01",
                        finished="2021-01-31")
            read.save()
            self.assertIsNotNone(read.pk)

            read = Read(content_object=obj, started="2021-02-01")
            read.save()
            self.assertIsNotNone(read.pk)

            read = Read(content_object=obj, finished="2021-02-28")
            read.save()
            self.assertIsNotNone(read.pk)
Exemplo n.º 8
0
    def test_print(self):
        read, created = Read.from_dict(
            {
                "started": "2021-01-01",
                "finished": "2021-01-31"
            }, self.edition)
        self.assertTrue(created)
        self.assertIsNotNone(read.pk)

        with StringIO() as cout:
            read.print(cout)
            self.assertEquals(
                "Field                            Value                              "
                +
                "                                \n=================================="
                +
                "==================================================================\n"
                +
                "Id                               1                                  "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Obj                              1: Example #1                      "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Started                          2021-01-01                         "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Finished                         2021-01-31                         "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n",
                cout.getvalue(),
            )

        read, created = Read.from_dict(
            {
                "started": "2021-01-01",
                "finished": "2021-01-31"
            }, self.issue)
        self.assertTrue(created)
        self.assertIsNotNone(read.pk)

        with StringIO() as cout:
            read.print(cout)
            self.assertEquals(
                "Field                            Value                              "
                +
                "                                \n=================================="
                +
                "==================================================================\n"
                +
                "Id                               2                                  "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Obj                              1: Example 1/2021                  "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Started                          2021-01-01                         "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Finished                         2021-01-31                         "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n",
                cout.getvalue(),
            )

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

        with StringIO() as cout:
            read.print(cout)
            self.assertEquals(
                "Field                            Value                              "
                +
                "                                \n=================================="
                +
                "==================================================================\n"
                +
                "Id                               3                                  "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Obj                              1: Really cool stuff               "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Started                          2021-01-01                         "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n"
                +
                "Finished                         2021-01-31                         "
                +
                "                                \n__________________________________"
                +
                "__________________________________________________________________\n",
                cout.getvalue(),
            )
Exemplo n.º 9
0
    def test_search(self):
        for obj in [self.edition, self.issue, self.paper]:
            read, created = Read.from_dict({"started": "2021-01-01"}, obj)
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)

            read, created = Read.from_dict(
                {
                    "date": "2021-01-10",
                    "finished": "2021-04-15"
                }, obj)
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)

            read, created = Read.from_dict({"finished": "2021-03-18"}, obj)
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)

            if type(obj) == Edition:
                edition, created = Edition.from_dict({}, obj.book)
                self.assertTrue(created)
                self.assertIsNotNone(edition.id)

                read, created = Read.from_dict(
                    {
                        "date": "2021-01-10",
                        "finished": "2021-01-31"
                    }, edition)
                self.assertTrue(created)
                self.assertIsNotNone(read.pk)

                self.assertEquals(4, Read.objects.all().count())
                self.assertEquals(4, Read.search("example").count())
                self.assertEquals(1,
                                  Read.search("4", editions=edition).count())
            elif type(obj) == Issue:
                issue, created = Issue.from_dict({"issue": "2/2021"},
                                                 obj.magazine)
                self.assertTrue(created)
                self.assertIsNotNone(issue.id)

                read, created = Read.from_dict(
                    {
                        "date": "2021-01-10",
                        "finished": "2021-01-31"
                    }, issue)
                self.assertTrue(created)
                self.assertIsNotNone(read.pk)

                self.assertEquals(8, Read.objects.all().count())
                self.assertEquals(8, Read.search("example").count())
                self.assertEquals(1, Read.search("8", issues=issue).count())
            elif type(obj) == Paper:
                paper, created = Paper.from_dict({"title": "Old stuff"})
                self.assertTrue(created)
                self.assertIsNotNone(paper.id)

                read, created = Read.from_dict(
                    {
                        "date": "2021-01-10",
                        "finished": "2021-01-31"
                    }, paper)
                self.assertTrue(created)
                self.assertIsNotNone(read.pk)

                self.assertEquals(12, Read.objects.all().count())
                self.assertEquals(3, Read.search("cool").count())
                self.assertEquals(1, Read.search("12", papers=paper).count())
Exemplo n.º 10
0
    def test_get(self):
        for obj in [self.edition, self.issue, self.paper]:
            read, created = Read.from_dict({"finished": "2021-01-01"}, obj)
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)

            if type(obj) == Edition:
                read2 = Read.get(obj.book.title)
            elif type(obj) == Issue:
                read2 = Read.get(f"{obj.magazine.name} {obj.issue}")
            elif type(obj) == Paper:
                read2 = Read.get(obj.title)
            self.assertIsNotNone(read2)
            self.assertEquals(read, read2)

            read2 = read.get(str(read.pk))
            self.assertIsNotNone(read2)
            self.assertEquals(read, read2)

            if type(obj) == Edition:
                edition, created = Edition.from_dict({"title": "Old stuff"},
                                                     obj.book)
                self.assertTrue(created)
                self.assertIsNotNone(edition.id)

                read, created = Read.from_dict(
                    {
                        "started": "2021-01-10",
                        "finished": "2021-01-31"
                    }, edition)
                self.assertTrue(created)
                self.assertIsNotNone(read.pk)

                read2 = read.get(str(read.pk), editions=edition)
                self.assertIsNotNone(read2)
                self.assertEquals(read, read2)
            elif type(obj) == Issue:
                issue, created = Issue.from_dict({"issue": "2/2021"},
                                                 obj.magazine)
                self.assertTrue(created)
                self.assertIsNotNone(issue.id)

                read, created = Read.from_dict(
                    {
                        "started": "2021-01-10",
                        "finished": "2021-01-31"
                    }, issue)
                self.assertTrue(created)
                self.assertIsNotNone(read.pk)

                read2 = read.get(str(read.pk), issues=issue)
                self.assertIsNotNone(read2)
                self.assertEquals(read, read2)
            elif type(obj) == Paper:
                paper, created = Paper.from_dict({"title": "Old stuff"})
                self.assertTrue(created)
                self.assertIsNotNone(paper.id)

                read, created = Read.from_dict(
                    {
                        "started": "2021-01-10",
                        "finished": "2021-01-31"
                    }, paper)
                self.assertTrue(created)
                self.assertIsNotNone(read.pk)

                read2 = read.get(str(read.pk), papers=paper)
                self.assertIsNotNone(read2)
                self.assertEquals(read, read2)
Exemplo n.º 11
0
    def test_from_to_dict(self):
        for obj in [self.edition, self.issue, self.paper]:
            read, created = Read.objects.get_or_create(
                content_type=ContentType.objects.get_for_model(obj),
                object_id=obj.pk,
                started=datetime.strptime("2021-01-01", "%Y-%m-%d").date(),
                finished=datetime.strptime("2021-01-10", "%Y-%m-%d").date(),
            )
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)
            self.assertEquals(
                {
                    "started": "2021-01-01",
                    "finished": "2021-01-10"
                }, read.to_dict())
            self.assertEquals(
                (read, False),
                Read.from_dict(
                    {
                        "started": "2021-01-01",
                        "finished": "2021-01-10"
                    }, obj),
            )

            read, created = Read.objects.get_or_create(
                content_type=ContentType.objects.get_for_model(obj),
                object_id=obj.pk,
                started=datetime.strptime("2021-01-31", "%Y-%m-%d").date(),
            )
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)
            self.assertEquals({
                "started": "2021-01-31",
                "finished": None
            }, read.to_dict())
            self.assertEquals(
                (read, False),
                Read.from_dict({
                    "started": "2021-01-31",
                    "finished": None
                }, obj),
            )

            read, created = Read.objects.get_or_create(
                content_type=ContentType.objects.get_for_model(obj),
                object_id=obj.pk,
                finished=datetime.strptime("2021-01-16", "%Y-%m-%d").date(),
            )
            self.assertTrue(created)
            self.assertIsNotNone(read.pk)
            self.assertEquals({
                "started": None,
                "finished": "2021-01-16"
            }, read.to_dict())
            self.assertEquals(
                (read, False),
                Read.from_dict({
                    "started": None,
                    "finished": "2021-01-16"
                }, obj),
            )
Exemplo n.º 12
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(),
            )
Exemplo n.º 13
0
def _book(args: Namespace, file: TextIO = sys.stdout):
    book: Optional[Book] = None
    if args.subparser == "add":
        book, created = Book.from_dict({
            "title":
            args.title,
            "authors":
            [Person.get_or_create(author).to_dict() for author in args.author],
            "series":
            Series.get_or_create(args.series).to_dict()
            if args.series else None,
            "volume":
            args.volume,
            "genres":
            [Genre.get_or_create(genre).to_dict() for genre in args.genre],
            "links":
            [Link.get_or_create(link).to_dict() for link in args.link],
        })

        if created:
            stdout.write(
                _('Successfully added book "%(title)s" with id "%(pk)d".') % {
                    "title": book.title,
                    "pk": book.pk
                },
                "=",
                file=file,
            )
            book.print(file)
        else:
            stdout.write(
                _('The book "%(title)s" already exists with id "%(pk)d", aborting...'
                  ) % {
                      "title": book.title,
                      "pk": book.pk
                  },
                "",
                file=file,
            )
    elif args.subparser == "delete":
        book = Book.get(args.book)
        if book:
            book.delete()
            stdout.write(
                _('Successfully deleted book "%(title)s" with id "%(pk)d".') %
                {
                    "title": book.title,
                    "pk": book.pk
                },
                "",
                file=file,
            )
        else:
            stdout.write(_("No book found."), "", file=file)
    elif args.subparser == "edit":
        book = Book.get(args.book)
        if book:
            book.edit(args.edit_subparser, args.value)
            stdout.write(
                _('Successfully edited book "%(title)s" with id "%(pk)d".') % {
                    "title": book.title,
                    "pk": book.pk
                },
                "=",
                file=file,
            )
            book.print(file)
        else:
            stdout.write(_("No book found."), "", file=file)
    elif args.subparser == "edition":
        book = Book.get(args.book)
        if book:
            if args.edition_subparser == "acquisition" and book:
                edition = Edition.get(args.edition, book)
                acquisition: Optional[Acquisition] = None
                if args.acquisition_subparser == "add" and edition:
                    acquisition, created = Acquisition.from_dict(
                        {
                            "date": args.date,
                            "price": args.price
                        }, edition)
                    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 edition:
                    acquisition = Acquisition.get(args.acquisition,
                                                  editions=edition)
                    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 edition:
                    acquisition = Acquisition.get(args.acquisition,
                                                  editions=edition)
                    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 edition found.")], "", file=file)
            elif args.edition_subparser == "add" and book:
                edition, created = Edition.from_dict(
                    {
                        "alternate_title":
                        args.alternate_title,
                        "isbn":
                        args.isbn,
                        "publishing_date":
                        args.publishing_date,
                        "cover":
                        args.cover,
                        "binding":
                        Binding.get_or_create(args.binding).to_dict()
                        if args.binding else None,
                        "publisher":
                        Publisher.get_or_create(args.publisher).to_dict()
                        if args.publisher else None,
                        "persons": [
                            Person.get_or_create(person).to_dict()
                            for person in args.person
                        ],
                        "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],
                    },
                    book,
                )
                if created:
                    stdout.write(
                        _('Successfully added edition "%(edition)s" with id "%(pk)d".'
                          ) % {
                              "edition": edition,
                              "pk": edition.pk
                          },
                        "=",
                        file=file,
                    )
                    edition.print(file)
                else:
                    stdout.write(
                        _('The edition "%(edition)s" already exists with id "%(pk)d",'
                          + " aborting...") % {
                              "edition": edition,
                              "pk": edition.pk
                          },
                        "",
                        file=file,
                    )
            elif args.edition_subparser == "edit" and book:
                edition = Edition.get(args.edition, book)
                if edition:
                    edition.edit(args.edit_subparser, args.value)
                    stdout.write(
                        _('Successfully edited edition "%(edition)s" with id "%(pk)d".'
                          ) % {
                              "edition": edition,
                              "pk": edition.pk
                          },
                        "=",
                        file=file,
                    )
                    edition.print(file)
                else:
                    stdout.write(_("No edition found."), "", file=file)
            elif args.edition_subparser == "info" and book:
                edition = Edition.get(args.edition, book)
                if edition:
                    edition.print(file)
                else:
                    stdout.write(_("No edition found."), "", file=file)
            elif args.edition_subparser == "list" and book:
                if args.shelf:
                    editions = Edition.list.by_shelf(args.shelf, book)
                elif args.search:
                    editions = Edition.list.by_term(args.search, book)
                else:
                    editions = Edition.objects.filter(book=book)
                stdout.write(
                    [
                        _("Id"),
                        _("Title"),
                        _("Binding"),
                        _("ISBN"),
                        _("Publishing date"),
                    ],
                    "=",
                    [0.05, 0.55, 0.7, 0.85],
                    file=file,
                )
                for i, has_next in lookahead(editions):
                    stdout.write(
                        [
                            i.pk,
                            i.get_title(), i.binding, i.isbn, i.publishing_date
                        ],
                        "_" if has_next else "=",
                        [0.05, 0.55, 0.7, 0.85],
                        file=file,
                    )
            elif args.edition_subparser == "open" and book:
                edition = Edition.get(args.edition, book)
                if edition:
                    edition_file = edition.files.get(pk=args.file)
                    path = settings.MEDIA_ROOT / edition_file.file.path
                    if sys.platform == "linux":
                        os.system(f'xdg-open "{path}"')
                    else:
                        os.system(f'open "{path}"')
                else:
                    stdout.write(_("No edition found."), "", file=file)
            elif args.edition_subparser == "read" and book:
                edition = Edition.get(args.edition, book)
                read: Optional[Read] = None
                if args.read_subparser == "add" and edition:
                    read, created = Read.from_dict(
                        {
                            "started": args.started,
                            "finished": args.finished
                        }, edition)
                    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 edition:
                    read = Read.get(args.read, editions=edition)
                    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 edition:
                    read = Read.get(args.read, editions=edition)
                    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 edition found."), "", file=file)
        else:
            stdout.write(_("No book found."), "", file=file)
    elif args.subparser == "info":
        book = Book.get(args.book)
        if book:
            book.print(file)
        else:
            stdout.write(_("No book found."), "", file=file)
    elif args.subparser == "list":
        if args.search:
            books = Book.search(args.search)
        elif args.shelf:
            books = Book.by_shelf(args.shelf)
        else:
            books = Book.objects.all()
        stdout.write(
            [_("Id"), ("Title"),
             _("Authors"),
             _("Series"),
             _("Volume")],
            "=",
            [0.05, 0.5, 0.75, 0.9],
            file=file,
        )
        for i, has_next in lookahead(books):
            stdout.write(
                [
                    i.pk,
                    i.title,
                    " ,".join(f"{a}" for a in i.authors.all()),
                    i.series.name if i.series else "",
                    i.volume,
                ],
                "_" if has_next else "=",
                [0.05, 0.5, 0.75, 0.9],
                file=file,
            )
Exemplo n.º 14
0
def _read(args: Namespace, file: TextIO = sys.stdout):
    read: Optional[Acquisition] = None
    if args.subparser == "add":
        edition = Edition.get(args.obj)
        paper = Paper.get(args.obj)
        issue = Issue.get(args.obj)

        obj = None
        if edition is None and paper is None and issue is None:
            stdout.write(_("No edition, issue or paper found."), "", file=file)
            return
        elif edition is not None and paper is None and issue is None:
            obj = edition
        elif edition is None and paper is not None and issue is None:
            obj = paper
        elif edition is None and paper is None and issue is not None:
            obj = issue

        if obj:
            read, created = Read.from_dict(
                {
                    "started": args.started,
                    "finished": args.finished
                }, obj)
            if created:
                stdout.write(
                    _('Successfully added read with id "%(pk)d" to "{obj}".') %
                    {
                        "pk": read.pk,
                        "obj": obj
                    },
                    "=",
                    file=file,
                )
                read.print(file)
            else:
                stdout.write(
                    _('The read already exists with id "%(pk)d", aborting...')
                    % {"pk": read.pk},
                    "",
                    file=file,
                )
        else:
            stdout.write(_("More than one paper, issue or paper found."),
                         "",
                         file=file)
    elif args.subparser == "delete":
        read = Read.get(args.read)
        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.subparser == "edit":
        read = Read.get(args.read)
        if read:
            read.edit(args.field, args.value)
            stdout.write(
                _('Successfully edited read with id "%(pk)d".') %
                {"pk": read.pk},
                "",
                file=file,
            )
            read.print(file)
        else:
            stdout.write(_("No read found."), "", file=file)
    elif args.subparser == "info":
        read = Read.get(args.read)
        if read:
            read.print(file)
        else:
            stdout.write(_("No read found."), "", file=file)
Exemplo 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)