Debian Codegraph @

src/calibre/gui2/add.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2014, Kovid Goyal <kovid at kovidgoyal.net>
3
4 import os
5 import shutil
6 import sys
7 import tempfile
8 import time
9 import traceback
10 import weakref
11 from collections import OrderedDict
12 from io import BytesIO
13 from queue import Empty
14 from threading import Thread
15
16 from qt.core import QObject, Qt, pyqtSignal
17
18 from calibre import as_unicode, prints
19 from calibre.constants import DEBUG, filesystem_encoding, ismacos, iswindows
20 from calibre.customize.ui import run_plugins_on_postadd, run_plugins_on_postimport
21 from calibre.db.adding import compile_rule, find_books_in_directory
22 from calibre.db.utils import find_identical_books
23 from calibre.ebooks.metadata import authors_to_sort_string
24 from calibre.ebooks.metadata.book.base import Metadata
25 from calibre.ebooks.metadata.opf2 import OPF
26 from calibre.gui2 import error_dialog, gprefs, warning_dialog
27 from calibre.gui2.dialogs.duplicates import DuplicatesQuestion
28 from calibre.gui2.dialogs.progress import ProgressDialog
29 from calibre.ptempfile import PersistentTemporaryDirectory
30 from calibre.utils import join_with_timeout
31 from calibre.utils.config import prefs
32 from calibre.utils.filenames import make_long_path_useable
33 from calibre.utils.icu import lower as icu_lower
34 from calibre.utils.ipc.pool import Failure, Pool
35 from calibre.utils.localization import _, ngettext
36
37
38 def validate_source(source, parent=None): # {{{
39 if isinstance(source, (str, bytes)):
40 if not os.path.exists(source):
41 error_dialog(parent, _('Cannot add books'), _('The path %s does not exist') % source, show=True)
42 return False
43 if not os.access(source, os.X_OK | os.R_OK):
44 error_dialog(parent, _('Cannot add books'), _('You do not have permission to read %s') % source, show=True)
45 return False
46 else:
47 ok = False
48 for path in source:
49 if os.access(path, os.R_OK):
50 ok = True
51 break
52 if not ok:
53 error_dialog(
54 parent,
55 _('Cannot add books'),
56 _('You do not have permission to read any of the selected files'),
57 det_msg='\n'.join(source),
58 show=True,
59 )
60 return False
61 return True
62
63
64 # }}}
65
66
67 def resolve_windows_links(paths, hwnd=None):
68 from calibre_extensions.winutil import resolve_lnk
69
70 for x in paths:
71 if x.lower().endswith('.lnk'):
72 try:
73 if hwnd is None:
74 x = resolve_lnk(x)
75 else:
76 x = resolve_lnk(x, 0, hwnd)
77 except Exception as e:
78 print('Failed to resolve link', x, 'with error:', e, file=sys.stderr)
79 continue
80 yield x
81
82
83 class Adder(QObject):
84 do_one_signal = pyqtSignal()
85
86 def __init__(
87 self,
88 source,
89 single_book_per_directory=True,
90 db=None,
91 parent=None,
92 callback=None,
93 pool=None,
94 list_of_archives=False,
95 ):
96 if isinstance(source, str):
97 source = make_long_path_useable(source)
98 else:
99 source = list(map(make_long_path_useable, source))
100 if not validate_source(source, parent):
101 return
102 QObject.__init__(self, parent)
103 self.author_map_rules = None
104 if gprefs.get('author_map_on_add_rules'):
105 from calibre.ebooks.metadata.author_mapper import compile_rules as acr
106
107 self.author_map_rules = acr(gprefs['author_map_on_add_rules'])
108 self.single_book_per_directory = single_book_per_directory
109 self.ignore_opf = False
110 self.list_of_archives = list_of_archives
111 self.callback = callback
112 self.add_formats_to_existing = prefs['add_formats_to_existing']
113 self.do_one_signal.connect(self.tick, type=Qt.ConnectionType.QueuedConnection)
114 self.pool = pool
115 self.pd = ProgressDialog(_('Adding books...'), _('Scanning for files...'), min=0, max=0, parent=parent, icon='add_book.png')
116 self.win_id = None
117 if parent is not None and hasattr(parent, 'effectiveWinId'):
118 self.win_id = parent.effectiveWinId()
119 if self.win_id is not None:
120 self.win_id = int(self.win_id)
121 self.db = getattr(db, 'new_api', None)
122 if self.db is not None:
123 self.dbref = weakref.ref(db)
124 self.source = source
125 self.tdir = PersistentTemporaryDirectory('_add_books')
126 self.scan_error = None
127 self.file_groups = OrderedDict()
128 self.abort_scan = False
129 self.duplicates = []
130 self.report = []
131 self.items = []
132 self.added_book_ids = set()
133 self.merged_formats_added_to = set()
134 self.merged_books = set()
135 self.added_duplicate_info = set()
136 self.pd.show()
137
138 self.scan_thread = Thread(target=self.scan, name='ScanBooks')
139 self.scan_thread.daemon = True
140 self.scan_thread.start()
141 self.do_one = self.monitor_scan
142 self.do_one_signal.emit()
143 if DEBUG:
144 self.start_time = time.time()
145
146 def break_cycles(self):
147 self.abort_scan = True
148 pd = self.pd
149 assert pd is not None
150 pd.close()
151 pd.deleteLater()
152 if self.pool is not None:
153 self.pool.shutdown()
154 if not self.items:
155 tdir = self.tdir
156 assert tdir is not None
157 shutil.rmtree(tdir, ignore_errors=True)
158 self.setParent(None)
159 self.find_identical_books_data = self.merged_books = self.added_duplicate_info = self.pool = self.items = self.duplicates = self.pd = self.db = (
160 self.dbref
161 ) = self.tdir = self.file_groups = self.scan_thread = None # noqa: E501
162 self.deleteLater()
163
164 def tick(self):
165 pd = self.pd
166 assert pd is not None
167 if pd.canceled:
168 try:
169 if callable(self.callback):
170 self.callback(self)
171 finally:
172 self.break_cycles()
173 return
174 self.do_one()
175
176 # Filesystem scan {{{
177
178 def scan(self):
179 file_groups = self.file_groups
180 assert file_groups is not None
181
182 try:
183 compiled_rules = tuple(map(compile_rule, gprefs.get('add_filter_rules', ())))
184 except Exception:
185 compiled_rules = ()
186 import traceback
187
188 traceback.print_exc()
189
190 if iswindows or ismacos:
191
192 def find_files(root):
193 for dirpath, dirnames, filenames in os.walk(root):
194 for files in find_books_in_directory(dirpath, self.single_book_per_directory, compiled_rules=compiled_rules):
195 if self.abort_scan:
196 return
197 if iswindows:
198 files = list(resolve_windows_links(files, hwnd=self.win_id))
199 if files:
200 file_groups[len(file_groups)] = files
201
202 else:
203
204 def find_files(root):
205 if isinstance(root, str):
206 root = root.encode(filesystem_encoding)
207 for dirpath, dirnames, filenames in os.walk(root):
208 try:
209 dirpath = dirpath.decode(filesystem_encoding)
210 except UnicodeDecodeError:
211 prints('Ignoring non-decodable directory:', dirpath)
212 continue
213 for files in find_books_in_directory(dirpath, self.single_book_per_directory, compiled_rules=compiled_rules):
214 if self.abort_scan:
215 return
216 file_groups[len(file_groups)] = files
217
218 def extract(source):
219 tdir = tempfile.mkdtemp(suffix='_archive', dir=self.tdir)
220 if source.lower().endswith('.zip'):
221 from calibre.utils.zipfile import extractall
222
223 try:
224 extractall(source, tdir)
225 except Exception:
226 prints('Corrupt ZIP file, trying to use local headers')
227 from calibre.utils.localunzip import extractall
228
229 extractall(source, tdir)
230 elif source.lower().endswith('.rar'):
231 from calibre.utils.unrar import extract
232
233 extract(source, tdir)
234 elif source.lower().endswith('.7z'):
235 from calibre.utils.seven_zip import extract
236
237 extract(source, tdir)
238 return tdir
239
240 try:
241 if isinstance(self.source, (str, bytes)):
242 find_files(self.source)
243 self.ignore_opf = True
244 else:
245 unreadable_files = []
246 for path in self.source:
247 if self.abort_scan:
248 return
249 if os.access(path, os.R_OK):
250 if self.list_of_archives:
251 find_files(extract(path))
252 self.ignore_opf = True
253 else:
254 x = [path]
255 if iswindows:
256 x = list(resolve_windows_links(x, hwnd=self.win_id))
257 if x:
258 file_groups[len(file_groups)] = x
259 else:
260 unreadable_files.append(path)
261 else:
262 unreadable_files.append(path)
263 if unreadable_files:
264 if not self.file_groups:
265 m = ngettext(
266 'You do not have permission to read the selected file.',
267 'You do not have permission to read the selected files.',
268 len(unreadable_files),
269 )
270 self.scan_error = m + '\n' + '\n'.join(unreadable_files)
271 else:
272 a = self.report.append
273 for f in unreadable_files:
274 a(_('Could not add {} as you do not have permission to read the file').format(f))
275 a('')
276 except Exception:
277 self.scan_error = traceback.format_exc()
278
279 def monitor_scan(self):
280 scan_thread = self.scan_thread
281 assert scan_thread is not None
282 scan_thread.join(0.05)
283 if scan_thread.is_alive():
284 self.do_one_signal.emit()
285 return
286 if self.scan_error is not None:
287 error_dialog(
288 self.pd,
289 _('Cannot add books'),
290 _('Failed to add any books, click "Show details" for more information.'),
291 det_msg=self.scan_error,
292 show=True,
293 )
294 self.break_cycles()
295 return
296 if not self.file_groups:
297 error_dialog(self.pd, _('Could not add'), _('No e-book files were found in %s') % self.source, show=True)
298 self.break_cycles()
299 return
300 pd = self.pd
301 assert pd is not None
302 pd.max = len(self.file_groups)
303 pd.title = ngettext(
304 'Reading metadata and adding to library (one book)...',
305 'Reading metadata and adding to library ({} books)...',
306 pd.max,
307 ).format(pd.max)
308 pd.msg = ''
309 pd.value = 0
310 self.pool = Pool(name='AddBooks') if self.pool is None else self.pool
311 if self.db is not None:
312 if self.add_formats_to_existing:
313 self.find_identical_books_data = self.db.data_for_find_identical_books()
314 else:
315 try:
316 self.pool.set_common_data(self.db.data_for_has_book())
317 except Failure as err:
318 error_dialog(
319 pd,
320 _('Cannot add books'),
321 _('Failed to add any books, click "Show details" for more information.'),
322 det_msg=as_unicode(err.failure_message) + '\n' + as_unicode(err.details),
323 show=True,
324 )
325 pd.canceled = True
326 self.groups_to_add = iter(self.file_groups)
327 self.do_one = self.do_one_group
328 self.do_one_signal.emit()
329
330 # }}}
331
332 def do_one_group(self):
333 try:
334 group_id = next(self.groups_to_add)
335 except StopIteration:
336 self.do_one = self.monitor_pool
337 self.do_one_signal.emit()
338 return
339 pool = self.pool
340 assert pool is not None
341 file_groups = self.file_groups
342 assert file_groups is not None
343 tdir = self.tdir
344 assert tdir is not None
345 pd = self.pd
346 assert pd is not None
347 try:
348 pool(group_id, 'calibre.ebooks.metadata.worker', 'read_metadata', file_groups[group_id], group_id, tdir)
349 except Failure as err:
350 error_dialog(
351 pd,
352 _('Cannot add books'),
353 _('Failed to add any books, click "Show details" for more information.'),
354 det_msg=as_unicode(err.failure_message) + '\n' + as_unicode(err.details),
355 show=True,
356 )
357 pd.canceled = True
358 self.do_one_signal.emit()
359
360 def monitor_pool(self):
361 pool = self.pool
362 assert pool is not None
363 pd = self.pd
364 assert pd is not None
365 file_groups = self.file_groups
366 assert file_groups is not None
367 try:
368 worker_result = pool.results.get(True, 0.05)
369 pool.results.task_done()
370 except Empty:
371 try:
372 pool.wait_for_tasks(timeout=0.01)
373 except RuntimeError:
374 pass # Tasks still remaining
375 except Failure as err:
376 error_dialog(
377 pd,
378 _('Cannot add books'),
379 _('Failed to add some books, click "Show details" for more information.'),
380 det_msg=str(err.failure_message) + '\n' + str(err.details),
381 show=True,
382 )
383 pd.canceled = True
384 else:
385 # All tasks completed
386 try:
387 join_with_timeout(pool.results, 0.01)
388 except RuntimeError:
389 pass # There are results remaining
390 else:
391 # No results left
392 self.process_duplicates()
393 return
394 else:
395 group_id = worker_result.id
396 if worker_result.is_terminal_failure:
397 error_dialog(
398 pd,
399 _('Critical failure'),
400 _(
401 'The read metadata worker process crashed while processing'
402 ' some files. Adding of books is aborted. Click "Show details"'
403 ' to see which files caused the problem.'
404 ),
405 show=True,
406 det_msg='\n'.join(file_groups[group_id]),
407 )
408 pd.canceled = True
409 else:
410 try:
411 self.process_result(group_id, worker_result.result)
412 except Exception:
413 self.report_metadata_failure(group_id, traceback.format_exc())
414 pd.value += 1
415
416 self.do_one_signal.emit()
417
418 def report_metadata_failure(self, group_id, details):
419 a = self.report.append
420 file_groups = self.file_groups
421 assert file_groups is not None
422 paths = file_groups[group_id]
423 a(''), a('-' * 70)
424 m = ngettext('Failed to read metadata from the file:', 'Failed to read metadata from the files:', len(paths))
425 a(m)
426 [a('\t' + f) for f in paths]
427 a(_('With error:')), a(details)
428 mi = Metadata(_('Unknown'))
429 mi.read_metadata_failed = False
430 return mi
431
432 def process_result(self, group_id, result):
433 file_groups = self.file_groups
434 assert file_groups is not None
435 pd = self.pd
436 assert pd is not None
437 added_duplicate_info = self.added_duplicate_info
438 assert added_duplicate_info is not None
439 if result.err:
440 mi = self.report_metadata_failure(group_id, result.traceback)
441 paths = file_groups[group_id]
442 has_cover = False
443 duplicate_info = set() if self.add_formats_to_existing else False
444 else:
445 paths, opf, has_cover, duplicate_info = result.value
446 try:
447 mi = OPF(BytesIO(opf), basedir=self.tdir, populate_spine=False, try_to_guess_cover=False).to_book_metadata()
448 mi.read_metadata_failed = False
449 except Exception:
450 mi = self.report_metadata_failure(group_id, traceback.format_exc())
451
452 if mi.is_null('title'):
453 for path in paths:
454 mi.title = os.path.splitext(os.path.basename(path))[0]
455 break
456 if mi.application_id == '__calibre_dummy__':
457 mi.application_id = None
458 if gprefs.get('tag_map_on_add_rules'):
459 from calibre.ebooks.metadata.tag_mapper import map_tags
460
461 mi.tags = map_tags(mi.tags, gprefs['tag_map_on_add_rules'])
462 if self.author_map_rules:
463 from calibre.ebooks.metadata.author_mapper import map_authors
464
465 new_authors = map_authors(mi.authors, self.author_map_rules)
466 if new_authors != mi.authors:
467 mi.authors = new_authors
468 if self.db is None:
469 mi.author_sort = authors_to_sort_string(mi.authors)
470 else:
471 mi.author_sort = self.db.author_sort_from_authors(mi.authors)
472
473 pd.msg = mi.title
474
475 assert self.tdir is not None
476 cover_path = os.path.join(self.tdir, f'{group_id}.cdata') if has_cover else None
477
478 if self.db is None:
479 if paths:
480 items = self.items
481 assert items is not None
482 items.append((mi, cover_path, paths))
483 return
484
485 if self.add_formats_to_existing:
486 identical_book_ids = find_identical_books(mi, self.find_identical_books_data)
487 if identical_book_ids:
488 try:
489 self.merge_books(mi, cover_path, paths, identical_book_ids)
490 except Exception:
491 a = self.report.append
492 a(''), a('-' * 70)
493 a(_('Failed to merge the book: ') + mi.title)
494 [a('\t' + f) for f in paths]
495 a(_('With error:')), a(traceback.format_exc())
496 else:
497 self.add_book(mi, cover_path, paths)
498 elif duplicate_info or icu_lower(mi.title or _('Unknown')) in added_duplicate_info:
499 duplicates = self.duplicates
500 assert duplicates is not None
501 duplicates.append((mi, cover_path, paths))
502 else:
503 self.add_book(mi, cover_path, paths)
504
505 def merge_books(self, mi, cover_path, paths, identical_book_ids):
506 merged_books = self.merged_books
507 assert merged_books is not None
508 merged_books.add((mi.title, ' & '.join(mi.authors)))
509 seen_fmts = set()
510 replace = gprefs['automerge'] == 'overwrite'
511 cover_removed = False
512 cdata = None
513 db = self.db
514 assert db is not None
515 for identical_book_id in identical_book_ids:
516 ib_fmts = {fmt.upper() for fmt in db.formats(identical_book_id)}
517 seen_fmts |= ib_fmts
518 self.add_formats(identical_book_id, paths, mi, replace=replace)
519 self.merged_formats_added_to.add(identical_book_id)
520 if cover_path and not db.field_for('cover', identical_book_id):
521 if cdata is None:
522 with open(cover_path, 'rb') as f:
523 cdata = f.read()
524 db.set_cover({identical_book_id: cdata})
525 if gprefs['automerge'] == 'new record':
526 incoming_fmts = {path.rpartition(os.extsep)[-1].upper() for path in paths}
527 if incoming_fmts.intersection(seen_fmts):
528 # There was at least one duplicate format so create a new
529 # record and put the incoming formats into it We should
530 # arguably put only the duplicate formats, but no real harm is
531 # done by having all formats
532 self.add_book(mi, cover_path, paths)
533 cover_removed = True
534 if not cover_removed and cover_path:
535 try:
536 os.remove(cover_path)
537 except Exception:
538 pass
539
540 def add_book(self, mi, cover_path, paths):
541 if DEBUG:
542 st = time.time()
543 try:
544 cdata = None
545 if cover_path:
546 with open(cover_path, 'rb') as f:
547 cdata = f.read()
548 try:
549 os.remove(cover_path)
550 except Exception:
551 pass
552 dbref = self.dbref
553 assert dbref is not None
554 db_inst = dbref()
555 assert db_inst is not None
556 book_id = db_inst.create_book_entry(mi, cover=cdata)
557 self.added_book_ids.add(book_id)
558 except Exception:
559 a = self.report.append
560 a(''), a('-' * 70)
561 a(_('Failed to add the book: ') + mi.title)
562 [a('\t' + f) for f in paths]
563 a(_('With error:')), a(traceback.format_exc())
564 return
565 self.add_formats(book_id, paths, mi, is_an_add=True)
566 try:
567 if self.add_formats_to_existing:
568 db = self.db
569 assert db is not None
570 db.update_data_for_find_identical_books(book_id, self.find_identical_books_data)
571 else:
572 added_duplicate_info = self.added_duplicate_info
573 assert added_duplicate_info is not None
574 added_duplicate_info.add(icu_lower(mi.title or _('Unknown')))
575 except Exception:
576 # Ignore this exception since all it means is that duplicate
577 # detection/automerge will fail for this book.
578 traceback.print_exc()
579 if DEBUG:
580 prints('Added', mi.title, f'to db in: {time.time() - st:.1f}')
581
582 def add_formats(self, book_id, paths, mi, replace=True, is_an_add=False):
583 fmap = {p.rpartition(os.path.extsep)[-1].lower(): p for p in paths}
584 fmt_map = {}
585 db = self.db
586 assert db is not None
587 dbref = self.dbref
588 assert dbref is not None
589 for fmt, path in fmap.items():
590 # The onimport plugins have already been run by the read metadata
591 # worker
592 if self.ignore_opf and fmt.lower() == 'opf':
593 continue
594 try:
595 if db.add_format(book_id, fmt, path, run_hooks=False, replace=replace):
596 run_plugins_on_postimport(dbref(), book_id, fmt)
597 fmt_map[fmt.lower()] = path
598 except Exception:
599 a = self.report.append
600 a(''), a('-' * 70)
601 a(_('Failed to add the file {0} to the book: {1}').format(path, mi.title))
602 a(_('With error:')), a(traceback.format_exc())
603 if is_an_add:
604 run_plugins_on_postadd(dbref(), book_id, fmt_map)
605
606 def process_duplicates(self):
607 if self.duplicates:
608 dbref = self.dbref
609 assert dbref is not None
610 pd = self.pd
611 assert pd is not None
612 d = DuplicatesQuestion(dbref(), self.duplicates, pd)
613 duplicates = tuple(d.duplicates)
614 d.deleteLater()
615 if duplicates:
616 self.do_one = self.process_duplicate
617 self.duplicates_to_process = iter(duplicates)
618 pd.title = _('Adding duplicates')
619 pd.msg = ''
620 pd.max, pd.value = len(duplicates), 0
621 self.do_one_signal.emit()
622 return
623 self.finish()
624
625 def process_duplicate(self):
626 try:
627 mi, cover_path, paths = next(self.duplicates_to_process)
628 except StopIteration:
629 self.finish()
630 return
631 pd = self.pd
632 assert pd is not None
633 pd.value += 1
634 pd.msg = mi.title
635 self.add_book(mi, cover_path, paths)
636 self.do_one_signal.emit()
637
638 def finish(self):
639 added_book_ids = self.added_book_ids
640 assert added_book_ids is not None
641 pd = self.pd
642 assert pd is not None
643 if DEBUG:
644 items = self.items
645 assert items is not None
646 prints(f'Added {len(added_book_ids or items)} books in {time.time() - self.start_time:.1f} seconds')
647 if self.report:
648 added_some = self.items or added_book_ids
649 d = warning_dialog if added_some else error_dialog
650 msg = (
651 _('There were problems adding some files, click "Show details" for more information')
652 if added_some
653 else _('Failed to add any books, click "Show details" for more information')
654 )
655 d(pd, _('Errors while adding'), msg, det_msg='\n'.join(self.report), show=True)
656
657 potentially_convertible = added_book_ids | self.merged_formats_added_to
658 from calibre.gui2.ui import get_gui
659
660 g = get_gui()
661 if gprefs['manual_add_auto_convert'] and potentially_convertible and g is not None:
662 g.iactions['Convert Books'].auto_convert_auto_add(potentially_convertible)
663
664 try:
665 if callable(self.callback):
666 self.callback(self)
667 finally:
668 self.break_cycles()
669
670 @property
671 def number_of_books_added(self):
672 return len(self.added_book_ids)