-
Notifications
You must be signed in to change notification settings - Fork 6
/
action.py
2900 lines (2502 loc) · 126 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 <griker@hotmail.com>'
__docformat__ = 'restructuredtext en'
import atexit, cPickle as pickle, glob, hashlib, json, os, re, shutil, sqlite3, sys
import tempfile, threading, time
from datetime import datetime
from dateutil import tz
from functools import partial
from lxml import etree, html
try:
from PyQt5.Qt import (Qt, QApplication, QCursor, QFileDialog, QFont, QIcon,
QMenu, QTimer, QUrl,
pyqtSignal)
except ImportError:
from PyQt4.Qt import (Qt, QApplication, QCursor, QFileDialog, QFont, QIcon,
QMenu, QTimer, QUrl,
pyqtSignal)
from calibre import browser
from calibre.constants import DEBUG
from calibre.customize.ui import device_plugins, disabled_device_plugins
from calibre.devices.idevice.libimobiledevice import libiMobileDevice
from calibre.devices.usbms.driver import debug_print
from calibre.ebooks.BeautifulSoup import BeautifulSoup, UnicodeDammit
from calibre.gui2 import Application, info_dialog, open_url, question_dialog, warning_dialog
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.device import device_signals
from calibre.gui2.dialogs.message_box import MessageBox
from calibre.library import current_library_name
from calibre.ptempfile import (PersistentTemporaryDirectory, PersistentTemporaryFile,
TemporaryDirectory, TemporaryFile)
from calibre.utils.config import config_dir, JSONConfig
from calibre.utils.zipfile import ZipFile, ZIP_STORED, is_zipfile
from calibre_plugins.marvin_manager import MarvinManagerPlugin
from calibre_plugins.marvin_manager.annotations_db import AnnotationsDB
from calibre_plugins.marvin_manager.book_status import BookStatusDialog
from calibre_plugins.marvin_manager.common_utils import (AbortRequestException,
Book, CommandHandler, CompileUI, IndexLibrary, Logger,
MoveBackup, MyBlockingBusy, PluginMetricsLogger,
ProgressBar, RestoreBackup, Struct,
from_json, get_icon, set_plugin_icon_resources, to_json, updateCalibreGUIView)
import calibre_plugins.marvin_manager.config as cfg
#from calibre_plugins.marvin_manager.dropbox import PullDropboxUpdates
# The first icon is the plugin icon, referenced by position.
# The rest of the icons are referenced by name
PLUGIN_ICONS = ['images/connected.png', 'images/disconnected.png']
class MarvinManagerAction(InterfaceAction, Logger):
INSTALLED_BOOKS_SNAPSHOT = "installed_books.zip"
REMOTE_CACHE_FOLDER = '/'.join(['/Library', 'calibre.mm'])
UTF_8_BOM = r'\xef\xbb\xbf'
icon = PLUGIN_ICONS[0]
# #mark ~~~ Minimum iOSRA version required ~~~
minimum_ios_driver_version = (1, 3, 6)
name = 'Marvin XD'
prefs = cfg.plugin_prefs
verbose = prefs.get('debug_plugin', False)
# Declare the main action associated with this plugin
action_spec = ('Marvin XD', None, None, None)
#popup_type = QToolButton.InstantPopup
action_add_menu = True
action_menu_clone_qaction = True
marvin_device_status_changed = pyqtSignal(dict)
plugin_device_connection_changed = pyqtSignal(object)
def about_to_show_menu(self):
self.rebuild_menus()
def compare_mainDb_profiles(self, stored_mainDb_profile):
'''
'''
current_mainDb_profile = self.profile_db()
matched = True
for key in sorted(current_mainDb_profile.keys()):
if current_mainDb_profile[key] != stored_mainDb_profile[key]:
matched = False
break
# Display mainDb_profile mismatch
if not matched:
self._log_location()
self._log(" {0:20} {1:37} {2:37}".format('key', 'stored', 'current'))
self._log("{0:—^23} {1:—^37} {2:—^37}".format('', '', ''))
self._log("{0} {1:20} {2:<37} {3:<37}".format(
'x' if stored_mainDb_profile['device'] != current_mainDb_profile['device'] else ' ',
'device',
stored_mainDb_profile['device'],
current_mainDb_profile['device']))
keys = current_mainDb_profile.keys()
keys.pop(keys.index('device'))
for key in sorted(keys):
self._log("{0} {1:20} {2:<37} {3:<37}".format(
'x' if stored_mainDb_profile[key] != current_mainDb_profile[key] else ' ',
key,
repr(stored_mainDb_profile[key]),
repr(current_mainDb_profile[key])))
return matched
def create_remote_backup(self):
'''
iPad1: 500 books in 90 seconds - 5.5 books/second
iPad Mini: 500 books in 64 seconds - 7.8 books/second
1) Issue backup command to Marvin
2) Get destination directory
3) Move generated backup from /Documents/Backup to local storage
'''
IOS_READ_RATE = 7500000 # 11.8 - 16 MB/sec OS X, Windows 6.6MB
TIMEOUT_PADDING_FACTOR = 1.5
WORST_CASE_ARCHIVE_RATE = 1800000 # MB/second
backup_folder = b'/'.join(['/Documents', 'Backup'])
backup_target = backup_folder + '/marvin.backup'
last_backup_folder = self.prefs.get('backup_folder', os.path.expanduser("~"))
def _confirm_overwrite(backup_target):
'''
Check for existing backup before overwriting
stats['st_mtime'], stats['st_size']
Return True: continue
Return False: cancel
'''
stats = self.ios.exists(backup_target, silent=True)
if stats:
d = datetime.fromtimestamp(float(stats['st_mtime']))
friendly_date = d.strftime("%A, %B %d, %Y")
friendly_time = d.strftime("%I:%M %p")
title = "A backup already exists!"
msg = ('<p>There is an existing backup of your Marvin library '
'created {0} at {1}.</p>'
'<p>Proceeding with this backup will '
'overwrite the existing backup.</p>'
'<p>Proceed?</p>'.format(friendly_date, friendly_time))
dlg = MessageBox(MessageBox.QUESTION, title, msg,
parent=self.gui, show_copy_button=False)
return dlg.exec_()
return True
def _confirm_lengthy_backup(total_books, total_seconds):
'''
If this is going to take some time, warn the user
'''
estimated_time = self.format_time(total_seconds, show_fractional=False)
self._log("estimated time to backup {0} books: {1}".format(
total_books, estimated_time))
# Confirm that user wants to proceed given estimated time to completion
book_descriptor = "books" if total_books > 1 else "book"
title = "Estimated time to create backup"
msg = ("<p>Creating a backup of " +
"{0:,} {1} in your Marvin library ".format(total_books, book_descriptor) +
"may take as long as {0}, depending on your iDevice.</p>".format(estimated_time) +
"<p>Proceed?</p>")
dlg = MessageBox(MessageBox.QUESTION, title, msg,
parent=self.gui, show_copy_button=False)
return dlg.exec_()
def _estimate_size():
'''
Estimate uncompressed size of backup
backup.xml approximately 4kB
'''
SMALL_COVER_AVERAGE = 25000
LARGE_COVER_AVERAGE = 100000
estimated_size = 0
books_size = 0
for book in self.connected_device.cached_books:
books_size += self.connected_device.cached_books[book]['size']
books_size += SMALL_COVER_AVERAGE
books_size += LARGE_COVER_AVERAGE
estimated_size += books_size
# Add size of mainDb
mdbs = os.stat(self.connected_device.local_db_path).st_size
estimated_size += mdbs
self._log("estimated size of uncompressed backup: {:,}".format(estimated_size))
return estimated_size
# ~~~ Entry point ~~~
self._log_location()
analytics = []
mainDb_profile = self.profile_db()
estimated_size = _estimate_size()
total_seconds = int(estimated_size/WORST_CASE_ARCHIVE_RATE)
timeout = int(total_seconds * TIMEOUT_PADDING_FACTOR)
estimated_time = self.format_time(total_seconds)
if timeout > CommandHandler.WATCHDOG_TIMEOUT:
if not _confirm_lengthy_backup(mainDb_profile['Books'], total_seconds):
return
else:
timeout = CommandHandler.WATCHDOG_TIMEOUT
if not _confirm_overwrite(backup_target):
self._log("user declined to overwrite existing backup")
return
# Construct the phase 1 ProgressBar
busy_panel_args = {'book_count': mainDb_profile['Books'],
'destination': 'destination folder',
'device': self.ios.device_name,
'estimated_time': estimated_time}
BACKUP_MSG_1 = ('<ol style="margin-right:1.5em">'
'<li style="margin-bottom:0.5em">Preparing backup of '
'{book_count:,} books …</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Select destination folder to store backup</li>'
'<li style="color:#bbb">Move backup from {device} to {destination}</li>'
'</ol>')
pb = ProgressBar(alignment=Qt.AlignLeft,
label=BACKUP_MSG_1.format(**busy_panel_args),
parent=self.gui,
window_title="Creating backup of {0}".format(self.ios.device_name))
# Init the command handler
ch = CommandHandler(self, pb=pb)
ch.init_pb(total_seconds)
ch.construct_general_command('backup')
start_time = time.time()
# Dispatch the command
pb.show()
ch.issue_command(timeout_override=timeout)
pb.hide()
actual_time = time.time() - start_time
args = {'estimated_size': estimated_size,
'book_count': mainDb_profile['Books'],
'estimated_time': self.format_time(total_seconds),
'actual_time': self.format_time(actual_time),
'pct_complete': pb.get_pct_complete(),
'archive_rate': estimated_size/actual_time,
'estimated_archive_rate': WORST_CASE_ARCHIVE_RATE}
analytics.append((
'1. Preparing backup\n'
' estimated size: {estimated_size:,}\n'
' book count: {book_count:,}\n'
' estimated time: {estimated_time}\n'
' actual time: {actual_time} ({pct_complete}%)\n'
' est. archive rate: {estimated_archive_rate:,}\n'
' actual archive rate: {archive_rate:,.0f} bytes/second\n'
).format(**args))
del pb
if ch.results['code']:
self._log("results: %s" % ch.results)
title = "Backup unsuccessful"
msg = ('<p>Unable to create backup of {0}.</p>'
'<p>Click <b>Show details</b> for more information.</p>').format(
self.ios.device_name)
det_msg = ch.results['details'] + '\n\n'
det_msg += self.format_device_profile()
# Set dialog det_msg to monospace
dialog = warning_dialog(self.gui, title, msg, det_msg=det_msg)
font = QFont('monospace')
font.setFixedPitch(True)
dialog.det_msg.setFont(font)
dialog.exec_()
return
# Move backup to the specified location
stats = self.ios.exists(backup_target)
if stats:
dn = self.ios.device_name
d = datetime.fromtimestamp(float(stats['st_mtime']))
storage_name = "{0} {1}.backup".format(
self.ios.device_name, d.strftime("%Y-%m-%d"))
destination_folder = str(QFileDialog.getExistingDirectory(
self.gui,
"Select destination folder to store backup",
last_backup_folder,
QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks))
if destination_folder:
# Qt apparently sometimes returns a file within the selected directory,
# rather than the directory itself. Validate destination_folder
if not os.path.isdir(destination_folder):
destination_folder = os.path.dirname(destination_folder)
# Display status
busy_panel_args['backup_size'] = int(int(stats['st_size'])/(1024*1024))
busy_panel_args['destination'] = destination_folder
BACKUP_MSG_3 = ('<ol style="margin-right:1.5em">'
'<li style="color:#bbb;margin-bottom:0.5em">Backup of {book_count:,} '
'books prepared</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Destination folder selected</li>'
'<li>Moving backup ({backup_size:,} MB) '
'from {device} to<br/>{destination} …</li>'
'</ol>')
# Create the ProgressBar in the main GUI thread
pb = ProgressBar(parent=self.gui, window_title="Moving backup",
alignment=Qt.AlignLeft)
pb.set_label(BACKUP_MSG_3.format(**busy_panel_args))
# Merge MXD state with backup image
temp_dir = PersistentTemporaryDirectory()
zip_dst = os.path.join(destination_folder, storage_name)
# Init the class
transfer_estimate = int(stats['st_size']) / IOS_READ_RATE
if transfer_estimate < 100 * 1024 * 1024:
SIDECAR_ESTIMATE = 2.5
elif transfer_estimate < 1000 * 1024 * 1024:
SIDECAR_ESTIMATE = 5.0
else:
SIDECAR_ESTIMATE = 10.0
kwargs = {
'backup_folder': backup_folder,
'destination_folder': destination_folder,
'ios': self.ios,
'parent': self,
'pb': pb,
'storage_name': storage_name,
'src_stats': stats,
'total_seconds': transfer_estimate + SIDECAR_ESTIMATE
}
move_operation = MoveBackup(**kwargs)
# Device cached hashes
device_cached_hashes = "{0}_cover_hashes.json".format(
re.sub('\W', '_', self.ios.device_name))
dch = os.path.join(self.resources_path, device_cached_hashes)
if os.path.exists(dch):
move_operation.mxd_device_cached_hashes = dch
# Remote content hashes
rhc = b'/'.join(['/Library', 'calibre.mm',
BookStatusDialog.HASH_CACHE_FS])
if self.ios.exists(rhc):
base_name = "mxd_{0}".format(BookStatusDialog.HASH_CACHE_FS)
thc = os.path.join(temp_dir, base_name)
with open(thc, 'wb') as out:
self.ios.copy_from_idevice(rhc, out)
move_operation.mxd_remote_content_hashes = thc
move_operation.mxd_remote_hash_cache_fs = BookStatusDialog.HASH_CACHE_FS
# mainDb profile
move_operation.mxd_mainDb_profile = mainDb_profile
"""
# self.installed_books
if self.installed_books:
move_operation.mxd_installed_books = json.dumps(
self.dehydrate_installed_books(self.installed_books),
default=to_json,
indent=2, sort_keys=True)
"""
# iOSRA booklist.zip
archive_path = '/'.join([self.REMOTE_CACHE_FOLDER, 'booklist.zip'])
if self.ios.exists(archive_path):
# Copy the stored booklist to a local temp file
with PersistentTemporaryFile(suffix=".zip") as local:
with open(local._name, 'w') as f:
self.ios.copy_from_idevice(archive_path, f)
move_operation.iosra_booklist = local._name
start_time = time.time()
pb.show()
move_operation.start()
while not move_operation.isFinished():
Application.processEvents()
transfer_size = int(stats['st_size'])
total_actual = time.time() - start_time
analytics.append((
'2. Destination folder\n'
' {0}\n').format(destination_folder))
args = {
'IOS_READ_RATE': IOS_READ_RATE,
'pct_complete': pb.get_pct_complete(),
'sidecar_actual': self.format_time(move_operation.sidecar_time),
'sidecar_estimate': self.format_time(SIDECAR_ESTIMATE),
'total_actual': self.format_time(total_actual),
'total_estimate': self.format_time(SIDECAR_ESTIMATE + transfer_estimate),
'transfer_actual': self.format_time(move_operation.transfer_time),
'transfer_estimate': self.format_time(transfer_estimate),
'transfer_rate': transfer_size/move_operation.transfer_time,
'transfer_size': transfer_size
}
analytics.append((
'3. Transferring backup\n'
' backup image size: {transfer_size:,}\n'
' est. transfer time: {transfer_estimate}\n'
' actual transfer time: {transfer_actual}\n'
' est. sidecar time: {sidecar_estimate}\n'
' actual sidecar time: {sidecar_actual}\n'
' est. total time: {total_estimate}\n'
' actual total time: {total_actual} ({pct_complete}%)\n'
' est. transfer rate: {IOS_READ_RATE:,} bytes/sec\n'
' actual transfer rate: {transfer_rate:,.0f} bytes/sec\n'
).format(**args))
local.close()
# Add the environment details to analytics
analytics.append(self.format_device_profile())
pb.hide()
# Inform user backup operation is complete
title = "Backup operation complete"
msg = '<p>Marvin library archived to<br/>{0}</p>'.format(zip_dst)
det_msg = '\n'.join(analytics)
# Set dialog det_msg to monospace
dialog = info_dialog(self.gui, title, msg, det_msg=det_msg)
font = QFont('monospace')
font.setFixedPitch(True)
dialog.det_msg.setFont(font)
dialog.exec_()
# Save the backup folder
self.prefs.set('backup_folder', destination_folder)
else:
# Inform user backup operation cancelled
title = "Backup cancelled"
msg = '<p>Backup of {0} cancelled</p>'.format(self.ios.device_name)
det_msg = ''
if analytics:
det_msg = '\n'.join(analytics)
MessageBox(MessageBox.WARNING, title, msg, det_msg=det_msg, parent=self.gui,
show_copy_button=False).exec_()
else:
self._log("No backup file found at {0}".format(backup_target))
def create_local_backup(self):
'''
Build a backup image locally
'''
self._log_location()
"""
# Get a list of files, covers from mainDb
con = sqlite3.connect(self.connected_device.local_db_path)
with con:
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute('''SELECT FileName, Hash FROM Books''')
rows = cur.fetchall()
mdb_epubs = [row[b'FileName'] for row in rows]
mdb_covers = ["{0}.jpg".format(row[b'Hash']) for row in rows]
"""
epubs_path = b'/Documents'
dir_contents = self.ios.listdir(epubs_path, get_stats=False)
epubs = []
for f in dir_contents:
if f.lower().endswith('.epub'):
epubs.append(f)
else:
self._log("ignoring {0}/{1}".format(epubs_path, f))
small_covers_path = self.connected_device._cover_subpath(size="small")
dir_contents = self.ios.listdir(small_covers_path, get_stats=False)
small_covers = []
for f in dir_contents:
if f.lower().endswith('.jpg'):
small_covers.append(f)
else:
self._log("ignoring {0}/{1}".format(small_covers_path, f))
large_covers_path = self.connected_device._cover_subpath(size="large")
dir_contents = self.ios.listdir(large_covers_path, get_stats=False)
large_covers = []
for f in dir_contents:
if f.lower().endswith('.jpg'):
large_covers.append(f)
else:
self._log("ignoring {0}/{1}".format(large_covers_path, f))
total_steps = len(epubs) + len(large_covers)
total_steps += 5 # MXD components
total_steps += 2 # backup.xml, mainDb.sqlite
total_steps += 1 # Move backup to destination folder
# Set up the progress panel
busy_panel_args = {'book_count': "{:,}".format(len(epubs)),
'destination': 'destination folder',
'device': self.ios.device_name,
'large_covers': "{:,}".format(len(large_covers)),
'small_covers': "{:,}".format(len(small_covers))
}
BACKUP_MSG_1 = (
'<ol style="margin-right:1.5em">'
'<li style="margin-bottom:0.5em">Preparing backup …</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Add {book_count} ePubs to archive</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Add {large_covers} covers to archive</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Select destination folder</li>'
'<li style="color:#bbb">Move backup to destination folder</li>'
'</ol>')
pb = ProgressBar(alignment=Qt.AlignLeft,
label=BACKUP_MSG_1.format(**busy_panel_args),
parent=self.gui,
window_title="Creating backup of {0}".format(self.ios.device_name))
pb.set_range(0, total_steps)
pb.set_maximum(total_steps)
pb.show()
start_time = time.time()
with TemporaryFile(suffix=".zip") as local_backup:
with ZipFile(local_backup, 'w') as zfw:
# Device cached hashes
device_cached_hashes = "{0}_cover_hashes.json".format(
re.sub('\W', '_', self.ios.device_name))
dch = os.path.join(self.resources_path, device_cached_hashes)
if os.path.exists(dch):
base_name = "mxd_{0}".format(BookStatusDialog.HASH_CACHE_FS)
zfw.write(dch, arcname=base_name)
pb.increment()
# Remote content hashes
rhc = b'/'.join(['/Library', 'calibre.mm',
BookStatusDialog.HASH_CACHE_FS])
if self.ios.exists(rhc):
with TemporaryFile() as lhc:
try:
with open(lhc, 'wb') as local_copy:
self.ios.copy_from_idevice(rhc, local_copy)
base_name = "mxd_{0}".format(BookStatusDialog.HASH_CACHE_FS)
zfw.write(local_copy.name, arcname=base_name)
except:
import traceback
self._log(traceback.format_exc())
pb.increment()
# mainDb profile
zfw.writestr("mxd_mainDb_profile.json",
json.dumps(self.profile_db(), sort_keys=True))
pb.increment()
# <current_library>_installed_books.zip
installed_books_archive = os.path.join(self.resources_path,
current_library_name().replace(' ', '_') + '_installed_books.zip')
if os.path.exists(installed_books_archive):
zfw.write(installed_books_archive, arcname="mxd_installed_books.zip")
pb.increment()
# iOSRA booklist.db
lhc = os.path.join(self.connected_device.resources_path, 'booklist.db')
if os.path.exists(lhc):
zfw.write(lhc, arcname="iosra_booklist.db")
pb.increment()
# Issue command to request backup.xml
command_type = "BACKUPMANIFEST"
ch = CommandHandler(self)
ch.construct_general_command(command_type)
ch.issue_command(get_response="backup.xml")
if ch.results['code']:
pb.hide()
self._log("results: %s" % ch.results)
title = "Unable to get backup.xml"
msg = ('<p>Unable to get backup.xml from Marvin.</p>'
'<p>Click <b>Show details</b> for more information.</p>').format(
self.ios.device_name)
det_msg = ch.results['details'] + '\n\n'
det_msg += self.format_device_profile()
# Set dialog det_msg to monospace
dialog = warning_dialog(self.gui, title, msg, det_msg=det_msg)
font = QFont('monospace')
font.setFixedPitch(True)
dialog.det_msg.setFont(font)
return dialog.exec_()
response = ch.results['response']
if re.match(self.UTF_8_BOM, response):
response = UnicodeDammit(response).unicode
response = "<?xml version='1.0' encoding='utf-8'?>" + response
zfw.writestr("backup.xml", response)
pb.increment()
# mainDb
zfw.write(self.connected_device.local_db_path, arcname='mainDb.sqlite')
pb.increment()
# ePubs
self._log("archiving {:,} epubs".format(len(epubs)))
BACKUP_MSG_2 = (
'<ol style="margin-right:1.5em">'
'<li style="color:#bbb;margin-bottom:0.5em">Backup image initialized</li>'
'<li style="margin-bottom:0.5em">Archiving {book_count} ePubs …</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Add {large_covers} covers to archive</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Select destination folder</li>'
'<li style="color:#bbb">Move backup to destination folder</li>'
'</ol>')
pb.set_label(BACKUP_MSG_2.format(**busy_panel_args))
for path in epubs:
# Get a local copy of the book
rbp = '/'.join(['/Documents', path])
with TemporaryFile() as lbp:
try:
with open(lbp, 'wb') as local_copy:
self.ios.copy_from_idevice(str(rbp), local_copy)
zfw.write(local_copy.name, arcname=path)
except:
import traceback
self._log(traceback.format_exc())
pb.increment()
# Large and small covers with one step
self._log("archiving {:,} covers and thumbs".format(len(large_covers)))
BACKUP_MSG_3 = (
'<ol style="margin-right:1.5em">'
'<li style="color:#bbb;margin-bottom:0.5em">Backup image initialized</li>'
'<li style="color:#bbb;margin-bottom:0.5em">{book_count} ePubs archived</li>'
'<li style="margin-bottom:0.5em">Archiving {large_covers} covers …</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Select destination folder</li>'
'<li style="color:#bbb">Move backup to destination folder</li>'
'</ol>')
pb.set_label(BACKUP_MSG_3.format(**busy_panel_args))
# Process large and small covers at the same time
# Assumes that len(large_covers) == len(small_covers)
for x in range(len(large_covers)):
# Get a local copy of the large cover
path = large_covers[x]
rcp = b'/'.join([large_covers_path, path])
with TemporaryFile() as lcp:
try:
with open(lcp, 'wb') as local_copy:
self.ios.copy_from_idevice(rcp, local_copy)
zfw.write(local_copy.name, arcname="L-{0}".format(path))
except:
import traceback
self._log(traceback.format_exc())
# Get a local copy of the small cover
path = small_covers[x]
rcp = b'/'.join([small_covers_path, path])
with TemporaryFile() as lcp:
try:
with open(lcp, 'wb') as local_copy:
self.ios.copy_from_idevice(str(rcp), local_copy)
zfw.write(local_copy.name, arcname="S-{0}".format(path))
except:
import traceback
self._log(traceback.format_exc())
pb.increment()
pb.hide()
actual_time = time.time() - start_time
self._log("archive created in {0} ({1:,.0f} bytes/second)".format(
self.format_time(actual_time),
os.stat(local_backup).st_size/actual_time))
# Get the destination folder
d = datetime.now()
storage_name = "{0} {1}.backup".format(
self.ios.device_name, d.strftime("%Y-%m-%d"))
destination_folder = str(QFileDialog.getExistingDirectory(
self.gui,
"Select destination folder to store backup",
self.prefs.get('backup_folder', os.path.expanduser("~")),
QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks))
if destination_folder:
# Qt apparently sometimes returns a file within the selected directory,
# rather than the directory itself. Validate destination_folder
if not os.path.isdir(destination_folder):
destination_folder = os.path.dirname(destination_folder)
BACKUP_MSG_4 = (
'<ol style="margin-right:1.5em">'
'<li style="color:#bbb;margin-bottom:0.5em">Backup image initialized</li>'
'<li style="color:#bbb;margin-bottom:0.5em">{book_count} ePubs archived</li>'
'<li style="color:#bbb;margin-bottom:0.5em">{large_covers} covers archived</li>'
'<li style="color:#bbb;margin-bottom:0.5em">Destination folder selected</li>'
'<li style="margin-bottom:0.5em">Moving {backup_size} MB backup to destination folder…</li>'
'</ol>')
busy_panel_args['backup_size'] = "{:,}".format(int(os.stat(local_backup).st_size/(1000*1000)))
pb.set_label(BACKUP_MSG_4.format(**busy_panel_args))
pb.show()
# Copy local_backup to destination folder
shutil.copy(local_backup, os.path.join(destination_folder, storage_name))
pb.increment()
pb.hide()
# Inform user backup operation is complete
title = "Backup operation complete"
msg = '<p>Marvin library backed up to {0}</p>'.format(destination_folder)
MessageBox(MessageBox.INFO, title, msg, parent=self.gui,
show_copy_button=False).exec_()
# Save the backup folder
self.prefs.set('backup_folder', destination_folder)
else:
# Inform user backup operation cancelled
title = "Backup cancelled"
try:
msg = '<p>Backup of {0} cancelled</p>'.format(self.ios.device_name)
except:
msg = '<p>Backup cancelled</p>'
det_msg = ''
MessageBox(MessageBox.WARNING, title, msg, det_msg=det_msg, parent=self.gui,
show_copy_button=False).exec_()
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 dehydrate_installed_books(self, installed_books):
'''
Convert installed_books to JSON-serializable format
'''
all_mxd_keys = sorted(Book.mxd_standard_keys + Book.mxd_custom_keys)
dehydrated = {}
for key in installed_books:
dehydrated[key] = {}
for mxd_attribute in all_mxd_keys:
dehydrated[key][mxd_attribute] = getattr(
installed_books[key], mxd_attribute, None)
return dehydrated
def developer_utilities(self, action):
'''
'''
self._log_location(action)
if action in ['Connected device profile', 'Create remote backup',
'Delete calibre hash cache', 'Delete Marvin hash cache',
'Delete installed books cache', 'Delete all caches',
'Nuke annotations',
'Reset column widths']:
if action == 'Delete Marvin hashes':
rhc = b'/'.join([self.REMOTE_CACHE_FOLDER, BookStatusDialog.HASH_CACHE_FS])
if self.ios.exists(rhc):
self.ios.remove(rhc)
self._log("remote hash cache at %s deleted" % rhc)
# Remove cover hashes for connected device
device_cached_hashes = "{0}_cover_hashes.json".format(
re.sub('\W', '_', self.ios.device_name))
dch = os.path.join(self.resources_path, device_cached_hashes)
if os.path.exists(dch):
os.remove(dch)
self._log("cover hashes at {0} deleted".format(dch))
else:
self._log("no cover hashes found at {0}".format(dch))
# Called by restore_from_backup, so no dialog
# info_dialog(self.gui, 'Developer utilities',
# 'Marvin hashes deleted', show=True,
# show_copy_button=False)
elif action == 'Delete installed books cache':
# Delete <current_library>_installed_books.zip
# Reset self.installed_books
self.installed_books = None
archive_path = os.path.join(self.resources_path,
current_library_name().replace(' ', '_') + '_installed_books.zip')
if os.path.exists(archive_path):
os.remove(archive_path)
self._log("installed books cache deleted: {}".format(os.path.basename(archive_path)))
info_dialog(self.gui, 'Developer utilities',
'installed books archives deleted: {}'.format(
os.path.basename(archive_path)),
show=True,
show_copy_button=False)
elif action == 'Connected device profile':
self.show_connected_device_profile()
elif action == 'Create remote backup':
self.create_remote_backup()
elif action == 'Delete calibre hashes':
self.gui.current_db.delete_all_custom_book_data('epub_hash')
self._log("cached epub hashes deleted")
# Invalidate the library hash map, as library contents may change before reconnection
if hasattr(self, 'library_scanner'):
if hasattr(self.library_scanner, 'hash_map'):
self.library_scanner.hash_map = None
info_dialog(self.gui, 'Developer utilities',
'calibre epub hashes deleted', show=True,
show_copy_button=False)
elif action == 'Delete all caches':
self.reset_caches()
elif action == 'Nuke annotations':
# nuke_annotations() has its own dialog informing progress
self.nuke_annotations()
elif action == 'Reset column widths':
self._log("deleting marvin_library_column_widths")
self.prefs.pop('marvin_library_column_widths')
self.prefs.commit()
info_dialog(self.gui, 'Developer utilities',
'Column widths reset', show=True,
show_copy_button=False)
else:
self._log("unsupported action '{0}'".format(action))
def device_diagnostics(self):
'''
Replacement for profile_connected_device()
'''
def _add_available_space():
available = self.connected_device.free_space()[0]
if available > 1024 * 1024 * 1024:
available = available / (1024 * 1024 * 1024)
fmt_str = "{:.2f} GB"
else:
available = int(available / (1024 * 1024))
fmt_str = "{:,} MB"
device_profile['available_space'] = fmt_str.format(available)
def _add_cache_files():
# Cache files
# Marvin:
# Library/mainDb.sqlite
# Library/calibre.mm/booklist.db
# Library/calibre.mm/content_hashes.db
# Local:
# <calibre resource dir>/iOS_reader_applications_resources/booklist.db
# <calibre resource dir>/Marvin_XD_resources/*_cover_hashes.json
# <calibre resource dir>/Marvin_XD_resources/installed_books.zip
from datetime import datetime
def _get_ios_stats(path):
mtime = st_size = None
stats = self.connected_device.ios.stat(path)
if stats:
st_size = int(stats['st_size'])
d = datetime.fromtimestamp(int(stats['st_mtime']))
mtime = d.strftime('%Y-%m-%d %H:%M:%S')
return {'mtime': mtime, 'size': st_size}
def _get_os_stats(path):
mtime = st_size = None
if os.path.exists(path):
stats = os.stat(path)
st_size = stats.st_size
d = datetime.fromtimestamp(stats.st_mtime)
mtime = d.strftime('%Y-%m-%d %H:%M:%S')
return {'mtime': mtime, 'size': st_size}
cache_files = {}
''' Marvin-specific cache files '''
cache_files['mainDb.sqlite (remote)'] = _get_ios_stats('/Library/mainDb.sqlite')
cache_files['mainDb.sqlite (local)'] = _get_os_stats(self.connected_device.local_db_path)
cache_files['booklist.db (remote)'] = _get_ios_stats('Library/calibre.mm/booklist.db')
cache_files['mxd_content_hashes.db (remote)'] = _get_ios_stats('Library/calibre.mm/content_hashes.db')
# booklist.db from iOSRA resources
path = os.path.join(self.connected_device.resources_path, 'booklist.db')
cache_files['booklist.db (local)'] = _get_os_stats(path)
# Per-library installed_books.zip archives
mxd_resources_path = self.resources_path
pattern = os.path.join(mxd_resources_path, "*_installed_books.zip")
for path in glob.glob(pattern):
ans = _get_os_stats(path)
name = path.rsplit(os.path.sep)[-1]
cache_files['mxd_{}'.format(name)] = ans
# Per-device cover hashes
pattern = os.path.join(mxd_resources_path, "/*_cover_hashes.json")
for path in glob.glob(pattern):
ans = _get_os_stats(path)
name = path.rsplit(os.path.sep)[-1]
cache_files['mxd_{}'.format(name)] = ans
device_profile['cache_files'] = cache_files
def _add_caching():
iosra_prefs = JSONConfig('plugins/iOS reader applications')
device_caching = {}
device_caching_enabled = iosra_prefs.get('device_booklist_caching')
allocation_factor = iosra_prefs.get('device_booklist_cache_limit', 0)
device_caching['enabled'] = device_caching_enabled
device_caching['allocation_factor'] = allocation_factor
allocated_space = int(self.connected_device.free_space()[0] * (allocation_factor / 100))
if allocated_space > 1024 * 1024 * 1024:
allocated_space = allocated_space / (1024 * 1024 * 1024)
fmt_str = "{:.2f} GB"
else:
allocated_space = int(allocated_space / (1024 * 1024))
fmt_str = "{:,} MB"
device_caching['allocated_space'] = fmt_str.format(allocated_space)
device_profile['device_caching'] = device_caching
def _add_installed_plugins():
# installed plugins
from calibre.customize.ui import initialized_plugins
user_installed_plugins = {}
for plugin in initialized_plugins():
path = getattr(plugin, 'plugin_path', None)
if path is not None:
name = getattr(plugin, 'name', None)
if name == self.name:
continue
author = getattr(plugin, 'author', None)
version = getattr(plugin, 'version', None)
user_installed_plugins[name] = {'author': author, 'version': "{0}.{1}.{2}".format(*version)}
device_profile['user_installed_plugins'] = user_installed_plugins
def _add_device_book_count():
# Device book count
device_profile['device_book_count'] = len(self.connected_device.cached_books)
def _add_device_info():
cdp = self.connected_device.device_profile
device_info = {}
all_fields = ['DeviceClass', 'DeviceColor', 'DeviceName', 'FSBlockSize',
'FSFreeBytes', 'FSTotalBytes', 'FirmwareVersion', 'HardwareModel',
'ModelNumber', 'PasswordProtected', 'ProductType', 'ProductVersion',
'SerialNumber', 'TimeIntervalSince1970', 'TimeZone',
'TimeZoneOffsetFromUTC', 'UniqueDeviceID']
superfluous = ['DeviceClass', 'DeviceColor', 'FSBlockSize', 'HardwareModel',
'SerialNumber', 'TimeIntervalSince1970', 'TimeZoneOffsetFromUTC',
'UniqueDeviceID', 'ModelNumber']
for item in sorted(cdp):
if item in superfluous:
continue
if item in ['FSTotalBytes', 'FSFreeBytes']:
device_info[item] = int(cdp[item])
else:
device_info[item] = cdp[item]
device_profile['device_info'] = device_info
def _add_library_profile():
library_profile = {}
cdb = self.gui.current_db
library_profile['epubs'] = len(cdb.search_getting_ids('formats:EPUB', ''))
#library_profile['pdfs'] = len(cdb.search_getting_ids('formats:PDF', ''))
#library_profile['mobis'] = len(cdb.search_getting_ids('formats:MOBI', ''))
device_profile['library_profile'] = library_profile
def _add_load_time():
if self.load_time:
elapsed = _seconds_to_time(self.load_time)
formatted = "{0:02d}:{1:02d}".format(int(elapsed['mins']), int(elapsed['secs']))
device_profile['load_time'] = formatted
else:
device_profile['load_time'] = "n/a"
def _add_iOSRA_version():
device_profile['iOSRA_version'] = "{0}.{1}.{2}".format(*self.connected_device.version)
def _add_mainDb_profiles():
archive_path = os.path.join(self.resources_path,
self.INSTALLED_BOOKS_SNAPSHOT)
stored_mainDb_profile = {}
if os.path.exists(archive_path):
with ZipFile(archive_path, 'r') as zfr:
if 'mainDb_profile.json' in zfr.namelist():
stored_mainDb_profile = json.loads(zfr.read('mainDb_profile.json'))
device_profile['stored_mainDb_profile'] = stored_mainDb_profile
device_profile['current_mainDb_profile'] = self.profile_db()
def _add_platform_profile():
# Platform info
import platform
from calibre.constants import (__appname__, get_version, isportable, isosx,