-
Notifications
You must be signed in to change notification settings - Fork 10
Book Submissions #114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
znedw
wants to merge
8
commits into
master
Choose a base branch
from
feature/books
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Book Submissions #114
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
faeb971
Feature: eBook uploads
znedw 40d22b1
More tags and links! ⛓️⛓️⛓️⛓️⛓️
znedw fb5ba59
Try a bit harder with Language detection 🏴☠️
znedw ea2b754
Automagic subcategorisation 🏷️
znedw 08edaba
Open Library integration for high-res covers 📚
znedw 553fa3d
Handle empty Language and/or Title 🐛
znedw 6101abb
Whoops 🐛
znedw e1a02b2
Merge branch 'master' into feature/books
znedw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| # -*- coding: utf-8 -*- | ||
| import subprocess | ||
|
|
||
| from .logging import log | ||
|
|
||
| COMMAND = "ebook-meta" | ||
|
|
||
|
|
||
| class EbookMetaException(Exception): | ||
| pass | ||
|
|
||
|
|
||
| def get_version(): | ||
| try: | ||
| ebook_meta = subprocess.Popen( | ||
| [COMMAND, '--version'], | ||
| stdout=subprocess.PIPE, stderr=subprocess.PIPE) | ||
| return ebook_meta.communicate()[0].decode('utf8') | ||
| except OSError: | ||
| raise EbookMetaException( | ||
| "Could not find {}, please ensure it is installed (via Calibre)." | ||
| .format(COMMAND)) | ||
|
|
||
|
|
||
| def read_metadata(path): | ||
| version = get_version() | ||
| log.debug('Found ebook-meta version: %s' % version) | ||
| log.info("Trying to read eBook metadata...") | ||
|
|
||
| output = subprocess.check_output( | ||
| '{} "{}"'.format(COMMAND, path), shell=True) | ||
| result = {} | ||
| for row in output.decode('utf8').split('\n'): | ||
| if ': ' in row: | ||
| try: | ||
| key, value = row.split(': ') | ||
| result[key.strip(' .')] = value.strip() | ||
| except ValueError: | ||
| pass | ||
| return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| # -*- coding: utf-8 -*- | ||
| from textwrap import dedent | ||
|
|
||
| import goodreads_api_client as gr | ||
| import pycountry | ||
|
|
||
| from .config import config | ||
| from .logging import log | ||
| from .calibre import read_metadata | ||
| from collections import OrderedDict | ||
|
|
||
| config.register( | ||
| 'Goodreads', 'api_key', | ||
| dedent("""\ | ||
| To find your Goodreads API key, login to https://www.goodreads.com/api/keys | ||
| Enter the API Key below | ||
| API Key""")) | ||
|
|
||
|
|
||
| def _extract_authors(authors): | ||
| if isinstance(authors['author'], OrderedDict): | ||
| return [{ | ||
| 'name': authors['author']['name'], | ||
| 'link': authors['author']['link'] | ||
| }] | ||
| else: | ||
| return [_extract_author(auth) | ||
| for auth in authors['author']] | ||
|
|
||
|
|
||
| def _extract_author(auth): | ||
| return { | ||
| 'name': auth['name'], | ||
| 'link': auth['link'] | ||
| } | ||
|
|
||
|
|
||
| def _extract_language(alpha_3): | ||
| return pycountry.languages.get(alpha_3=alpha_3).name | ||
|
|
||
|
|
||
| def _process_book(books): | ||
| keys_wanted = ['id', 'title', 'isbn', 'isbn13', 'description', | ||
| 'language_code', 'publication_year', 'publisher', | ||
| 'image_url', 'url', 'authors', 'average_rating', 'work'] | ||
| book = {k: v for k, v in books if k in keys_wanted} | ||
| book['authors'] = _extract_authors(book['authors']) | ||
| book['ratings_count'] = int(book['work']['ratings_count']['#text']) | ||
| book['language'] = _extract_language(book['language_code']) | ||
| return book | ||
|
|
||
|
|
||
| class Goodreads(object): | ||
| def __init__(self, interactive=True): | ||
| self.goodreads = gr.Client( | ||
| developer_key=config.get('Goodreads', 'api_key')) | ||
|
|
||
| def show_by_isbn(self, isbn): | ||
| return _process_book(self.goodreads.Book.show_by_isbn( | ||
| isbn).items()) | ||
|
|
||
| def search(self, path): | ||
|
|
||
| book = read_metadata(path) | ||
| isbn = '' | ||
| try: | ||
| isbn = book['Identifiers'].split(':')[1] | ||
| except KeyError: | ||
| pass | ||
|
|
||
| if isbn: | ||
| log.debug("Searching Goodreads by ISBN {} for '{}'", | ||
| isbn, book['Title']) | ||
| return self.show_by_isbn(isbn) | ||
| elif book['Title']: | ||
| search_term = book['Title'] | ||
| log.debug( | ||
| "Searching Goodreads by Title only for '{}'", search_term) | ||
| book_results = self.goodreads.search_book(search_term) | ||
| print("Results:") | ||
| for i, book in enumerate(book_results['results']['work']): | ||
| print('{}: {} by {} ({})' | ||
| .format(i, book['best_book']['title'], | ||
| book['best_book']['author']['name'], | ||
| book['original_publication_year'] | ||
| .get('#text', ''))) | ||
|
|
||
| while True: | ||
| choice = input('Select number or enter an alternate' | ||
| ' search term' | ||
| ' (or an ISBN with isbn: prefix):' | ||
| ' [0-{}, 0 default] ' | ||
| .format( | ||
| len(book_results['results']['work']) - 1)) | ||
| try: | ||
| choice = int(choice) | ||
| except ValueError: | ||
| if choice: | ||
| return self.show_by_isbn(choice.replace('isbn:', '')) | ||
| choice = 0 | ||
|
|
||
| try: | ||
| result = book_results['results']['work'][choice] | ||
| except IndexError: | ||
| pass | ||
| else: | ||
| id = result['best_book']['id'].get('#text', '') | ||
| log.debug("Selected Goodreads item {}", id) | ||
| log.debug("Searching Goodreads by ID {}", id) | ||
| return _process_book(self.goodreads.Book.show( | ||
| id).items()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| # -*- coding: utf-8 -*- | ||
| import requests | ||
| import json | ||
|
|
||
| from .logging import log | ||
|
|
||
| API_URL = 'https://www.googleapis.com/books/v1/' | ||
|
|
||
| cache = {} | ||
|
|
||
|
|
||
| def find_cover(isbn): | ||
| if _get_or_set(key=isbn): | ||
| return _extract_cover(cache[isbn]) | ||
|
|
||
| path = 'volumes?q=isbn:{}'.format(isbn) | ||
| resp = requests.get(API_URL+path) | ||
| log.debug('Fetching alt cover art from {}'.format(resp.url)) | ||
| if resp.status_code == 200: | ||
| content = json.loads(resp.content) | ||
| _get_or_set(key=isbn, value=content) | ||
| return _extract_cover(content) | ||
| else: | ||
| log.warn('Couldn\'t find cover art for ISBN {}'.format(isbn)) | ||
| return '' | ||
|
|
||
|
|
||
| def find_categories(isbn): | ||
| if _get_or_set(key=isbn): | ||
| return _extract_categories(cache[isbn]) | ||
|
|
||
| path = 'volumes?q=isbn:{}'.format(isbn) | ||
| resp = requests.get(API_URL+path) | ||
| log.debug('Fetching categories from {}'.format(resp.url)) | ||
| if resp.status_code == 200: | ||
| content = json.loads(resp.content) | ||
| _get_or_set(key=isbn, value=content) | ||
| return _extract_categories(content) | ||
| else: | ||
| log.warn('Couldn\'t find categories for ISBN {}'.format(isbn)) | ||
| return '' | ||
|
|
||
|
|
||
| def _get_or_set(**kwargs): | ||
| value = kwargs.get('value', None) | ||
| key = kwargs.get('key', None) | ||
| if value: | ||
| cache[key] = value | ||
| return value | ||
| elif key in cache: | ||
| return cache[key] | ||
|
|
||
|
|
||
| def _extract_categories(book): | ||
| return (book['items'][0]['volumeInfo'] | ||
| ['categories'] or '') | ||
|
|
||
|
|
||
| def _extract_cover(book): | ||
| return (book['items'][0]['volumeInfo'] | ||
| ['imageLinks']['thumbnail'] or '') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.