summaryrefslogtreecommitdiff
path: root/scripts/openlibrary2lesana
blob: c3d38e33931ffa90f080c6ce9525a04f27c2921a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3

import argparse
import logging
import os
import sys

import dateutil.parser
import requests

import lesana
import lesana.command

OPENAPI_BASE = "https://openlibrary.org"
OPENAPI_ISBN_URL = OPENAPI_BASE + '/isbn/{isbn}.json'


logger = logging.getLogger(__name__)


class OL2L(lesana.command.Command):
    """
    Manage collections
    """

    arguments = [
        (
            ['--collection', '-c'],
            dict(
                help='Name of the lesana collection, default is .',
                default='.',
            ),
        ),
        (
            ['--template', '-t'],
            {
                "help": "Template, "
                + "default is templates/from_openlibrary.yaml",
                "default": 'templates/from_openlibrary.yaml',
            },
        ),
        (
            ['isbn'],
            {
                'help': "ISBN of the book we want to search"
            },
        ),
    ]

    def _load_args(self):
        self.parser = argparse.ArgumentParser()
        for arg in self.arguments:
            self.parser.add_argument(*arg[0], **arg[1])
        self.args = self.parser.parse_args()

    def main(self):
        self._load_args()
        self.collection = self.collection_class(
            directory=self.args.collection
        )

        logging.info("Looking for %s on OpenLibrary", self.args.isbn)
        res = requests.get(OPENAPI_ISBN_URL.format(isbn=self.args.isbn))

        if res.status_code != 200:
            logger.error("No such isbn found on openlibrary")
            sys.exit(1)

        edition = res.json()

        langs = []
        for l in edition.get("languages", []):
            langs.append(l["key"].split("/")[-1])

        pub_date = dateutil.parser.parse(edition.get("publish_date"))

        authors = []
        for aid in edition.get("authors", []):
            logging.info("Retrieving %s from OpenLibrary", aid)
            res = requests.get(OPENAPI_BASE + aid["key"] + ".json")
            authors.append(res.json())

        data = {
            "edition": edition,
            "langs": langs,
            "pub_date": pub_date,
            "authors": authors,
        }

        entry = self.collection.entry_from_rendered_template(
            self.args.template,
            data
        )
        filepath = os.path.join(self.collection.itemdir, entry.fname)
        filepath = os.path.normpath(filepath)
        if self.edit_file_in_external_editor(filepath):
            self.collection.update_cache([entry.fname])
            if self.collection.settings["git"]:
                self.collection.git_add_files([filepath])
        saved_entry = self.collection.entry_from_eid(entry.eid)
        print(saved_entry)


def main():
    OL2L().main()


if __name__ == '__main__':
    main()