-
Notifications
You must be signed in to change notification settings - Fork 3
/
transfers.py
1601 lines (1373 loc) · 68.9 KB
/
transfers.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
import os
import time
import datetime
import simplejson
import mimetypes
from httplib import socket
from collections import deque
from PyQt4.QtGui import QMainWindow, QWidget, QMessageBox, QIcon, QPixmap, QMovie, QLabel, QScrollArea
from PyQt4.QtGui import QSpacerItem, QSizePolicy, QHBoxLayout, QVBoxLayout, QGridLayout, QFont
from PyQt4.QtCore import Qt, QObject, QTimer, QDateTime, QSize, QDir
from data import Collection, Resource
from connectionmanager import NetworkWorker
from ui.ui_transferwidget import Ui_TransferWidget
from ui.ui_transferitem import Ui_TransferItem
from ui.ui_synctransferitem import Ui_SyncTransferItem
""" Sync manager handles manual and automatic syncs """
class SyncManager(QObject):
def __init__(self, controller):
QObject.__init__(self)
self.controller = controller
self.datahandler = controller.datahandler
self.config_helper = controller.config_helper
self.ui = controller.ui
self.logger = controller.logger
self.connection = controller.connection
# Init poll timer
self.poll_timer = QTimer(self)
self.poll_timer.timeout.connect(self.thread_poller)
# Metadata threading variables
self.active_metadata_thread = None
self.queued_metadata_threads = deque()
# Active sync variables
self.sync_metadata = None
self.sync_sub_folders_left = False
self.sync_ongoing = False
self.sync_fetching_sync_root = True
self.sync_root = None
self.sync_total_results = []
def check_metadata_queue(self):
if self.active_metadata_thread == None:
try:
self.active_metadata_thread = self.queued_metadata_threads.popleft()
self.active_metadata_thread.start()
self.poll_timer.start(50)
except IndexError:
self.finish_sync()
self.sync_ongoing = False
self.active_metadata_thread = None
self.poll_timer.stop()
def thread_poller(self):
if self.active_metadata_thread == None:
self.poll_timer.stop()
return
self.active_metadata_thread.join(0.01)
if not self.active_metadata_thread.isAlive():
if self.active_metadata_thread.error != None:
self.ui.show_banner("Could not complete sync, connection failed")
self.logger.sync_error("Could not complete sync, connection failed")
self.sync_parse_response(self.active_metadata_thread.response)
del self.active_metadata_thread
self.active_metadata_thread = None
self.check_metadata_queue()
def can_sync(self, sync_path):
if self.connection.client == None:
self.ui.show_banner("Cannot synchronize, not connected to Dropbox")
self.logger.sync("Cannot synchronize, no network connection")
return False
if self.connection.connection_available() == False:
self.ui.show_banner("Cannot synchronize, no network connection")
self.logger.sync("Cannot synchronize, no network connection")
return False
if self.datahandler.only_sync_on_wlan:
if not self.connection.connection_is_wlan():
self.ui.show_banner("Synchronizing without WLAN disabled in settings", 4000)
return False
if len(self.controller.transfer_manager.queued_transfer_threads) > 0 or self.controller.transfer_manager.active_transfer != None:
self.ui.show_banner("There are ongoing active transfers\nPlease wait for them to complete")
return False
if len(self.connection.data_workers) > 0:
self.ui.show_banner("Data is still being written from previous downloads\nPlease wait a moment and try synchronizing again", 5000)
return False
if self.sync_ongoing:
self.ui.show_banner("Synchronization already in progress")
self.logger.sync("Synchronizing already in progress")
return False
if sync_path == "" or sync_path == "/":
self.ui.show_banner("Cannot synchronize, path / invalid")
self.logger.sync("Cannot synchronize, path / invalid")
return False
if sync_path == "None":
self.ui.show_banner("Synchronizing disabled in settings", 2000)
return False
if sync_path[0] != "/":
self.ui.show_banner("Cannot synchronize, path '" + sync_path + "' invalid")
self.logger.sync("Cannot synchronize, path '" + sync_path + "' invalid")
return False
dir_check = QDir(self.datahandler.get_data_dir_path())
if not dir_check.exists():
self.ui.show_note("Cannot synchronize, download dir " + self.datahandler.get_data_dir_path() + " does not exist. Please set a new folder in settings.")
return False
# If got this far, we should be ok to sync
return True
def sync_media(self):
path_local = self.datahandler.user_home + "/MyDocs/DCIM"
remote_paths = []
path_remote_base = "/N900Media"
path_remote_images = "/N900Media/Photos"
path_remote_videos = "/N900Media/Videos"
remote_paths.append(path_remote_base)
remote_paths.append(path_remote_images)
remote_paths.append(path_remote_videos)
if not self.can_sync(path_remote_base):
return
# Local check
if not QDir(path_local).exists():
self.logger.sync_error("Could not verify media location from " + path_local)
self.ui.show_banner("Errors occurred, check log", 2000)
return
# Remote base folder check
response_images = None
response_videos = None
response = self.connection.client.metadata("dropbox", path_remote_base, 10000, None)
if response.status == 404:
answer = QMessageBox.question(self.ui.main_widget, " ",
"You need to create media folders /N900Media/Photos and /N900Media/Videos to dropbox to proceed. \n\nDo you wish to Continue?", QMessageBox.Yes, QMessageBox.No)
if answer == QMessageBox.No:
return
# Create all base, videos and images folder
for remote_path in remote_paths:
if self.connection.create_folder_blocking(remote_path):
self.logger.info("Created remote folder " + remote_path + " succesfully")
else:
self.logger.info("Failed to create remote folder " + remote_path + ", aborting media sync")
self.ui.show_banner("Errors occurred, check log", 2000)
return
else:
self.ui.show_banner("Preparing media synchronization, please wait...", 2000)
# Check images
response_images = self.connection.client.metadata("dropbox", path_remote_images, 10000, None)
if response_images.status == 404:
response_images = None
answer = QMessageBox.question(self.ui.main_widget, " ", "You need to create media folder /N900Media/Photos to dropbox to proceed. \n\nDo you wish to Continue?", QMessageBox.Yes, QMessageBox.No)
if answer == QMessageBox.No:
return
if self.connection.create_folder_blocking(path_remote_images):
self.logger.info("Created remote folder " + path_remote_images + " succesfully")
else:
self.logger.info("Failed to create remote folder " + path_remote_images + ", aborting media sync")
self.ui.show_banner("Errors occurred, check log", 2000)
return
# Check videos
response_videos = self.connection.client.metadata("dropbox", path_remote_videos, 10000, None)
if response_videos.status == 404:
response_videos = None
answer = QMessageBox.question(self.ui.main_widget, " ", "You need to create media folder /N900Media/Videos to dropbox to proceed. \n\nDo you wish to Continue?", QMessageBox.Yes, QMessageBox.No)
if answer == QMessageBox.No:
return
if self.connection.create_folder_blocking(path_remote_videos):
self.logger.info("Created remote folder " + path_remote_videos + " succesfully")
else:
self.logger.info("Failed to create remote folder " + path_remote_videos + ", aborting media sync")
self.ui.show_banner("Errors occurred, check log", 2000)
return
# Folder checks ok, lets sync
self.ui.set_synching(True)
# Get metadata for both destinations if still needed
if response_images == None:
response_images = self.connection.client.metadata("dropbox", path_remote_images, 10000, None)
if response_videos == None:
response_videos = self.connection.client.metadata("dropbox", path_remote_videos, 10000, None)
if response_images.status != 200 or response_videos.status != 200:
self.logger.sync_error("Error fetching media photos and videos metadata")
self.ui.show_banner("Errors occurred, check log", 2000)
self.ui.set_synching(False)
return
# Parse metadatas to get remote file lists
data_photos = self.connection.data_parser.parse_metadata_static(response_images.data)
data_videos = self.connection.data_parser.parse_metadata_static(response_videos.data)
if data_photos == None or data_videos == None:
self.logger.sync_error("Error fetching media photos and videos metadata")
self.ui.show_banner("Errors occurred, check log", 2000)
self.ui.set_synching(False)
return
# Round up files
remote_files = []
for file_obj in data_photos.get_files():
remote_files.append(file_obj.get_name())
for file_obj in data_videos.get_files():
remote_files.append(file_obj.get_name())
# Check local folder and compare to remote files
sending_local_files = {}
for filename in os.listdir(path_local):
full_path = path_local + "/" + filename
if os.path.isdir(full_path):
continue
try:
found = remote_files.index(filename)
except ValueError:
sending_local_files[filename] = full_path
if len(sending_local_files) == 0:
self.ui.show_banner("All media up to date, nothing to upload", 4000)
self.ui.set_synching(False)
return
videos = {}
videos_size = 0
images = {}
images_size = 0
for (name, path) in sending_local_files.iteritems():
ext = name.split(".")[-1]
if ext == "mp4":
videos[name] = path
videos_size += os.path.getsize(path)
else:
images[name] = path
images_size += os.path.getsize(path)
confirmation_ul = SyncDialog(self.ui.main_widget)
confirmation_ul.setWindowTitle("Camera Photos Upload Confirmation")
button_ul_all = confirmation_ul.addButton("Upload All", QMessageBox.YesRole)
button_ul_photos = confirmation_ul.addButton("Upload Photos", QMessageBox.ActionRole)
button_ul_videos = confirmation_ul.addButton("Upload Videos", QMessageBox.DestructiveRole)
button_ul_cancel = confirmation_ul.addButton("Cancel", QMessageBox.NoRole)
confirmation_ul.add_titles(" ", "Files", "Size")
confirmation_ul.add_row("Photos", str(len(images)), self.datahandler.humanize_bytes(images_size))
confirmation_ul.add_row("Videos", str(len(videos)), self.datahandler.humanize_bytes(videos_size))
confirmation_ul.add_totals(" ", str(len(images)+len(videos)), self.datahandler.humanize_bytes(images_size+videos_size))
confirmation_ul.finalize()
if len(images) == 0:
button_ul_photos.setEnabled(False)
if len(videos) == 0:
button_ul_videos.setEnabled(False)
# Photo UL dialog: Upload All = 0, Upload Photos = 1, Cancel = 3, Upload Videos = 2
send_photos = False
send_videos = False
upload_files = 0
upload_bytes = 0
result = confirmation_ul.exec_()
if result == 3:
return
elif result == 0:
send_photos = True
send_videos = True
upload_files = len(images) + len(videos)
upload_bytes = images_size + videos_size
elif result == 1:
send_photos = True
upload_files = len(images)
upload_bytes = images_size
elif result == 2:
send_videos = True
upload_files = len(videos)
upload_bytes = videos_size
sync_widget = SyncTransferItem(self)
sync_widget.set_totals(0, upload_files)
sync_widget.set_sizes("0", self.datahandler.humanize_bytes(upload_bytes))
sync_widget.ui.dl_size.hide()
self.controller.transfer_manager.set_current_sync(sync_widget)
self.controller.transfer_widget.add_sync_reporting(sync_widget)
if send_photos:
for (name, path) in images.iteritems():
self.connection.upload_file(path_remote_images, "dropbox", path, True)
if send_videos:
for (name, path) in videos.iteritems():
self.connection.upload_file(path_remote_videos, "dropbox", path, True)
self.ui.set_synching(False)
self.ui.show_transfer_widget()
def sync_now(self, sync_path):
if not self.can_sync(sync_path):
return
self.sync_ongoing = True
self.sync_fetching_sync_root = True
self.sync_root = None
self.sync_total_results = []
self.ui.show_banner("Preparing synchronization, please wait...", 2000)
self.ui.set_synching(True)
# Make metadata fetch thread
metadata_worker = NetworkWorker()
metadata_worker.set_callable(self.connection.client.metadata, "dropbox", sync_path, 10000, None)
self.queued_metadata_threads.append(metadata_worker)
self.check_metadata_queue()
def sync_parse_response(self, response):
if response != None:
if response.status == 200:
sync_result = self.parse_metadata(response.data)
if sync_result == None:
self.ui.show_banner("Fatal synchronization error, cannot continue")
self.logger.sync_error("Fatal synchronization error, cannot continue")
return
self.sync_total_results.append(sync_result)
if sync_result.total_folders > 0:
for child_folder in sync_result.fetch_meatadata_folders:
metadata_worker = NetworkWorker()
metadata_worker.set_callable(self.connection.client.metadata, "dropbox", child_folder.path, 10000, None)
self.queued_metadata_threads.append(metadata_worker)
else:
try:
e = simplejson.loads(response.body)["error"]
except:
e = "Invalid path"
self.ui.show_banner("Synchronizing failed - " + e)
self.logger.sync_error("Could not fetch metadata from sync path: " + e)
self.check_metadata_queue()
def parse_metadata(self, data):
try:
if data["is_dir"]:
parent_root = data["root"]
sync_folder = Collection(data["path"], data["modified"], data["icon"], data["thumb_exists"], parent_root, data["hash"])
# Add children to folder
for item in data["contents"]:
path = item["path"]
size = item["size"]
modified = item["modified"]
icon = item["icon"]
has_thumb = item["thumb_exists"]
if item["is_dir"]:
child = Collection(path, modified, icon, has_thumb, parent_root)
else:
child = Resource(path, size, item["bytes"], modified, item["mime_type"], icon, has_thumb, parent_root)
sync_folder.add_item(child)
# Store root data
if self.sync_fetching_sync_root:
self.sync_root = SyncRoot(sync_folder)
self.sync_fetching_sync_root = False
# Store sync results for this path
result = SyncResult(self.datahandler, sync_folder)
result.check_local_path(self.sync_root)
result.check_files_for_changes()
return result
else:
self.ui.show_banner("Sync error, check log")
self.logger.sync_error("Sync path is not a folder, stopping sync")
return None
except Exception, e:
self.ui.show_banner("Sync error, check log")
self.logger.sync_error("Parsing sync path metadata failed: " + str(e))
return None
def finish_sync(self):
confirm_dl = True
confirm_ul = True
new_ul_files = False
confirmation_dl = SyncDialog(self.ui.main_widget)
confirmation_dl.setWindowTitle("Synchronization Download Confirmation")
button_dl_continue = confirmation_dl.addButton("Download All", QMessageBox.YesRole)
button_dl_ignore = confirmation_dl.addButton("Ignore Files", QMessageBox.ActionRole)
button_dl_cancel = confirmation_dl.addButton("Cancel", QMessageBox.NoRole)
confirmation_ul = SyncDialog(self.ui.main_widget)
confirmation_ul.setWindowTitle("Synchronization Upload Confirmation")
button_ul_continue = confirmation_ul.addButton("Upload All", QMessageBox.YesRole)
button_ul_ignore = confirmation_ul.addButton("Ignore Files", QMessageBox.ActionRole)
button_ul_cancel = confirmation_ul.addButton("Cancel", QMessageBox.NoRole)
button_ul_remove = confirmation_ul.addButton("Remove New \nLocal Files", QMessageBox.DestructiveRole)
# DOWNLOADS
total_dl_files = 0
total_dl_folders = 0
total_dl_bytes = 0
confirmation_dl.add_titles("Downloading", "Files", "Size")
# Download files
for result in self.sync_total_results:
if result.total_dl_files == 0:
continue
total_dl_folders += 1
total_dl_files += result.total_dl_files
total_dl_bytes += result.total_dl_bytes
confirmation_dl.add_row(result.remote_path, str(result.total_dl_files), self.datahandler.humanize_bytes(result.total_dl_bytes))
# Totals
confirmation_dl.add_totals("Total", str(total_dl_files), self.datahandler.humanize_bytes(total_dl_bytes))
if total_dl_files == 0:
confirm_dl = False
confirmation_dl.finalize()
# UPLOAD
total_ul_files = 0
total_ul_folders = 0
total_ul_bytes = 0
confirmation_ul.add_titles("Uploading", "Files", "Size")
# Upload files
create_new_folders = []
all_skipped_uploads = []
for result in self.sync_total_results:
total_ul_bytes += result.total_ul_bytes
total_ul_files += result.total_ul_files
all_skipped_uploads += result.skipped_uploads
# New files to upload
for filename in result.new_files_to_upload:
new_ul_files = True
fileonly = filename.split("/")[-1]
confirmation_ul.add_row(result.remote_path + "/" + fileonly, "NEW FILE", self.datahandler.humanize_bytes(os.path.getsize(filename)))
# Files to update
for filename in result.out_of_date_files_upload:
fileonly = filename.split("/")[-1]
confirmation_ul.add_row(result.remote_path + "/" + fileonly, "CHANGED FILE", self.datahandler.humanize_bytes(os.path.getsize(filename)))
# New folders and files under them to upload
for (remote_folder, local_files) in result.new_folders_to_files.iteritems():
create_new_folders.append(result.remote_path + "/" + remote_folder)
folder_size = 0
folder_files = 0
for filename in local_files:
folder_size += os.path.getsize(filename)
folder_files += 1
total_ul_bytes += folder_size
total_ul_files += folder_files
total_ul_folders += 1
if folder_files == 0:
continue
confirmation_ul.add_row(result.remote_path + "/" + remote_folder, str(folder_files), self.datahandler.humanize_bytes(folder_size))
# Totals
confirmation_ul.add_totals("Total", str(total_ul_files), self.datahandler.humanize_bytes(total_ul_bytes))
if total_ul_files == 0:
confirm_ul = False
# New folders
if len(create_new_folders) > 0:
create_new_folders.sort()
confirmation_ul.add_spacer()
confirmation_ul.add_titles("Creating New Folders to DropBox")
for remote_path in create_new_folders:
confirmation_ul.add_row(remote_path)
confirmation_ul.finalize()
# Show confirmation dialog
if confirm_dl == True or confirm_ul == True:
# DL dialog: OK = 0, IGNORE = 1, CANCEL = 2
# UL dialog: OK = 0, IGNORE = 1, CANCEL = 2, REMOVE LOCAL = 3
answer_dl = -1
answer_ul = -1
if confirm_dl:
answer_dl = confirmation_dl.exec_()
if answer_dl == 2:
del confirmation_dl
del confirmation_ul
self.ui.show_banner("Synchronization canceled")
self.ui.set_synching(False)
return
if confirm_ul:
if new_ul_files == False:
button_ul_remove.hide()
answer_ul = confirmation_ul.exec_()
if answer_ul == 2:
del confirmation_dl
del confirmation_ul
self.ui.show_banner("Synchronization canceled")
self.ui.set_synching(False)
return
elif answer_ul == 3:
self.ui.show_banner("Removing new local files\nPlease wait...", 2000)
# Remove new local files and ask again
uploads_remaining = False
self.logger.sync("Removing local files that were not in DropBox")
for sync_result in self.sync_total_results:
for filepath in sync_result.new_files_to_upload:
self.logger.sync("- " + filepath)
total_ul_files -= 1
total_ul_bytes -= os.path.getsize(filepath)
os.remove(filepath)
if len(sync_result.new_folders_to_files) > 0 or len(sync_result.out_of_date_files_upload) > 0:
uploads_remaining = True
sync_result.new_files_to_upload = []
# Reconfirm if needed
if uploads_remaining:
confirmation_ul.hide_new_uploads()
button_ul_remove.hide()
confirmation_ul.set_totals(str(total_ul_files), self.datahandler.humanize_bytes(total_ul_bytes))
answer_ul = confirmation_ul.exec_()
else:
answer_ul = -1
# Check for additional child results, these are present
# if we have totally new folders with new files for upload
additional_results = []
for sync_result in self.sync_total_results:
if len(sync_result.child_upload_results) > 0:
additional_results += sync_result.child_upload_results
self.sync_total_results += additional_results
store_dir = self.datahandler.get_data_dir_path()
sync_widget = None
if answer_dl == 0 or answer_ul == 0:
sync_widget = SyncTransferItem(self)
sync_widget.set_totals(total_dl_files, total_ul_files)
sync_widget.set_sizes(self.datahandler.humanize_bytes(total_dl_bytes), self.datahandler.humanize_bytes(total_ul_bytes))
self.controller.transfer_manager.set_current_sync(sync_widget)
self.controller.transfer_widget.add_sync_reporting(sync_widget)
# Do downloads
if answer_dl == 0:
# Update ui and log
post_files = " file from " if total_dl_files == 1 else " files from "
post_folders = " folder" if total_dl_folders == 1 else " folders"
banner_total_size_string = ", total of " + self.datahandler.humanize_bytes(total_dl_bytes)
message = "Downloading " + str(total_dl_files) + post_files + str(total_dl_folders) + post_folders + banner_total_size_string
self.logger.sync(message)
for sync_result in self.sync_total_results:
# Create directory
if sync_result.local_folder_exists == False:
sync_result.create_local_path()
# Queue downloads
for sync_file in sync_result.out_of_date_files:
self.connection.get_file(sync_file.path, sync_file.root, sync_result.local_path + "/" + sync_file.get_name(), sync_file.size, sync_file.mime_type, True)
elif answer_dl == 1:
self.logger.sync("Ignoring downloads")
elif answer_dl == -1:
self.logger.sync("No synchronization downloads, all file up to date")
# Do uploads
if answer_ul == 0:
post_ul_files = " file and creating " if total_ul_files == 1 else " files and "
post_ul_folders = " folder" if total_ul_folders == 1 else " folders"
banner_total_ul_size_string = ", total of " + self.datahandler.humanize_bytes(total_ul_bytes)
message_ul = "Uploading " + str(total_ul_files) + post_ul_files + str(total_ul_folders) + post_ul_folders + banner_total_ul_size_string
self.logger.sync(message_ul)
# Create new remote dirs
if len(create_new_folders) > 0:
create_new_folders.sort() # sort so we create forlder from bottom up
for remote_path in create_new_folders:
if self.connection.create_folder_blocking(remote_path):
self.logger.info("Created remote folder " + remote_path + " succesfully")
else:
self.logger.info("Failed to create remote folder " + remote_path)
for sync_result in self.sync_total_results:
# Queue uploads
for ul_sync_file in sync_result.out_of_date_files_upload:
self.connection.upload_file(sync_result.remote_path, "dropbox", ul_sync_file, True)
for ul_sync_file in sync_result.new_files_to_upload:
self.connection.upload_file(sync_result.remote_path, "dropbox", ul_sync_file, True)
elif answer_ul == 1:
self.logger.sync("Ignoring uploads")
elif answer_dl == -1:
self.logger.sync("No synchronization uploads, all file up to date")
if sync_widget != None:
self.ui.show_transfer_widget()
else:
self.ui.set_synching(False)
else:
self.ui.show_banner("Nothing to sync - all files up to date")
self.ui.set_synching(False)
# Cleanup
del confirmation_dl
del confirmation_ul
""" SyncRoot has data about the main synchronization path """
class SyncRoot:
def __init__(self, data):
self.path = data.path
self.name = data.name
""" SyncResult has data about a path in the synchronization """
class SyncResult:
def __init__(self, datahandler, sync_folder):
self.datahandler = datahandler
self.logger = datahandler.logger
self.data = sync_folder
if sync_folder != None:
self.remote_path = self.to_unicode(sync_folder.path)
self.local_path = None
if sync_folder != None:
self.local_folder_exists = False
else:
self.local_folder_exists = True
self.child_upload_results = []
self.out_of_date_files = []
self.out_of_date_files_upload = []
self.new_files_to_upload = []
self.fetch_meatadata_folders = []
self.skipped_uploads = []
self.new_folders_to_files = {}
self.total_folders = 0
self.total_dl_files = 0
self.total_dl_bytes = 0
self.total_ul_files = 0
self.total_ul_bytes = 0
def __str__(self):
print "SYNC RESULT"
print "> Remote path :", self.remote_path
print "> Local path :", self.local_path
print "> Sub folders :", str(len(self.fetch_meatadata_folders))
print ""
print "> Creating new :", self.new_folders_to_files
print "> Downloading :", str(len(self.out_of_date_files))
print "> Uploading"
print " >> Update :", str(len(self.out_of_date_files_upload))
print " >> New :", str(len(self.new_files_to_upload))
return ""
def check_local_path(self, sync_root):
if self.remote_path == sync_root.path:
self.local_path = self.datahandler.datadirpath(sync_root.name)
elif self.remote_path.startswith(sync_root.path):
self.local_path = self.remote_path[len(sync_root.path):]
self.local_path = sync_root.name + self.local_path
self.local_path = self.datahandler.datadirpath(self.local_path)
else:
self.logger.sync_error("Error parsing path in SyncResult.check_local_path()")
return
if os.path.exists(self.local_path):
self.local_folder_exists = True
def create_local_path(self):
if self.total_dl_files == 0:
return
if not os.path.exists(self.local_path):
try:
os.makedirs(self.local_path)
self.local_folder_exists = True
except OSError:
self.logger.sync_error("Failed to create folder in SyncResult.create_local_path(): " + str(self.local_path))
def check_files_for_changes(self):
# Mark subfolders
for child_folder in self.data.get_folders():
self.fetch_meatadata_folders.append(child_folder)
# Mark out of date files, comparing device and remote files
for child_file in self.data.get_files():
try:
if self.local_folder_exists == False:
self.out_of_date_files.append(child_file)
else:
local_file_path = self.local_path + "/" + child_file.get_name()
if os.path.exists(local_file_path):
device_modified = time.strftime("%d.%m.%Y %H:%M:%S", time.gmtime(os.path.getmtime(local_file_path)))
# Parse timestamps
device_datetime = self.parse_timestamp(device_modified)
remote_datetime = self.parse_timestamp(child_file.modified)
device_size_bytes = os.path.getsize(local_file_path)
remote_size_bytes = child_file.size_bytes
if device_datetime == None or remote_datetime == None:
self.logger.warning("Parsing timestamp for " + local_file_path + " failed, skipping sync.")
continue
# Check for changes
if remote_datetime > device_datetime and device_size_bytes != remote_size_bytes:
self.out_of_date_files.append(child_file)
elif device_datetime > remote_datetime and device_size_bytes != remote_size_bytes:
if self.upload_path_check(local_file_path):
self.out_of_date_files_upload.append(local_file_path)
else:
self.out_of_date_files.append(child_file)
except OSError, e:
self.logger.sync_error("OSError was raised while syncing: " + str(e))
# Mark new files on the device for upload
local_folders = []
remote_filenames = []
for remote_file in self.data.get_files():
remote_filenames.append(remote_file.get_name())
try:
for filename in os.listdir(self.local_path):
full_path = self.local_path + "/" + filename
if os.path.isdir(full_path):
local_folders.append(filename)
continue
try:
index = remote_filenames.index(filename)
except:
if self.upload_path_check(full_path):
self.new_files_to_upload.append(full_path)
except OSError, e:
pass # Trying to open non existing non-ascii folder, its marked for DL at this point...
# Mark new local folders for upload
remote_folders = []
for metadata in self.fetch_meatadata_folders:
remote_folders.append(metadata.get_name())
for local_folder_name in local_folders:
try:
index = remote_folders.index(local_folder_name)
except:
full_new_path = self.local_path + "/" + local_folder_name
self.get_all_files(full_new_path)
# Create child results from self.new_folders_to_files
for (subfolder, fileslist) in self.new_folders_to_files.iteritems():
child_result = SyncResult(self.datahandler, None)
child_result.remote_path = self.to_unicode(self.remote_path + "/" + subfolder)
for filepath in fileslist:
child_result.new_files_to_upload.append(filepath)
self.child_upload_results.append(child_result)
# Calculate totals
self.total_folders = len(self.fetch_meatadata_folders)
self.total_dl_files = len(self.out_of_date_files)
for f in self.out_of_date_files:
self.total_dl_bytes += f.size_bytes
self.total_ul_files = len(self.new_files_to_upload) + len(self.out_of_date_files_upload)
for f in self.new_files_to_upload:
self.total_ul_bytes += os.path.getsize(f)
for f in self.out_of_date_files_upload:
self.total_ul_bytes += os.path.getsize(f)
def parse_timestamp(self, timestamp):
main_parts = timestamp.split(" ")
date_parts = main_parts[0].split(".")
time_parts = main_parts[1].split(":")
data = {}
data["day"] = int(date_parts[0])
data["month"] = int(date_parts[1])
data["year"] = int(date_parts[2])
data["hour"] = int(time_parts[0])
data["min"] = int(time_parts[1])
data["sec"] = int(time_parts[2])
try:
datetime_data = datetime.datetime(data["year"], data["month"], data["day"], data["hour"], data["min"], data["sec"])
except Exception, e:
self.logger.sync_error("Exception occurred when parsing timestamp: " + str(e))
return None
return datetime_data
def upload_path_check(self, path):
# Test if filename/path is ok for upload, unfortunately non-ascii
# paths are skipped due to dropbox not accepting them
try:
str(path)
if path.endswith("~"):
self.logger.warning("Skipping sync upload for temp file: " + path.encode("utf-8"))
self.skipped_uploads.append(path)
return False
except:
self.logger.warning("Skipping sync upload for non-ascii path: " + path.encode("utf-8"))
self.skipped_uploads.append(path)
return False
return True
def get_all_files(self, search_path):
basefolder = search_path.split("/")[-1]
for (path, dirs, files) in os.walk(search_path):
if path != search_path:
subfolder = basefolder + path[len(search_path):]
else:
subfolder = basefolder
self.new_folders_to_files[subfolder] = []
for filename in files:
if self.upload_path_check(path + "/" + filename):
self.new_folders_to_files[subfolder].append(path + "/" + filename)
def to_unicode(self, obj, encoding = "utf-8"):
if isinstance(obj, basestring):
if not isinstance(obj, unicode):
obj = unicode(obj, encoding)
return obj
""" SyncDialog is for showing information of sync results and provides button for how to proceed """
class SyncDialog(QMessageBox):
def __init__(self, par):
QMessageBox.__init__(self)
# Grid layout
self.grid_layout = QGridLayout()
self.grid_layout.setHorizontalSpacing(15)
self.grid_layout.setContentsMargins(0,0,0,0)
# Make a main widget with the grid layout
self.widget = QWidget()
self.widget.setFont(QFont("Arial", 14))
self.widget.setLayout(QVBoxLayout())
self.widget.layout().addLayout(self.grid_layout)
# Make a scrollview for the box itself
self.view = QScrollArea()
self.view.setWidget(self.widget)
self.view.setWidgetResizable(True)
self.view.setMinimumHeight(360)
# Add view and show dialog
self.layout().setHorizontalSpacing(0)
self.layout().setVerticalSpacing(0)
self.layout().setContentsMargins(0,0,10,10)
self.layout().addWidget(self.view, 0, 0)
self.layout().addWidget(self.view, 0, 0)
# Internal data
self.row = -1
self.style_title = "QLabel { font-size: 20pt; color: #0099FF; font-weight: bold;}"
self.style_totals = "QLabel { font-size: 14pt; color: rgb(94,189,0); }"
self.new_file_widgets = []
self.label_total_files = None
self.label_total_size = None
def iterate_row(self):
self.row += 1
def add_spacer(self, height = 15):
self.iterate_row()
self.grid_layout.addItem(QSpacerItem(1, height, QSizePolicy.Fixed, QSizePolicy.Fixed), self.row, 0)
def finalize(self):
self.widget.layout().addSpacerItem(QSpacerItem(1, 1, QSizePolicy.Fixed, QSizePolicy.Expanding))
def add_titles(self, text1, text2 = None, text3 = None):
self.iterate_row()
l1 = QLabel(text1)
l1.setStyleSheet(self.style_title)
if text2 != None:
l2 = QLabel(text2)
l2.setStyleSheet(self.style_title)
else:
l2 = None
if text3 != None:
l3 = QLabel(text3)
l3.setStyleSheet(self.style_title)
else:
l3 = None
self.add_widgets(l1, l2, l3)
def add_row(self, text1, text2 = None, text3 = None):
self.iterate_row()
l1 = QLabel(text1)
l2 = None
l3 = None
if text2 != None:
l2 = QLabel(text2)
if text3 != None:
l3 = QLabel(text3)
self.add_widgets(l1, l2, l3)
if text2 == "NEW FILE":
self.new_file_widgets.append(l1)
self.new_file_widgets.append(l2)
self.new_file_widgets.append(l3)
def add_totals(self, text1, text2 = None, text3 = None):
self.iterate_row()
l1 = QLabel(text1)
l1.setStyleSheet(self.style_totals)
if text2 != None:
l2 = QLabel(text2)
l2.setStyleSheet(self.style_totals)
self.label_total_files = l2
else:
l2 = None
if text3 != None:
l3 = QLabel(text3)
l3.setStyleSheet(self.style_totals)
self.label_total_size = l3
else:
l3 = None
self.add_widgets(l1, l2, l3)
def add_widgets(self, w1, w2, w3, align = Qt.AlignBottom):
self.grid_layout.addWidget(w1, self.row, 0, align)
if w2 != None:
self.grid_layout.addWidget(w2, self.row, 1, align)
if w3 != None:
self.grid_layout.addWidget(w3, self.row, 2, align | Qt.AlignRight)
def hide_new_uploads(self):
for w in self.new_file_widgets:
w.hide()
def set_totals(self, files, size):
if self.label_total_files != None:
self.label_total_files.setText(files)
if self.label_total_size != None:
self.label_total_size.setText(size)
""" TransferManager monitors upload/downloads and relays info to TransferWidget """
class TransferManager(QObject):
def __init__(self, controller):
QObject.__init__(self)
self.datahandler = controller.datahandler
self.config_helper = controller.config_helper
self.ui = controller.ui
self.logger = controller.logger
self.connection = controller.connection
self.connection.set_transfer_manager(self)
self.client = None
# UI interactions
self.show_loading_ui = self.connection.show_loading_ui
self.show_information = self.connection.show_information
# Init poll timer
self.poll_timer = QTimer(self)
self.poll_timer.timeout.connect(self.thread_poller)
# Init thread monitoring
self.active_transfer = None
self.queued_transfer_threads = deque()
# Tranfer to ui item dict
self.tranfer_to_widget = {}
self.sync_widget = None
def set_client(self, client):
self.client = client
def set_current_sync(self, widget):
self.sync_widget = widget
def set_transfer_widget(self, transfer_widget):
self.transfer_widget = transfer_widget
def start_poller(self, timeout_msec = 50):
self.poll_timer.start(timeout_msec)
def stop_poller(self):
self.poll_timer.stop()
def get_transfer_widget(self, transfer):
try:
transfer_widget = self.tranfer_to_widget[self.active_transfer]
except KeyError:
self.logger.transfer_error("Could not find transfer widget!")
transfer_widget = None
return transfer_widget
def thread_poller(self):
if self.active_transfer == None:
self.stop_poller()
return
self.active_transfer.join(0.01)
if not self.active_transfer.isAlive():
transfer = self.active_transfer
transfer_widget = self.get_transfer_widget(transfer)
self.active_transfer = None
if transfer.error != None:
transfer_widget.set_failed()
self.logger.transfer_error(transfer.transfer_type + " of " + transfer.file_name + " failed, no connection?")