-
Notifications
You must be signed in to change notification settings - Fork 24
/
action.py
1400 lines (1218 loc) · 61 KB
/
action.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
# coding: utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Greg Riker <[email protected]>, 2014-2020 additions by David Forrester <[email protected]>'
__docformat__ = 'restructuredtext en'
import imp, inspect, os, re, sys, tempfile, threading, types
# calibre Python 3 compatibility.
try:
from urllib.parse import urlparse
except ImportError as e:
from urlparse import urlparse
import six
from six import text_type as unicode
from functools import partial
from zipfile import ZipFile
from calibre.devices.usbms.driver import debug_print
try:
from PyQt5.Qt import (pyqtSignal, Qt, QApplication, QIcon, QMenu, QMessageBox, QPixmap,
QTimer, QToolButton, QUrl)
except ImportError as e:
debug_print("Error loading QT5: ", e)
from PyQt4.Qt import (pyqtSignal, Qt, QApplication, QIcon, QMenu, QMessageBox, QPixmap,
QTimer, QToolButton, QUrl)
from calibre.constants import DEBUG, isosx, iswindows
try:
from calibre.devices.idevice.libimobiledevice import libiMobileDevice
LIBIMOBILEDEVICE_AVAILABLE = True
except ImportError as e:
debug_print("Annotations plugin: Error loading libiMobileDevice. This hasn't worked for a while, and is blacklisted in calibre v3.")
debug_print("Annotations plugin: Error is: ", e)
LIBIMOBILEDEVICE_AVAILABLE = False
from calibre.ebooks.BeautifulSoup import BeautifulSoup
from calibre.ebooks import normalize
from calibre.gui2 import Application, open_url
from calibre.gui2.device import device_signals
from calibre.gui2.dialogs.message_box import MessageBox
from calibre.gui2.actions import InterfaceAction
from calibre.library import current_library_name
from calibre.utils.config import config_dir
from calibre_plugins.annotations.annotated_books import AnnotatedBooksDialog
from calibre_plugins.annotations.annotations import merge_annotations, merge_annotations_with_comments
from calibre_plugins.annotations.annotations_db import AnnotationsDB
from calibre_plugins.annotations.common_utils import (
CoverMessageBox, HelpView, ImportAnnotationsTextDialog, ImportAnnotationsFileDialog, IndexLibrary,
Logger, ProgressBar, Struct,
get_cc_mapping, get_clippings_cid, get_icon, get_pixmap, get_resource_files,
get_selected_book_mi, plugin_tmpdir,
set_cc_mapping, set_plugin_icon_resources)
#import calibre_plugins.annotations.config as cfg
from calibre_plugins.annotations.config import plugin_prefs
from calibre_plugins.annotations.find_annotations import FindAnnotationsDialog
from calibre_plugins.annotations.message_box_ui import COVER_ICON_SIZE
from calibre_plugins.annotations.reader_app_support import *
from calibre.constants import numeric_version as calibre_version
# The first icon is the plugin icon, referenced by position.
# The rest of the icons are referenced by name
PLUGIN_ICONS = ['images/annotations.png', 'images/apple.png',
'images/bluefire_reader.png',
'images/device_connected.png', 'images/device.png',
'images/exporting_app.png',
'images/goodreader.png', 'images/ibooks.png',
'images/kindle_for_ios.png',
'images/magnifying_glass.png', 'images/marvin.png',
'images/matches_hide.png', 'images/matches_show.png',
'images/stanza.png']
try:
debug_print("Annotations::action.py - loading translations")
load_translations()
except NameError:
debug_print("Annotations::action.py - exception when loading translations")
pass # load_translations() added in calibre 1.9
class AnnotationsAction(InterfaceAction, Logger):
accepts_drops = True
ios_fs = None
mount_point = None
name = 'Annotations'
SELECT_DESTINATION_MSG = _("Select a book to receive annotations when annotation metadata cannot be matched with library metadata.")
SELECT_DESTINATION_DET_MSG = _(
"To determine which book will receive incoming annotations, annotation metadata (Title, Author, UUID) is compared to library metadata.\n\n"
"Annotations whose metadata completely matches library metadata will be added automatically to the corresponding book.\n\n"
"For partial metadata matches, you will be prompted to confirm the book receiving the annotations.\n\n"
"If no metadata matches, you will be prompted to confirm the currently selected book to receive the annotations.\n")
# Declare the main action associated with this plugin
action_spec = ('Annotations', None,
_('Import annotations from eBook reader'), ())
action_menu_clone_qaction = True
action_add_menu = True
popup_type = QToolButton.InstantPopup
plugin_device_connection_changed = pyqtSignal(object)
def about_to_show_menu(self):
self.launch_library_scanner()
self.rebuild_menus()
# subclass override
def accept_enter_event(self, event, md):
if False:
for fmt in md.formats():
self._log("fmt: %s" % fmt)
if md.hasFormat("text/uri-list"):
return True
else:
return False
# subclass override
def accept_drag_move_event(self, event, md):
if md.hasFormat("text/uri-list"):
return True
else:
return False
def add_annotations_to_calibre(self, book_mi, annotations_db, cid):
"""
Add annotations from a single db to calibre
Update destination Comments or #<custom>
"""
update_field = get_cc_mapping('annotations', 'field', 'Comments')
self._log_location(update_field)
library_db = self.opts.gui.current_db
mi = library_db.get_metadata(cid, index_is_id=True)
# Get the newly imported annotations
self._log_location("Getting new annotations as soup...")
raw_annotations = self.opts.db.annotations_to_html(annotations_db, book_mi)
self._log_location("New raw_annotations=%s" % raw_annotations)
new_soup = BeautifulSoup(self.opts.db.annotations_to_html(annotations_db, book_mi))
self._log_location("new_soup=%s" % new_soup)
new_annotation_string = None
if update_field == "Comments":
# Append merged annotations to end of existing Comments
# Any older annotations?
comments = library_db.comments(cid, index_is_id=True)
if comments is None:
comments = unicode(new_soup)
else:
# Keep comments, update annotations
comments_soup = BeautifulSoup(comments)
comments = merge_annotations_with_comments(self, cid, comments_soup, new_soup)
new_annotation_string = comments
else:
# Generate annotations formatted for custom field
# Any older annotations?
if mi.get_user_metadata(update_field, False)['#value#'] is None:
new_annotation_string = unicode(new_soup)
else:
# Merge new hashes into old
self._log_location("Current Annotation in library=%s" % mi.get_user_metadata(update_field, False)['#value#'])
old_soup = BeautifulSoup(mi.get_user_metadata(update_field, False)['#value#'])
self._log_location("Have old soup=%s" % old_soup)
merged_soup = merge_annotations(self, cid, old_soup, new_soup)
new_annotation_string = unicode(merged_soup)
# self._log_location("Have merged soup=%s" % merged_soup)
# self._log_location("Updateing GUI view")
#self.gui.library_view.select_rows([cid], using_ids=True)
self._log(" annotations updated: '%s' cid:%d " % (mi.title, cid))
return new_annotation_string
def create_menu_item(self, m, menu_text, image=None, tooltip=None, shortcut=None):
ac = self.create_action(spec=(menu_text, None, tooltip, shortcut), attr=menu_text)
if image:
ac.setIcon(QIcon(image))
m.addAction(ac)
return ac
def create_menu_item_ex(self, m, unique_name, menu_text, image=None, tooltip=None, shortcut=None, triggered=None, enabled=True):
ac = self.create_menu_action(m, unique_name, menu_text, icon=image, shortcut=shortcut,
description=tooltip, triggered=triggered)
ac.setEnabled(enabled)
self.menu_actions.append(ac)
return ac
def describe_confidence(self, confidence, book_mi, library_mi):
def _title_mismatch():
msg = _("TITLE MISMATCH:") + "\n"
msg += _(" library:") + " %s\n" % library_mi.title
msg += _(" imported:") + " %s\n" % book_mi.title
#msg += "Mismatches can occur if the book's metadata has been edited outside of calibre.\n\n"
return msg
def _author_mismatch():
msg = _("AUTHOR MISMATCH:") + "\n"
msg += _(" library:") + " %s\n" % ', '.join(library_mi.authors)
msg += _(" imported:") + " %s\n" % book_mi.author
#msg += "Mismatches can occur if the book's metadata has been edited outside of calibre.\n\n"
return msg
def _uuid_mismatch():
msg = _("UUID MISMATCH:") + "\n"
msg += _(" library:") + " %s\n" % library_mi.uuid
msg += _(" imported:") + " %s\n" % (book_mi.uuid if book_mi.uuid else 'uuid unavailable')
#msg += "Mismatches can occur if the book was added from a different installation of calibre.\n\n"
return msg
if confidence < 5:
det_msg = '{:-^45}\n'.format(_('confidence:') + ' %d' % confidence)
if confidence == 4:
det_msg = _author_mismatch()
elif confidence == 3:
det_msg = _title_mismatch()
det_msg += _author_mismatch()
elif confidence == 2:
det_msg = _uuid_mismatch()
elif confidence == 1:
det_msg = _author_mismatch()
det_msg += _uuid_mismatch()
elif confidence == 0:
det_msg = _title_mismatch()
det_msg += _author_mismatch()
det_msg += _uuid_mismatch()
else:
det_msg = _("Metadata matches")
return det_msg
# subclass override
def drop_event(self, event, md):
mime = "text/uri-list"
if md.hasFormat(mime):
self.dropped_url = str(md.data(mime))
QTimer.singleShot(1, self.do_drop_event)
return True
return False
def do_drop_event(self):
# Allow the accepted event to process
QApplication.processEvents()
self.selected_mi = get_selected_book_mi(self.get_options(),
msg=self.SELECT_DESTINATION_MSG,
det_msg=self.SELECT_DESTINATION_DET_MSG)
if not self.selected_mi:
return
self.launch_library_scanner()
# Let the library scanner run
sleep(0.1)
QApplication.processEvents()
# Wait for library_scanner to complete
if self.library_scanner.isRunning():
self._log("waiting for library_scanner()")
self.library_scanner.wait()
path = urlparse(self.dropped_url).path.strip()
scheme = urlparse(self.dropped_url).scheme
path = re.sub('%20', ' ', path)
self._log_location(path)
if iswindows:
if path.startswith('/Shared Folders'):
path = re.sub(r'\/Shared Folders', 'Z:', path)
elif path.startswith('/'):
path = path[1:]
extension = path.rpartition('.')[2]
if scheme == 'file' and extension in ['mrv', 'mrvi', 'txt']:
with open(path) as f:
raw = f.read()
# See if anyone can parse it
exporting_apps = ReaderApp.get_exporting_app_classes()
for app_class in exporting_apps:
rac = app_class(self)
handled = rac.parse_exported_highlights(raw, log_failure=False)
if handled:
try:
self.present_annotated_books(rac, source="imported")
except:
pass
break
else:
title = _("Unable to import annotations")
msg = "<p>{0}</p>".format(("Unable to import anotations from <tt>{0}</tt>.".format(os.path.basename(path))))
MessageBox(MessageBox.INFO, title, msg, show_copy_button=False).exec_()
self._log_location("INFO: %s" % msg)
def fetch_device_annotations(self, annotated_book_list, source):
self._log_location(source)
if annotated_book_list:
d = AnnotatedBooksDialog(self, annotated_book_list, self.get_annotations_as_HTML, source)
if d.exec_():
if d.selected_books:
book_count = 0
for reader_app in d.selected_books:
book_count += len(d.selected_books[reader_app])
self.opts.pb.set_maximum(book_count)
# Update the progress bar
self.opts.pb.set_label(_("Adding annotations to calibre"))
self.opts.pb.set_value(0)
self.opts.pb.show()
updated_annotations = 0
try:
for reader_app in d.selected_books:
Application.processEvents()
annotations_db = ReaderApp.generate_annotations_db_name(reader_app, source)
updated_annotations += self.process_selected_books(d.selected_books, reader_app, annotations_db)
except:
import traceback
traceback.print_exc()
title = _("Error fetching annotations")
msg = self.format_as_paragraph(_("Unable to fetch annotations from {0}.").format(source))
det_msg = traceback.format_exc()
MessageBox(MessageBox.ERROR, title, msg, det_msg, show_copy_button=False).exec_()
self._log_location("ERROR: %s" % msg)
self.opts.pb.hide()
if updated_annotations:
self.report_updated_annotations(updated_annotations)
else:
title = _("No annotated books found on device")
msg = self.format_as_paragraph(_('Unable to find any annotations on {0} matching books in your library.').format(source))
MessageBox(MessageBox.INFO, title, msg, show_copy_button=False).exec_()
self._log_location("INFO: %s" % msg)
def fetch_ios_annotations(self, an):
"""
Selectively import annotations from books on mounted iOS device
"""
self.selected_mi = get_selected_book_mi(self.get_options(),
msg=self.SELECT_DESTINATION_MSG,
det_msg=self.SELECT_DESTINATION_DET_MSG)
if not self.selected_mi:
return
#annotated_book_list = self.get_annotated_books_on_ios_device()
annotated_book_list = self.get_annotated_books_in_ios_reader_app(an)
if annotated_book_list:
self.fetch_device_annotations(annotated_book_list, self.ios.device_name)
def fetch_usb_connected_device_annotations(self):
self._log_location("Start")
if self.connected_device is not None:
self._log_location("Have device")
self.launch_library_scanner()
self.fetch_usb_device_annotations(self.get_connected_device_primary_name())
def get_connected_device_primary_name(self):
if self.connected_device.name == 'MTP Device Interface':
self._log_location("get_connected_device_primary_name - Have MTP device - self.get_connected_device_primary_name='%s'" % self.connected_device.current_friendly_name)
# get actual device name from the MTP driver (used for Android devices)
device_name = self.connected_device.current_friendly_name
# group all Onyx devices under same name, because they behave the same
import re
if re.compile(r"^(Nova|Poke|Note|MAX)").match(device_name):
device_name = 'Boox'
else:
# non-Android devices have dedicated drivers
device_name = self.connected_device.name
return device_name.split()[0]
def fetch_usb_device_annotations(self, reader_app):
"""
Selectively import annotations from books on mounted USB device
"""
annotations_column = get_cc_mapping('annotations', 'field')
msg = None
if not annotations_column:
msg = self.format_as_paragraph(_('Unable to import annotations as the annotations column has not been configured...'))
elif annotations_column == 'Comments':
pass
elif not annotations_column in self.gui.current_db.custom_field_keys():
msg = self.format_as_paragraph(_('Unable to import annotations as the annotations column does not exist.'))
if msg:
title = _("Unable to import annotations")
MessageBox(MessageBox.ERROR, title, msg, show_copy_button=False).exec_()
self._log_location("ERROR: %s" % msg)
return
self.selected_mi = get_selected_book_mi(self.get_options(),
msg=self.SELECT_DESTINATION_MSG,
det_msg=self.SELECT_DESTINATION_DET_MSG)
if not self.selected_mi:
return
self.opts.pb.set_label(_("Fetch annotations from USB device"))
self.opts.pb.set_value(0)
self.opts.pb.show()
annotated_book_list = self.get_annotated_books_on_usb_device(reader_app)
self._log_location("DEBUG: %s" % annotated_book_list)
self.opts.pb.hide()
self.fetch_device_annotations(annotated_book_list, self.opts.device_name)
def find_annotations(self):
'''
Launch the Find Annotations dialog, filter GUI to show matching set
'''
fa = FindAnnotationsDialog(self.opts)
if fa.exec_():
db = self.gui.current_db
db.set_marked_ids(fa.matched_ids)
self.gui.search.setEditText('marked:true')
self.gui.search.do_search()
# subclass override
def genesis(self):
# General initialization, occurs when calibre launches
self.init_logger()
self.menus_lock = threading.RLock()
self.sync_lock = threading.RLock()
self.connected_device = None
self.indexed_library = None
self.library_indexed = False
self.library_last_modified = None
self.resources_path = os.path.join(config_dir, 'plugins', 'annotations_resources')
# Read the plugin icons and store for potential sharing with the config widget
icon_resources = self.load_resources(PLUGIN_ICONS)
set_plugin_icon_resources(self.name, icon_resources)
# Instantiate libiMobileDevice
try:
self.ios = libiMobileDevice(
verbose=plugin_prefs.get('cfg_libimobiledevice_debug_log_checkbox', False))
except Exception as e:
self._log_location('ERROR', "Error loading library libiMobileDevice: %s" % (str(e)))
self.ios = None
# Build an opts object
self.opts = self.init_options()
# Assign our menu to this action and an icon
self.menu = QMenu(self.gui)
self.qaction.setMenu(self.menu)
self.qaction.setIcon(get_icon(PLUGIN_ICONS[0]))
#self.qaction.triggered.connect(self.main_menu_button_clicked)
self.menu.aboutToShow.connect(self.about_to_show_menu)
self.menu_actions = []
# spec = self.action_spec[:3]
# spec.append(())
# ac = self.create_action(spec=spec)
# ac.triggered.connect(self.fetch_usb_connected_device_annotations)
# Instantiate the database
db = AnnotationsDB(self.opts, path=os.path.join(config_dir, 'plugins', 'annotations.db'))
self.opts.conn = db.connect()
self.opts.db = db
# Init the prefs file
self.init_prefs()
# Load the dynamic reader classes
self.load_dynamic_reader_classes()
# Populate dialog resources
self.inflate_dialog_resources()
# Populate the help resources
self.inflate_help_resources()
def generate_confidence(self, book_mi):
'''
Match imported metadata against library metadata
Confidence:
5: book_id
5: uuid + title + author or book_id + title + author
4: uuid + title
3: uuid
2: title + author
1: title
0:
Input: {'title':<title>, 'author':<author>, 'uuid':<uuid>}
Output: cid, confidence_index
'''
# If have a book id, the book has already been matched
try:
book_id = int(book_mi['book_id'])
except:
book_id = -1
if (book_mi['book_id'] is not None and book_id > 0):
cid = book_id
confidence = 5
return cid, confidence
if self.library_scanner.isRunning():
self._log_location("DEBUG: Waiting for library scanner")
self.library_scanner.wait()
self._log_location("DEBUG: Library scanner has completed")
title_map = self.library_scanner.title_map
uuid_map = self.library_scanner.uuid_map
confidence = 0
cid = None
title = normalize(book_mi['title'])
self._log_location("DEBUG: book_mi=%s" % book_mi)
# Check uuid_map
if (book_mi['uuid'] in uuid_map and
title == uuid_map[book_mi['uuid']]['title'] and
book_mi['author'] in uuid_map[book_mi['uuid']]['authors']):
cid = uuid_map[book_mi['uuid']]['id']
confidence = 5
elif (book_mi['uuid'] in uuid_map and
title == uuid_map[book_mi['uuid']]['title']):
cid = uuid_map[book_mi['uuid']]['id']
confidence = 4
elif book_mi['uuid'] in uuid_map:
cid = uuid_map[book_mi['uuid']]['id']
confidence = 3
# Check title_map
elif (title in title_map and
book_mi['author'] in title_map[title]['authors']):
cid = title_map[title]['id']
confidence = 2
else:
if title in title_map:
cid = title_map[title]['id']
confidence = 1
return cid, confidence
def get_annotated_books_in_ios_reader_app(self, reader_app):
'''
'''
try:
annotated_book_list = []
sql_reader_apps = iOSReaderApp.get_sqlite_app_classes(by_name=True)
reader_app_class = sql_reader_apps[reader_app]
# Save a reference for merge_annotations
self.reader_app_class = reader_app_class
# Instantiate reader_app_class
ra = reader_app_class(self)
ra.app_id = self.installed_app_aliases[reader_app]
self.opts.pb.show()
ra.open()
ra.get_installed_books()
ra.get_active_annotations()
books_db = ra.generate_books_db_name(reader_app, self.ios.device_name)
annotations_db = ra.generate_annotations_db_name(reader_app, self.ios.device_name)
books = ra.get_books(books_db)
ra.close()
self.opts.pb.hide()
if books is None:
return
# Get the books for this db
this_book_list = []
for book in books:
book_mi = {}
for key in list(book.keys()):
book_mi[key] = book[key]
if not book_mi['active']:
continue
annotation_count = self.opts.db.get_annotation_count(annotations_db, book_mi['book_id'])
last_update = self.opts.db.get_last_update(books_db, book_mi['book_id'], as_timestamp=True)
if annotation_count:
this_book_list.append({
'annotations': annotation_count,
'author': book_mi['author'],
'author_sort': book_mi['author_sort'] if book_mi['author_sort'] else book_mi['author'],
'book_id': book_mi['book_id'],
'genre': book_mi['genre'],
'last_update': last_update,
'reader_app': reader_app,
'title': book_mi['title'],
'title_sort': book_mi['title_sort'] if book_mi['title_sort'] else book_mi['title'],
'uuid': book_mi['uuid'],
})
annotated_book_list += this_book_list
except:
self.opts.pb.hide()
import traceback
traceback.print_exc()
title = _("Error fetching annotations")
msg = self.format_as_paragraph(_('Unable to fetch annotations from {0}.').format(reader_app))
MessageBox(MessageBox.ERROR, title, msg, show_copy_button=False).exec_()
self._log_location("ERROR: %s" % msg)
return annotated_book_list
def get_annotated_books_on_usb_device(self, reader_app):
self._log_location()
self.opts.pb.set_label(_("Fetching annotations from device"))
self.opts.pb.set_value(0)
annotated_book_list = []
usb_readers = USBReader.get_usb_reader_classes()
reader_app_class = usb_readers[reader_app]
# Save a reference for merge_annotations
self.reader_app_class = reader_app_class
# Instantiate reader_app_class
ra = reader_app_class(self)
ra.open()
ra.get_installed_books()
ra.get_active_annotations()
books_db = ra.generate_books_db_name(reader_app, self.opts.device_name)
annotations_db = ra.generate_annotations_db_name(reader_app, self.opts.device_name)
books = ra.get_books(books_db)
ra.close()
#books = self.opts.db.get_books(books_db)
if books is not None:
self.opts.pb.set_label(_("Compiling annotations for a book"))
self.opts.pb.set_value(0)
# Get the books for this db
this_book_list = []
for book in books:
book_mi = {}
for key in list(book.keys()):
book_mi[key] = book[key]
if not book_mi['active']:
continue
annotation_count = self.opts.db.get_annotation_count(annotations_db, book_mi['book_id'])
last_update = self.opts.db.get_last_update(books_db, book_mi['book_id'], as_timestamp=True)
if annotation_count:
book_dict = {
'annotations': annotation_count,
'author': book_mi['author'],
'author_sort': book_mi['author_sort'] if book_mi['author_sort'] else book_mi['author'],
'book_id': book_mi['book_id'],
'genre': book_mi['genre'],
'last_update': last_update,
'reader_app': reader_app,
'title': book_mi['title'],
'title_sort': book_mi['title_sort'] if book_mi['title_sort'] else book_mi['title'],
'uuid': book_mi['uuid'],
}
confidence = book_mi.get('confidence', None)
if confidence is not None:
book_dict['confidence'] = confidence
this_book_list.append(book_dict)
annotated_book_list += this_book_list
self.opts.pb.hide()
return annotated_book_list
def get_annotations_as_HTML(self, annotations_db, book_mi):
soup = self.opts.db.annotations_to_html(annotations_db, book_mi)
return soup
def get_options(self):
# Defer adding the connected device until we need the information, as it
# takes some time for the device to be recognized.
self.opts['device_name'] = None
if self.connected_device:
self.opts['device_name'] = self.get_connected_device_primary_name()
self.opts['mount_point'] = self.mount_point
return self.opts
def inflate_dialog_resources(self):
'''
Copy the dialog files to our resource directory
'''
self._log_location()
dialogs = []
with ZipFile(self.plugin_path, 'r') as zf:
for candidate in zf.namelist():
# Qt UI files
if candidate.startswith('dialogs/') and candidate.endswith('.ui'):
dialogs.append(candidate)
# Corresponding class definitions
if candidate.startswith('dialogs/') and candidate.endswith('.py'):
dialogs.append(candidate)
dr = self.load_resources(dialogs)
for dialog in dialogs:
if not dialog in dr:
continue
fs = os.path.join(self.resources_path, dialog)
if not os.path.exists(fs):
# If the file doesn't exist in the resources dir, add it
if not os.path.exists(os.path.dirname(fs)):
os.makedirs(os.path.dirname(fs))
with open(fs, 'wb') as f:
f.write(dr[dialog])
else:
# Is the .ui file current?
update_needed = False
with open(fs, 'r') as f:
if f.read() != dr[dialog]:
update_needed = True
if update_needed:
with open(fs, 'wb') as f:
f.write(dr[dialog])
def inflate_help_resources(self):
'''
Extract the help resources from the plugin
'''
help_resources = []
with ZipFile(self.plugin_path, 'r') as zf:
for candidate in zf.namelist():
if candidate == 'help/help.html' or candidate.startswith('help/images/'):
help_resources.append(candidate)
rd = self.load_resources(help_resources)
for resource in help_resources:
if not resource in rd:
continue
fs = os.path.join(self.resources_path, resource)
if os.path.isdir(fs) or fs.endswith('/'):
continue
if not os.path.exists(os.path.dirname(fs)):
os.makedirs(os.path.dirname(fs))
with open(fs, 'wb') as f:
f.write(rd[resource])
def init_logger(self):
"""
Create the logger with profiling support
"""
if DEBUG:
env = 'linux'
if isosx:
env = "OS X"
elif iswindows:
env = "Windows"
version = self.interface_action_base_plugin.version
title = "%s plugin %d.%d.%d" % (self.name, version[0], version[1], version[2])
self._log("{:~^80}".format(" %s (%s) " % (title, env)))
def init_options(self, disable_caching=False):
"""
Build an opts object with a ProgressBar
"""
opts = Struct(
disable_caching=plugin_prefs.get('cfg_disable_caching_checkbox', True),
gui=self.gui,
icon=get_icon(PLUGIN_ICONS[0]),
ios = self.ios,
parent=self,
prefs=plugin_prefs,
resources_path=self.resources_path,
verbose=DEBUG)
opts['pb'] = ProgressBar(parent=self.gui, window_title=self.name)
self._log_location("disable_caching: %s" % opts.disable_caching)
return opts
def init_prefs(self):
'''
Set the initial default values as needed
'''
pref_map = {
#'cfg_annotations_destination_comboBox': 'Comments',
#'cfg_annotations_destination_field': 'Comments',
'cfg_news_clippings_lineEdit': _('My News Clippings'),
'developer_mode': False,
'COMMENTS_DIVIDER': '· · • · ✦ · • · ·',
'HORIZONTAL_RULE': "<hr width='80%' />",
'plugin_version': "%d.%d.%d" % self.interface_action_base_plugin.version}
for pm in pref_map:
if not plugin_prefs.get(pm, None):
plugin_prefs.set(pm, pref_map[pm])
# Clean up existing JSON file < v1.3.0
if plugin_prefs.get('plugin_version', "0.0.0") < "1.3.0":
self._log_location("Updating prefs to %d.%d.%d" %
self.interface_action_base_plugin.version)
for obsolete_setting in ['cfg_annotations_destination_field',
'cfg_annotations_destination_comboBox']:
if plugin_prefs.get(obsolete_setting, None) is not None:
self._log("removing obsolete entry '{0}'".format(obsolete_setting))
plugin_prefs.__delitem__(obsolete_setting)
plugin_prefs.set('plugin_version', "%d.%d.%d" % self.interface_action_base_plugin.version)
def import_annotations(self, reader_app):
"""
Dispatch to reader_app_class handling exported annotations.
Generate a confidence index 0-4 based on matches
"""
self._log_location(reader_app)
supported_reader_apps = ReaderApp.get_reader_app_classes()
reader_app_class = supported_reader_apps[reader_app]
# Save a reference for merge_annotations
self.reader_app_class = reader_app_class
self.selected_mi = get_selected_book_mi(self.get_options(),
msg=self.SELECT_DESTINATION_MSG,
det_msg=self.SELECT_DESTINATION_DET_MSG)
if not self.selected_mi:
return
ra_confidence = reader_app_class.import_fingerprint
if ra_confidence or self.selected_mi is not None:
exporting_apps = iOSReaderApp.get_exporting_app_classes()
reader_app = exporting_apps[reader_app_class]
# Open the Import Annotations dialog
if reader_app_class.SUPPORTS_FILE_CHOOSER:
raw_data = ImportAnnotationsFileDialog(self, reader_app_class).text()
else:
raw_data = ImportAnnotationsTextDialog(self, reader_app, reader_app_class).text()
if(raw_data):
# Instantiate reader_app_class
rac = reader_app_class(self)
success = rac.parse_exported_highlights(raw_data)
if not success:
self._log("errors parsing data for import")
# Keep around for debugging.
# msg = QMessageBox()
# msg.setIcon(QMessageBox.Critical)
# msg.setText("Import Error")
# msg.setInformativeText('Error parsing data.')
# msg.setWindowTitle("Import Error")
# msg.exec_()
# Present the imported books, get a list of books to add to calibre
if rac.annotated_book_list:
self.present_annotated_books(rac, source="imported")
# subclass override
def initialization_complete(self):
self.rebuild_menus()
# Subscribe to device connection events
device_signals.device_connection_changed.connect(self.on_device_connection_changed)
def launch_library_scanner(self):
'''
Call IndexLibrary() to index current_db by uuid, title
Need a test to see if db has been updated since last run. Until then,
optimization disabled.
After indexing, self.library_scanner.uuid_map and .id_map are populated
'''
if (self.library_last_modified == self.gui.current_db.last_modified() and
self.indexed_library is self.gui.current_db and
self.library_indexed):
self._log_location("library index current")
else:
self._log_location("updating library index")
self.library_scanner = IndexLibrary(self)
self.library_scanner.signal.connect(self.library_index_complete)
QTimer.singleShot(1, self.start_library_indexing)
# subclass override
def library_changed(self, db):
self._log_location(current_library_name())
self.library_indexed = False
self.indexed_library = None
self.library_last_modified = None
def library_index_complete(self):
self._log_location()
self.library_indexed = True
self.indexed_library = self.gui.current_db
self.library_last_modified = self.gui.current_db.last_modified()
def load_dynamic_reader_classes(self):
'''
Load reader classes dynamically from readers/ folder in plugin zip file
Load additional classes under development from paths specified in config file
'''
self._log_location()
# Load the builtin classes
folder = 'readers/'
reader_app_classes = get_resource_files(self.plugin_path, folder=folder)
sample_classes = ['SampleExportingApp', 'SampleFetchingApp']
for rac in reader_app_classes:
basename = re.sub(folder, '', rac)
name = re.sub('readers/', '', rac).split('.')[0]
if name in sample_classes:
continue
tmp_file = os.path.join(tempfile.gettempdir(), plugin_tmpdir, basename)
if not os.path.exists(os.path.dirname(tmp_file)):
os.makedirs(os.path.dirname(tmp_file))
with open(tmp_file, 'wb') as tf:
tf.write(get_resources(rac))
self._log(" loading built-in class '%s'" % name)
imp.load_source(name, tmp_file)
os.remove(tmp_file)
# Load locally defined classes specified in config file
additional_readers = plugin_prefs.get('additional_readers', None)
sample_path = 'path/to/your/reader_class.py'
if additional_readers is None:
# Create an entry for editing
plugin_prefs.set('additional_readers', [sample_path])
else:
for ac in additional_readers:
if os.path.exists(ac):
name = os.path.basename(ac).split('.')[0]
name = re.sub('_', '', name)
self._log(" loading external class '%s'" % name)
try:
imp.load_source(name, ac)
except:
# If additional_class fails to import, exit
import traceback
traceback.print_exc()
raise SystemExit
elif ac != sample_path:
self._log(" unable to load external class from '%s' (file not found)" % ac)
def main_menu_button_clicked(self):
'''
'''
self.show_configuration()
def nuke_annotations(self):
db = self.gui.current_db
id = db.FIELD_MAP['id']
# Get all eligible custom fields
all_custom_fields = db.custom_field_keys()
self.custom_fields = {}
for custom_field in all_custom_fields:
field_md = db.metadata_for_field(custom_field)
if field_md['datatype'] in ['comments']:
self.custom_fields[field_md['name']] = {'field': custom_field,
'datatype': field_md['datatype']}
fields = ['Comments']
for cfn in self.custom_fields:
fields.append(cfn)
fields.sort()
# Warn the user that we're going to do it
title = _('Remove annotations?')
msg = self.format_as_paragraph(_("All existing annotations will be removed from {0}.").format(
', '.join(fields))) + self.format_as_paragraph(_("Proceed?"))
d = MessageBox(MessageBox.QUESTION,
title, msg,
show_copy_button=False)
if not d.exec_():
return
self._log_location("QUESTION: %s" % msg)
# Show progress
pb = ProgressBar(parent=self.gui, window_title=_("Removing annotations"), on_top=True)
total_books = len(db.data)
pb.set_maximum(total_books)
pb.set_value(0)
pb.set_label('{:^100}'.format(_("Scanning {0} of {1}").format(0, total_books)))
pb.show()
book_ids_updated = []
for i, record in enumerate(db.data.iterall()):
mi = db.get_metadata(record[id], index_is_id=True)
pb.set_label('{:^100}'.format(_("Scanning {0} of {1}").format(i, total_books)))
# Remove user_annotations from Comments
if mi.comments:
soup = BeautifulSoup(mi.comments)
uas = soup.find('div', 'user_annotations')
if uas:
uas.extract()
# Remove comments_divider from Comments
cd = soup.find('div', 'comments_divider')
if cd:
cd.extract()
# Save stripped Comments
mi.comments = unicode(soup)
# Update the record
db.set_metadata(record[id], mi, set_title=False, set_authors=False,
commit=True, force_changes=True, notify=True)
# Removed user_annotations from custom fields
for cfn in self.custom_fields:
cf = self.custom_fields[cfn]['field']
if True:
soup = BeautifulSoup(mi.get_user_metadata(cf, False)['#value#'])
uas = soup.findAll('div', 'user_annotations')