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
|
import PIL.Image
import cli.new.format as format
import cli.new.reader as reader
import io
import os
import pathlib
import requests
import shutil
import subprocess
def run(books_library, book_source=None):
# Get data
title = reader.required('Title')
subtitle = reader.optional('Subtitle')
authors = reader.non_empty_list('Authors')
author_sort = reader.required('Authors sorting')
genres = reader.non_empty_list('Genres')
year = reader.integer('Year')
lang = reader.choices('Lang', ['fr', 'en', 'de'])
summary = format.cleanup_text(reader.multi_line('Summary'), lang)
cover_url = reader.required('Cover url')
read = reader.choices('Read', ['Read', 'Unread', 'Reading', 'Stopped'])
# Output paths
author_path = format.path_part(author_sort)
title_path = format.path_part(title)
output_dir = f'{books_library}/{author_path}/{title_path}'
metadata_path = f'{output_dir}/metadata.toml'
cover_path = f'{output_dir}/cover.webp'
if not book_source is None:
ext = format.extension(book_source)
book_path = f'{output_dir}/book{ext}'
book_source_dir = os.path.dirname(os.path.realpath(book_source))
book_source_new = f'{book_source_dir}/{author_path}-{title_path}.mobi'
# Metadata
metadata = f"""title = "{title}"
subtitle = "{subtitle}"
authors = {format.list(authors)}
authorsSort = "{author_sort}"
genres = {format.list(genres)}
date = {year}
summary = \"\"\"
{summary}
\"\"\"
read = "{read}"
"""
# Ask for confirmation
print(f'About to create:\n\n- {metadata_path}\n- {cover_path}')
if not book_source is None:
print(f'- {book_path}')
print(f'\nAnd moving:\n\n {book_source},\n -> {book_source_new}.')
print()
reader.confirm('OK?')
# Create files
pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)
download_cover(cover_url, cover_path)
with open(metadata_path, 'w') as f:
f.write(metadata)
if not book_path is None:
shutil.copyfile(book_source, book_path)
if format.extension(book_source) in ['mobi', 'azw3']:
os.rename(book_source, book_source_new)
else:
subprocess.run(['ebook-convert', book_source, book_source_new])
os.remove(book_source)
# Download cover as WEBP
def download_cover(url, path):
response = requests.get(url, headers={ 'User-Agent': 'python-script' })
image = PIL.Image.open(io.BytesIO(response.content))
width, height = image.size
if width > 300:
image = image.resize((300, int(300 * height / width)), PIL.Image.LANCZOS)
image = image.convert('RGB')
image.save(path, 'WEBP', optimize=True, quality=85)
|