-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathscreenimporting.py
More file actions
1515 lines (1357 loc) · 62.1 KB
/
Copy pathscreenimporting.py
File metadata and controls
1515 lines (1357 loc) · 62.1 KB
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 datetime
from shutil import copy2
import time
import threading
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.screenmanager import Screen
from kivy.properties import ObjectProperty, StringProperty, ListProperty, BooleanProperty, NumericProperty, DictProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.treeview import TreeViewNode
try:
from shutil import disk_usage
except:
disk_usage = None
from generalcommands import local_path, list_files, format_size, naming, get_file_info, offset_file_time
from generalelements import NormalPopup, ScanningPopup, NormalLabel, InputPopup, TreeViewButton, NormalDropDown, MenuButton, ExpandableButton
from filebrowser import FileBrowser
from generalconstants import *
from kivy.lang.builder import Builder
Builder.load_string("""
<ImportScreen>:
canvas.before:
Color:
rgba: app.theme.background
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: 'vertical'
MainHeader:
NormalButton:
text: 'Back To Library'
on_release: root.back()
HeaderLabel:
text: 'Import Photos'
InfoLabel:
DatabaseLabel:
InfoButton:
SettingsButton:
BoxLayout:
orientation: 'horizontal'
BoxLayout:
orientation: 'vertical'
size_hint_x: .75
Header:
size_hint_y: None
height: app.button_scale
NormalLabel:
text: 'Import From:'
NormalButton:
id: newPresetButton
disabled: True
text: 'New Preset'
on_release: root.add_preset()
MainArea:
Scroller:
id: presetsContainer
do_scroll_x: False
GridLayout:
height: self.minimum_height
size_hint_y: None
cols: 1
id: presets
LargeBufferX:
StackLayout:
size_hint_x: .25 if root.show_naming else 0
opacity: 1 if root.show_naming else 0
Scroller:
size_hint_y: 1
GridLayout:
size_hint_y: None
height: self.minimum_height
cols: 1
NormalLabel:
text_size: self.width, None
height: self.texture_size[1]
text: 'Naming Method Details\\n\\nYou may type in an import folder template into this field, the folder names will be generated from the template. The following characters are not allowed: . \\ / : * ? < > | \\nEncase the title and surrounding characters in < > to hide the surrounding characters if the title is not set. "Folder< - %t>" would result in "Folder" if Title is not set.\\n\\nThe following keys will be replaced in the input to create a folder name:'
GridLayout:
cols: 3
size_hint_y: None
size_hint_y: 1
height: (app.button_scale * 11)
ShortLabel:
text: '%Y'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Full Year (2016)'
ShortLabel:
text: '%y'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Year Decade Digits (16)'
ShortLabel:
text: '%B'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Full Month Name (January)'
ShortLabel:
text: '%b'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Month In 3 Letters (Jan)'
ShortLabel:
text: '%M'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Month In 2 Digits (01)'
ShortLabel:
text: '%m'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Month In Digits, No Padding (1)'
ShortLabel:
text: '%D'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Day Of Month In 2 Digits (04)'
ShortLabel:
text: '%d'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Day Of Month, No Padding (4)'
ShortLabel:
text: '%T'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Folder Title (My Pictures)'
ShortLabel:
text: '%t'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Folder Title With Underscores (My_Pictures)'
ShortLabel:
text: '%%'
ShortLabel:
text: ' - '
LeftNormalLabel:
text: 'Percent Sign (%)'
<ImportingScreen>:
canvas.before:
Color:
rgba: app.theme.background
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: 'vertical'
MainHeader:
NormalButton:
text: 'Back To Library'
on_release: root.back()
MediumBufferX:
NormalButton:
text: 'Import Photos'
on_release: root.finalize_import()
MediumBufferX:
ShortLabel:
id: totalSize
text: ''
MediumBufferX:
NormalToggle:
state: 'down' if root.delete_originals == True else 'normal'
text: 'Delete Original Photos' if root.delete_originals else 'Dont Delete Original Photos'
on_press: root.set_delete_originals(self.state)
HeaderLabel:
text: 'Import Photos'
InfoLabel:
DatabaseLabel:
InfoButton:
SettingsButton:
MainArea:
orientation: 'horizontal'
SplitterPanelLeft:
id: leftpanel
#width: app.leftpanel_width
BoxLayout:
orientation: 'vertical'
Header:
size_hint_y: None
height: app.button_scale
NormalLabel:
text: 'Folders:'
NormalButton:
text: 'Delete'
on_release: root.delete_folder()
warn: True
NormalButton:
text: 'New'
on_release: root.add_folder()
BoxLayout:
Scroller:
id: foldersContainer
do_scroll_x: True
NormalTreeView:
id: folders
Header:
size_hint_y: None
height: app.button_scale
NormalLabel:
text: 'File Date Offset:'
FloatInput:
hint_text: "Hours"
text: root.timezone_offset
on_text: root.timezone_offset = self.text
BoxLayout:
orientation: 'vertical'
Header:
ShortLabel:
text: 'Current Photos In:'
NormalLabel:
id: folderName
text: ''
LargeBufferX:
NormalButton:
text: 'Toggle Select'
on_release: root.toggle_select()
NormalButton:
id: deleteButton
text: 'Remove Selected'
disabled: True
warn: True
on_release: root.delete()
Header:
id: folderDetails
BoxLayout:
size_hint_x: 0.5
ShortLabel:
text: 'Title:'
NormalInput:
disabled: True
id: folderTitle
input_filter: app.test_album
multiline: False
text: ''
on_text: root.new_title(self)
SmallBufferX:
BoxLayout:
ShortLabel:
text: 'Description:'
NormalInput:
disabled: True
id: folderDescription
input_filter: app.test_description
multiline: True
text: ''
on_text: root.new_description(self)
NormalRecycleView:
id: photosContainer
viewclass: 'PhotoRecycleThumbWide'
SelectableRecycleGridWide:
id: photos
<ImportPresetArea>:
cols: 1 if app.simple_interface else 2
size_hint_y: None
padding: app.padding
spacing: app.padding, 0
height: (app.button_scale * (13 if app.simple_interface else 7))+(app.padding*2)
GridLayout:
cols: 2
spacing: app.padding, 0
size_hint_y: None
height: app.button_scale * 6
GridLayout:
cols: 1
size_hint_x: None
size_hint_y: None
width: self.minimum_width
height: app.button_scale * 6
NormalLabel:
size_hint_x: None
width: self.texture_size[0]
text: 'Preset Name: '
NormalLabel:
size_hint_x: None
width: self.texture_size[0]
text: 'Folder Name: '
NormalLabel:
size_hint_x: None
width: self.texture_size[0]
text: 'Naming Method: '
NormalLabel:
size_hint_x: None
width: self.texture_size[0]
text: 'Adjust File Date Hours: '
NormalLabel:
size_hint_x: None
width: self.texture_size[0]
text: 'Delete Originals: '
NormalLabel:
size_hint_x: None
width: self.texture_size[0]
text: 'Import To: '
NormalLabel:
size_hint_x: None
width: self.texture_size[0]
text: 'Database: '
GridLayout:
cols: 1
size_hint_y: None
height: app.button_scale * 6
NormalInput:
size_hint_x: 1
text: root.title
multiline: False
input_filter: app.test_album
on_focus: root.set_title(self)
NormalLabel:
text: root.naming_example
NormalInput:
size_hint_x: 1
text: root.naming_method
multiline: False
input_filter: root.test_naming_method
on_focus: root.new_naming_method(self)
FloatInput:
size_hint_x: 1
text: root.timezone_offset
hint_text: 'Hours'
multiline: False
on_focus: root.set_timezone_offset(self)
NormalToggle:
size_hint_x: 1
state: 'down' if root.delete_originals == True else 'normal'
text: str(root.delete_originals)
on_press: root.set_delete_originals(self.state)
MenuStarterButtonWide:
size_hint_x: 1
text: root.import_to_folder_friendly[root.single_folder]
on_release: root.import_to_folder_dropdown.open(self)
MenuStarterButtonWide:
id: importToButton
size_hint_x: 1
text: root.import_to
on_release: root.imports_dropdown.open(self)
BoxLayout:
size_hint_y: None
height: app.button_scale * 6
orientation: 'vertical'
NormalLabel:
text_size: self.size
halign: 'left'
valign: 'middle'
text: 'Import From Folders:'
Scroller:
size_hint_y: None
height: app.button_scale * 4
NormalTreeView:
size_hint_y: None
height: app.button_scale * 4
id: importPresetFolders
hide_root: True
root_options: {'text': 'Import From Folders:', 'font_size':app.text_scale}
WideButton:
text: 'Add Folder...'
on_release: root.add_folder()
<ImportPresetFolder>:
orientation: 'horizontal'
size_hint_y: None
height: app.button_scale
NormalLabel:
text: root.folder
RemoveButton:
id: importPresetFolderRemove
on_release: root.remove_folder()
""")
class ImportScreen(Screen):
"""Screen layout for beginning the import photos process.
Displays import presets and allows the user to pick one.
"""
popup = None
selected_import = NumericProperty(-1)
show_naming = BooleanProperty(False)
def back(self, *_):
app = App.get_running_app()
app.show_database()
return True
def dismiss_extra(self):
"""Dummy function, not valid for this screen, but the app calls it when escape is pressed."""
return False
def import_preset(self):
"""Activates the import process using the selected import preset."""
app = App.get_running_app()
preset = app.imports[self.selected_import]
if not preset['import_from']:
app.message("Please Set An Import Directory.")
return
good_paths = []
for path in preset['import_from']:
if os.path.exists(path):
good_paths.append(path)
if not good_paths:
app.message("No Import From Directories Exist.")
return
if not os.path.exists(preset['import_to']):
app.message("Import To Directory Does Not Exist.")
return
database_folders = app.config.get('Database Directories', 'paths')
database_folders = local_path(database_folders)
if database_folders.strip(' '):
databases = database_folders.split(';')
else:
databases = []
if preset['import_to'] not in databases:
app.message("Please Set A Photo Directory To Import To.")
return
app.importing_screen.import_to = preset['import_to']
app.importing_screen.naming_method = preset['naming_method']
app.importing_screen.delete_originals = preset['delete_originals']
app.importing_screen.import_from = preset['import_from']
app.importing_screen.single_folder = preset['single_folder']
app.importing_screen.timezone_offset = preset['timezone_offset']
app.importing_screen.import_index = self.selected_import
app.show_importing()
def add_preset(self):
"""Creates a new blank import preset."""
app = App.get_running_app()
app.import_preset_new()
self.selected_import = len(app.imports) - 1
self.update_treeview()
def on_leave(self):
"""Called when the screen is left. Save the import presets."""
app = App.get_running_app()
app.clear_drags()
app.import_preset_write()
presets = self.ids['presets']
presets.clear_widgets()
def on_enter(self):
"""Called on entering the screen, updates the treeview and variables."""
self.show_naming = False
self.selected_import = -1
self.update_treeview()
def update_treeview(self):
"""Clears and redraws all the import presets in the treeview."""
app = App.get_running_app()
presets = self.ids['presets']
#Clear old presets
presets.clear_widgets()
#Check if database folders are set, cant import without somewhere to import to.
database_folders = app.config.get('Database Directories', 'paths')
database_folders = local_path(database_folders)
if database_folders.strip(' '):
databases = database_folders.split(';')
else:
databases = []
new_preset_button = self.ids['newPresetButton']
if databases:
new_preset_button.disabled = False
for index, import_preset in enumerate(app.imports):
preset = ImportPreset(index=index, text=import_preset['title'], owner=self, import_to=import_preset['import_to'])
preset.data = import_preset
if index == self.selected_import:
preset.expanded = True
presets.add_widget(preset)
else:
new_preset_button.disabled = True
presets.add_widget(NormalLabel(text="You Must Set Up A Photo Directory Before Importing Photos"))
def has_popup(self):
"""Detects if the current screen has a popup active.
Returns: True or False
"""
if self.popup:
if self.popup.open:
return True
return False
def dismiss_popup(self, *_):
"""Close a currently open popup for this screen."""
if self.popup:
self.popup.dismiss()
self.popup = None
def key(self, key):
"""Dummy function, not valid for this screen but the app calls it."""
if not self.popup or (not self.popup.open):
pass
class ImportingScreen(Screen):
"""Screen layout for photo importing process.
Displays photos from directories and lets you select which ones to import.
"""
import_index = NumericProperty(0) #Index of the import preset being used
type = StringProperty('')
selected = StringProperty('')
import_to = StringProperty('')
naming_method = StringProperty('')
delete_originals = BooleanProperty(False)
single_folder = StringProperty('formatted')
import_from = ListProperty()
popup = None
import_photos = []
duplicates = []
photos = []
folders = {}
unsorted = []
removed = []
total_size = 0
cancel_scanning = BooleanProperty(False) #The importing process thread checks this and will stop if set to True.
scanningpopup = None #Popup dialog showing the importing process progress.
scanningthread = None #Importing files thread.
popup_update_thread = None #Updates the percentage and time index on scanning popup
percent_completed = NumericProperty()
start_time = NumericProperty()
import_scanning = BooleanProperty(False)
timezone_offset = StringProperty('')
def back(self, *_):
app = App.get_running_app()
app.show_database()
return True
def rescale_screen(self):
app = App.get_running_app()
self.ids['leftpanel'].width = app.left_panel_width()
def get_selected_photos(self, fullpath=False):
photos = self.ids['photos']
photos_container = self.ids['photosContainer']
selected_indexes = photos.selected_nodes
selected_photos = []
for selected in selected_indexes:
if fullpath:
selected_photos.append(photos_container.data[selected]['fullpath'])
else:
selected_photos.append(photos_container.data[selected]['photoinfo'])
return selected_photos
def dismiss_extra(self):
"""Cancels the import process if it is running"""
if self.import_scanning:
self.cancel_import()
return True
else:
return False
def date_to_folder(self, date_info):
"""Generates a string from a date in the format YYYYMMDD."""
folder = str(date_info.year)+str(date_info.month).zfill(2)+str(date_info.day).zfill(2)
return folder
def on_leave(self, *_):
app = App.get_running_app()
app.clear_drags()
if app.imports[self.import_index]['timezone_offset'] != self.timezone_offset:
app.imports[self.import_index]['timezone_offset'] = self.timezone_offset
app.import_preset_write()
def on_enter(self):
"""Called when the screen is entered. Sets up variables, and scans the import folders."""
app = App.get_running_app()
self.ids['leftpanel'].width = app.left_panel_width()
self.duplicates = []
self.import_photos = []
self.folders = {}
self.unsorted = []
self.removed = []
self.total_size = 0
self.import_scanning = False
#Display message that folder scanning is in progress
self.cancel_scanning = False
self.scanningpopup = ScanningPopup(title='Scanning Import Folders...', auto_dismiss=False, size_hint=(None, None), size=(app.popup_x, app.button_scale * 4))
self.scanningpopup.open()
scanning_button = self.scanningpopup.ids['scanningButton']
scanning_button.bind(on_release=self.cancel_import)
self.percent_completed = 0
self.scanningthread = threading.Thread(target=self.scan_folders)
self.import_scanning = True
self.scanningthread.start()
self.start_time = time.time()
def scan_folders(self, *_):
"""Function that scans the import folders for valid files to import and populates all dialogs."""
app = App.get_running_app()
current_timestamp = time.time()
#Scan the folders
for folder in self.import_from:
if os.path.isdir(folder):
files = list_files(folder)
for file_info in files:
#update popup
if self.cancel_scanning:
self.scanning_canceled()
return
self.percent_completed = self.percent_completed + 1
if self.percent_completed > 100:
self.percent_completed = 0
self.scanningpopup.scanning_percentage = self.percent_completed
extension = os.path.splitext(file_info[0])[1].lower()
if extension in app.imagetypes or extension in app.movietypes:
photo_info = get_file_info(file_info, import_mode=True)
is_in_database = app.in_database(photo_info, time_offset=self.timezone_offset)
if not is_in_database:
is_in_imported = app.in_imported(photo_info, time_offset=self.timezone_offset)
if not is_in_imported:
#Non-imported file encountered
self.total_size = self.total_size+photo_info[4]
self.import_photos.append(photo_info)
if self.single_folder == 'single':
date = current_timestamp
else:
date = photo_info[3]
date_info = datetime.datetime.fromtimestamp(date)
foldername = self.date_to_folder(date_info)
year = str(date_info.year)
month = str(date_info.month).zfill(2)
if self.single_folder == 'year':
parent = year
folderdate = os.path.join(parent, foldername)
if year not in self.folders:
self.folders[year] = {'name': year, 'naming': False, 'title': '', 'description': '', 'year': date_info.year, 'month': date_info.month, 'day': date_info.day, 'photos': [], 'parent': ''}
elif self.single_folder == 'month':
parent = os.path.join(year, month)
folderdate = os.path.join(parent, foldername)
if year not in self.folders:
self.folders[year] = {'name': year, 'naming': False, 'title': '', 'description': '', 'year': date_info.year, 'month': date_info.month, 'day': date_info.day, 'photos': [], 'parent': ''}
if parent not in self.folders:
self.folders[parent] = {'name': month, 'naming': False, 'title': '', 'description': '', 'year': date_info.year, 'month': date_info.month, 'day': date_info.day, 'photos': [], 'parent': year}
else:
folderdate = foldername
parent = ''
if folderdate not in self.folders:
self.folders[folderdate] = {'name': foldername, 'naming': True, 'title': '', 'description': '', 'year': date_info.year, 'month': date_info.month, 'day': date_info.day, 'photos': [], 'parent': parent}
self.folders[folderdate]['photos'].append(photo_info)
else:
self.duplicates.append(photo_info)
else:
self.duplicates.append(photo_info)
self.scanningpopup.dismiss()
self.scanningpopup = None
self.scanningpopup = None
self.import_scanning = False
Clock.schedule_once(self.scanning_completed)
def scanning_completed(self, *_):
self.update_treeview()
self.update_photolist()
def scanning_canceled(self):
app = App.get_running_app()
app.message("Canceled import scanning.")
self.scanningpopup.dismiss()
self.scanningpopup = None
self.import_scanning = False
Clock.schedule_once(lambda *dt: app.show_database())
def cancel_import(self, unknown=False):
"""Cancel the import process."""
self.cancel_scanning = True
def finalize_import(self):
"""Begin the final stage of the import - copying files."""
app = App.get_running_app()
#Create popup to show importing progress
self.cancel_scanning = False
self.scanningpopup = ScanningPopup(title='Importing Files', auto_dismiss=False, size_hint=(None, None), size=(app.popup_x, app.button_scale * 4))
self.scanningpopup.open()
scanning_button = self.scanningpopup.ids['scanningButton']
scanning_button.bind(on_release=self.cancel_import)
#Start importing thread
self.percent_completed = 0
self.scanningthread = threading.Thread(target=self.importing_process)
self.import_scanning = True
self.scanningthread.start()
self.start_time = time.time()
def importing_process(self):
"""Function that actually imports the files."""
app = App.get_running_app()
folders = self.folders
import_to = self.import_to
total_size = self.total_size
imported_size = 0
self.scanningpopup.scanning_text = "Importing "+format_size(total_size)+' 0%'
imported_folders = []
imported_files = 0
failed_files = 0
if disk_usage:
free_space = disk_usage(import_to)[2]
if total_size > free_space:
self.scanningpopup.dismiss()
self.scanningpopup = None
app.message("Not enough free drive space! Cancelled import.")
Clock.schedule_once(lambda *dt: app.show_import())
#Scan folders
for folder_path in folders:
if self.cancel_scanning:
break
folder = folders[folder_path]
folder_name = folder['name']
if folder['photos']:
if folder['naming']:
folder_name = naming(self.naming_method, title=folder['title'], year=folder['year'], month=folder['month'], day=folder['day'])
photos = folder['photos']
parent = folder['parent']
if parent:
path_string = []
while parent:
newfolder = folders[parent]
newfolder_name = newfolder['name']
if newfolder['naming']:
newfolder_name = naming(self.naming_method, title=newfolder['title'], year=newfolder['year'], month=newfolder['month'], day=newfolder['day'])
path_string.append(newfolder_name)
parent = newfolder['parent']
for path in path_string:
folder_name = os.path.join(path, folder_name)
if '%T' in self.naming_method:
title = ''
else:
title = folder['title']
folderinfo = [folder_name, title, folder['description']]
path = os.path.join(import_to, folder_name)
if not os.path.isdir(path):
os.makedirs(path)
if not app.database_folder_exists(folderinfo[0]):
app.database_folder_add(folderinfo)
else:
if folderinfo[1]:
app.database_folder_update_title(folderinfo[0], folderinfo[1])
if folderinfo[2]:
app.database_folder_update_description(folderinfo[0], folderinfo[2])
#Scan and import photos in folder
for photo in photos:
if self.cancel_scanning:
break
completed = (imported_size/total_size)
remaining = 1 - completed
self.percent_completed = 100*completed
self.scanningpopup.scanning_percentage = self.percent_completed
seconds_elapsed = time.time() - self.start_time
time_elapsed = ' Time: '+str(datetime.timedelta(seconds=int(seconds_elapsed)))
if self.percent_completed > 0:
seconds_remain = (seconds_elapsed * remaining) / completed
time_remain = ' Remaining: ' + str(datetime.timedelta(seconds=int(seconds_remain)))
else:
time_remain = ''
self.scanningpopup.scanning_text = "Importing "+format_size(total_size)+' '+str(int(self.percent_completed))+'% '+time_elapsed+time_remain
old_full_filename = os.path.join(photo[2], photo[0])
new_photo_fullpath = os.path.join(folder_name, photo[10])
new_full_filename = os.path.join(import_to, new_photo_fullpath)
thumbnail_data = app.database_thumbnail_get(photo[0], temporary=True)
if not app.database_exists(new_photo_fullpath):
photo[0] = new_photo_fullpath
photo[1] = folder_name
photo[2] = import_to
photo[6] = int(time.time())
try:
copy2(old_full_filename, new_full_filename)
except:
failed_files = failed_files + 1
imported_size = imported_size + photo[4]
else:
try:
timezone_offset = float(self.timezone_offset)
except:
timezone_offset = 0.0
if timezone_offset:
new_cre, new_mod = offset_file_time(new_full_filename, timezone_offset)
photo[3] = new_mod
if self.delete_originals:
if os.path.isfile(new_full_filename):
if os.path.getsize(new_full_filename) == os.path.getsize(old_full_filename):
os.remove(old_full_filename)
app.database_add(photo)
app.database_imported_add(photo[0], photo[10], photo[3])
if thumbnail_data:
thumbnail = thumbnail_data[2]
app.database_thumbnail_write(photo[0], int(time.time()), thumbnail, photo[13])
imported_size = imported_size+photo[4]
imported_files = imported_files + 1
else:
failed_files = failed_files + 1
imported_size = imported_size + photo[4]
"""
imported_folders.append(folder_name)
"""
app.imported.commit()
app.photos.commit()
app.folders.commit()
app.thumbnails.commit()
app.update_photoinfo(folders=imported_folders)
self.scanningpopup.dismiss()
if failed_files:
failed = ' Could not import ' + str(failed_files) + ' files.'
else:
failed = ''
if not self.cancel_scanning:
if imported_files:
app.message("Finished importing "+str(imported_files)+" files."+failed)
else:
if imported_files:
app.message("Canceled importing, "+str(imported_files)+" files were imported."+failed)
else:
app.message("Canceled importing, no files were imported.")
self.scanningpopup = None
self.import_scanning = False
Clock.schedule_once(lambda *dt: app.show_database())
def set_delete_originals(self, state):
"""Enable the 'Delete Originals' option."""
if state == 'down':
self.delete_originals = True
else:
self.delete_originals = False
def previous_album(self):
"""Switch to the previous album in the list."""
database = self.ids['folders']
selected_album = database.selected_node
if selected_album:
nodes = list(database.iterate_all_nodes())
index = nodes.index(selected_album)
if index <= 1:
index = len(nodes)
new_selected_album = nodes[index-1]
database.select_node(new_selected_album)
new_selected_album.on_press()
database_container = self.ids['foldersContainer']
database_container.scroll_to(new_selected_album)
def next_album(self):
"""Switch to the next item on the list."""
database = self.ids['folders']
selected_album = database.selected_node
if selected_album:
nodes = list(database.iterate_all_nodes())
index = nodes.index(selected_album)
if index >= len(nodes)-1:
index = 0
new_selected_album = nodes[index+1]
database.select_node(new_selected_album)
new_selected_album.on_press()
database_container = self.ids['foldersContainer']
database_container.scroll_to(new_selected_album)
def delete(self):
"""Remove selected files and place them in the unsorted folder."""
if self.type == 'folder' or (self.type == 'extra' and self.selected == 'unsorted'):
selected_files = self.get_selected_photos()
for photo in selected_files:
if self.selected != 'unsorted':
self.folders[self.selected]['photos'].remove(photo)
self.unsorted.append(photo)
self.update_treeview()
self.update_photolist()
def add_folder(self):
"""Begin the add folder process, create an input popup."""
content = InputPopup(hint='Folder Name', text='Enter A Folder Name:')
app = App.get_running_app()
content.bind(on_answer=self.add_folder_answer)
self.popup = NormalPopup(title='Create Folder', content=content, size_hint=(None, None), size=(app.popup_x, app.button_scale * 4), auto_dismiss=False)
self.popup.open()
def add_folder_answer(self, instance, answer):
"""Confirm adding the folder.
Arguments:
instance: Dialog that called this function.
answer: String, if set to 'yes', folder is created.
"""
app = App.get_running_app()
if answer == 'yes':
text = instance.ids['input'].text.strip(' ')
if text:
if self.type == 'extra':
root = ''
else:
root = self.selected
path = os.path.join(root, text)
if path not in self.folders:
self.folders[path] = {'name': text, 'parent': root, 'naming': False, 'title': '', 'description': '', 'year': 0, 'month': 0, 'day': 0, 'photos': []}
else:
app.message("Folder already exists.")
self.dismiss_popup()
self.update_treeview()
def delete_folder(self):
"""Delete the selected import folder and move photos to the unsorted folder."""
if self.type == 'folder' and self.selected:
folder_info = self.folders[self.selected]
photos = folder_info['photos']
for photo in photos:
self.unsorted.append(photo)
del self.folders[self.selected]
self.selected = ''
self.type = 'None'
self.update_treeview()
self.update_photolist()
def toggle_select(self):
"""Toggles the selection of photos in the current album."""
photos = self.ids['photos']
photos.toggle_select()
self.update_selected()
def select_none(self):
"""Deselects all photos."""
photos = self.ids['photos']
photos.clear_selection()
self.update_selected()
def update_treeview(self):
"""Clears and repopulates the left-side folder list."""
folder_list = self.ids['folders']
#Clear the treeview list
nodes = list(folder_list.iterate_all_nodes())
for node in nodes:
folder_list.remove_node(node)
selected_node = None
#folder_item = TreeViewButton(target='removed', type='extra', owner=self, view_album=False)
#folder_item.folder_name = 'Removed (Never Scan Again)'
#total_photos = len(self.removed)
#folder_item.total_photos_numeric = total_photos
#if total_photos > 0:
# folder_item.total_photos = '('+str(total_photos)+')'
#folder_list.add_node(folder_item)
#if self.selected == 'removed' and self.type == 'extra':
# selected_node = folder_item