-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
linux.py
1339 lines (1190 loc) · 51.1 KB
/
linux.py
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
''' Post installation script for linux '''
import errno
import os
import stat
import sys
import textwrap
from functools import partial
from subprocess import check_call, check_output
from calibre import CurrentDir, __appname__, guess_type, prints
from calibre.constants import isbsd, islinux
from calibre.customize.ui import all_input_formats
from calibre.ptempfile import TemporaryDirectory
from calibre.utils.localization import _
from calibre.utils.resources import get_image_path as I
from calibre.utils.resources import get_path as P
from polyglot.builtins import iteritems
entry_points = {
'console_scripts': [
'ebook-device = calibre.devices.cli:main',
'ebook-meta = calibre.ebooks.metadata.cli:main',
'ebook-convert = calibre.ebooks.conversion.cli:main',
'ebook-polish = calibre.ebooks.oeb.polish.main:main',
'markdown-calibre = markdown.__main__:run',
'web2disk = calibre.web.fetch.simple:main',
'calibre-server = calibre.srv.standalone:main',
'lrf2lrs = calibre.ebooks.lrf.lrfparser:main',
'lrs2lrf = calibre.ebooks.lrf.lrs.convert_from:main',
'calibre-debug = calibre.debug:main',
'calibredb = calibre.db.cli.main:main',
'calibre-parallel = calibre.utils.ipc.worker:main',
'calibre-customize = calibre.customize.ui:main',
'calibre-complete = calibre.utils.complete:main',
'fetch-ebook-metadata = calibre.ebooks.metadata.sources.cli:main',
'calibre-smtp = calibre.utils.smtp:main',
],
'gui_scripts' : [
__appname__+' = calibre.gui_launch:calibre',
'lrfviewer = calibre.gui2.lrf_renderer.main:main',
'ebook-viewer = calibre.gui_launch:ebook_viewer',
'ebook-edit = calibre.gui_launch:ebook_edit',
],
}
def polyglot_write(stream):
stream_write = stream.write
def write(x):
if not isinstance(x, bytes):
x = x.encode('utf-8')
return stream_write(x)
return write
class PreserveMIMEDefaults: # {{{
def __init__(self):
self.initial_values = {}
def __enter__(self):
def_data_dirs = '/usr/local/share:/usr/share'
paths = os.environ.get('XDG_DATA_DIRS', def_data_dirs)
paths = paths.split(':')
paths.append(os.environ.get('XDG_DATA_HOME', os.path.expanduser(
'~/.local/share')))
paths = list(filter(os.path.isdir, paths))
if not paths:
# Env var had garbage in it, ignore it
paths = def_data_dirs.split(':')
paths = list(filter(os.path.isdir, paths))
self.paths = {os.path.join(x, 'applications/defaults.list') for x in
paths}
self.initial_values = {}
for x in self.paths:
try:
with open(x, 'rb') as f:
self.initial_values[x] = f.read()
except:
self.initial_values[x] = None
def __exit__(self, *args):
for path, val in iteritems(self.initial_values):
if val is None:
try:
os.remove(path)
except:
pass
elif os.path.exists(path):
try:
with open(path, 'r+b') as f:
if f.read() != val:
f.seek(0)
f.truncate()
f.write(val)
except OSError as e:
if e.errno != errno.EACCES:
raise
# }}}
# Uninstall script {{{
UNINSTALL = '''\
#!/bin/sh
# Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
search_for_python() {{
# We have to search for python as Ubuntu, in its infinite wisdom decided
# to release 18.04 with no python symlink, making it impossible to run polyglot
# python scripts.
# We cannot use command -v as it is not implemented in the posh shell shipped with
# Ubuntu/Debian. Similarly, there is no guarantee that which is installed.
# Shell scripting is a horrible joke, thank heavens for python.
local IFS=:
if [ $ZSH_VERSION ]; then
# zsh does not split by default
setopt sh_word_split
fi
local candidate_path
local candidate_python
local pythons=python3:python2
# disable pathname expansion (globbing)
set -f
for candidate_path in $PATH
do
if [ ! -z $candidate_path ]
then
for candidate_python in $pythons
do
if [ ! -z "$candidate_path" ]
then
if [ -x "$candidate_path/$candidate_python" ]
then
printf "$candidate_path/$candidate_python"
return
fi
fi
done
fi
done
set +f
printf "python"
}}
PYTHON=$(search_for_python)
echo Using python executable: $PYTHON
$PYTHON -c "import sys; exec(sys.stdin.read());" "$0" <<'CALIBRE_LINUX_INSTALLER_HEREDOC'
#!{python}
# vim:fileencoding=UTF-8
from __future__ import print_function, unicode_literals
euid = {euid}
import os, subprocess, shutil, tempfile, sys
try:
raw_input
except NameError:
raw_input = input
sys.stdin = open('/dev/tty')
if os.geteuid() != euid:
print('The installer was last run as user id:', euid, 'To remove all files you must run the uninstaller as the same user')
if raw_input('Proceed anyway? [y/n]:').lower() != 'y':
raise SystemExit(1)
frozen_path = {frozen_path!r}
if not frozen_path or not os.path.exists(os.path.join(frozen_path, 'resources', 'calibre-mimetypes.xml')):
frozen_path = None
dummy_mime_path = tempfile.mkdtemp(prefix='mime-hack.')
for f in {mime_resources!r}:
# dummyfile
f = os.path.basename(f)
file = os.path.join(dummy_mime_path, f)
open(file, 'w').close()
cmd = ['xdg-mime', 'uninstall', file]
print('Removing mime resource:', f)
ret = subprocess.call(cmd, shell=False)
if ret != 0:
print('WARNING: Failed to remove mime resource', f)
for x in tuple({manifest!r}) + tuple({appdata_resources!r}) + (sys.argv[-1], frozen_path, dummy_mime_path):
if not x or not os.path.exists(x):
continue
print('Removing', x)
try:
if os.path.isdir(x):
shutil.rmtree(x)
else:
os.unlink(x)
except Exception as e:
print('Failed to delete', x)
print('\t', e)
icr = {icon_resources!r}
mimetype_icons = []
def remove_icon(context, name, size, update=False):
cmd = ['xdg-icon-resource', 'uninstall', '--context', context, '--size', size, name]
if not update:
cmd.insert(2, '--noupdate')
print('Removing icon:', name, 'from context:', context, 'at size:', size)
ret = subprocess.call(cmd, shell=False)
if ret != 0:
print('WARNING: Failed to remove icon', name)
for i, (context, name, size) in enumerate(icr):
if context == 'mimetypes':
mimetype_icons.append((name, size))
continue
remove_icon(context, name, size, update=i == len(icr) - 1)
mr = {menu_resources!r}
for f in mr:
cmd = ['xdg-desktop-menu', 'uninstall', f]
print('Removing desktop file:', f)
ret = subprocess.call(cmd, shell=False)
if ret != 0:
print('WARNING: Failed to remove menu item', f)
print()
if mimetype_icons and raw_input('Remove the e-book format icons? [y/n]:').lower() in ['', 'y']:
for i, (name, size) in enumerate(mimetype_icons):
remove_icon('mimetypes', name, size, update=i == len(mimetype_icons) - 1)
CALIBRE_LINUX_INSTALLER_HEREDOC
'''
# }}}
# Completion {{{
class ZshCompleter: # {{{
def __init__(self, opts):
self.opts = opts
self.dest = None
base = os.path.dirname(self.opts.staging_sharedir)
self.detect_zsh(base)
if not self.dest and base == '/usr/share':
# Ubuntu puts site-functions in /usr/local/share
self.detect_zsh('/usr/local/share')
self.commands = {}
def detect_zsh(self, base):
for x in ('vendor-completions', 'vendor-functions', 'site-functions'):
c = os.path.join(base, 'zsh', x)
if os.path.isdir(c) and os.access(c, os.W_OK):
self.dest = os.path.join(c, '_calibre')
break
def get_options(self, parser, cover_opts=('--cover',), opf_opts=('--opf',),
file_map={}):
if hasattr(parser, 'option_list'):
options = parser.option_list
for group in parser.option_groups:
options += group.option_list
else:
options = parser
for opt in options:
lo, so = opt._long_opts, opt._short_opts
if opt.takes_value():
lo = [x+'=' for x in lo]
so = [x+'+' for x in so]
ostrings = lo + so
ostrings = '{%s}'%','.join(ostrings) if len(ostrings) > 1 else ostrings[0]
exclude = ''
if opt.dest is None:
exclude = "'(- *)'"
h = opt.help or ''
h = h.replace('"', "'").replace('[', '(').replace(
']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'")
h = h.replace('%default', str(opt.default))
arg = ''
if opt.takes_value():
arg = ':"%s":'%h
if opt.dest in {'extract_to', 'debug_pipeline', 'to_dir', 'outbox', 'with_library', 'library_path'}:
arg += "'_path_files -/'"
elif opt.choices:
arg += "(%s)"%'|'.join(opt.choices)
elif set(file_map).intersection(set(opt._long_opts)):
k = set(file_map).intersection(set(opt._long_opts))
exts = file_map[tuple(k)[0]]
if exts:
arg += "'_files -g \"%s\"'"%(' '.join('*.%s'%x for x in
tuple(exts) + tuple(x.upper() for x in exts)))
else:
arg += "_files"
elif (opt.dest in {'pidfile', 'attachment'}):
arg += "_files"
elif set(opf_opts).intersection(set(opt._long_opts)):
arg += "'_files -g \"*.opf\"'"
elif set(cover_opts).intersection(set(opt._long_opts)):
arg += "'_files -g \"%s\"'"%(' '.join('*.%s'%x for x in
tuple(pics) + tuple(x.upper() for x in pics)))
help_txt = '"[%s]"'%h
yield '%s%s%s%s '%(exclude, ostrings, help_txt, arg)
def opts_and_exts(self, name, op, exts, cover_opts=('--cover',),
opf_opts=('--opf',), file_map={}):
if not self.dest:
return
exts = sorted({x.lower() for x in exts})
extra = ('''"*:filename:_files -g '(#i)*.(%s)'" ''' % '|'.join(exts),)
opts = '\\\n '.join(tuple(self.get_options(
op(), cover_opts=cover_opts, opf_opts=opf_opts, file_map=file_map)) + extra)
txt = '_arguments -s \\\n ' + opts
self.commands[name] = txt
def opts_and_words(self, name, op, words, takes_files=False):
if not self.dest:
return
extra = ("'*:filename:_files' ",) if takes_files else ()
opts = '\\\n '.join(tuple(self.get_options(op())) + extra)
txt = '_arguments -s \\\n ' + opts
self.commands[name] = txt
def do_ebook_convert(self, f):
from calibre.customize.ui import available_output_formats
from calibre.ebooks.conversion.cli import create_option_parser, group_titles
from calibre.ebooks.conversion.plumber import supported_input_formats
from calibre.utils.logging import DevNull
from calibre.web.feeds.recipes.collection import get_builtin_recipe_titles
input_fmts = set(supported_input_formats())
output_fmts = set(available_output_formats())
iexts = {x.upper() for x in input_fmts}.union(input_fmts)
oexts = {x.upper() for x in output_fmts}.union(output_fmts)
w = polyglot_write(f)
# Arg 1
w('\n_ebc_input_args() {')
w('\n local extras; extras=(')
w('\n {-h,--help}":Show Help"')
w('\n "--version:Show program version"')
w('\n "--list-recipes:List builtin recipe names"')
for recipe in sorted(set(get_builtin_recipe_titles())):
recipe = recipe.replace(':', '\\:').replace('"', '\\"')
w('\n "%s.recipe"'%(recipe))
w('\n ); _describe -t recipes "ebook-convert builtin recipes" extras')
w('\n _files -g "%s"'%' '.join('*.%s'%x for x in iexts))
w('\n}\n')
# Arg 2
w('\n_ebc_output_args() {')
w('\n local extras; extras=(')
for x in output_fmts:
w('\n ".{0}:Convert to a .{0} file with the same name as the input file"'.format(x))
w('\n ); _describe -t output "ebook-convert output" extras')
w('\n _files -g "%s"'%' '.join('*.%s'%x for x in oexts))
w('\n _path_files -/')
w('\n}\n')
log = DevNull()
def get_parser(input_fmt='epub', output_fmt=None):
of = ('dummy2.'+output_fmt) if output_fmt else 'dummy'
return create_option_parser(('ec', 'dummy1.'+input_fmt, of, '-h'), log)[0]
# Common options
input_group, output_group = group_titles()
p = get_parser()
opts = p.option_list
for group in p.option_groups:
if group.title not in {input_group, output_group}:
opts += group.option_list
opts.append(p.get_option('--pretty-print'))
opts.append(p.get_option('--input-encoding'))
opts = '\\\n '.join(tuple(
self.get_options(opts, file_map={'--search-replace':()})))
w('\n_ebc_common_opts() {')
w('\n _arguments -s \\\n ' + opts)
w('\n}\n')
# Input/Output format options
for fmts, group_title, func in (
(input_fmts, input_group, '_ebc_input_opts_%s'),
(output_fmts, output_group, '_ebc_output_opts_%s'),
):
for fmt in fmts:
is_input = group_title == input_group
if is_input and fmt in {'rar', 'zip', 'oebzip'}:
continue
p = (get_parser(input_fmt=fmt) if is_input
else get_parser(output_fmt=fmt))
opts = None
for group in p.option_groups:
if group.title == group_title:
opts = [o for o in group.option_list if
'--pretty-print' not in o._long_opts and
'--input-encoding' not in o._long_opts]
if not opts:
continue
opts = '\\\n '.join(tuple(sorted(self.get_options(opts))))
w('\n%s() {'%(func%fmt))
w('\n _arguments -s \\\n ' + opts)
w('\n}\n')
w('\n_ebook_convert() {')
w('\n local iarg oarg context state_descr state line\n typeset -A opt_args\n local ret=1')
w("\n _arguments '1: :_ebc_input_args' '*::ebook-convert output:->args' && ret=0")
w("\n case $state in \n (args)")
w('\n iarg=${line[1]##*.}; ')
w("\n _arguments '1: :_ebc_output_args' '*::ebook-convert options:->args' && ret=0")
w("\n case $state in \n (args)")
w('\n oarg=${line[1]##*.}')
w('\n iarg="_ebc_input_opts_${(L)iarg}"; oarg="_ebc_output_opts_${(L)oarg}"')
w('\n _call_function - $iarg; _call_function - $oarg; _ebc_common_opts; ret=0')
w('\n ;;\n esac')
w("\n ;;\n esac\n return ret")
w('\n}\n')
def do_ebook_edit(self, f):
from calibre.ebooks.oeb.polish.import_book import IMPORTABLE
from calibre.ebooks.oeb.polish.main import SUPPORTED
from calibre.gui2.tweak_book.main import option_parser
tweakable_fmts = SUPPORTED | IMPORTABLE
parser = option_parser()
opt_lines = []
for opt in parser.option_list:
lo, so = opt._long_opts, opt._short_opts
if opt.takes_value():
lo = [x+'=' for x in lo]
so = [x+'+' for x in so]
ostrings = lo + so
ostrings = '{%s}'%','.join(ostrings) if len(ostrings) > 1 else '"%s"'%ostrings[0]
h = opt.help or ''
h = h.replace('"', "'").replace('[', '(').replace(
']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'")
h = h.replace('%default', str(opt.default))
help_txt = '"[%s]"'%h
opt_lines.append(ostrings + help_txt + ' \\')
opt_lines = ('\n' + (' ' * 8)).join(opt_lines)
polyglot_write(f)('''
_ebook_edit() {{
local curcontext="$curcontext" state line ebookfile expl
typeset -A opt_args
_arguments -C -s \\
{}
"1:ebook file:_files -g '(#i)*.({})'" \\
'*:file in ebook:->files' && return 0
case $state in
files)
ebookfile=${{~${{(Q)line[1]}}}}
if [[ -f "$ebookfile" && "$ebookfile" =~ '\\.[eE][pP][uU][bB]$' ]]; then
_zip_cache_name="$ebookfile"
_zip_cache_list=( ${{(f)"$(zipinfo -1 $_zip_cache_name 2>/dev/null)"}} )
else
return 1
fi
_wanted files expl 'file from ebook' \\
_multi_parts / _zip_cache_list && return 0
;;
esac
return 1
}}
'''.format(opt_lines, '|'.join(tweakable_fmts)) + '\n\n')
def do_calibredb(self, f):
from calibre.customize.ui import available_catalog_formats
from calibre.db.cli.main import COMMANDS, option_parser_for
parsers, descs = {}, {}
for command in COMMANDS:
p = option_parser_for(command)()
parsers[command] = p
lines = [x.strip().partition('.')[0] for x in p.usage.splitlines() if x.strip() and
not x.strip().startswith('%prog')]
descs[command] = lines[0]
w = polyglot_write(f)
w('\n_calibredb_cmds() {\n local commands; commands=(\n')
w(' {-h,--help}":Show help"\n')
w(' "--version:Show version"\n')
for command, desc in iteritems(descs):
w(' "%s:%s"\n'%(
command, desc.replace(':', '\\:').replace('"', '\'')))
w(' )\n _describe -t commands "calibredb command" commands \n}\n')
subcommands = []
for command, parser in iteritems(parsers):
exts = []
if command == 'catalog':
exts = [x.lower() for x in available_catalog_formats()]
elif command == 'set_metadata':
exts = ['opf']
exts = set(exts).union(x.upper() for x in exts)
pats = ('*.%s'%x for x in exts)
extra = ("'*:filename:_files -g \"%s\"' "%' '.join(pats),) if exts else ()
if command in {'add', 'add_format'}:
extra = ("'*:filename:_files' ",)
opts = '\\\n '.join(tuple(self.get_options(
parser)) + extra)
txt = ' _arguments -s \\\n ' + opts
subcommands.append('(%s)'%command)
subcommands.append(txt)
subcommands.append(';;')
w('\n_calibredb() {')
w(
r'''
local state line state_descr context
typeset -A opt_args
local ret=1
_arguments \
'1: :_calibredb_cmds' \
'*::calibredb subcommand options:->args' \
&& ret=0
case $state in
(args)
case $line[1] in
(-h|--help|--version)
_message 'no more arguments' && ret=0
;;
%s
esac
;;
esac
return ret
'''%'\n '.join(subcommands))
w('\n}\n\n')
def write(self):
if self.dest:
for c in ('calibredb', 'ebook-convert', 'ebook-edit'):
self.commands[c] = ' _%s "$@"' % c.replace('-', '_')
with open(self.dest, 'wb') as f:
w = polyglot_write(f)
w('#compdef ' + ' '.join(self.commands)+'\n')
self.do_ebook_convert(f)
self.do_calibredb(f)
self.do_ebook_edit(f)
w('case $service in\n')
for c, txt in iteritems(self.commands):
w('%s)\n%s\n;;\n'%(c, txt))
w('esac\n')
# }}}
def get_bash_completion_path(root, share, info):
if root == '/usr':
# Try to get the system bash completion dir since we are installing to
# /usr
try:
path = check_output('pkg-config --variable=completionsdir bash-completion'.split()).decode('utf-8').strip().partition(os.pathsep)[0]
except Exception:
info('Failed to find directory to install bash completions, using default.')
path = '/usr/share/bash-completion/completions'
if path and os.path.exists(path) and os.path.isdir(path):
return path
else:
# Use the default bash-completion dir under staging_share
return os.path.join(share, 'bash-completion', 'completions')
def write_completion(self, bash_comp_dest, zsh):
from calibre.customize.ui import available_input_formats
from calibre.debug import option_parser as debug_op
from calibre.ebooks import BOOK_EXTENSIONS
from calibre.ebooks.lrf.lrfparser import option_parser as lrf2lrsop
from calibre.ebooks.metadata.cli import filetypes as meta_filetypes
from calibre.ebooks.metadata.cli import option_parser as metaop
from calibre.ebooks.metadata.sources.cli import option_parser as fem_op
from calibre.ebooks.oeb.polish.import_book import IMPORTABLE
from calibre.ebooks.oeb.polish.main import SUPPORTED
from calibre.ebooks.oeb.polish.main import option_parser as polish_op
from calibre.gui2.lrf_renderer.main import option_parser as lrfviewerop
from calibre.gui2.main import option_parser as guiop
from calibre.gui2.tweak_book.main import option_parser as tweak_op
from calibre.gui2.viewer.main import option_parser as viewer_op
from calibre.srv.standalone import create_option_parser as serv_op
from calibre.utils.smtp import option_parser as smtp_op
input_formats = sorted(all_input_formats())
tweak_formats = sorted(x.lower() for x in SUPPORTED|IMPORTABLE)
if bash_comp_dest and not os.path.exists(bash_comp_dest):
os.makedirs(bash_comp_dest)
complete = 'calibre-complete'
if getattr(sys, 'frozen_path', None):
complete = os.path.join(getattr(sys, 'frozen_path'), complete)
def o_and_e(name, *args, **kwargs):
bash_compfile = os.path.join(bash_comp_dest, name)
with open(bash_compfile, 'wb') as f:
f.write(opts_and_exts(name, *args, **kwargs))
self.manifest.append(bash_compfile)
zsh.opts_and_exts(name, *args, **kwargs)
def o_and_w(name, *args, **kwargs):
bash_compfile = os.path.join(bash_comp_dest, name)
with open(bash_compfile, 'wb') as f:
f.write(opts_and_words(name, *args, **kwargs))
self.manifest.append(bash_compfile)
zsh.opts_and_words(name, *args, **kwargs)
o_and_e('calibre', guiop, BOOK_EXTENSIONS)
o_and_e('lrf2lrs', lrf2lrsop, ['lrf'], file_map={'--output':['lrs']})
o_and_e('ebook-meta', metaop,
list(meta_filetypes()), cover_opts=['--cover', '-c'],
opf_opts=['--to-opf', '--from-opf'])
o_and_e('ebook-polish', polish_op,
[x.lower() for x in SUPPORTED], cover_opts=['--cover', '-c'],
opf_opts=['--opf', '-o'])
o_and_e('lrfviewer', lrfviewerop, ['lrf'])
o_and_e('ebook-viewer', viewer_op, input_formats)
o_and_e('ebook-edit', tweak_op, tweak_formats)
o_and_w('fetch-ebook-metadata', fem_op, [])
o_and_w('calibre-smtp', smtp_op, [])
o_and_w('calibre-server', serv_op, [])
o_and_e('calibre-debug', debug_op, ['py', 'recipe', 'epub', 'mobi', 'azw', 'azw3', 'docx'], file_map={
'--tweak-book':['epub', 'azw3', 'mobi'],
'--subset-font':['ttf', 'otf'],
'--exec-file':['py', 'recipe'],
'--add-simple-plugin':['py'],
'--inspect-mobi':['mobi', 'azw', 'azw3'],
'--viewer':sorted(available_input_formats()),
})
with open(os.path.join(bash_comp_dest, 'ebook-device'), 'wb') as f:
f.write(textwrap.dedent('''\
_ebook_device_ls()
{
local pattern search listing prefix
pattern="$1"
search="$1"
if [[ -n "{$pattern}" ]]; then
if [[ "${pattern:(-1)}" == "/" ]]; then
pattern=""
else
pattern="$(basename ${pattern} 2> /dev/null)"
search="$(dirname ${search} 2> /dev/null)"
fi
fi
if [[ "x${search}" == "x" || "x${search}" == "x." ]]; then
search="/"
fi
listing="$(ebook-device ls ${search} 2>/dev/null)"
prefix="${search}"
if [[ "x${prefix:(-1)}" != "x/" ]]; then
prefix="${prefix}/"
fi
echo $(compgen -P "${prefix}" -W "${listing}" "${pattern}")
}
_ebook_device()
{
local cur prev
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
COMPREPLY=()
case "${prev}" in
ls|rm|mkdir|touch|cat )
COMPREPLY=( $(_ebook_device_ls "${cur}") )
return 0
;;
cp )
if [[ ${cur} == dev:* ]]; then
COMPREPLY=( $(_ebook_device_ls "${cur:7}") )
return 0
else
_filedir
return 0
fi
;;
dev )
COMPREPLY=( $(compgen -W "cp ls rm mkdir touch cat info books df" "${cur}") )
return 0
;;
* )
if [[ ${cur} == dev:* ]]; then
COMPREPLY=( $(_ebook_device_ls "${cur:7}") )
return 0
else
if [[ ${prev} == dev:* ]]; then
_filedir
return 0
else
COMPREPLY=( $(compgen -W "dev:" "${cur}") )
return 0
fi
return 0
fi
;;
esac
}
complete -o nospace -F _ebook_device ebook-device''').encode('utf-8'))
self.manifest.append(os.path.join(bash_comp_dest, 'ebook-device'))
with open(os.path.join(bash_comp_dest, 'ebook-convert'), 'wb') as f:
f.write(('complete -o nospace -C %s ebook-convert'%complete).encode('utf-8'))
self.manifest.append(os.path.join(bash_comp_dest, 'ebook-convert'))
zsh.write()
# }}}
class PostInstall:
def task_failed(self, msg):
self.warn(msg, 'with error:')
import traceback
tb = '\n\t'.join(traceback.format_exc().splitlines())
self.info('\t'+tb)
print()
def warning(self, *args, **kwargs):
print('\n'+'_'*20, 'WARNING','_'*20)
prints(*args, **kwargs)
print('_'*50)
print('\n')
self.warnings.append((args, kwargs))
sys.stdout.flush()
def __init__(self, opts, info=prints, warn=None, manifest=None):
self.opts = opts
self.info = info
self.warn = warn
self.warnings = []
if self.warn is None:
self.warn = self.warning
if not self.opts.staging_bindir:
self.opts.staging_bindir = os.path.join(self.opts.staging_root,
'bin')
if not self.opts.staging_sharedir:
self.opts.staging_sharedir = os.path.join(self.opts.staging_root,
'share', 'calibre')
self.opts.staging_etc = '/etc' if self.opts.staging_root == '/usr' else \
os.path.join(self.opts.staging_root, 'etc')
prefix = getattr(self.opts, 'prefix', None)
if prefix and prefix != self.opts.staging_root:
self.opts.staged_install = True
os.environ['XDG_DATA_DIRS'] = os.path.join(self.opts.staging_root, 'share')
os.environ['XDG_UTILS_INSTALL_MODE'] = 'system'
from calibre.utils.serialize import msgpack_loads
scripts = msgpack_loads(P('scripts.calibre_msgpack', data=True))
self.manifest = manifest or []
if getattr(sys, 'frozen_path', False):
if os.access(self.opts.staging_bindir, os.W_OK):
self.info('Creating symlinks...')
for exe in scripts:
dest = os.path.join(self.opts.staging_bindir, exe)
if os.path.lexists(dest):
os.unlink(dest)
tgt = os.path.join(getattr(sys, 'frozen_path'), exe)
self.info('\tSymlinking %s to %s'%(tgt, dest))
os.symlink(tgt, dest)
self.manifest.append(dest)
else:
self.warning(textwrap.fill(
'No permission to write to %s, not creating program launch symlinks,'
' you should ensure that %s is in your PATH or create the symlinks yourself' % (
self.opts.staging_bindir, getattr(sys, 'frozen_path', 'the calibre installation directory'))))
self.icon_resources = []
self.menu_resources = []
self.mime_resources = []
self.appdata_resources = []
if islinux or isbsd:
self.setup_completion()
if islinux or isbsd:
self.setup_desktop_integration()
if not getattr(self.opts, 'staged_install', False):
self.create_uninstaller()
from calibre.utils.config import config_dir
if os.path.exists(config_dir):
os.chdir(config_dir)
if islinux or isbsd:
for f in os.listdir('.'):
if os.stat(f).st_uid == 0:
import shutil
shutil.rmtree(f) if os.path.isdir(f) else os.unlink(f)
if os.stat(config_dir).st_uid == 0:
os.rmdir(config_dir)
if warn is None and self.warnings:
self.info('\n\nThere were %d warnings\n'%len(self.warnings))
for args, kwargs in self.warnings:
self.info('*', *args, **kwargs)
print()
def create_uninstaller(self):
base = self.opts.staging_bindir
if not os.access(base, os.W_OK) and getattr(sys, 'frozen_path', False):
base = sys.frozen_path
dest = os.path.join(base, 'calibre-uninstall')
self.info('Creating un-installer:', dest)
raw = UNINSTALL.format(
python='/usr/bin/python', euid=os.geteuid(),
manifest=self.manifest, icon_resources=self.icon_resources,
mime_resources=self.mime_resources, menu_resources=self.menu_resources,
appdata_resources=self.appdata_resources, frozen_path=getattr(sys, 'frozen_path', None))
try:
with open(dest, 'wb') as f:
f.write(raw.encode('utf-8'))
os.chmod(dest, stat.S_IRWXU|stat.S_IRGRP|stat.S_IROTH)
if os.geteuid() == 0:
os.chown(dest, 0, 0)
except:
if self.opts.fatal_errors:
raise
self.task_failed('Creating uninstaller failed')
def setup_completion(self): # {{{
try:
self.info('Setting up command-line completion...')
zsh = ZshCompleter(self.opts)
if zsh.dest:
self.info('Installing zsh completion to:', zsh.dest)
self.manifest.append(zsh.dest)
bash_comp_dest = get_bash_completion_path(self.opts.staging_root, os.path.dirname(self.opts.staging_sharedir), self.info)
if bash_comp_dest is not None:
self.info('Installing bash completion to:', bash_comp_dest+os.sep)
write_completion(self, bash_comp_dest, zsh)
except TypeError as err:
if 'resolve_entities' in str(err):
print('You need python-lxml >= 2.0.5 for calibre')
sys.exit(1)
raise
except OSError as e:
if e.errno == errno.EACCES:
self.warning('Failed to setup completion, permission denied')
if self.opts.fatal_errors:
raise
self.task_failed('Setting up completion failed')
except:
if self.opts.fatal_errors:
raise
self.task_failed('Setting up completion failed')
# }}}
def setup_desktop_integration(self): # {{{
try:
self.info('Setting up desktop integration...')
self.do_setup_desktop_integration()
except Exception:
if self.opts.fatal_errors:
raise
self.task_failed('Setting up desktop integration failed')
def do_setup_desktop_integration(self):
env = os.environ.copy()
cc = check_call
if getattr(sys, 'frozen_path', False) and 'LD_LIBRARY_PATH' in env:
paths = env.get('LD_LIBRARY_PATH', '').split(os.pathsep)
paths = [x for x in paths if x]
npaths = [x for x in paths if x != sys.frozen_path+'/lib']
env['LD_LIBRARY_PATH'] = os.pathsep.join(npaths)
cc = partial(check_call, env=env)
if getattr(self.opts, 'staged_install', False):
for d in {'applications', 'desktop-directories', 'icons/hicolor', 'mime/packages'}:
os.makedirs(os.path.join(self.opts.staging_root, 'share', d), exist_ok=True)
with TemporaryDirectory() as tdir, CurrentDir(tdir):
with PreserveMIMEDefaults():
self.install_xdg_junk(cc, env)
def install_xdg_junk(self, cc, env):
def install_single_icon(iconsrc, basename, size, context, is_last_icon=False):
filename = f'{basename}-{size}.png'
render_img(iconsrc, filename, width=int(size), height=int(size))
cmd = ['xdg-icon-resource', 'install', '--noupdate', '--context', context, '--size', str(size), filename, basename]
if is_last_icon:
del cmd[2]
cc(cmd)
self.icon_resources.append((context, basename, str(size)))
def install_icons(iconsrc, basename, context, is_last_icon=False):
sizes = (16, 32, 48, 64, 128, 256)
for size in sizes:
install_single_icon(iconsrc, basename, size, context, is_last_icon and size is sizes[-1])
icons = [x.strip() for x in '''\
mimetypes/lrf.png application-lrf mimetypes
mimetypes/lrf.png text-lrs mimetypes
mimetypes/mobi.png application-x-mobipocket-ebook mimetypes
mimetypes/tpz.png application-x-topaz-ebook mimetypes
mimetypes/azw2.png application-x-kindle-application mimetypes
mimetypes/azw3.png application-x-mobi8-ebook mimetypes
lt.png calibre-gui apps
viewer.png calibre-viewer apps
tweak.png calibre-ebook-edit apps
'''.splitlines() if x.strip()]
for line in icons:
iconsrc, basename, context = line.split()
install_icons(iconsrc, basename, context, is_last_icon=line is icons[-1])
mimetypes = set()
for x in all_input_formats():
mt = guess_type('dummy.'+x)[0]
if mt and 'chemical' not in mt and 'ctc-posml' not in mt:
mimetypes.add(mt)
mimetypes.discard('application/octet-stream')
def write_mimetypes(f, extra=''):
line = 'MimeType={};'.format(';'.join(mimetypes))
if extra:
line += extra + ';'
f.write(line.encode('utf-8') + b'\n')
from calibre.ebooks.oeb.polish.import_book import IMPORTABLE
from calibre.ebooks.oeb.polish.main import SUPPORTED
with open('calibre-lrfviewer.desktop', 'wb') as f:
f.write(VIEWER.encode('utf-8'))
with open('calibre-ebook-viewer.desktop', 'wb') as f:
f.write(EVIEWER.encode('utf-8'))
write_mimetypes(f)
with open('calibre-ebook-edit.desktop', 'wb') as f:
f.write(ETWEAK.encode('utf-8'))
mt = {guess_type('a.' + x.lower())[0] for x in (SUPPORTED|IMPORTABLE)} - {None, 'application/octet-stream'}
f.write(('MimeType=%s;\n'%';'.join(mt)).encode('utf-8'))
with open('calibre-gui.desktop', 'wb') as f:
f.write(GUI.encode('utf-8'))
write_mimetypes(f, 'x-scheme-handler/calibre')
des = ('calibre-gui.desktop', 'calibre-lrfviewer.desktop',
'calibre-ebook-viewer.desktop', 'calibre-ebook-edit.desktop')
appdata = os.path.join(os.path.dirname(self.opts.staging_sharedir), 'metainfo')
translators = None
if not os.path.exists(appdata):
try:
os.mkdir(appdata)
except:
self.warning('Failed to create %s not installing appdata files' % appdata)
if os.path.exists(appdata) and not os.access(appdata, os.W_OK):
self.warning('Do not have write permissions for %s not installing appdata files' % appdata)
else:
from calibre.utils.localization import get_all_translators
translators = dict(get_all_translators())
APPDATA = get_appdata()
for x in des:
cmd = ['xdg-desktop-menu', 'install', '--noupdate', './'+x]
cc(' '.join(cmd), shell=True)
self.menu_resources.append(x)
ak = x.partition('.')[0]
if ak in APPDATA and translators is not None and os.access(appdata, os.W_OK):
self.appdata_resources.append(write_appdata(ak, APPDATA[ak], appdata, translators))
MIME_BASE = 'calibre-mimetypes.xml'
MIME = P(MIME_BASE)
self.mime_resources.append(MIME_BASE)
if not getattr(self.opts, 'staged_install', False):
cc(['xdg-mime', 'install', MIME])
cc(['xdg-desktop-menu', 'forceupdate'])
else:
from shutil import copyfile
copyfile(MIME, os.path.join(env['XDG_DATA_DIRS'], 'mime', 'packages', MIME_BASE))
# }}}
def option_parser():
from calibre.utils.config import OptionParser
parser = OptionParser()
parser.add_option('--make-errors-fatal', action='store_true', default=False,
dest='fatal_errors', help='If set die on errors.')
parser.add_option('--root', dest='staging_root', default='/usr',
help='Prefix under which to install files')
parser.add_option('--bindir', default=None, dest='staging_bindir',
help='Location where calibre launcher scripts were installed. Typically /usr/bin')
parser.add_option('--sharedir', default=None, dest='staging_sharedir',
help='Location where calibre resources were installed, typically /usr/share/calibre')
return parser
def options(option_parser):
parser = option_parser()
options = parser.option_list
for group in parser.option_groups:
options += group.option_list
opts = []
for opt in options:
opts.extend(opt._short_opts)
opts.extend(opt._long_opts)