Debian Codegraph @

src/calibre/linux.py

raw ◀ ▶
5 Debian patches touch this file
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
3
4 """Post installation script for linux"""
5
6 import errno
7 import os
8 import stat
9 import sys
10 import textwrap
11 from functools import partial
12 from subprocess import check_call, check_output
13
14 from calibre import CurrentDir, __appname__, guess_type, prints
15 from calibre.constants import isbsd, islinux
16 from calibre.customize.ui import all_input_formats
17 from calibre.ptempfile import TemporaryDirectory
18 from calibre.utils.localization import _
19 from calibre.utils.resources import get_image_path as I
20 from calibre.utils.resources import get_path as P
21
22 entry_points = {
23 'console_scripts': [
24 'ebook-device = calibre.devices.cli:main',
25 'ebook-meta = calibre.ebooks.metadata.cli:main',
26 'ebook-convert = calibre.ebooks.conversion.cli:main',
27 'ebook-polish = calibre.ebooks.oeb.polish.main:main',
28 'markdown-calibre = markdown.__main__:run',
29 'web2disk = calibre.web.fetch.simple:main',
30 'calibre-server = calibre.srv.standalone:main',
31 'lrf2lrs = calibre.ebooks.lrf.lrfparser:main',
32 'lrs2lrf = calibre.ebooks.lrf.lrs.convert_from:main',
33 'calibre-debug = calibre.debug:main',
34 'calibredb = calibre.db.cli.main:main',
35 'calibre-parallel = calibre.utils.ipc.worker:main',
36 'calibre-customize = calibre.customize.ui:main',
37 'calibre-complete = calibre.utils.complete:main',
38 'fetch-ebook-metadata = calibre.ebooks.metadata.sources.cli:main',
39 'calibre-smtp = calibre.utils.smtp:main',
40 ],
41 'gui_scripts': [
42 __appname__ + ' = calibre.gui_launch:calibre',
43 'lrfviewer = calibre.gui2.lrf_renderer.main:main',
44 'ebook-viewer = calibre.gui_launch:ebook_viewer',
45 'ebook-edit = calibre.gui_launch:ebook_edit',
46 ],
47 }
48
49
50 def polyglot_write(stream):
51 stream_write = stream.write
52
53 def write(x):
54 if not isinstance(x, bytes):
55 x = x.encode('utf-8')
56 return stream_write(x)
57
58 return write
59
60
61 class PreserveMIMEDefaults: # {{{
62 def __init__(self):
63 self.initial_values = {}
64
65 def __enter__(self):
66 def_data_dirs = '/usr/local/share:/usr/share'
67 paths = os.environ.get('XDG_DATA_DIRS', def_data_dirs)
68 paths = paths.split(':')
69 paths.append(os.environ.get('XDG_DATA_HOME', os.path.expanduser('~/.local/share')))
70 paths = list(filter(os.path.isdir, paths))
71 if not paths:
72 # Env var had garbage in it, ignore it
73 paths = def_data_dirs.split(':')
74 paths = list(filter(os.path.isdir, paths))
75 self.paths = {os.path.join(x, 'applications/defaults.list') for x in paths}
76 self.initial_values = {}
77 for x in self.paths:
78 try:
79 with open(x, 'rb') as f:
80 self.initial_values[x] = f.read()
81 except Exception:
82 self.initial_values[x] = None
83
84 def __exit__(self, *args):
85 for path, val in self.initial_values.items():
86 if val is None:
87 try:
88 os.remove(path)
89 except Exception:
90 pass
91 elif os.path.exists(path):
92 try:
93 with open(path, 'r+b') as f:
94 if f.read() != val:
95 f.seek(0)
96 f.truncate()
97 f.write(val)
98 except OSError as e:
99 if e.errno != errno.EACCES:
100 raise
101
102
103 # }}}
104
105 # Uninstall script {{{
106
107 UNINSTALL = '''\
108 #!/bin/sh
109 # Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
110
111 search_for_python() {{
112 # We have to search for python as Ubuntu, in its infinite wisdom decided
113 # to release 18.04 with no python symlink, making it impossible to run polyglot
114 # python scripts.
115
116 # We cannot use command -v as it is not implemented in the posh shell shipped with
117 # Ubuntu/Debian. Similarly, there is no guarantee that which is installed.
118 # Shell scripting is a horrible joke, thank heavens for python.
119 local IFS=:
120 if [ $ZSH_VERSION ]; then
121 # zsh does not split by default
122 setopt sh_word_split
123 fi
124 local candidate_path
125 local candidate_python
126 local pythons=python3:python2
127 # disable pathname expansion (globbing)
128 set -f
129 for candidate_path in $PATH
130 do
131 if [ ! -z $candidate_path ]
132 then
133 for candidate_python in $pythons
134 do
135 if [ ! -z "$candidate_path" ]
136 then
137 if [ -x "$candidate_path/$candidate_python" ]
138 then
139 printf "$candidate_path/$candidate_python"
140 return
141 fi
142 fi
143 done
144 fi
145 done
146 set +f
147 printf "python"
148 }}
149
150 PYTHON=$(search_for_python)
151 echo Using python executable: $PYTHON
152
153 $PYTHON -c "import sys; exec(sys.stdin.read());" "$0" <<'CALIBRE_LINUX_INSTALLER_HEREDOC'
154 #!{python}
155 # vim:fileencoding=UTF-8
156 from __future__ import print_function, unicode_literals
157 euid = {euid}
158
159 import os, subprocess, shutil, tempfile, sys
160
161 try:
162 raw_input
163 except NameError:
164 raw_input = input
165 sys.stdin = open('/dev/tty')
166
167 if os.geteuid() != euid:
168 print('The installer was last run as user id:', euid, 'To remove all files you must run the uninstaller as the same user')
169 if raw_input('Proceed anyway? [y/n]:').lower() != 'y':
170 raise SystemExit(1)
171
172 frozen_path = {frozen_path!r}
173 if not frozen_path or not os.path.exists(os.path.join(frozen_path, 'resources', 'calibre-mimetypes.xml')):
174 frozen_path = None
175
176 dummy_mime_path = tempfile.mkdtemp(prefix='mime-hack.')
177 for f in {mime_resources!r}:
178 # dummyfile
179 f = os.path.basename(f)
180 file = os.path.join(dummy_mime_path, f)
181 open(file, 'w').close()
182 cmd = ['xdg-mime', 'uninstall', file]
183 print('Removing mime resource:', f)
184 ret = subprocess.call(cmd, shell=False)
185 if ret != 0:
186 print('WARNING: Failed to remove mime resource', f)
187
188 for x in tuple({manifest!r}) + tuple({appdata_resources!r}) + (sys.argv[-1], frozen_path, dummy_mime_path):
189 if not x or not os.path.exists(x):
190 continue
191 print('Removing', x)
192 try:
193 if os.path.isdir(x):
194 shutil.rmtree(x)
195 else:
196 os.unlink(x)
197 except Exception as e:
198 print('Failed to delete', x)
199 print('\t', e)
200
201 icr = {icon_resources!r}
202 mimetype_icons = []
203
204 def remove_icon(context, name, size, update=False):
205 cmd = ['xdg-icon-resource', 'uninstall', '--context', context, '--size', size, name]
206 if not update:
207 cmd.insert(2, '--noupdate')
208 print('Removing icon:', name, 'from context:', context, 'at size:', size)
209 ret = subprocess.call(cmd, shell=False)
210 if ret != 0:
211 print('WARNING: Failed to remove icon', name)
212
213 for i, (context, name, size) in enumerate(icr):
214 if context == 'mimetypes':
215 mimetype_icons.append((name, size))
216 continue
217 remove_icon(context, name, size, update=i == len(icr) - 1)
218
219 mr = {menu_resources!r}
220 for f in mr:
221 cmd = ['xdg-desktop-menu', 'uninstall', f]
222 print('Removing desktop file:', f)
223 ret = subprocess.call(cmd, shell=False)
224 if ret != 0:
225 print('WARNING: Failed to remove menu item', f)
226
227 print()
228
229 if mimetype_icons and raw_input('Remove the e-book format icons? [y/n]:').lower() in ['', 'y']:
230 for i, (name, size) in enumerate(mimetype_icons):
231 remove_icon('mimetypes', name, size, update=i == len(mimetype_icons) - 1)
232 CALIBRE_LINUX_INSTALLER_HEREDOC
233 '''
234
235 # }}}
236
237 # Completion {{{
238
239
240 class ZshCompleter: # {{{
241 def __init__(self, opts):
242 self.opts = opts
243 self.dest = None
244 base = os.path.dirname(self.opts.staging_sharedir)
245 self.detect_zsh(base)
246 if not self.dest and base == '/usr/share': # ty: ignore[redundant-condition]
247 # Ubuntu puts site-functions in /usr/local/share
248 self.detect_zsh('/usr/local/share')
249
250 self.commands = {}
251
252 def detect_zsh(self, base):
253 for x in ('vendor-completions', 'vendor-functions', 'site-functions'):
254 c = os.path.join(base, 'zsh', x)
255 if os.path.isdir(c) and os.access(c, os.W_OK):
256 self.dest = os.path.join(c, '_calibre')
257 break
258
259 def get_options(self, parser, cover_opts=('--cover',), opf_opts=('--opf',), file_map={}):
260 if hasattr(parser, 'option_list'):
261 options = parser.option_list
262 for group in parser.option_groups:
263 options += group.option_list
264 else:
265 options = parser
266 for opt in options:
267 lo, so = opt._long_opts, opt._short_opts
268 if opt.takes_value():
269 lo = [x + '=' for x in lo]
270 so = [x + '+' for x in so]
271 ostrings = lo + so
272 ostrings = '{{{}}}'.format(','.join(ostrings)) if len(ostrings) > 1 else ostrings[0]
273 exclude = ''
274 if opt.dest is None:
275 exclude = "'(- *)'"
276 h = opt.help or ''
277 h = h.replace('"', "'").replace('[', '(').replace(']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'")
278 h = h.replace('%default', str(opt.default))
279 arg = ''
280 if opt.takes_value():
281 arg = f':"{h}":'
282 if opt.dest in {'extract_to', 'debug_pipeline', 'to_dir', 'outbox', 'with_library', 'library_path'}:
283 arg += "'_path_files -/'"
284 elif opt.choices:
285 arg += '({})'.format('|'.join(opt.choices))
286 elif set(file_map).intersection(set(opt._long_opts)):
287 k = tuple(set(file_map).intersection(set(opt._long_opts)))
288 exts = file_map[k[0]]
289 if exts:
290 exts = (f'*.{x}' for x in sorted(exts + [x.upper() for x in exts]))
291 arg += "'_files -g \"{}\"'".format(' '.join(exts))
292 else:
293 arg += '_files'
294 elif opt.dest in {'pidfile', 'attachment'}:
295 arg += '_files'
296 elif set(opf_opts).intersection(set(opt._long_opts)):
297 arg += "'_files -g \"*.opf\"'"
298 elif set(cover_opts).intersection(set(opt._long_opts)):
299 exts = (f'*.{x}' for x in sorted(pics + [x.upper() for x in pics]))
300 arg += "'_files -g \"{}\"'".format(' '.join(exts))
301
302 help_txt = f'"[{h}]"'
303 yield f'{exclude}{ostrings}{help_txt}{arg} '
304
305 def opts_and_exts(self, name, op, exts, cover_opts=('--cover',), opf_opts=('--opf',), file_map={}):
306 if not self.dest:
307 return
308 exts = sorted({x.lower() for x in exts})
309 extra = ('''"*:filename:_files -g '(#i)*.({})'" '''.format('|'.join(exts)),)
310 opts = '\\\n '.join(tuple(self.get_options(op(), cover_opts=cover_opts, opf_opts=opf_opts, file_map=file_map)) + extra)
311 txt = '_arguments -s \\\n ' + opts
312 self.commands[name] = txt
313
314 def opts_and_words(self, name, op, words, takes_files=False):
315 if not self.dest:
316 return
317 extra = ("'*:filename:_files' ",) if takes_files else ()
318 opts = '\\\n '.join(tuple(self.get_options(op())) + extra)
319 txt = '_arguments -s \\\n ' + opts
320 self.commands[name] = txt
321
322 def do_ebook_convert(self, f):
323 from calibre.customize.ui import available_output_formats
324 from calibre.ebooks.conversion.cli import create_option_parser, group_titles
325 from calibre.ebooks.conversion.plumber import supported_input_formats
326 from calibre.utils.logging import DevNull
327 from calibre.web.feeds.recipes.collection import get_builtin_recipe_titles
328
329 input_fmts = sorted(set(supported_input_formats()))
330 output_fmts = sorted(set(available_output_formats()))
331 iexts = sorted({x.upper() for x in input_fmts}.union(input_fmts))
332 oexts = sorted({x.upper() for x in output_fmts}.union(output_fmts))
333 w = polyglot_write(f)
334 # Arg 1
335 w('\n_ebc_input_args() {')
336 w('\n local extras; extras=(')
337 w('\n {-h,--help}":Show Help"')
338 w('\n "--version:Show program version"')
339 w('\n "--list-recipes:List builtin recipe names"')
340 for recipe in sorted(set(get_builtin_recipe_titles())):
341 recipe = recipe.replace(':', '\\:').replace('"', '\\"')
342 w(f'\n "{recipe}.recipe"')
343 w('\n ); _describe -t recipes "ebook-convert builtin recipes" extras')
344 w('\n _files -g "{}"'.format(' '.join(f'*.{x}' for x in iexts)))
345 w('\n}\n')
346
347 # Arg 2
348 w('\n_ebc_output_args() {')
349 w('\n local extras; extras=(')
350 for x in output_fmts:
351 w(f'\n ".{x}:Convert to a .{x} file with the same name as the input file"')
352 w('\n ); _describe -t output "ebook-convert output" extras')
353 w('\n _files -g "{}"'.format(' '.join(f'*.{x}' for x in oexts)))
354 w('\n _path_files -/')
355 w('\n}\n')
356
357 log = DevNull()
358
359 def get_parser(input_fmt='epub', output_fmt=None):
360 of = ('dummy2.' + output_fmt) if output_fmt else 'dummy'
361 return create_option_parser(('ec', 'dummy1.' + input_fmt, of, '-h'), log)[0]
362
363 # Common options
364 input_group, output_group = group_titles()
365 p = get_parser()
366 opts = p.option_list
367 for group in p.option_groups:
368 if group.title not in {input_group, output_group}:
369 opts += group.option_list
370 opts.append(p.get_option('--pretty-print'))
371 opts.append(p.get_option('--input-encoding'))
372 opts = '\\\n '.join(tuple(self.get_options(opts, file_map={'--search-replace': ()})))
373 w('\n_ebc_common_opts() {')
374 w('\n _arguments -s \\\n ' + opts)
375 w('\n}\n')
376
377 # Input/Output format options
378 for fmts, group_title, func in (
379 (input_fmts, input_group, '_ebc_input_opts_%s'),
380 (output_fmts, output_group, '_ebc_output_opts_%s'),
381 ):
382 for fmt in fmts:
383 is_input = group_title == input_group
384 if is_input and fmt in {'rar', 'zip', 'oebzip'}:
385 continue
386 p = get_parser(input_fmt=fmt) if is_input else get_parser(output_fmt=fmt)
387 opts = None
388 for group in p.option_groups:
389 if group.title == group_title:
390 opts = [o for o in group.option_list if '--pretty-print' not in o._long_opts and '--input-encoding' not in o._long_opts]
391 if not opts:
392 continue
393 opts = '\\\n '.join(tuple(sorted(self.get_options(opts))))
394 w('\n%s() {' % (func % fmt))
395 w('\n _arguments -s \\\n ' + opts)
396 w('\n}\n')
397
398 w('\n_ebook_convert() {')
399 w('\n local iarg oarg context state_descr state line\n typeset -A opt_args\n local ret=1')
400 w("\n _arguments '1: :_ebc_input_args' '*::ebook-convert output:->args' && ret=0")
401 w('\n case $state in \n (args)')
402 w('\n iarg=${line[1]##*.}; ')
403 w("\n _arguments '1: :_ebc_output_args' '*::ebook-convert options:->args' && ret=0")
404 w('\n case $state in \n (args)')
405
406 w('\n oarg=${line[1]##*.}')
407 w('\n iarg="_ebc_input_opts_${(L)iarg}"; oarg="_ebc_output_opts_${(L)oarg}"')
408 w('\n _call_function - $iarg; _call_function - $oarg; _ebc_common_opts; ret=0')
409 w('\n ;;\n esac')
410
411 w('\n ;;\n esac\n return ret')
412 w('\n}\n')
413
414 def do_ebook_edit(self, f):
415 from calibre.ebooks.oeb.polish.import_book import IMPORTABLE
416 from calibre.ebooks.oeb.polish.main import SUPPORTED
417 from calibre.gui2.tweak_book.main import option_parser
418
419 tweakable_fmts = sorted(SUPPORTED | IMPORTABLE)
420 parser = option_parser()
421 opt_lines = []
422 for opt in parser.option_list:
423 lo, so = opt._long_opts, opt._short_opts
424 if opt.takes_value():
425 lo = [x + '=' for x in lo]
426 so = [x + '+' for x in so]
427 ostrings = lo + so
428 ostrings = '{{{}}}'.format(','.join(ostrings)) if len(ostrings) > 1 else f'"{ostrings[0]}"'
429 h = opt.help or ''
430 h = h.replace('"', "'").replace('[', '(').replace(']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'")
431 h = h.replace('%default', str(opt.default))
432 help_txt = f'"[{h}]"'
433 opt_lines.append(ostrings + help_txt + ' \\')
434 opt_lines = ('\n' + (' ' * 8)).join(opt_lines)
435
436 polyglot_write(f)(
437 '''
438 _ebook_edit() {{
439 local curcontext="$curcontext" state line ebookfile expl
440 typeset -A opt_args
441
442 _arguments -C -s \\
443 {}
444 "1:ebook file:_files -g '(#i)*.({})'" \\
445 '*:file in ebook:->files' && return 0
446
447 case $state in
448 files)
449 ebookfile=${{~${{(Q)line[1]}}}}
450
451 if [[ -f "$ebookfile" && "$ebookfile" =~ '\\.[eE][pP][uU][bB]$' ]]; then
452 _zip_cache_name="$ebookfile"
453 _zip_cache_list=( ${{(f)"$(zipinfo -1 $_zip_cache_name 2>/dev/null)"}} )
454 else
455 return 1
456 fi
457 _wanted files expl 'file from ebook' \\
458 _multi_parts / _zip_cache_list && return 0
459 ;;
460 esac
461
462 return 1
463 }}
464 '''.format(opt_lines, '|'.join(tweakable_fmts))
465 + '\n\n'
466 )
467
468 def do_calibredb(self, f):
469 from calibre.customize.ui import available_catalog_formats
470 from calibre.db.cli.main import COMMANDS, option_parser_for
471
472 parsers, descs = {}, {}
473 for command in COMMANDS:
474 p = option_parser_for(command)()
475 parsers[command] = p
476 lines = [x.strip().partition('.')[0] for x in p.usage.splitlines() if x.strip() and not x.strip().startswith('%prog')]
477 descs[command] = lines[0]
478
479 w = polyglot_write(f)
480 w('\n_calibredb_cmds() {\n local commands; commands=(\n')
481 w(' {-h,--help}":Show help"\n')
482 w(' "--version:Show version"\n')
483 for command, desc in descs.items():
484 w(' "{}:{}"\n'.format(command, desc.replace(':', '\\:').replace('"', "'")))
485 w(' )\n _describe -t commands "calibredb command" commands \n}\n')
486
487 subcommands = []
488 for command, parser in parsers.items():
489 exts = []
490 if command == 'catalog':
491 exts = [x.lower() for x in available_catalog_formats()]
492 elif command == 'set_metadata':
493 exts = ['opf']
494 exts = sorted(set(exts).union(x.upper() for x in exts))
495 pats = (f'*.{x}' for x in exts)
496 extra = ("'*:filename:_files -g \"{}\"' ".format(' '.join(pats)),) if exts else ()
497 if command in {'add', 'add_format'}:
498 extra = ("'*:filename:_files' ",)
499 opts = '\\\n '.join(tuple(self.get_options(parser)) + extra)
500 txt = ' _arguments -s \\\n ' + opts
501 subcommands.append(f'({command})')
502 subcommands.append(txt)
503 subcommands.append(';;')
504
505 w('\n_calibredb() {')
506 w(
507 r'''
508 local state line state_descr context
509 typeset -A opt_args
510 local ret=1
511
512 _arguments \
513 '1: :_calibredb_cmds' \
514 '*::calibredb subcommand options:->args' \
515 && ret=0
516
517 case $state in
518 (args)
519 case $line[1] in
520 (-h|--help|--version)
521 _message 'no more arguments' && ret=0
522 ;;
523 {}
524 esac
525 ;;
526 esac
527
528 return ret
529 '''.format('\n '.join(subcommands))
530 )
531 w('\n}\n\n')
532
533 def write(self):
534
535 if self.dest:
536 for c in ('calibredb', 'ebook-convert', 'ebook-edit'):
537 self.commands[c] = ' _{} "$@"'.format(c.replace('-', '_'))
538 with open(self.dest, 'wb') as f:
539 w = polyglot_write(f)
540 w('#compdef ' + ' '.join(self.commands) + '\n')
541 self.do_ebook_convert(f)
542 self.do_calibredb(f)
543 self.do_ebook_edit(f)
544 w('case $service in\n')
545 for c, txt in self.commands.items():
546 w(f'{c})\n{txt}\n;;\n')
547 w('esac\n')
548
549
550 # }}}
551
552
553 def get_bash_completion_path(root, share, info):
554 if root == '/usr':
555 # Try to get the system bash completion dir since we are installing to
556 # /usr
557 try:
558 path = check_output('pkg-config --variable=completionsdir bash-completion'.split()).decode('utf-8').strip().partition(os.pathsep)[0]
559 except Exception:
560 info('Failed to find directory to install bash completions, using default.')
561 path = '/usr/share/bash-completion/completions'
562 if path and os.path.exists(path) and os.path.isdir(path):
563 return path
564 else:
565 # Use the default bash-completion dir under staging_share
566 return os.path.join(share, 'bash-completion', 'completions')
567
568
569 def write_completion(self, bash_comp_dest, zsh):
570 from calibre.customize.ui import available_input_formats
571 from calibre.debug import option_parser as debug_op
572 from calibre.ebooks import BOOK_EXTENSIONS
573 from calibre.ebooks.lrf.lrfparser import option_parser as lrf2lrsop
574 from calibre.ebooks.metadata.cli import filetypes as meta_filetypes
575 from calibre.ebooks.metadata.cli import option_parser as metaop
576 from calibre.ebooks.metadata.sources.cli import option_parser as fem_op
577 from calibre.ebooks.oeb.polish.import_book import IMPORTABLE
578 from calibre.ebooks.oeb.polish.main import SUPPORTED
579 from calibre.ebooks.oeb.polish.main import option_parser as polish_op
580 from calibre.gui2.lrf_renderer.main import option_parser as lrfviewerop
581 from calibre.gui2.main import option_parser as guiop
582 from calibre.gui2.tweak_book.main import option_parser as tweak_op
583 from calibre.gui2.viewer.main import option_parser as viewer_op
584 from calibre.srv.standalone import create_option_parser as serv_op
585 from calibre.utils.smtp import option_parser as smtp_op
586
587 input_formats = sorted(all_input_formats())
588 tweak_formats = sorted(x.lower() for x in SUPPORTED | IMPORTABLE)
589
590 if bash_comp_dest and not os.path.exists(bash_comp_dest):
591 os.makedirs(bash_comp_dest)
592
593 complete = 'calibre-complete'
594 if getattr(sys, 'frozen_path', None):
595 complete = os.path.join(getattr(sys, 'frozen_path'), complete)
596
597 def o_and_e(name, *args, **kwargs):
598 bash_compfile = os.path.join(bash_comp_dest, name)
599 with open(bash_compfile, 'wb') as f:
600 f.write(opts_and_exts(name, *args, **kwargs))
601 self.manifest.append(bash_compfile)
602 zsh.opts_and_exts(name, *args, **kwargs)
603
604 def o_and_w(name, *args, **kwargs):
605 bash_compfile = os.path.join(bash_comp_dest, name)
606 with open(bash_compfile, 'wb') as f:
607 f.write(opts_and_words(name, *args, **kwargs))
608 self.manifest.append(bash_compfile)
609 zsh.opts_and_words(name, *args, **kwargs)
610
611 o_and_e('calibre', guiop, BOOK_EXTENSIONS)
612 o_and_e('lrf2lrs', lrf2lrsop, ['lrf'], file_map={'--output': ['lrs']})
613 o_and_e('ebook-meta', metaop, list(meta_filetypes()), cover_opts=['--cover', '-c'], opf_opts=['--to-opf', '--from-opf'])
614 o_and_e(
615 'ebook-polish',
616 polish_op,
617 [x.lower() for x in SUPPORTED],
618 cover_opts=['--cover', '-c'],
619 opf_opts=['--opf', '-o'],
620 )
621 o_and_e('lrfviewer', lrfviewerop, ['lrf'])
622 o_and_e('ebook-viewer', viewer_op, input_formats)
623 o_and_e('ebook-edit', tweak_op, tweak_formats)
624 o_and_w('fetch-ebook-metadata', fem_op, [])
625 o_and_w('calibre-smtp', smtp_op, [])
626 o_and_w('calibre-server', serv_op, [])
627 o_and_e(
628 'calibre-debug',
629 debug_op,
630 ['py', 'recipe', 'epub', 'mobi', 'azw', 'azw3', 'docx'],
631 file_map={
632 '--tweak-book': ['epub', 'azw3', 'mobi'],
633 '--subset-font': ['ttf', 'otf'],
634 '--exec-file': ['py', 'recipe'],
635 '--add-simple-plugin': ['py'],
636 '--inspect-mobi': ['mobi', 'azw', 'azw3'],
637 '--viewer': sorted(available_input_formats()),
638 },
639 )
640 with open(os.path.join(bash_comp_dest, 'ebook-device'), 'wb') as f:
641 f.write(
642 textwrap.dedent('''\
643 _ebook_device_ls()
644 {
645 local pattern search listing prefix
646 pattern="$1"
647 search="$1"
648 if [[ -n "{$pattern}" ]]; then
649 if [[ "${pattern:(-1)}" == "/" ]]; then
650 pattern=""
651 else
652 pattern="$(basename ${pattern} 2> /dev/null)"
653 search="$(dirname ${search} 2> /dev/null)"
654 fi
655 fi
656
657 if [[ "x${search}" == "x" || "x${search}" == "x." ]]; then
658 search="/"
659 fi
660
661 listing="$(ebook-device ls ${search} 2>/dev/null)"
662
663 prefix="${search}"
664 if [[ "x${prefix:(-1)}" != "x/" ]]; then
665 prefix="${prefix}/"
666 fi
667
668 echo $(compgen -P "${prefix}" -W "${listing}" "${pattern}")
669 }
670
671 _ebook_device()
672 {
673 local cur prev
674 cur="${COMP_WORDS[COMP_CWORD]}"
675 prev="${COMP_WORDS[COMP_CWORD-1]}"
676 COMPREPLY=()
677 case "${prev}" in
678 ls|rm|mkdir|touch|cat )
679 COMPREPLY=( $(_ebook_device_ls "${cur}") )
680 return 0
681 ;;
682 cp )
683 if [[ ${cur} == dev:* ]]; then
684 COMPREPLY=( $(_ebook_device_ls "${cur:7}") )
685 return 0
686 else
687 _filedir
688 return 0
689 fi
690 ;;
691 dev )
692 COMPREPLY=( $(compgen -W "cp ls rm mkdir touch cat info books df" "${cur}") )
693 return 0
694 ;;
695 * )
696 if [[ ${cur} == dev:* ]]; then
697 COMPREPLY=( $(_ebook_device_ls "${cur:7}") )
698 return 0
699 else
700 if [[ ${prev} == dev:* ]]; then
701 _filedir
702 return 0
703 else
704 COMPREPLY=( $(compgen -W "dev:" "${cur}") )
705 return 0
706 fi
707 return 0
708 fi
709 ;;
710 esac
711 }
712 complete -o nospace -F _ebook_device ebook-device''').encode('utf-8')
713 )
714 self.manifest.append(os.path.join(bash_comp_dest, 'ebook-device'))
715 with open(os.path.join(bash_comp_dest, 'ebook-convert'), 'wb') as f:
716 f.write((f'complete -o nospace -C {complete} ebook-convert').encode())
717 self.manifest.append(os.path.join(bash_comp_dest, 'ebook-convert'))
718 zsh.write()
719
720
721 # }}}
722
723
724 class PostInstall:
725 def task_failed(self, msg):
726 if self.warn:
727 self.warn(msg, 'with error:')
728 import traceback
729
730 tb = '\n\t'.join(traceback.format_exc().splitlines())
731 self.info('\t' + tb)
732 print()
733
734 def warning(self, *args, **kwargs):
735 print('\n' + '_' * 20, 'WARNING', '_' * 20)
736 prints(*args, **kwargs)
737 print('_' * 50)
738 print('\n')
739 self.warnings.append((args, kwargs))
740 sys.stdout.flush()
741
742 def __init__(self, opts, info=prints, warn=None, manifest=None):
743 self.opts = opts
744 self.info = info
745 self.warn = warn
746 self.warnings = []
747 if self.warn is None:
748 self.warn = self.warning
749
750 if not self.opts.staging_bindir:
751 self.opts.staging_bindir = os.path.join(self.opts.staging_root, 'bin')
752 if not self.opts.staging_sharedir:
753 self.opts.staging_sharedir = os.path.join(self.opts.staging_root, 'share', 'calibre')
754 self.opts.staging_etc = '/etc' if self.opts.staging_root == '/usr' else os.path.join(self.opts.staging_root, 'etc')
755
756 prefix = getattr(self.opts, 'prefix', None)
757 if prefix and prefix != self.opts.staging_root:
758 self.opts.staged_install = True
759 os.environ['XDG_DATA_DIRS'] = os.path.join(self.opts.staging_root, 'share')
760 os.environ['XDG_UTILS_INSTALL_MODE'] = 'system'
761
762 from calibre.utils.serialize import msgpack_loads
763
764 scripts = msgpack_loads(P('scripts.calibre_msgpack', data=True))
765 self.manifest = manifest or []
766 if getattr(sys, 'frozen_path', False):
767 if os.access(self.opts.staging_bindir, os.W_OK):
768 self.info('Creating symlinks...')
769 for exe in scripts:
770 dest = os.path.join(self.opts.staging_bindir, exe)
771 if os.path.lexists(dest):
772 os.unlink(dest)
773 tgt = os.path.join(getattr(sys, 'frozen_path'), exe)
774 self.info(f'\tSymlinking {tgt} to {dest}')
775 os.symlink(tgt, dest)
776 self.manifest.append(dest)
777 else:
778 self.warning(
779 textwrap.fill(
780 'No permission to write to {}, not creating program launch symlinks,'
781 ' you should ensure that {} is in your PATH or create the symlinks yourself'.format(
782 self.opts.staging_bindir, getattr(sys, 'frozen_path', 'the calibre installation directory')
783 )
784 )
785 )
786
787 self.icon_resources = []
788 self.menu_resources = []
789 self.mime_resources = []
790 self.appdata_resources = []
791 if islinux or isbsd:
792 self.setup_completion()
793 if islinux or isbsd:
794 self.setup_desktop_integration()
795 if not getattr(self.opts, 'staged_install', False):
796 self.create_uninstaller()
797
798 from calibre.utils.config import config_dir
799
800 if os.path.exists(config_dir):
801 os.chdir(config_dir)
802 if islinux or isbsd:
803 for f in os.listdir('.'):
804 if os.stat(f).st_uid == 0:
805 import shutil
806
807 shutil.rmtree(f) if os.path.isdir(f) else os.unlink(f)
808 if os.stat(config_dir).st_uid == 0:
809 os.rmdir(config_dir)
810
811 if warn is None and self.warnings:
812 self.info(f'\n\nThere were {len(self.warnings)} warnings\n')
813 for args, kwargs in self.warnings:
814 self.info('*', *args, **kwargs)
815 print()
816
817 def create_uninstaller(self):
818 base = self.opts.staging_bindir
819 if not os.access(base, os.W_OK) and getattr(sys, 'frozen_path', ''):
820 base = getattr(sys, 'frozen_path')
821 dest = os.path.join(base, 'calibre-uninstall')
822 self.info('Creating un-installer:', dest)
823 raw = UNINSTALL.format(
824 python='/usr/bin/python',
825 euid=os.geteuid(),
826 manifest=self.manifest,
827 icon_resources=self.icon_resources,
828 mime_resources=self.mime_resources,
829 menu_resources=self.menu_resources,
830 appdata_resources=self.appdata_resources,
831 frozen_path=getattr(sys, 'frozen_path', None),
832 )
833 try:
834 with open(dest, 'wb') as f:
835 f.write(raw.encode('utf-8'))
836 os.chmod(dest, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
837 if os.geteuid() == 0:
838 os.chown(dest, 0, 0)
839 except Exception:
840 if self.opts.fatal_errors:
841 raise
842 self.task_failed('Creating uninstaller failed')
843
844 def setup_completion(self): # {{{
845 try:
846 self.info('Setting up command-line completion...')
847 zsh = ZshCompleter(self.opts)
848 if zsh.dest:
849 self.info('Installing zsh completion to:', zsh.dest)
850 self.manifest.append(zsh.dest)
851 bash_comp_dest = get_bash_completion_path(self.opts.staging_root, os.path.dirname(self.opts.staging_sharedir), self.info)
852 if bash_comp_dest is not None:
853 self.info('Installing bash completion to:', bash_comp_dest + os.sep)
854 write_completion(self, bash_comp_dest, zsh)
855 except TypeError as err:
856 if 'resolve_entities' in str(err):
857 print('You need python-lxml >= 2.0.5 for calibre')
858 sys.exit(1)
859 raise
860 except OSError as e:
861 if e.errno == errno.EACCES:
862 self.warning('Failed to setup completion, permission denied')
863 if self.opts.fatal_errors:
864 raise
865 self.task_failed('Setting up completion failed')
866 except Exception:
867 if self.opts.fatal_errors:
868 raise
869 self.task_failed('Setting up completion failed')
870
871 # }}}
872
873 def setup_desktop_integration(self): # {{{
874 try:
875 self.info('Setting up desktop integration...')
876 self.do_setup_desktop_integration()
877 except Exception:
878 if self.opts.fatal_errors:
879 raise
880 self.task_failed('Setting up desktop integration failed')
881
882 def do_setup_desktop_integration(self):
883 env = os.environ.copy()
884 cc = check_call
885 if getattr(sys, 'frozen_path', '') and 'LD_LIBRARY_PATH' in env:
886 paths = env.get('LD_LIBRARY_PATH', '').split(os.pathsep)
887 paths = [x for x in paths if x]
888 npaths = [x for x in paths if x != getattr(sys, 'frozen_path') + '/lib']
889 env['LD_LIBRARY_PATH'] = os.pathsep.join(npaths)
890 cc = partial(check_call, env=env)
891
892 if getattr(self.opts, 'staged_install', False):
893 for d in ('applications', 'desktop-directories', 'icons/hicolor', 'mime/packages'):
894 os.makedirs(os.path.join(self.opts.staging_root, 'share', d), exist_ok=True)
895
896 with TemporaryDirectory() as tdir, CurrentDir(tdir):
897 with PreserveMIMEDefaults():
898 self.install_xdg_junk(cc, env)
899
900 def install_xdg_junk(self, cc, env):
901
902 def install_single_icon(iconsrc, basename, size, context, is_last_icon=False):
903 filename = f'{basename}-{size}.png'
904 render_img(iconsrc, filename, width=int(size), height=int(size))
905 cmd = [
906 'xdg-icon-resource',
907 'install',
908 '--noupdate',
909 '--context',
910 context,
911 '--size',
912 str(size),
913 filename,
914 basename,
915 ]
916 if is_last_icon:
917 del cmd[2]
918 cc(cmd)
919 self.icon_resources.append((context, basename, str(size)))
920
921 def install_icons(iconsrc, basename, context, is_last_icon=False):
922 sizes = (16, 32, 48, 64, 128, 256)
923 for size in sizes:
924 install_single_icon(iconsrc, basename, size, context, is_last_icon and size is sizes[-1])
925
926 icons = [
927 x.strip()
928 for x in '''\
929 mimetypes/lrf.png application-lrf mimetypes
930 mimetypes/lrf.png text-lrs mimetypes
931 mimetypes/mobi.png application-x-mobipocket-ebook mimetypes
932 mimetypes/tpz.png application-x-topaz-ebook mimetypes
933 mimetypes/azw2.png application-x-kindle-application mimetypes
934 mimetypes/azw3.png application-x-mobi8-ebook mimetypes
935 lt.png calibre-gui apps
936 viewer.png calibre-viewer apps
937 tweak.png calibre-ebook-edit apps
938 '''.splitlines()
939 if x.strip()
940 ]
941 for line in icons:
942 iconsrc, basename, context = line.split()
943 install_icons(iconsrc, basename, context, is_last_icon=line is icons[-1])
944
945 mimetypes = set()
946 for x in all_input_formats():
947 mt = guess_type('dummy.' + x)[0]
948 if mt and 'chemical' not in mt and 'ctc-posml' not in mt:
949 mimetypes.add(mt)
950 mimetypes.discard('application/octet-stream')
951 mimetypes = sorted(mimetypes)
952
953 def write_mimetypes(f, extra=''):
954 line = 'MimeType={};'.format(';'.join(mimetypes))
955 if extra:
956 line += extra + ';'
957 f.write(line.encode('utf-8') + b'\n')
958
959 from calibre.ebooks.oeb.polish.import_book import IMPORTABLE
960 from calibre.ebooks.oeb.polish.main import SUPPORTED
961
962 with open('calibre-lrfviewer.desktop', 'wb') as f:
963 f.write(VIEWER.encode('utf-8'))
964 with open('calibre-ebook-viewer.desktop', 'wb') as f:
965 f.write(EVIEWER.encode('utf-8'))
966 write_mimetypes(f)
967 with open('calibre-ebook-edit.desktop', 'wb') as f:
968 f.write(ETWEAK.encode('utf-8'))
969 mt = {guess_type('a.' + x.lower())[0] for x in (SUPPORTED | IMPORTABLE)} - {
970 None,
971 'application/octet-stream',
972 }
973 mt = sorted(mt)
974 f.write(('MimeType={};\n'.format(';'.join(mt))).encode('utf-8'))
975 with open('calibre-gui.desktop', 'wb') as f:
976 f.write(GUI.encode('utf-8'))
977 write_mimetypes(f, 'x-scheme-handler/calibre')
978 des = (
979 'calibre-gui.desktop',
980 'calibre-lrfviewer.desktop',
981 'calibre-ebook-viewer.desktop',
982 'calibre-ebook-edit.desktop',
983 )
984 appdata = os.path.join(os.path.dirname(self.opts.staging_sharedir), 'metainfo')
985 translators = None
986 if not os.path.exists(appdata):
987 try:
988 os.mkdir(appdata)
989 except Exception:
990 self.warning(f'Failed to create {appdata} not installing appdata files')
991 if os.path.exists(appdata) and not os.access(appdata, os.W_OK):
992 self.warning(f'Do not have write permissions for {appdata} not installing appdata files')
993 else:
994 from calibre.utils.localization import get_all_translators
995
996 translators = dict(get_all_translators())
997
998 APPDATA = get_appdata()
999 for x in des:
1000 cmd = ['xdg-desktop-menu', 'install', '--noupdate', './' + x]
1001 cc(' '.join(cmd), shell=True)
1002 self.menu_resources.append(x)
1003 ak = x.partition('.')[0]
1004 if ak in APPDATA and translators is not None and os.access(appdata, os.W_OK):
1005 self.appdata_resources.append(write_appdata(ak, APPDATA[ak], appdata, translators))
1006
1007 MIME_BASE = 'calibre-mimetypes.xml'
1008 MIME = P(MIME_BASE)
1009 self.mime_resources.append(MIME_BASE)
1010 if not getattr(self.opts, 'staged_install', False):
1011 cc(['xdg-mime', 'install', MIME])
1012 cc(['xdg-desktop-menu', 'forceupdate'])
1013 else:
1014 from shutil import copyfile
1015
1016 copyfile(MIME, os.path.join(env['XDG_DATA_DIRS'], 'mime', 'packages', MIME_BASE))
1017
1018 # }}}
1019
1020
1021 def option_parser():
1022 from calibre.utils.config import OptionParser
1023
1024 parser = OptionParser()
1025 parser.add_option('--make-errors-fatal', action='store_true', default=False, dest='fatal_errors', help='If set die on errors.')
1026 parser.add_option('--root', dest='staging_root', default='/usr', help='Prefix under which to install files')
1027 parser.add_option(
1028 '--bindir',
1029 default=None,
1030 dest='staging_bindir',
1031 help='Location where calibre launcher scripts were installed. Typically /usr/bin',
1032 )
1033 parser.add_option(
1034 '--sharedir',
1035 default=None,
1036 dest='staging_sharedir',
1037 help='Location where calibre resources were installed, typically /usr/share/calibre',
1038 )
1039
1040 return parser
1041
1042
1043 def options(option_parser):
1044 parser = option_parser()
1045 options = parser.option_list
1046 for group in parser.option_groups:
1047 options += group.option_list
1048 opts = []
1049 for opt in options:
1050 opts.extend(opt._short_opts)
1051 opts.extend(opt._long_opts)
1052 return opts
1053
1054
1055 def opts_and_words(name, op, words, takes_files=False):
1056 opts = '|'.join(options(op))
1057 words = '|'.join([w.replace("'", "\\'") for w in words])
1058 fname = name.replace('-', '_')
1059 return (
1060 '_'
1061 + fname
1062 + '()'
1063 + f'''
1064 {{
1065 local cur opts
1066 local IFS=$'|\\t'
1067 COMPREPLY=()
1068 cur="${{COMP_WORDS[COMP_CWORD]}}"
1069 opts="{opts}"
1070 words="{words}"
1071
1072 case "${{cur}}" in
1073 -* )
1074 COMPREPLY=( $(compgen -W "${{opts}}" -- ${{cur}}) )
1075 COMPREPLY=( $( echo ${{COMPREPLY[@]}} | sed 's/ /\\\\ /g' | tr '\\n' '\\t' ) )
1076 return 0
1077 ;;
1078 * )
1079 COMPREPLY=( $(compgen -W "${{words}}" -- ${{cur}}) )
1080 COMPREPLY=( $( echo ${{COMPREPLY[@]}} | sed 's/ /\\\\ /g' | tr '\\n' '\\t' ) )
1081 return 0
1082 ;;
1083 esac
1084
1085 }}
1086 complete -F _'''
1087 + fname
1088 + ' '
1089 + name
1090 + '\n\n'
1091 ).encode('utf-8')
1092
1093
1094 pics = ['bmp', 'gif', 'jpeg', 'jpg', 'png'] # keep sorted alphabetically
1095
1096
1097 def opts_and_exts(name, op, exts, cover_opts=('--cover',), opf_opts=(), file_map={}):
1098 opts = ' '.join(options(op))
1099 exts.extend([i.upper() for i in exts])
1100 exts = '|'.join(sorted(exts))
1101 fname = name.replace('-', '_')
1102 spics = pics + [i.upper() for i in pics]
1103 spics = '|'.join(sorted(spics))
1104 special_exts_template = '''\
1105 %s )
1106 _filedir %s
1107 return 0
1108 ;;
1109 '''
1110 extras = []
1111 for eopts, eexts in ((cover_opts, '${pics}'), (opf_opts, "'@(opf)'")):
1112 for opt in eopts:
1113 extras.append(special_exts_template % (opt, eexts))
1114 extras = '\n'.join(extras)
1115
1116 return (
1117 '_'
1118 + fname
1119 + '()'
1120 + '''
1121 {{
1122 local cur prev opts
1123 COMPREPLY=()
1124 cur="${{COMP_WORDS[COMP_CWORD]}}"
1125 prev="${{COMP_WORDS[COMP_CWORD-1]}}"
1126 opts="{opts}"
1127 pics="@({pics})"
1128
1129 case "${{prev}}" in
1130 {extras}
1131 esac
1132
1133 case "${{cur}}" in
1134 {extras}
1135 -* )
1136 COMPREPLY=( $(compgen -W "${{opts}}" -- ${{cur}}) )
1137 return 0
1138 ;;
1139 * )
1140 _filedir '@({exts})'
1141 return 0
1142 ;;
1143 esac
1144
1145 }}
1146 complete -o filenames -F _'''.format(**dict(pics=spics, opts=opts, extras=extras, exts=exts))
1147 + fname
1148 + ' '
1149 + name
1150 + '\n\n'
1151 ).encode('utf-8')
1152
1153
1154 VIEWER = '''\
1155 [Desktop Entry]
1156 Version=1.0
1157 Type=Application
1158 Name=LRF viewer
1159 GenericName=Viewer for LRF files
1160 Comment=Viewer for LRF files (SONY ebook format files)
1161 TryExec=lrfviewer
1162 Exec=lrfviewer %f
1163 Icon=calibre-viewer
1164 MimeType=application/x-sony-bbeb;
1165 Categories=Office;Viewer;
1166 Keywords=lrf;viewer;
•1167 X-AppStream-Ignore=true
1168 '''
1169
1170 EVIEWER = '''\
1171 [Desktop Entry]
1172 Version=1.0
1173 Type=Application
1174 Name=E-book viewer
1175 GenericName=Viewer for E-books
1176 Comment=Viewer for E-books in all the major formats
1177 TryExec=ebook-viewer
•1178 Exec=ebook-viewer %f
1179 Icon=calibre-viewer
1180 Categories=Office;Viewer;
1181 Keywords=epub;ebook;viewer;
1182 '''
1183
1184 ETWEAK = '''\
1185 [Desktop Entry]
1186 Version=1.0
1187 Type=Application
1188 Name=E-book editor
1189 GenericName=Editor for E-books
1190 Comment=Edit E-books in various formats
1191 TryExec=ebook-edit
•1192 Exec=ebook-edit %f
1193 Icon=calibre-ebook-edit
1194 Categories=Office;WordProcessor
1195 Keywords=epub;ebook;editor;
1196 '''
1197
1198 GUI = '''\
1199 [Desktop Entry]
1200 Version=1.0
1201 Type=Application
1202 Name=calibre
1203 GenericName=E-book library management
1204 Comment=E-book library management: Convert, view, share, catalogue all your e-books
1205 TryExec=calibre
•1206 Exec=calibre %U
1207 Icon=calibre-gui
1208 Categories=Office;
1209 X-GNOME-UsesNotifications=true
1210 Keywords=epub;ebook;manager;
1211 '''
1212
1213
1214 def get_appdata():
1215 def _(x):
1216 return x # Make sure the text below is not translated, but is marked for translation
1217
1218 return {
1219 'calibre-gui': {
1220 'name': 'calibre',
1221 'summary': _('The one stop solution to all your e-book needs'),
1222 'description': (
1223 _('calibre is the one stop solution to all your e-book needs.'),
1224 _(
1225 'You can use calibre to catalog your books, fetch metadata for them automatically, convert them from and to all the various e-book formats, send them to your e-book reader devices, read the books on your computer, edit the books in a dedicated e-book editor and even make them available over the network with the built-in Content server. You can also download news and periodicals in e-book format from over a thousand different news and magazine websites.' # noqa: E501
1226 ),
1227 ),
•1228 'provides': [
1229 {'modalias': 'usb:v2237p*d*ic08isc*ip*'},
1230 {'modalias': 'usb:v0525pA4A5d*ic08isc*ip*'},
1231 ],
1232 'screenshots': (
1233 (
1234 1408,
1235 792,
1236 'https://lh4.googleusercontent.com/-bNE1hc_3pIc/UvHLwKPGBPI/AAAAAAAAASA/8oavs_c6xoU/w1408-h792-no/main-default.png',
1237 ),
1238 (
1239 1408,
1240 792,
1241 'https://lh4.googleusercontent.com/-Zu2httSKABE/UvHMYK30JJI/AAAAAAAAATg/dQTQUjBvV5s/w1408-h792-no/main-grid.png',
1242 ),
1243 (
1244 1408,
1245 792,
1246 'https://lh3.googleusercontent.com/-_trYUjU_BaY/UvHMYSdKhlI/AAAAAAAAATc/auPA3gyXc6o/w1408-h792-no/main-flow.png',
1247 ),
1248 ),
1249 'desktop-id': 'calibre-gui.desktop',
•1250 'appstream-id': 'com.calibre_ebook.calibre',
1251 'include-releases': True,
1252 },
1253 'calibre-ebook-edit': {
1254 'name': 'calibre - E-book Editor',
1255 'summary': _('Edit the text and styles inside e-books'),
1256 'description': (
1257 _('The calibre E-book editor allows you to edit the text and styles inside the book with a live preview of your changes.'),
1258 _(
1259 'It can edit books in both the EPUB and AZW3 (Kindle) formats. It includes various useful tools for checking the book for errors, editing the Table of Contents, performing automated cleanups, etc.' # noqa: E501
1260 ),
1261 ),
1262 'screenshots': (
1263 (
1264 1408,
1265 792,
1266 'https://lh5.googleusercontent.com/-M2MAVc3A8e4/UvHMWqGRa8I/AAAAAAAAATA/cecQeWUYBVs/w1408-h792-no/edit-default.png',
1267 ),
1268 (
1269 1408,
1270 792,
1271 'https://lh4.googleusercontent.com/-WhoMxuRb34c/UvHMWqN8aGI/AAAAAAAAATI/8SDBYWXb7-8/w1408-h792-no/edit-check.png',
1272 ),
1273 (
1274 887,
1275 575,
1276 'https://lh6.googleusercontent.com/-KwaOwHabnBs/UvHMWidjyXI/AAAAAAAAAS8/H6xmCeLnSpk/w887-h575-no/edit-toc.png',
1277 ),
1278 ),
1279 'desktop-id': 'calibre-ebook-edit.desktop',
•1280 'appstream-id': 'com.calibre_ebook.calibre.ebook_edit',
1281 },
1282 'calibre-ebook-viewer': {
1283 'name': 'calibre - E-book Viewer',
1284 'summary': _('Read e-books in over a dozen different formats'),
1285 'description': (
1286 _('The calibre E-book viewer allows you to read e-books in over a dozen different formats.'),
1287 _('It has a full screen mode for distraction free reading and can display the text with multiple columns per screen.'),
1288 ),
•1289 'provides': [
1290 {'modalias': 'usb:v2237p*d*ic08isc*ip*'},
1291 {'modalias': 'usb:v0525pA4A5d*ic08isc*ip*'},
1292 ],
1293 'screenshots': (
1294 (
1295 1408,
1296 792,
1297 'https://lh5.googleusercontent.com/-dzSO82BPpaE/UvHMYY5SpNI/AAAAAAAAATk/I_kF9fYWrZM/w1408-h792-no/viewer-default.png',
1298 ),
1299 (
1300 1920,
1301 1080,
1302 'https://lh6.googleusercontent.com/-n32Ae5RytAk/UvHMY0QD94I/AAAAAAAAATs/Zw8Yz08HIKk/w1920-h1080-no/viewer-fs.png',
1303 ),
1304 ),
1305 'desktop-id': 'calibre-ebook-viewer.desktop',
•1306 'appstream-id': 'com.calibre_ebook.calibre.ebook_viewer',
1307 },
1308 }
1309
1310
1311 def changelog_bullet_to_text(bullet):
1312 # It would be great if we could use any fancier formatting here, but the
1313 # only allowed inline formatting within the AppData description bullet
1314 # points are emphasis (italics) and code (monospaced font)
1315 text = [bullet['title']]
1316 if 'author' in bullet:
1317 text.append(' by ')
1318 text.append(bullet['author'])
1319 if 'description' in bullet or 'tickets' in bullet:
1320 text.append(' (')
1321 if 'description' in bullet:
1322 text.append(bullet['description'])
1323 if 'tickets' in bullet:
1324 if 'description' in bullet:
1325 text.append(' – ')
1326 text.append('Closes tickets: ')
1327 text.append(', '.join(map(str, bullet['tickets'])))
1328 text.append(')')
1329 return ''.join(text)
1330
1331
1332 def make_appdata_releases():
1333 import json
1334
1335 from lxml.builder import E
1336
1337 changelog = json.loads(P('changelog.json', data=True))
1338
1339 releases = E.releases()
1340 for revision in changelog:
1341 # Formatting of release description tries to resemble that of
1342 # https://calibre-ebook.com/whats-new while taking into account the limits imposed by
1343 # https://www.freedesktop.org/software/appstream/docs/chap-Metadata.html#tag-description
1344 description = E.description()
1345 if 'new features' in revision:
1346 description.append(E.p('New features:'))
1347 description.append(E.ol(*(E.li(changelog_bullet_to_text(bullet)) for bullet in revision['new features'])))
1348 if 'bug fixes' in revision:
1349 description.append(E.p('Bug fixes:'))
1350 description.append(E.ol(*(E.li(changelog_bullet_to_text(bullet)) for bullet in revision['bug fixes'])))
1351 if 'new recipes' in revision:
1352 description.append(E.p('New news sources:'))
1353 description.append(E.ol(*(E.li(changelog_bullet_to_text(bullet)) for bullet in revision['new recipes'])))
1354 if 'improved recipes' in revision:
1355 description.append(E.p('Improved news sources:'))
1356 description.append(E.ol(*(E.li(name) for name in revision['improved recipes'])))
1357 releases.append(E.release(description, version=revision['version'], date=revision['date']))
1358 return releases
1359
1360
1361 def write_appdata(key, entry, base, translators):
1362 from lxml.builder import E
•1363 from lxml.etree import Element, tostring
1364
1365 fpath = os.path.join(base, f'{key}.metainfo.xml')
1366 screenshots = E.screenshots()
1367 for w, h, url in entry['screenshots']:
1368 s = E.screenshot(E.image(url, width=str(w), height=str(h)))
1369 screenshots.append(s)
1370 screenshots[0].set('type', 'default')
1371 description = E.description()
1372 for para in entry['description']:
1373 description.append(E.p(para))
1374 for lang, t in translators.items():
1375 tp = t.gettext(para)
1376 if tp != para:
1377 description.append(E.p(tp, **{'{http://www.w3.org/XML/1998/namespace}lang': lang}))
1378
1379 root = E.component(
•1380 E.id(entry['appstream-id']),
1381 E.name(entry['name']),
1382 E.metadata_license('CC0-1.0'),
1383 E.project_license('GPL-3.0'),
1384 E.developer(E.name('Kovid Goyal'), id='kovidgoyal.net'),
1385 E.summary(entry['summary']),
1386 E.content_rating(
1387 # Information Sharing: Using any online API, e.g. a user-counter
1388 # Details at https://calibre-ebook.com/dynamic/calibre-usage .
1389 E.content_attribute('mild', id='social-info'),
1390 # In-App Purchases: Users are encouraged to donate real money, e.g. using Patreon
1391 E.content_attribute('mild', id='money-purchasing'),
1392 type='oars-1.1',
1393 ),
1394 description,
1395 E.url('https://calibre-ebook.com/', type='homepage'),
1396 screenshots,
1397 E.launchable(entry['desktop-id'], type='desktop-id'),
1398 type='desktop-application',
1399 )
1400 for lang, t in translators.items():
1401 tp = t.gettext(entry['summary'])
1402 if tp != entry['summary']:
1403 root.append(E.summary(tp, **{'{http://www.w3.org/XML/1998/namespace}lang': lang}))
•1404 if 0 < len(entry.get('provides', [])):
1405 provides = E.provides()
1406 for p in entry['provides']:
1407 for tag in p.keys():
1408 provided = Element(tag)
1409 provided.text = p[tag]
1410 provides.append(provided)
1411 root.append(provides)
1412 if entry.get('include-releases', False):
1413 try:
1414 root.append(make_appdata_releases())
1415 except Exception:
1416 import traceback
1417
1418 traceback.print_exc()
1419 with open(fpath, 'wb') as f:
1420 f.write(tostring(root, encoding='utf-8', xml_declaration=True, pretty_print=True))
1421 return fpath
1422
1423
1424 def render_img(image, dest, width=128, height=128):
•1425 from PIL import Image
1426
•1427 img = Image.open(fp=I(image)).resize(size=(int(width), int(height)))
1428 img.save(fp=dest)
1429
1430
1431 def main():
1432 p = option_parser()
1433 opts, args = p.parse_args()
1434 PostInstall(opts)
1435 return 0
1436
1437
1438 def cli_index_strings():
1439 return (
1440 _('Command Line Interface'),
1441 _(
1442 'On macOS, the command line tools are inside the calibre bundle, for example,'
1443 ' if you installed calibre in :file:`/Applications` the command line tools'
1444 ' are in :file:`/Applications/calibre.app/Contents/MacOS/`. So, for example, to run :file:`ebook-convert`'
1445 ' you would use: :file:`/Applications/calibre.app/Contents/MacOS/ebook-convert`.'
1446 ),
1447 _('Documented commands'),
1448 _('Undocumented commands'),
1449 _('You can see usage for undocumented commands by executing them without arguments in a terminal.'),
1450 _('Change language'),
1451 _('Search'),
1452 )
1453
1454
1455 if __name__ == '__main__':
1456 sys.exit(main())