-
Notifications
You must be signed in to change notification settings - Fork 10
/
core.py
executable file
·769 lines (673 loc) · 31.1 KB
/
core.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
#
# core.py
#
# Copyright (C) 2009 laharah <laharah+fbt@gmail.com>
#
# Basic plugin template created by:
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
# Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2009 Damien Churchill <damoxc@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the OpenSSL
# library.
# You must obey the GNU General Public License in all respects for all of
# the code used other than OpenSSL. If you modify file(s) with this
# exception, you may extend this exception to your version of the file(s),
# but you are not obligated to do so. If you do not wish to do so, delete
# this exception statement from your version. If you delete this exception
# statement from all source files in the program, then also delete it here.
#
import os
import traceback
# noinspection PyUnresolvedReferences
from deluge.plugins.pluginbase import CorePluginBase
# noinspection PyUnresolvedReferences
import deluge.component as component
# noinspection PyUnresolvedReferences
import deluge.configmanager
# noinspection PyUnresolvedReferences
from deluge.core.rpcserver import export
from twisted.internet import threads, defer
import pyfilebot
from common import Log
import filebottool.auto_sort
log = Log()
DEFAULT_PREFS = {
"rename_dialog_last_settings": {
"handler_name": None,
"database": None,
"output": None,
"format_string": None,
"rename_action": None,
"show_advanced": False,
"query_override": None,
"on_conflict": None,
"episode_order": None,
"language_code": None,
"download_subs": False,
"subs_language": None,
"encoding": "UTF-8"
},
"saved_handlers": {},
"plugin_preferences": {},
"auto_sort_rules": [],
}
class Core(CorePluginBase):
"""The Plugin Core"""
# noinspection PyAttributeOutsideInit
def enable(self):
self.config = deluge.configmanager.ConfigManager(
"filebottool.conf", DEFAULT_PREFS)
try:
self.filebot_version = pyfilebot.get_version()
log.info("Filebot Found with version {0}".format(
self.filebot_version))
except pyfilebot.FilebotFatalError:
log.error("Filebot cannot be found!")
self.filebot_version = None
self.torrent_manager = component.get("TorrentManager")
self.listening_dictionary = {}
#register event/alert hooks:
component.get("AlertManager").register_handler("storage_moved_alert",
self._on_storage_moved)
event_manager = component.get("EventManager")
event_manager.register_event_handler("TorrentFolderRenamedEvent",
self._on_folder_renamed)
event_manager.register_event_handler("TorrentFileRenamedEvent",
self._on_file_renamed)
event_manager.register_event_handler("TorrentFinishedEvent", self._auto_sort)
def disable(self):
component.get("AlertManager").deregister_handler(self._on_storage_moved)
event_manager = component.get("EventManager")
event_manager.deregister_event_handler("TorrentFolderRenamedEvent",
self._on_folder_renamed)
event_manager.deregister_event_handler("TorrentFileRenamedEvent",
self._on_file_renamed)
event_manager.deregister_event_handler("TorrentFinishedEvent", self._auto_sort)
def update(self):
pass
#########
# Section: Event Handlers
#########
def _on_storage_moved(self, alert):
"""handler for storage movements, Checks listening dictionary if it's
a relevant movement"""
torrent_id = str(alert.handle.info_hash())
log.debug("_on_storage_moved({0})".format(torrent_id))
if torrent_id not in self.listening_dictionary:
return
if self.listening_dictionary[torrent_id]["move_storage"]:
del self.listening_dictionary[torrent_id]["move_storage"]
self._check_listening_dictionary(torrent_id)
def _on_folder_renamed(self, torrent_id, old, new):
"""handler for folder renames, Checks plugin listening dictionary and
takes appropriate action.
"""
log.debug("_on_folder_moved({0},{1}, {2})".format(torrent_id, old, new))
if torrent_id not in self.listening_dictionary:
return
if self.listening_dictionary[torrent_id]["folder_rename"] == (old, new):
del self.listening_dictionary[torrent_id]["folder_rename"]
self._check_listening_dictionary(torrent_id)
def _on_file_renamed(self, torrent_id, index, name):
"""handler for file renames, Checks plugin listening dictionary and
takes appropriate action."""
log.debug("on_file_renamed({0},{1}, {2})".format(torrent_id, index, name))
if torrent_id not in self.listening_dictionary:
return
if index in self.listening_dictionary[torrent_id]:
del self.listening_dictionary[torrent_id][index]
self._check_listening_dictionary(torrent_id)
def _check_listening_dictionary(self, torrent_id):
"""called after events, checks if the plugin has been waiting for the
event and decides what to do."""
if torrent_id in self.listening_dictionary:
if not self.listening_dictionary[torrent_id]:
del self.listening_dictionary[torrent_id]
self.torrent_manager[torrent_id].resume()
log.debug("listning dictionary updated: {0}".format(
self.listening_dictionary))
def _auto_sort(self, torrent_id):
"""called on completed torrents for matching auto sort rules"""
rules = self.config["auto_sort_rules"]
handler = filebottool.auto_sort.check_rules(torrent_id, rules)
if handler:
try:
handler_settings = self.config["saved_handlers"][handler]
except KeyError:
log.error("no handler with name '{0}' could be found!".format(handler))
return
self.do_rename([torrent_id], handler_settings=handler_settings)
#########
# Section: Filebot interaction
#########
# noinspection PyPep8Naming
def _translate_filebot_movements(self, torrent_id, filebot_moves):
"""translates a filebot run into deluge torrent info
Args:
torrent_id
filebot_moves: a list of movements made by filebot
returns: tuple(new_path, new_toplevel, [(index, new file path), ...])
"""
if not filebot_moves:
log.info("No movements for {0}".format(torrent_id))
return
torrent = self.torrent_manager[torrent_id]
current_save_path = torrent.get_status(["save_path"])["save_path"]
current_files = torrent.get_files()
renames = {}
for f in current_files:
renames[self._get_full_os_path(current_save_path, f["path"])] = {
"index": f["index"]
}
# compact the relative moves filebot returns into absolute paths
filebot_moves = [(m[0], os.path.abspath(os.path.join(
os.path.dirname(m[0]), m[1]))) for m in filebot_moves]
# cross-reference
for old, new in filebot_moves:
try:
renames[old]["new_path"] = new
except KeyError:
log.error("could not find index for {0} in the torrent, problem "
"with movement matching.".format(old))
raise
# get new top level based on gcd of new paths
if len(current_files) > 1:
# gcd = Greatest Common Directory, or a torrent's top level.
gcd = os.path.dirname(os.path.commonprefix([m[1] for m
in filebot_moves]))
current_GCD = os.path.join(
torrent.get_status(["save_path"])["save_path"],
torrent.get_status(["name"])["name"])
else:
gcd = None
current_GCD = None
if gcd:
new_save_path = os.path.dirname(gcd)
else:
new_save_path = os.path.dirname(
renames[renames.keys()[0]]["new_path"])
# build filemove tuples by striping out new_save_path
# spliting on sep, and joining with '/'
deluge_moves = []
for old in renames:
if "new_path" not in renames[old]:
continue
if old == renames[old]["new_path"]:
#rename not needed
continue
index = renames[old]["index"]
new_deluge_path = renames[old]["new_path"].replace(new_save_path,
"")[1:]
new_deluge_path = "/".join(new_deluge_path.split(os.path.sep))
deluge_moves.append((index, new_deluge_path))
if gcd == current_GCD:
gcd = None
else:
gcd = os.path.basename(gcd)
if new_save_path == current_save_path:
new_save_path = None
return new_save_path, gcd, deluge_moves
def _redirect_torrent_paths(self, torrent_id, (new_save_path, new_top_lvl,
new_file_paths), original_state=None):
"""redirects a torrent's files and save paths to the new locations.
registers them to the listening dictionary
Args:
torrent_id
a tuple from _translate_filebot_movements
"""
torrent = self.torrent_manager[torrent_id]
if any([new_save_path, new_top_lvl, new_file_paths]):
self.listening_dictionary[torrent_id] = {}
if new_save_path:
self.listening_dictionary[torrent_id]["move_storage"] = new_save_path
torrent.move_storage(new_save_path)
if new_top_lvl:
if len(torrent.get_files()) > 1:
current_top_lvl = torrent.get_files()[0]["path"].split("/")[0] + "/"
self.listening_dictionary[torrent_id]["folder_rename"] = (
current_top_lvl, new_top_lvl + "/")
torrent.rename_folder(current_top_lvl, new_top_lvl)
if new_file_paths:
for index, path in new_file_paths:
self.listening_dictionary[torrent_id][index] = True
torrent.rename_files(new_file_paths)
#prefent resume if torrent was originally paused
if original_state == "Paused":
del self.listening_dictionary[torrent_id]
def _file_conflicts(self, torrent_id, filebot_translation,
skipped_files):
"""
builds a list of exsisting file conflicts for a given torrent rename.
:param torrent_id:
:param filebot_translation:
:return: list of conflicting files
"""
torrent = self.torrent_manager[torrent_id]
if not filebot_translation:
return []
original_files = torrent.get_files()
original_save_path = torrent.get_status(["save_path"])["save_path"]
mockup = self._get_mockup_files_dictionary(torrent_id,
filebot_translation)
new_files = mockup
new_save_path = filebot_translation[0]
if not new_save_path:
new_save_path = original_save_path
original_files = [(f["index"], f["path"]) for f in original_files]
new_files = [(f["index"], f["path"]) for f in new_files]
original_paths = [self._get_full_os_path(original_save_path, f[1])
for f in sorted(original_files)]
new_paths = [self._get_full_os_path(new_save_path, f[1]) for
f in sorted(new_files)]
extra_files = []
for f in mockup:
if f["index"] not in [x[0] for x in filebot_translation[2]]:
extra_files.append(
self._get_full_os_path(new_save_path, f["path"]))
conflicts = []
for original_path, new_path in zip(original_paths, new_paths):
if new_path == original_path:
continue
if (original_path not in skipped_files and
new_path not in extra_files):
continue
if os.path.exists(new_path):
conflicts.append(new_path)
return conflicts
@defer.inlineCallbacks
def _rollback(self, filebot_movements, torrent_id):
targets = [pair[1] for pair in filebot_movements[1]]
try:
results = yield threads.deferToThread(pyfilebot.revert, targets)
except pyfilebot.FilebotRuntimeError, err:
log.error("FILEBOT ERROR: {0}".format(err))
defer.returnValue(None)
# noinspection PyUnboundLocalVariable
log.info("Successfully rolled back files: {0}".format(results[1]))
log.info("forcing recheck on {0}".format(torrent_id))
self.torrent_manager[torrent_id].force_recheck()
#########
# Section: Utilities
#########
def _get_filebot_target(self, torrent_id):
"""returns the path of the file or folder that filebot should target
Args: torrent_id: torrent_id
returns: path
"""
log.debug("targets list for torrent {0}".format(torrent_id))
torrent = self.torrent_manager[torrent_id]
save_path = torrent.get_status(["save_path"])["save_path"]
targets = [self._get_full_os_path(save_path, f["path"]) for f in
torrent.get_files()]
log.debug("targets found: {0}".format(targets))
return targets
@staticmethod
def _get_full_os_path(save_path, deluge_path):
"""given a save path and a deluge file path, return the actual os
path of a given file"""
return os.path.sep.join(save_path.split(os.path.sep) +
deluge_path.split('/'))
@staticmethod
def _configure_filebot_handler(settings, handler=None):
"""Configures a handler using the given settings dictionary.
If no handler is given a new handler is created. Invalid settings
will be skipped
*settings*: a dictionary in format {"setting": value, ...}
*handler*: the handler you want to use, defaults to new Handler
*returns*: a configured handler.
"""
if not handler:
handler = pyfilebot.FilebotHandler()
valid_handler_attributes = [
"format_string",
"database",
"output",
"episode_order",
"rename_action",
"recursive",
"language_code",
"encoding",
"on_conflict",
"query_override",
"non_strict",
"mode"
]
for attribute in valid_handler_attributes:
if attribute in settings:
try:
handler.__setattr__(attribute, settings[attribute])
except ValueError:
log.warning("{0} is not a valid value for {1}, "
"skipping...".format(settings[attribute],
attribute))
return handler
def _get_mockup_files_dictionary(self, torrent_id, translation):
"""Given a translation from _translate_filebot_movements, return a
mock-up of what the new files will look like"""
torrent = self.torrent_manager[torrent_id]
new_files = list(torrent.get_files())
if not translation:
return new_files
_, new_top_level, new_paths = translation
if new_top_level:
for f in new_files:
old_top_level = f["path"].split("/")[0]
f["path"] = f["path"].replace(old_top_level, new_top_level, 1)
for index, new_path in new_paths:
for f in new_files:
if f["index"] == index:
f["path"] = new_path
return new_files
#########
# Section: Public API
#########
@export
def set_config(self, config):
"""Sets the config dictionary"""
for key in config.keys():
self.config[key] = config[key]
self.config.save()
log.debug("config saved")
@export
def get_filebot_version(self):
if not self.filebot_version:
try:
self.filebot_version = pyfilebot.get_version()
except pyfilebot.FilebotFatalError:
self.filebot_version = None
return self.filebot_version
@export
@defer.inlineCallbacks
def do_dry_run(self, torrent_id, handler_settings=None, handler=None):
"""
Executes a dry run on torrent_id using handler_settings
Args:
torrent_id: deluge ID of torrent
handler_settings: dictionary containing the handler settings
handler: optional handler object
Returns: Tuple in format:
((success, errors_dict), (new_save_path, files_dictionary))
"""
if not handler:
if handler_settings:
handler = self._configure_filebot_handler(handler_settings,
handler)
else:
handler = pyfilebot.FilebotHandler()
handler.rename_action = "test"
target = self._get_filebot_target(torrent_id)
log.debug("running filbot dry run for torrent: {0} with target {1}".format(
torrent_id, target))
try:
filebot_results = yield threads.deferToThread(handler.rename,
target)
except pyfilebot.FilebotRuntimeError as err:
log.error("FILEBOT ERROR: {0}".format(err.msg))
defer.returnValue(((False, {torrent_id:('FilebotRuntimeError', err.msg)}),
('FILEBOTERROR', None)))
except Exception as e:
log.error("Unexpected error in pyfilebot: {0}".format(e))
log.error(traceback.format_exc())
defer.returnValue(((False, {torrent_id:(str(e.__class__.__name__), str(e))}),
('FILEBOTTOOLERROR', None)))
# noinspection PyUnboundLocalVariable
log.debug("recieved results from filebot: {0}".format(filebot_results))
deluge_movements = self._translate_filebot_movements(torrent_id,
filebot_results[1])
if not deluge_movements:
new_save_path = self.torrent_manager[torrent_id].get_status(
["save_path"])["save_path"]
defer.returnValue(((True, None), (new_save_path, self.torrent_manager[
torrent_id].get_files())))
log.debug("REQUIRED DELUGE MOVEMENTS: {0}".format(deluge_movements))
new_save_path = deluge_movements[0]
if not new_save_path:
new_save_path = self.torrent_manager[torrent_id].get_status(
["save_path"])["save_path"]
conflicts = self._file_conflicts(torrent_id, deluge_movements, filebot_results[2])
if conflicts:
overwrite = handler.on_conflict == 'override'
errors = {}
errors[torrent_id] = ('File Conflict',
'The following files already exsist{0}:\n{1}'.format(
' and will be overwritten!' if overwrite else '',
''.join(' ' + f + '\n' for f in conflicts))
)
defer.returnValue((
(True if not conflicts else False, None if not conflicts else errors),
(new_save_path,
self._get_mockup_files_dictionary(torrent_id, deluge_movements))))
@export
@defer.inlineCallbacks
def do_rename(self, torrent_ids, handler_settings=None, handler=None):
"""executes a filebot run.
Args:
torrent_id: id of torrent to execute against
handler_settings: an optional dictionary of settings build a filebot
handler from
handler: an optional FilebotHandler to use (overrides
handler_settings)
returns:
tuple in format (success, errors_dictionary, messages).
"""
if not handler:
if handler_settings:
handler = self._configure_filebot_handler(handler_settings,
handler)
else:
handler = pyfilebot.FilebotHandler()
errors = {}
new_files = []
for torrent_id in torrent_ids:
link = "link" in handler.rename_action or handler.rename_action == 'copy'
target = self._get_filebot_target(torrent_id)
log.debug("beginning filebot run on torrent {0}, with target {1}".format(
torrent_id, target))
original_torrent_state = self.torrent_manager[torrent_id].state
if not link:
self.torrent_manager[torrent_id].pause()
try:
filebot_results = yield threads.deferToThread(handler.rename,
target)
except pyfilebot.FilebotRuntimeError as err:
log.error("FILEBOT ERROR{0}".format(err))
errors[torrent_id] = (str(err), err.msg)
filebot_results = ["", {}, {}]
if original_torrent_state == "Seeding":
self.torrent_manager[torrent_id].resume()
continue
except Exception as e:
log.error("Unexpected error from pyfilebot: {0}".format(e))
log.error(traceback.format_exc())
errors[torrent_id] = (str(err.__class__.__name__), err.msg)
filebot_results = ["", {}, {}]
continue
log.debug("recieved results from filebot: {0}".format(
filebot_results))
if not link:
deluge_movements = self._translate_filebot_movements(torrent_id,
filebot_results[1])
else:
deluge_movements = None
new_files += filebot_results[1]
if not deluge_movements:
if original_torrent_state == "Seeding":
self.torrent_manager[torrent_id].resume()
conflicts = self._file_conflicts(torrent_id,
deluge_movements,
filebot_results[2])
if conflicts and handler.on_conflict == 'override':
for conflict in conflicts:
os.remove(conflict)
elif conflicts:
log.warning("Raname is not safe on torrent {0}. "
"Rolling Back and recheking".format(torrent_id))
self._rollback(filebot_results, torrent_id)
errors[torrent_id] = (
"File Conflict", "Problem with moving torrent \"{0}\".\n"
"The following files already exsist:\n{1}"
"Rolling back to previous state and rechecking.".format(
self.torrent_manager[torrent_id].get_status( ["name"])["name"],
''.join(' '+f+'\n' for f in conflicts)))
continue
if deluge_movements:
log.debug("Attempting to re-reoute torrent: {0}".format(
deluge_movements))
self._redirect_torrent_paths(
torrent_id, deluge_movements,
original_state=original_torrent_state)
# download subs
if handler_settings:
if handler_settings['download_subs']:
handler.output = None
if link:
deluge_movements = self._translate_filebot_movements(torrent_id, filebot_results[1])
mock = self._get_mockup_files_dictionary(torrent_id, deluge_movements)
new_save = deluge_movements[0] if deluge_movements else None
if not new_save:
torrent = self.torrent_manager[torrent_id]
new_save = torrent.get_status(["save_path"])["save_path"]
target = [self._get_full_os_path(new_save, f['path']) for f in mock]
try:
subs = yield threads.deferToThread(handler.get_subtitles,
target, language_code=handler_settings['subs_language'])
if not subs:
log.info("No subs found for torrent {0}".format(torrent_id))
else:
log.info('Downloaded subs: {0}'.format(subs))
new_files += subs
except pyfilebot.FilebotRuntimeError as err:
log.error("FILEBOTERROR: {0}").format(err)
errors[torrent_id] = (str(err), err.msg)
if errors:
defer.returnValue((False, errors, new_files))
else:
defer.returnValue((True, None, new_files))
@export
@defer.inlineCallbacks
def do_revert(self, torrent_id):
"""calls filebottool.revert() on files in a torrent. Will only allow
one torrent at a time"""
targets = self._get_filebot_target(torrent_id)
log.debug("reverting torrent {0} with targets {1}".format(torrent_id,
targets))
original_torrent_state = self.torrent_manager[torrent_id].state
self.torrent_manager[torrent_id].pause()
handler = pyfilebot.FilebotHandler()
try:
# noinspection PyUnresolvedReferences
filebot_results = yield threads.deferToThread(handler.revert,
targets)
except Exception, err:
log.error("FILEBOT ERROR {0}".format(err))
defer.returnValue((False, err))
# noinspection PyUnboundLocalVariable
deluge_movements = self._translate_filebot_movements(torrent_id,
filebot_results[1])
if not deluge_movements:
if original_torrent_state == "Seeding":
self.torrent_manager[torrent_id].resume()
defer.returnValue((True, None))
conflicts = self._file_conflicts(torrent_id,
deluge_movements,
filebot_results[2])
if conflicts:
log.warning('Rename unsafe for torrent {0}, conflicting files:{1}'.format(
torrent_id, conflicts))
log.warning('Rolling back torrent {0}.'.format(torrent_id))
self._rollback(filebot_results, torrent_id)
defer.returnValue((False, "Rename is not safe on torrent {0}.\n"
"The following files already exsist:\n"
"{1}"
"Rolling Back and recheking.".format(torrent_id,
''.join(' ' + f + '\n' for f in conflicts))))
log.debug("Attempting to re-reoute torrent: {00}".format(
deluge_movements))
self._redirect_torrent_paths(torrent_id, deluge_movements,
original_state=original_torrent_state)
defer.returnValue((True, None))
@export
def save_rename_dialog_settings(self, new_settings):
log.debug("recieved settings from client: {0}".format(new_settings))
for setting in DEFAULT_PREFS["rename_dialog_last_settings"]:
try:
if new_settings[setting] is not None:
self.config["rename_dialog_last_settings"][setting] = (
new_settings[setting])
try:
log.debug("setting saved: {0} : {1}".format(
setting, new_settings[setting]))
except UnicodeEncodeError:
log.debug("setting saved: {0}".format(setting))
else:
self.config["rename_dialog_last_settings"][setting] = None
except KeyError:
pass
#query_override should not be saved between runs
self.config["rename_dialog_last_settings"]["query_override"] = None
self.config.save()
@export
def get_rename_dialog_info(self, torrent_ids):
"""returns the needed variables and torrent info needed to build a
rename dialog"""
log.debug("dialog info requested, packing dialog info.")
dialog_info = {"torrent_ids": torrent_ids}
if len(torrent_ids) == 1:
torrent = self.torrent_manager[torrent_ids[0]]
dialog_info["torrent_save_path"] = torrent.get_status(
['save_path'])['save_path']
dialog_info["files"] = torrent.get_files()
dialog_info["filebot_version"] = self.get_filebot_version()
rename_dialog_last_settings = self.config["rename_dialog_last_settings"]
dialog_info["rename_dialog_last_settings"] = rename_dialog_last_settings
dialog_info['saved_handlers'] = self.config['saved_handlers']
dialog_info.update(self.get_filebot_valid_values())
log.debug("sending dialog info to client: {0}".format(dialog_info))
return dialog_info
# noinspection PyDictCreation
@export
def get_filebot_valid_values(self):
"""gathers valid arguments to filebot from pyfilebot.
returns: dictionary of lists in format {"valid_databases": [
'imdb'...]...}
"""
valid_args = {}
valid_args["valid_databases"] = pyfilebot.FILEBOT_DATABASES
valid_args["valid_rename_actions"] = pyfilebot.FILEBOT_RENAME_ACTIONS
valid_args["valid_on_conflicts"] = pyfilebot.FILEBOT_ON_CONFLICT
valid_args["valid_episode_orders"] = pyfilebot.FILEBOT_ORDERS
return valid_args
@export
def update_handlers(self, handlers):
log.debug("Updating saved handlers: {}".format(handlers))
self.config["saved_handlers"] = handlers
self.config.save()
@export
def test_function(self):
"""used for testing purposes"""
pass
@export
def get_config(self):
"""Returns the config dictionary"""
log.debug("Sending Config")
return self.config.config