-
Notifications
You must be signed in to change notification settings - Fork 4
/
lobookmover.py
2034 lines (1460 loc) · 73.9 KB
/
lobookmover.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
"""
lobookmover.py
This contains all the book moving fuction the script uses. Also the path generator
Version 2.1:
Copyright 2010-2012 Stonepaw
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import clr
import re
import System
from System import Func, Action, ArgumentException, ArgumentNullException, NotSupportedException, Single
from System.Text import StringBuilder
from System.IO import Path, File, FileInfo, DirectoryInfo, Directory, IOException, PathTooLongException, DirectoryNotFoundException
import loforms
from loforms import PathTooLongForm, MultiValueSelectionFormArgs, MultiValueSelectionFormResult, MultiValueSelectionForm
import locommon
from locommon import Mode, get_earliest_book, name_to_field, field_to_name, check_metadata_rules, check_excluded_folders, UNDOFILE, UndoCollection, get_last_book
from loduplicate import DuplicateResult, DuplicateForm, DuplicateAction
import lologger
clr.AddReference("System.Drawing")
from System.Drawing.Imaging import ImageFormat
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import DialogResult
clr.AddReferenceByPartialName('ComicRack.Engine')
from cYo.Projects.ComicRack.Engine import MangaYesNo, YesNo
clr.AddReference("Microsoft.VisualBasic")
from Microsoft.VisualBasic import FileIO
class MoveResult(object):
Success = 1
Failed = 2
Skipped = 3
Duplicate = 4
FailedMove = 5
class BookToMove(object):
def __init__(self, book, path, index, failed_fields):
self.book = book
self.path = path
self.profile_index = index
self.failed_fields = failed_fields
class BookMoverResult(object):
def __init__(self, report_text, failed_or_skipped):
self.report_text = report_text
self.failed_or_skipped = failed_or_skipped
class ProfileReport(object):
def __init__(self, total, name, mode):
self.success = 0
self.failed = 0
self.skipped = 0
self._total = total
self._name = name
self._mode = mode
def get_report(self, cancelled):
if cancelled:
self.skipped = self._total - self.success - self.failed
return "%s:\nSuccessfully %s: %s\tSkipped: %s\tFailed: %s" % (self._name, ModeText.get_mode_past(self._mode), self.success,
self.skipped, self.failed)
class ModeText(object):
@staticmethod
def get_mode_text(mode):
if mode == Mode.Move:
return "move"
elif mode == Mode.Copy:
return "copy"
else:
return "move (simulated)"
@staticmethod
def get_mode_present(mode):
if mode == Mode.Copy:
return "copying"
elif mode == Mode.Move:
return "moving"
else:
return "moving (simulated)"
@staticmethod
def get_mode_past(mode):
if mode == Mode.Copy:
return "copied"
elif mode == Mode.Move:
return "moved"
else:
return "moved (simulated)"
class BookMover(object):
def __init__(self, worker, form, logger):
self.worker = worker
self.form = form
self.logger = logger
self.pathmaker = PathMaker(form, None)
self.failed_or_skipped = False
#Hold books that are duplicates so they can be all asked at the end.
self.HeldDuplicateBooks = []
self.HeldDuplicateCount = 0
#These variables are for when the script is in test mode
self.CreatedPaths = []
self.MovedBooks = []
#This hold a list of the book moved and is saved in undo.txt for the undo script
self.undo_collection = UndoCollection()
#For duplicates
self.always_do_duplicate_action = False
self.duplicate_action = None
def create_book_paths(self, books, profiles):
"""Find the destination paths for all the books given a set of profiles.
Only the last file path is found if the book can be moved under several profiles.
If several profiles are in copy mode, the book will be copied several times.
Returns a list of BookToMove objects.
"""
books_and_paths = []
self.profile_reports = [ProfileReport(len(books), profile.Name, profile.Mode) for profile in profiles]
for book in books:
path = ""
profile_index = None
failed_fields = []
if book.FilePath:
self.report_book_name = book.FilePath
else:
self.report_book_name = book.Caption
for profile in profiles:
index = profiles.index(profile)
self.profile = profile
self.pathmaker.profile = profile
self.logger.SetProfile(profile.Name)
result = self.create_book_path(book)
if result is MoveResult.Skipped:
self.profile_reports[index].skipped += 1
self.failed_or_skipped = True
continue
elif result is MoveResult.Failed:
self.profile_reports[index].failed += 1
self.failed_or_skipped = True
continue
else:
if profile.Mode == Mode.Copy:
books_and_paths.append(BookToMove(book, result, index, self.pathmaker.failed_fields))
continue
else:
if path:
self.profile_reports[profile_index].skipped +=1
self.logger.Add("Skipped", self.report_book_name, "The book is moved by a later profile", profiles[profile_index].Name)
self.failed_or_skipped = True
path = result
profile_index = index
failed_fields = self.pathmaker.failed_fields
if path:
self.profile = profiles[profile_index]
self.logger.SetProfile(self.profile.Name)
#Because the path can already be at location the final profile says the book may be moved with the wrong profile is this is checked earlier.
result = self.check_path_problems(book, Path.GetFileName(path), path)
if result is MoveResult.Skipped:
self.profile_reports[profile_index].skipped = True
self.failed_or_skipped = True
else:
books_and_paths.append(BookToMove(book, path, profile_index, failed_fields))
for item in books_and_paths:
print item.book.FilePath + " : " + item.path
return books_and_paths
def create_book_path(self, book):
"""Creates the new path and checks it for some problems.
Returns the path or a MoveResult if something goes wrong.
"""
if book.FilePath:
self.report_book_name = book.FilePath
else:
self.report_book_name = book.Caption
if book.FilePath and not File.Exists(book.FilePath):
self.logger.Add("Failed", self.report_book_name, "The file does not exist")
return MoveResult.Failed
if not self.book_should_be_moved_with_rules(book):
return MoveResult.Skipped
#Fileless
if not book.FilePath:
if not self.profile.MoveFileless:
self.logger.Add("Skipped", self.report_book_name, "The book is fileless and fileless images are not being created")
return MoveResult.Skipped
elif self.profile.MoveFileless and not book.CustomThumbnailKey:
self.logger.Add("Failed", self.report_book_name, "The fileless book does not have a custom thumbnail")
return MoveResult.Failed
folder_path, file_name, failed = self.pathmaker.make_path(book, self.profile.FolderTemplate, self.profile.FileTemplate)
full_path = Path.Combine(folder_path, file_name)
if failed:
self.failed_or_skipped = True
failed_report_verb = " are"
if len(self.pathmaker.failed_fields) == 1:
failed_report_verb = " is"
if not self.profile.MoveFailed:
self.logger.Add("Failed", self.report_book_name, ",".join(self.pathmaker.failed_fields) + failed_report_verb + " empty.")
return MoveResult.Failed
if not file_name:
self.logger("Failed", self.report_book_name, "The created filename was blank")
return MoveResult.Failed
return full_path
def process_books(self, books, profiles):
books_to_move = self.create_book_paths(books, profiles)
if not books_to_move:
header_text = "\n\n".join([profile_report.get_report(True) for profile_report in self.profile_reports])
report = BookMoverResult(header_text, self.failed_or_skipped)
self.logger.add_header(header_text)
return report
percentage = 1.0/len(books_to_move)*100
progress = 0.0
count = 0
for book in books_to_move:
if self.worker.CancellationPending:
self.logger.Add("Canceled", str(len(books_to_move) - count) + " operations", "User cancelled the script")
header_text = "\n\n".join([profile_report.get_report(True) for profile_report in self.profile_reports])
report = BookMoverResult(header_text, self.failed_or_skipped)
self.logger.add_header(header_text)
return report
count += 1
progress += percentage
self.profile = profiles[book.profile_index]
self.logger.SetProfile(self.profile.Name)
result = self.process_book(book)
if result is MoveResult.Duplicate:
count -= 1
progress -= percentage
self.HeldDuplicateBooks.append(book)
continue
elif result is MoveResult.Skipped:
self.failed_or_skipped = True
self.profile_reports[book.profile_index].skipped += 1
self.worker.ReportProgress(int(round(progress)))
continue
elif result is MoveResult.Failed:
self.failed_or_skipped = True
self.profile_reports[book.profile_index].failed += 1
self.worker.ReportProgress(int(round(progress)))
continue
elif result is MoveResult.Success:
self.profile_reports[book.profile_index].success += 1
self.worker.ReportProgress(int(round(progress)))
continue
self.HeldDuplicateCount = len(self.HeldDuplicateBooks)
for book in self.HeldDuplicateBooks:
if self.worker.CancellationPending:
self.logger.Add("Canceled", str(len(books_to_move) - count) + " operations", "User cancelled the script")
header_text = "\n\n".join([profile_report.get_report(True) for profile_report in self.profile_reports])
report = BookMoverResult(header_text, self.failed_or_skipped)
self.logger.add_header(header_text)
return report
count += 1
progress += percentage
self.profile = profiles[book.profile_index]
self.logger.SetProfile(self.profile.Name)
result = self.process_duplicate_book(book)
self.HeldDuplicateCount -= 1
if result is MoveResult.Skipped:
self.failed_or_skipped = True
self.profile_reports[book.profile_index].skipped += 1
self.worker.ReportProgress(int(round(progress)))
continue
elif result is MoveResult.Failed:
self.failed_or_skipped = True
self.profile_reports[book.profile_index].failed += 1
self.worker.ReportProgress(int(round(progress)))
continue
elif result is MoveResult.Success:
self.profile_reports[book.profile_index].success += 1
self.worker.ReportProgress(int(round(progress)))
continue
if len(self.undo_collection) > 0:
self.undo_collection.save(UNDOFILE)
header_text = "\n\n".join([profile_report.get_report(True) for profile_report in self.profile_reports])
report = BookMoverResult(header_text, self.failed_or_skipped)
self.logger.add_header(header_text)
return report
def process_book(self, book_to_move):
book = book_to_move.book
if book.FilePath:
self.report_book_name = book.FilePath
else:
self.report_book_name = book.Caption
full_path = book_to_move.path
result, full_path = self.check_path_to_long(book, full_path)
if result is not None:
return result
#Duplicate
if File.Exists(full_path) or full_path in self.MovedBooks:
return MoveResult.Duplicate
#Create here because needed for cleaning directories later
old_folder_path = book.FileDirectory
folder_path = Path.GetDirectoryName(full_path)
result = self.create_folder(folder_path, book)
if result is not MoveResult.Success:
return result
if not book.FilePath:
result = self.create_fileless_image(book, full_path)
else:
result = self.move_book(book, full_path)
if self.profile.RemoveEmptyFolder and self.profile.Mode == Mode.Move:
if old_folder_path:
self.remove_empty_folders(DirectoryInfo(old_folder_path))
self.remove_empty_folders(DirectoryInfo(folder_path))
if book_to_move.failed_fields and result == MoveResult.Success:
if len(book_to_move.failed_fields) > 1:
failed_report_verb = " are"
else:
failed_report_verb = " is"
self.logger.Add("Failed", self.report_book_name, ",".join(book_to_move.failed_fields) + failed_report_verb + " empty. " + ModeText.get_mode_past(self.profile.Mode) + " to " + full_path)
return MoveResult.Failed
return result
def process_duplicate_book(self, book_to_move):
book = book_to_move.book
full_path = book_to_move.path
if book.FilePath:
self.report_book_name = book.FilePath
else:
self.report_book_name = book.Caption
#Since the duplicate is checked for last in the orginal process_book function there is no need to check for path errors.
if File.Exists(full_path) or full_path in self.MovedBooks:
#Find the existing book if it occurs in the library
oldbook = self.find_duplicate_book(full_path)
if oldbook == None:
oldbook = FileInfo(full_path)
rename_path = self.create_rename_path(full_path)
rename_filename = Path.GetFileName(rename_path)
if not self.always_do_duplicate_action:
result = self.form.Invoke(Func[type(self.profile), type(book), type(oldbook), str, int, DuplicateResult](self.form.ShowDuplicateForm), System.Array[object]([self.profile, book, oldbook, rename_filename, self.HeldDuplicateCount]))
self.duplicate_action = result.action
if result.always_do_action:
self.always_do_duplicate_action = True
if self.duplicate_action is DuplicateAction.Cancel:
if book.FilePath:
self.logger.Add("Skipped", self.report_book_name, "A file already exists at: " + full_path + " and the user declined to overwrite it")
else:
self.logger.Add("Skipped", self.report_book_name, "The image already exists at: " + full_path + " and the user declined to overwrite it")
return MoveResult.Skipped
elif self.duplicate_action is DuplicateAction.Rename:
#Check if the created path is too long
if len(rename_path) > 259:
result = self.form.Invoke(Func[str, object](self.get_smaller_path), System.Array[System.Object]([rename_path]))
if result is None:
self.logger.Add("Skipped", self.report_book_name, "The path was too long and the user skipped shortening it")
return MoveResult.Skipped
return self.process_duplicate_book(BookToMove(book, result, book_to_move.profile_index, book_to_move.failed_fields))
return self.process_duplicate_book(BookToMove(book, rename_path, book_to_move.profile_index, book_to_move.failed_fields))
elif self.duplicate_action is DuplicateAction.Overwrite:
try:
if self.profile.Mode == Mode.Simulate:
#Because the script goes into a loop if in test mode here since no files are actually changed. return a success
self.logger.Add("Deleted (simulated)", full_path)
if book.FilePath:
self.logger.Add(ModeText.get_mode_past(self.profile.Mode), book.FilePath, "to: " + full_path)
else:
self.logger.Add("Created image", full_path)
self.MovedBooks.append(full_path)
return MoveResult.Success
else:
if self.profile.CopyReadPercentage and type(oldbook) is not FileInfo:
book.LastPageRead = oldbook.LastPageRead
FileIO.FileSystem.DeleteFile(full_path, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin)
except Exception, ex:
self.logger.Add("Failed", self.report_book_name, "Failed to overwrite " + full_path + ". The error was: " + str(ex))
return MoveResult.Failed
#Since we are only working with images there is no need to remove a book from the library
if book.FilePath and type(oldbook) is not FileInfo:
ComicRack.App.RemoveBook(oldbook)
return self.process_duplicate_book(book_to_move)
old_folder_path = book.FileDirectory
if book.FilePath:
result = self.move_book(book, full_path)
else:
result = self.create_fileless_image(book, full_path)
if self.profile.RemoveEmptyFolder and self.profile.Mode == Mode.Move:
if old_folder_path:
self.remove_empty_folders(DirectoryInfo(old_folder_path))
self.remove_empty_folders(FileInfo(full_path).Directory)
if book_to_move.failed_fields and result == MoveResult.Success:
if len(book_to_move.failed_fields) > 1:
failed_report_verb = " are"
else:
failed_report_verb = " is"
self.logger.Add("Failed", self.report_book_name, ",".join(book_to_move.failed_fields) + failed_report_verb + " empty. " + ModeText.get_mode_present(self.profile.Mode) + " to " + full_path)
return MoveResult.Failed
return result
def move_book(self, book, path):
#Finally actually move the book
try:
if self.profile.Mode == Mode.Move:
File.Move(book.FilePath, path)
self.undo_collection.append(book.FilePath, path, self.profile.Name)
book.FilePath = path
elif self.profile.Mode == Mode.Simulate:
self.logger.Add(ModeText.get_mode_past(self.profile.Mode), book.FilePath, "to: " + path)
self.MovedBooks.append(path)
elif self.profile.Mode == Mode.Copy:
File.Copy(book.FilePath, path)
if self.profile.CopyMode:
newbook = ComicRack.App.AddNewBook(False)
newbook.FilePath = path
CopyData(book, newbook)
return MoveResult.Success
except Exception, ex:
self.logger.Add("Failed", self.report_book_name, "because an error occured. The error was: " + str(ex))
return MoveResult.Failed
def create_fileless_image(self, book, path):
#Finally actually move the book
try:
image = ComicRack.App.GetComicThumbnail(book, 0)
format = None
if self.profile.FilelessFormat == ".jpg":
format = ImageFormat.Jpeg
elif self.profile.FilelessFormat == ".png":
format = ImageFormat.Png
elif self.profile.FilelessFormat == ".bmp":
format = ImageFormat.Bmp
if self.profile.Mode == Mode.Simulate:
self.logger.Add("Created image", path)
self.MovedBooks.append(path)
else:
image.Save(path, format)
return MoveResult.Success
except Exception, ex:
self.logger.Add("Failed", self.report_book_name, "Failed to create the image because an error occured. The error was: " + str(ex))
return MoveResult.Failed
def book_should_be_moved_with_rules(self, book):
"""Checks the exlcuded folders and metadata rules to see if the book should be moved.
Returns True if the book should be moved.
"""
if not check_excluded_folders(book.FilePath, self.profile):
self.logger.Add("Skipped", self.report_book_name, "The book is located in an excluded path")
return False
if not check_metadata_rules(book, self.profile):
self.logger.Add("Skipped", self.report_book_name, "The book qualified under the exclude rules")
return False
return True
def check_path_problems(self, book, file_name, full_path):
if full_path == book.FilePath:
self.logger.Add("Skipped", self.report_book_name, "The book is already located at the calculated path")
return MoveResult.Skipped
#In some cases the filepath is the same but has different cases. The FileInfo object dosn't catch this but the File.Move function
#Thinks that it is a duplicate.
if full_path.lower() == book.FilePath.lower():
#In that case, better rename it to the correct case
if self.profile.Mode == Mode.Simulate:
self.logger.Add("Renaming", self.report_book_name, "to: " + full_path)
else:
book.RenameFile(file_name)
self.logger.Add("Skipped", self.report_book_name, "The book is already located at the calculated path")
return MoveResult.Skipped
return None
def check_path_to_long(self, book, full_path):
if len(full_path) > 259:
result = self.form.Invoke(Func[str, object](self.get_smaller_path), System.Array[System.Object]([full_path]))
if result is None:
self.logger.Add("Skipped", self.report_book_name, "The calculated path was too long and the user skipped shortening it")
return MoveResult.Skipped, ""
full_path = result
return None, full_path
def find_duplicate_book(self, path):
"""
Trys to find a book in the CR library via a path
"""
for book in ComicRack.App.GetLibraryBooks():
if book.FilePath == path:
return book
return None
def create_folder(self, folder_path, book):
"""Creates the folder path.
Returns MoveResult.Succes if the creation succeeded, MoveResult.Failed if something went wrong.
"""
if not Directory.Exists(folder_path):
try:
if self.profile.Mode == Mode.Simulate:
if not folder_path in self.CreatedPaths:
self.logger.Add("Created Folder", folder_path)
self.CreatedPaths.append(folder_path)
else:
Directory.CreateDirectory(folder_path)
except (IOException, ArgumentException, ArgumentNullException, PathTooLongException, DirectoryNotFoundException, NotSupportedException), ex:
self.logger.Add("Failed to create folder", folder_path, "Book " + self.report_book_name + " was not moved.\nThe error was: " + str(type(ex)) + ": " + ex.Message)
return MoveResult.Failed
return MoveResult.Success
def create_rename_path(self, path):
#By pescuma. modified slightly
extension = Path.GetExtension(path)
base = path[:-len(extension)]
base = re.sub(" \([0-9]\)$", "", base)
for i in range(100):
newpath = base + " (" + str(i+1) + ")" + extension
#For test mode
if newpath in self.MovedBooks:
continue
if File.Exists(newpath):
continue
else:
return newpath
def remove_empty_folders(self, directory):
"""
Recursivly deletes directories until an non-empty directory is found or the directory is in the excluded list
directory should be a DirectoryInfo object
"""
if not directory.Exists:
return
#Only delete if no file or folder and not in folder never to delete
if len(directory.GetFiles()) == 0 and len(directory.GetDirectories()) == 0 and not directory.FullName in self.profile.ExcludedEmptyFolder:
parent = directory.Parent
directory.Delete()
self.remove_empty_folders(parent)
def get_smaller_path(self, path):
p = PathTooLongForm(path)
r = p.ShowDialog()
if r != DialogResult.OK:
return None
return p._Path.Text
class UndoMover(BookMover):
def __init__(self, worker, form, undo_collection, profiles, logger):
self.worker = worker
self.form = form
self.undo_collection = undo_collection
self.AlwaysDoAction = False
self.HeldDuplicateBooks = {}
self.logger = logger
self.profiles = profiles
self.failed_or_skipped = False
def process_books(self):
books, notfound = self.get_library_books()
success = 0
failed = 0
skipped = 0
count = 0
for book in books + notfound:
count += 1
if self.worker.CancellationPending:
skipped = len(books) + len(notfound) - success - failed
self.logger.Add("Canceled", str(skipped) + " files", "User cancelled the script")
report = BookMoverResult("Successfully moved: %s\tFailed to move: %s\tSkipped: %s\n\n" % (success, failed, skipped), failed > 0 or skipped > 0)
#self.logger.SetCountVariables(failed, skipped, success)
return report
result = self.process_book(book)
if result is MoveResult.Duplicate:
count -= 1
continue
elif result is MoveResult.Skipped:
skipped += 1
self.worker.ReportProgress(count)
continue
elif result is MoveResult.Failed:
failed += 1
self.worker.ReportProgress(count)
continue
elif result is MoveResult.Success:
success += 1
self.worker.ReportProgress(count)
continue
self.HeldDuplicateCount = len(self.HeldDuplicateBooks)
for book in self.HeldDuplicateBooks:
if self.worker.CancellationPending:
skipped = len(books) + len(notfound) - success - failed
self.logger.Add("Canceled", str(skipped) + " files", "User cancelled the script")
report = BookMoverResult("Successfully moved: %s\tFailed to move: %s\tSkipped: %s\n\n" % (success, failed, skipped), failed > 0 or skipped > 0)
#self.logger.SetCountVariables(failed, skipped, success)
return report
result = self.process_duplicate_book(book, self.HeldDuplicateBooks[book])
self.HeldDuplicateCount -= 1
if result is MoveResult.Skipped:
skipped += 1
self.worker.ReportProgress(count)
continue
elif result is MoveResult.Failed:
failed += 1
self.worker.ReportProgress(count)
continue
elif result is MoveResult.Success:
success += 1
self.worker.ReportProgress(count)
continue
report = BookMoverResult("Successfully moved: %s\tFailed to move: %s\tSkipped: %s\n\n" % (success, failed, skipped), failed > 0 or skipped > 0)
#self.logger.SetCountVariables(failed, skipped, success)
return report
def MoveBooks(self):
success = 0
failed = 0
skipped = 0
count = 0
#get a list of the books
books, notfound = self.get_library_books()
for book in books + notfound:
if type(book) == str:
path = self.undo_collection[book]
oldfile = book
else:
path = self.undo_collection[book.FilePath]
oldfile = book.FilePath
count += 1
if self.worker.CancellationPending:
#User pressed cancel
skipped = len(books) + len(notfound) - success - failed
self.report.Append("\n\nOperation cancelled by user.")
break
if not File.Exists(oldfile):
self.report.Append("\n\nFailed to move\n%s\nbecause the file does not exist." % (oldfile))
failed += 1
self.worker.ReportProgress(count)
continue
if path == oldfile:
self.report.Append("\n\nSkipped moving book\n%s\nbecause it is already located at the calculated path." % (oldfile))
skipped += 1
self.worker.ReportProgress(count)
continue
#Created the directory if need be
f = FileInfo(path)
if f.Exists:
self.HeldDuplicateBooks.append(book)
count -= 1
continue
d = f.Directory
if not d.Exists:
d.Create()
if type(book) == str:
oldpath = FileInfo(book).DirectoryName
else:
oldpath = book.FileDirectory
result = self.MoveBook(book, path)
if result == MoveResult.Success:
success += 1
elif result == MoveResult.Failed:
failed += 1
elif result == MoveResult.Skipped:
skipped += 1
#If cleaning directories
if self.settings.RemoveEmptyFolder:
self.CleanDirectories(DirectoryInfo(oldpath))
self.CleanDirectories(DirectoryInfo(f.DirectoryName))
self.worker.ReportProgress(count)
#Deal with the duplicates
for book in self.HeldDuplicateBooks[:]:
if type(book) == str:
path = self.undo_collection[book]
oldpath = book
else:
path = self.undo_collection[book.FilePath]
oldpath = book.FilePath
count += 1
if self.worker.CancellationPending:
#User pressed cancel
skipped = len(books) + len(notfound) - success - failed
self.report.Append("\n\nOperation cancelled by user.")
break
#Created the directory if need be
f = FileInfo(path)
d = f.Directory
if not d.Exists:
d.Create()
if type(book) == str:
oldpath = FileInfo(book).DirectoryName
else:
oldpath = book.FileDirectory
result = self.MoveBook(book, path)
if result == MoveResult.Success:
success += 1
elif result == MoveResult.Failed:
failed += 1
elif result == MoveResult.Skipped:
skipped += 1
#If cleaning directories
if self.settings.RemoveEmptyFolder:
self.CleanDirectories(DirectoryInfo(oldpath))
self.CleanDirectories(DirectoryInfo(f.DirectoryName))
self.HeldDuplicateBooks.remove(book)
self.worker.ReportProgress(count)
#Return the report to the worker thread
report = "Successfully moved: %s\nFailed to move: %s\nSkipped: %s" % (success, failed, skipped)
return [failed + skipped, report, self.report.ToString()]
def process_book(self, book):
if type(book) == str:
undo_path = self.undo_collection.undo_path(book)
current_path = book
self.report_book_name = book
else:
undo_path = self.undo_collection.undo_path(book.FilePath)
current_path = book.FilePath
self.report_book_name = book.FilePath
self.profile = self.profiles[self.undo_collection.profile(current_path)]
if not File.Exists(current_path):
self.logger.Add("Failed", self.report_book_name, "The file does not exist")
return MoveResult.Failed
result = self.check_path_problems(current_path, undo_path)
if result is not None:
return result
#Don't need to check path to long
#Duplicate
if File.Exists(undo_path):
self.HeldDuplicateBooks[book] = undo_path
return MoveResult.Duplicate
#Create here because needed for cleaning directories later
old_folder_path = FileInfo(current_path).DirectoryName
result = self.create_folder(old_folder_path, book)
if result is not MoveResult.Success:
return result
result = self.move_book(book, undo_path)
if self.profile.RemoveEmptyFolder:
self.remove_empty_folders(DirectoryInfo(old_folder_path))
self.remove_empty_folders(FileInfo(undo_path).Directory)
return result
def process_duplicate_book(self, book, undo_path):
if type(book) == str:
current_path = book
self.report_book_name = book
else:
current_path = book.FilePath
self.report_book_name = book.FilePath
self.profile = self.profiles[self.undo_collection.profile(current_path)]
#Since the duplicate is checked for last in the orginal process_book function there is no need to check for path errors.
if File.Exists(undo_path):
#Find the existing book if it occurs in the library
oldbook = self.find_duplicate_book(undo_path)
if oldbook == None:
oldbook = FileInfo(undo_path)
rename_path = self.create_rename_path(undo_path)
rename_filename = Path.GetFileName(rename_path)
if not self.always_do_duplicate_action: