-
Notifications
You must be signed in to change notification settings - Fork 6
/
common_utils.py
2016 lines (1679 loc) · 71.3 KB
/
common_utils.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]>'
__docformat__ = 'restructuredtext en'
import base64, cStringIO, json, os, re, sys, time, traceback
from collections import defaultdict
from datetime import datetime
from lxml import etree
from threading import Thread, Timer
from time import sleep
#from zipfile import ZipFile
from calibre import browser, sanitize_file_name
from calibre.constants import __version__, iswindows, isosx
from calibre.devices.usbms.driver import debug_print
from calibre.ebooks.BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag
from calibre.ebooks.metadata import title_sort
from calibre.ebooks.metadata.book.base import Metadata
from calibre.gui2 import Application
from calibre.gui2.dialogs.message_box import MessageBox
from calibre.gui2.progress_indicator import ProgressIndicator
from calibre.library import current_library_name
from calibre.utils.config import config_dir
from calibre.utils.ipc import RC
from calibre.utils.zipfile import ZipFile, ZIP_STORED
try:
from PyQt5.Qt import (Qt, QAbstractItemModel, QAction, QApplication,
QCheckBox, QComboBox, QCursor, QDial, QDialog, QDialogButtonBox,
QDoubleSpinBox, QFont, QFrame, QIcon,
QKeySequence, QLabel, QLineEdit,
QPixmap, QProgressBar, QPushButton,
QRadioButton, QSizePolicy, QSlider, QSpinBox,
QThread, QTimer, QUrl,
QVBoxLayout,
pyqtSignal)
from PyQt5.QtWebKitWidgets import QWebView
from PyQt5.uic import compileUi
except ImportError as e:
from calibre.devices.usbms.driver import debug_print
debug_print("Error loading QT5: ", e)
from PyQt4.Qt import (Qt, QAbstractItemModel, QAction, QApplication,
QCheckBox, QComboBox, QCursor, QDial, QDialog, QDialogButtonBox,
QDoubleSpinBox, QFont, QFrame, QIcon,
QKeySequence, QLabel, QLineEdit,
QPixmap, QProgressBar, QPushButton,
QRadioButton, QSizePolicy, QSlider, QSpinBox,
QThread, QTimer, QUrl,
QVBoxLayout,
pyqtSignal)
from PyQt4.QtWebKit import QWebView
from PyQt4.uic import compileUi
try:
from calibre.gui2 import QVariant
del QVariant
except ImportError:
is_qt4 = False
convert_qvariant = lambda x: x
else:
is_qt4 = True
def convert_qvariant(x):
vt = x.type()
if vt == x.String:
return unicode(x.toString())
if vt == x.List:
return [convert_qvariant(i) for i in x.toList()]
return x.toPyObject()
# Stateful controls: (<class>,<list_name>,<get_method>,<default>,<set_method(s)>)
# multiple set_methods are chained, i.e. the results of the first call are passed to the second
# Currently a max of two chained CONTROL_SET methods are implemented, explicity for comboBox
CONTROLS = [
(QCheckBox, 'checkBox_controls', 'isChecked', False, 'setChecked'),
(QComboBox, 'comboBox_controls', 'currentText', '', ('findText', 'setCurrentIndex')),
(QDial, 'dial_controls', 'value', 0, 'setValue'),
(QDoubleSpinBox, 'doubleSpinBox_controls', 'value', 0, 'setValue'),
(QLineEdit, 'lineEdit_controls', 'text', '', 'setText'),
(QRadioButton, 'radioButton_controls', 'isChecked', False, 'setChecked'),
(QSlider, 'slider_controls', 'value', 0, 'setValue'),
(QSpinBox, 'spinBox_controls', 'value', 0, 'setValue'),
]
CONTROL_CLASSES = [control[0] for control in CONTROLS]
CONTROL_TYPES = [control[1] for control in CONTROLS]
CONTROL_GET = [control[2] for control in CONTROLS]
CONTROL_DEFAULT = [control[3] for control in CONTROLS]
CONTROL_SET = [control[4] for control in CONTROLS]
plugin_tmpdir = 'calibre_annotations_plugin'
plugin_icon_resources = {}
''' Constants '''
EMPTY_STAR = u'\u2606'
FULL_STAR = u'\u2605'
''' Base classes '''
class Logger():
'''
A self-modifying class to print debug statements.
If disabled in prefs, methods are neutered at first call for performance optimization
'''
LOCATION_TEMPLATE = "{cls}:{func}({arg1}) {arg2}"
def _log(self, msg=None):
'''
Upon first call, switch to appropriate method
'''
from calibre_plugins.marvin_manager.config import plugin_prefs
if not plugin_prefs.get('debug_plugin', False):
# Neuter the method
self._log = self.__null
self._log_location = self.__null
else:
# Log the message, then switch to real method
if msg:
debug_print(" {0}".format(str(msg)))
else:
debug_print()
self._log = self.__log
self._log_location = self.__log_location
def __log(self, msg=None):
'''
The real method
'''
if msg:
debug_print(" {0}".format(str(msg)))
else:
debug_print()
def _log_location(self, *args):
'''
Upon first call, switch to appropriate method
'''
from calibre_plugins.marvin_manager.config import plugin_prefs
if not plugin_prefs.get('debug_plugin', False):
# Neuter the method
self._log = self.__null
self._log_location = self.__null
else:
# Log the message from here so stack trace is valid
arg1 = arg2 = ''
if len(args) > 0:
arg1 = str(args[0])
if len(args) > 1:
arg2 = str(args[1])
debug_print(self.LOCATION_TEMPLATE.format(cls=self.__class__.__name__,
func=sys._getframe(1).f_code.co_name,
arg1=arg1, arg2=arg2))
# Switch to real method
self._log = self.__log
self._log_location = self.__log_location
def __log_location(self, *args):
'''
The real method
'''
arg1 = arg2 = ''
if len(args) > 0:
arg1 = str(args[0])
if len(args) > 1:
arg2 = str(args[1])
debug_print(self.LOCATION_TEMPLATE.format(cls=self.__class__.__name__,
func=sys._getframe(1).f_code.co_name,
arg1=arg1, arg2=arg2))
def __null(self, *args, **kwargs):
'''
Optimized method when logger is silent
'''
pass
class Book(Metadata):
'''
A simple class describing a book
See ebooks.metadata.book.base #46
'''
# 14 standard field keys from Metadata
mxd_standard_keys = ['author_sort', 'authors', 'comments', 'device_collections',
'last_updated', 'pubdate', 'publisher', 'rating', 'series',
'series_index', 'tags', 'title', 'title_sort', 'uuid']
# 19 private field keys
mxd_custom_keys = ['articles', 'cid', 'calibre_collections', 'cover_file',
'date_added', 'date_opened', 'deep_view_prepared',
'flags', 'hash', 'highlights', 'match_quality',
'metadata_mismatches', 'mid', 'on_device', 'path', 'pin',
'progress', 'vocabulary', 'word_count']
def __init__(self, title, author):
if type(author) is list:
Metadata.__init__(self, title, authors=author)
else:
Metadata.__init__(self, title, authors=[author])
def __eq__(self, other):
all_mxd_keys = self.mxd_standard_keys + self.mxd_custom_keys
for attr in all_mxd_keys:
v1, v2 = [getattr(obj, attr, object()) for obj in [self, other]]
if v1 is object() or v2 is object():
return False
elif v1 != v2:
return False
return True
def __ne__(self, other):
all_mxd_keys = self.mxd_standard_keys + self.mxd_custom_keys
for attr in all_mxd_keys:
v1, v2 = [getattr(obj, attr, object()) for obj in [self, other]]
if v1 is object() or v2 is object():
return True
elif v1 != v2:
return True
return False
def title_sorter(self):
return title_sort(self.title)
class MyAbstractItemModel(QAbstractItemModel):
def __init__(self, *args):
QAbstractItemModel.__init__(self, *args)
class Struct(dict):
"""
Create an object with dot-referenced members or dictionary
"""
def __init__(self, **kwds):
dict.__init__(self, kwds)
self.__dict__ = self
def __repr__(self):
return '\n'.join([" %s: %s" % (key, repr(self[key])) for key in sorted(self.keys())])
class AnnotationStruct(Struct):
"""
Populate an empty annotation structure with fields for all possible values
"""
def __init__(self):
super(AnnotationStruct, self).__init__(
annotation_id=None,
book_id=None,
epubcfi=None,
genre=None,
highlight_color=None,
highlight_text=None,
last_modification=None,
location=None,
location_sort=None,
note_text=None,
reader=None,
)
class BookStruct(Struct):
"""
Populate an empty book structure with fields for all possible values
"""
def __init__(self):
super(BookStruct, self).__init__(
active=None,
author=None,
author_sort=None,
book_id=None,
genre='',
last_annotation=None,
path=None,
title=None,
title_sort=None,
uuid=None
)
class SizePersistedDialog(QDialog):
'''
This dialog is a base class for any dialogs that want their size/position
restored when they are next opened.
'''
def __init__(self, parent, unique_pref_name, stays_on_top=False):
if stays_on_top:
QDialog.__init__(self, parent.opts.gui, Qt.WindowStaysOnTopHint)
else:
QDialog.__init__(self, parent.opts.gui)
self.unique_pref_name = unique_pref_name
self.prefs = parent.opts.prefs
self.geom = self.prefs.get(unique_pref_name, None)
self.finished.connect(self.dialog_closing)
# Hook ESC key
self.esc_action = a = QAction(self)
self.addAction(a)
a.triggered.connect(self.esc)
a.setShortcuts([QKeySequence('Esc', QKeySequence.PortableText)])
def dialog_closing(self, result):
geom = bytearray(self.saveGeometry())
self.prefs.set(self.unique_pref_name, geom)
def esc(self, *args):
pass
def resize_dialog(self):
if self.geom is None:
self.resize(self.sizeHint())
else:
self.restoreGeometry(self.geom)
''' Exceptions '''
class AbortRequestException(Exception):
'''
'''
pass
class DeviceNotMountedException(Exception):
''' '''
pass
''' Dialogs '''
class HelpView(SizePersistedDialog):
'''
Modeless dialog for presenting HTML help content
'''
def __init__(self, parent, icon, prefs, html=None, page=None, title=''):
self.prefs = prefs
#QDialog.__init__(self, parent=parent)
super(HelpView, self).__init__(parent, 'help_dialog')
self.setWindowTitle(title)
self.setWindowIcon(icon)
self.l = QVBoxLayout(self)
self.setLayout(self.l)
self.wv = QWebView()
if html is not None:
self.wv.setHtml(html)
elif page is not None:
self.wv.load(QUrl(page))
self.wv.setMinimumHeight(100)
self.wv.setMaximumHeight(16777215)
self.wv.setMinimumWidth(400)
self.wv.setMaximumWidth(16777215)
self.wv.setGeometry(0, 0, 400, 100)
self.wv.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.l.addWidget(self.wv)
# Sizing
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
self.setSizePolicy(sizePolicy)
self.resize_dialog()
class MyBlockingBusy(QDialog):
NORMAL = 0
REQUESTED = 1
ACKNOWLEDGED = 2
def __init__(self, gui, msg, size=100, window_title='Marvin XD', show_cancel=False,
on_top=False):
flags = Qt.FramelessWindowHint
if on_top:
flags = Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
QDialog.__init__(self, gui, flags)
self._layout = QVBoxLayout()
self.setLayout(self._layout)
self.cancel_status = 0
self.is_running = False
# Add the spinner
self.pi = ProgressIndicator(self)
self.pi.setDisplaySize(size)
self._layout.addSpacing(15)
self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
self._layout.addSpacing(15)
# Fiddle with the message
self.msg = QLabel(msg)
#self.msg.setWordWrap(True)
self.font = QFont()
self.font.setPointSize(self.font.pointSize() + 2)
self.msg.setFont(self.font)
self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
sp = QSizePolicy()
sp.setHorizontalStretch(True)
sp.setVerticalStretch(False)
sp.setHeightForWidth(False)
self.msg.setSizePolicy(sp)
self.msg.setMinimumHeight(self.font.pointSize() + 8)
#self.msg.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self._layout.addSpacing(15)
if show_cancel:
self.bb = QDialogButtonBox()
self.cancel_button = QPushButton(QIcon(I('window-close.png')), 'Cancel')
self.bb.addButton(self.cancel_button, self.bb.RejectRole)
self.bb.clicked.connect(self.button_handler)
self._layout.addWidget(self.bb)
self.setWindowTitle(window_title)
self.resize(self.sizeHint())
def accept(self):
self.stop()
return QDialog.accept(self)
def button_handler(self, button):
'''
Only change cancel_status from NORMAL to REQUESTED
'''
if self.bb.buttonRole(button) == QDialogButtonBox.RejectRole:
if self.cancel_status == self.NORMAL:
self.cancel_status = self.REQUESTED
self.cancel_button.setEnabled(False)
def reject(self):
'''
Cannot cancel this dialog manually
'''
pass
def set_text(self, text):
self.msg.setText(text)
def start(self):
self.is_running = True
self.pi.startAnimation()
def stop(self):
self.is_running = False
self.pi.stopAnimation()
class ProgressBar(QDialog, Logger):
def __init__(self,
alignment=Qt.AlignHCenter, frameless=True, label='Label goes here',
max_items=100, on_top=False, parent=None, window_title='Progress Bar'
):
if on_top:
_flags = Qt.WindowStaysOnTopHint
if frameless:
_flags |= Qt.FramelessWindowHint
QDialog.__init__(self, parent=parent,
flags=_flags)
else:
_flags = Qt.Dialog
if frameless:
_flags |= Qt.FramelessWindowHint
QDialog.__init__(self, parent=parent,
flags=_flags)
self.application = Application
self.setWindowTitle(window_title)
self.l = QVBoxLayout(self)
self.setLayout(self.l)
if frameless and window_title:
# Add a label with window title
self.title = QLabel(window_title)
self.title.setAlignment(Qt.AlignHCenter)
self.font = QFont()
self.font.setPointSize(self.font.pointSize() + 2)
self.font.setBold(True)
self.title.setFont(self.font)
self.l.addWidget(self.title)
self.hl = QFrame()
self.hl.setFrameShape(QFrame.HLine)
self.hl.setFrameShadow(QFrame.Sunken)
self.l.addWidget(self.hl)
else:
self.setWindowTitle(window_title)
self.label = QLabel(label)
self.label.setAlignment(alignment)
self.font = QFont()
self.font.setPointSize(self.font.pointSize() + 2)
self.label.setFont(self.font)
self.l.addWidget(self.label)
self.l.addSpacing(15)
self.progressBar = QProgressBar(self)
self.progressBar.setRange(0, max_items)
self.progressBar.setMinimum(0)
self.progressBar.setMaximum(0)
self.progressBar.setValue(0)
self.l.addWidget(self.progressBar)
self.l.addSpacing(15)
self.close_requested = False
self.resize(self.sizeHint())
def closeEvent(self, event):
self._log_location()
self.close_requested = True
def get_pct_complete(self):
pct_complete = float(self.progressBar.value() / self.progressBar.maximum())
return int(pct_complete * 100)
def increment(self):
try:
if self.progressBar.value() < self.progressBar.maximum():
self.progressBar.setValue(self.progressBar.value() + 1)
self.refresh()
except:
self._log_location()
import traceback
self._log(traceback.format_exc())
def refresh(self):
self.application.processEvents()
def set_label(self, value):
self.label.setText(value)
self.resize(self.sizeHint())
self.label.repaint()
self.refresh()
def set_maximum(self, value):
self.progressBar.setMaximum(value)
self.refresh()
def set_range(self, min, max):
self.progressBar.setRange(min, max)
self.refresh()
def set_value(self, value):
self.progressBar.setValue(value)
self.progressBar.repaint()
self.refresh()
''' Threads '''
class IndexLibrary(QThread):
'''
Build indexes of library:
title_map: {title: {'authors':…, 'id':…, 'uuid:'…}, …}
uuid_map: {uuid: {'author's:…, 'id':…, 'title':…, 'path':…}, …}
id_map: {id: {'uuid':…, 'author':…}, …}
'''
signal = pyqtSignal(object)
def __init__(self, parent):
QThread.__init__(self, parent)
# self.signal = SIGNAL("library_index_complete")
self.cdb = parent.opts.gui.current_db
self.id_map = None
self.hash_map = None
self.active_virtual_library = None
def run(self):
self.title_map = self.index_by_title()
self.uuid_map = self.index_by_uuid()
# self.emit(self.signal)
self.signal.emit("library_index_complete")
def add_to_hash_map(self, hash, uuid):
'''
When a book has been bound to a calibre uuid, we need to add it to the hash map
'''
if hash not in self.hash_map:
self.hash_map[hash] = [uuid]
else:
self.hash_map[hash].append(uuid)
def build_hash_map(self):
'''
Generate a reverse dict of hash:[uuid] from self.uuid_map
Allow for multiple uuids with same hash (dupes)
Hashes are added to uuid_map in book_status:_scan_library_books()
'''
hash_map = {}
for uuid, v in self.uuid_map.items():
try:
if v['hash'] not in hash_map:
hash_map[v['hash']] = [uuid]
else:
hash_map[v['hash']].append(uuid)
except:
# Book deleted since scan
pass
self.hash_map = hash_map
return hash_map
def index_by_title(self):
'''
By default, any search restrictions or virtual libraries are applied
calibre.db.view:search_getting_ids()
'''
by_title = {}
cids = self.cdb.search_getting_ids('formats:EPUB', '')
for cid in cids:
title = self.cdb.title(cid, index_is_id=True)
by_title[title] = {
'authors': self.cdb.authors(cid, index_is_id=True).split(','),
'id': cid,
'uuid': self.cdb.uuid(cid, index_is_id=True)
}
return by_title
def index_by_uuid(self):
'''
By default, any search restrictions or virtual libraries are applied
calibre.db.view:search_getting_ids()
'''
by_uuid = {}
cids = self.cdb.search_getting_ids('formats:EPUB', '')
for cid in cids:
uuid = self.cdb.uuid(cid, index_is_id=True)
by_uuid[uuid] = {
'authors': self.cdb.authors(cid, index_is_id=True).split(','),
'id': cid,
'title': self.cdb.title(cid, index_is_id=True),
}
return by_uuid
class InventoryCollections(QThread):
'''
Build a list of books with collection assignments
'''
signal = pyqtSignal(object)
def __init__(self, parent):
QThread.__init__(self, parent)
# self.signal = SIGNAL("collection_inventory_complete")
self.cdb = parent.opts.gui.current_db
self.cfl = get_cc_mapping('collections', 'field', None)
self.ids = []
#self.heatmap = {}
def run(self):
self.inventory_collections()
# self.emit(self.signal)
self.signal.emit("collection_inventory_complete")
def inventory_collections(self):
id = self.cdb.FIELD_MAP['id']
if self.cfl is not None:
for record in self.cdb.data.iterall():
mi = self.cdb.get_metadata(record[id], index_is_id=True)
collection_list = mi.get_user_metadata(self.cfl, False)['#value#']
if collection_list:
# Add this cid to list of library books with active collection assignments
self.ids.append(record[id])
if False:
# Update the heatmap
for ca in collection_list:
if ca not in self.heatmap:
self.heatmap[ca] = 1
else:
self.heatmap[ca] += 1
class MoveBackup(QThread, Logger):
'''
Move a (potentially large) backup file from connected device to local fs
'''
TIMER_TICK = 0.25
def __init__(self, **kwargs):
'''
kwargs: {'backup_folder', 'destination_folder', 'ios',
'parent', 'pb', 'storage_name', 'stats', total_seconds}
'''
self._log_location()
try:
for key in kwargs:
setattr(self, key, kwargs.get(key))
QThread.__init__(self, self.parent)
for prop in ['iosra_booklist', 'mxd_mainDb_profile', 'mxd_device_cached_hashes',
'mxd_installed_books', 'mxd_remote_content_hashes', 'success',
'timer']:
setattr(self, prop, None)
self.dst = os.path.join(self.destination_folder,
sanitize_file_name(self.storage_name))
self.src = b"{0}/marvin.backup".format(self.backup_folder)
self._init_pb()
except:
import traceback
self._log(traceback.format_exc())
def run(self):
try:
backup_size = "{:,} MB".format(int(int(self.src_stats['st_size'])/(1024*1024)))
self._log_location()
self._log("moving {0} to '{1}'".format(backup_size, self.destination_folder))
start_time = time.time()
# Remove any older file of the same name at destination
if os.path.isfile(self.dst):
os.remove(self.dst)
# Copy from the iDevice to destination
with open(self.dst, 'wb') as out:
self.ios.copy_from_idevice(self.src, out)
# Validate transferred file sizes, do cleanup
self._verify()
self.transfer_time = time.time() - start_time
# Append MXD components
self._append_mxd_components()
self._cleanup()
except:
self.pb.close()
import traceback
self._log(traceback.format_exc())
def _append_mxd_components(self):
self._log_location()
if (self.iosra_booklist or
self.mxd_mainDb_profile or
self.mxd_device_cached_hashes or
self.mxd_installed_books or
self.mxd_remote_content_hashes):
start_time = time.time()
with ZipFile(self.dst, mode='a') as zfa:
if self.iosra_booklist:
zfa.write(self.iosra_booklist, arcname="iosra_booklist.zip")
if self.mxd_mainDb_profile:
zfa.writestr("mxd_mainDb_profile.json",
json.dumps(self.mxd_mainDb_profile, sort_keys=True))
if self.mxd_device_cached_hashes:
base_name = "mxd_cover_hashes.json"
zfa.write(self.mxd_device_cached_hashes, arcname=base_name)
if self.mxd_installed_books:
base_name = "mxd_installed_books.json"
zfa.writestr(base_name, self.mxd_installed_books)
if self.mxd_remote_content_hashes:
from calibre_plugins.marvin_manager.book_status import BookStatusDialog
base_name = "mxd_{0}".format(BookStatusDialog.HASH_CACHE_FS)
zfa.write(self.mxd_remote_content_hashes, arcname=base_name)
self.sidecar_time = time.time() - start_time
else:
self.sidecar_time = 0
def _cleanup(self):
self._log_location()
try:
self.ios.remove(self.src)
self.ios.remove(self.backup_folder)
self.timer.cancel()
except:
import traceback
self._log(traceback.format_exc())
def _init_pb(self):
self._log_location()
try:
max = int(self.total_seconds/self.TIMER_TICK) + 1
self.pb.set_maximum(max)
self.pb.set_range(0, max)
self.timer = Timer(self.TIMER_TICK, self._ticked)
self.timer.start()
except:
import traceback
self._log(traceback.format_exc())
def _ticked(self):
'''
Increment the progress bar, restart the timer
Don't let it get to 100%
'''
try:
if self.pb.progressBar.value() < self.pb.progressBar.maximum() - 1:
self.pb.increment()
self.timer = Timer(self.TIMER_TICK, self._ticked)
self.timer.start()
except:
import traceback
self._log(traceback.format_exc())
def _verify(self):
'''
Confirm that the file was properly transferred
'''
src_size = int(self.src_stats['st_size'])
dst_size = os.stat(self.dst).st_size
self.success = (src_size == dst_size)
self._log_location('backup verified' if self.success else '')
if not self.success:
self._log("file sizes did not match:")
self._log("src_size: {0}".format(src_size))
self._log("dst_size: {0}".format(dst_size))
class PluginMetricsLogger(Thread, Logger):
'''
Post an event to the logging server
'''
# #mark ~~~ logging URL ~~~
#URL = "http://localhost:8378"
URL = "http://calibre-plugins.com:7584"
def __init__(self, **args):
Thread.__init__(self)
self.args = args
self.construct_header()
def construct_header(self):
'''
Build the default header information describing the environment plus the passed
plugin metadata
'''
import mechanize
self.req = mechanize.Request(self.URL)
self.req.add_header('CALIBRE_OS', 'Windows' if iswindows else 'OS X' if isosx else 'other')
self.req.add_header('CALIBRE_VERSION', __version__)
self.req.add_header('CALIBRE_PLUGIN', self.args.get('plugin'))
self.req.add_header('PLUGIN_VERSION', self.args.get('version'))
def run(self):
br = browser()
try:
ans = br.open(self.req).read().strip()
self._log_location(ans)
except Exception as e:
import traceback
self._log(traceback.format_exc())
class RestoreBackup(QThread, Logger):
'''
Copy a (potentially large) backup file from local fs to connected device
ProgressBar needs to be created from main GUI thread
'''
TIMER_TICK = 0.25
def __init__(self, **kwargs):
'''
kwargs: {'backup_image', 'ios', 'msg', 'parent', 'pb', 'total_seconds'}
'''
self._log_location()
try:
for key in kwargs:
setattr(self, key, kwargs.get(key))
QThread.__init__(self, self.parent)
self.src_size = os.stat(self.backup_image).st_size
self.success = None
self.timer = None
self._init_pb()
except:
import traceback
self._log(traceback.format_exc())
def run(self):
self._log_location()
try:
tmp = b'/'.join(['/Documents', 'restore_image.tmp'])
self.dst = b'/'.join(['/Documents', 'marvin.backup'])
self.ios.copy_to_idevice(self.backup_image, tmp)
self.ios.rename(tmp, self.dst)
self._verify()
self._cleanup()
except:
import traceback
self._log(traceback.format_exc())
def _cleanup(self):
self._log_location()
try:
self.timer.cancel()
except:
import traceback
self._log(traceback.format_exc())
def _init_pb(self):
self._log_location()
try:
max = int(self.total_seconds/self.TIMER_TICK)
self.pb.set_maximum(max)
self.pb.set_range(0, max)
self.timer = Timer(self.TIMER_TICK, self._ticked)
self.timer.start()
except:
import traceback
self._log(traceback.format_exc())
def _ticked(self):
'''
Increment the progress bar, restart the timer
Don't let it get to 100%
'''
try:
if self.pb.progressBar.value() < self.pb.progressBar.maximum() - 1:
self.pb.increment()
self.timer = Timer(self.TIMER_TICK, self._ticked)
self.timer.start()
except:
import traceback
self._log(traceback.format_exc())
def _verify(self):
'''
Confirm source size == dest size
'''
self._log_location()
try:
self.dst_size = int(self.ios.exists(self.dst)['st_size'])
except:
self.dst_size = -1
if self.src_size != self.dst_size:
self.success = False
self.ios.remove(self.dst)
else:
self.success = True
class RowFlasher(QThread):
'''
Flash rows_to_flash to show where ops occurred
'''
signal = pyqtSignal(object)
def __init__(self, parent, model, rows_to_flash):
QThread.__init__(self)
# self.signal = SIGNAL("flasher_complete")
self.model = model
self.parent = parent
self.rows_to_flash = rows_to_flash
self.mode = 'old'
self.cycles = self.parent.prefs.get('flasher_cycles', 3) + 1
self.new_time = self.parent.prefs.get('flasher_new_time', 300)
self.old_time = self.parent.prefs.get('flasher_old_time', 100)
def run(self):
QTimer.singleShot(self.old_time, self.update)
while self.cycles:
QApplication.processEvents()
# self.emit(self.signal)
self.signal.emit("flasher_complete")
def toggle_values(self, mode):
for row, item in self.rows_to_flash.items():
self.model.set_match_quality(row, item[mode])
def update(self):
if self.mode == 'new':
self.toggle_values('old')
self.mode = 'old'
QTimer.singleShot(self.old_time, self.update)
elif self.mode == 'old':
self.toggle_values('new')
self.mode = 'new'
self.cycles -= 1