/
config.py
1328 lines (1014 loc) · 50.5 KB
/
config.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
# coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
#
# This file is part of Medusa.
#
# Medusa is free software: you can 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.
#
# Medusa 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 Medusa. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import datetime
import logging
import os.path
import re
from builtins import object
from builtins import str
from contextlib2 import suppress
from medusa import common, db, helpers, logger, naming, providers
from medusa.app import app
from medusa.helper.common import try_int
from medusa.helpers.utils import split_and_strip
from medusa.logger.adapters.style import BraceAdapter
from medusa.schedulers import scheduler
from medusa.updater.version_checker import CheckVersion
from requests.compat import urlsplit
from six import iteritems, string_types, text_type
from six.moves.urllib.parse import urlunsplit, uses_netloc
from tornado.web import StaticFileHandler
log = BraceAdapter(logging.getLogger(__name__))
log.logger.addHandler(logging.NullHandler())
# Address poor support for scgi over unix domain sockets
# this is not nicely handled by python currently
# http://bugs.python.org/issue23636
uses_netloc.append('scgi')
naming_ep_type = ('%(seasonnumber)dx%(episodenumber)02d',
's%(seasonnumber)02de%(episodenumber)02d',
'S%(seasonnumber)02dE%(episodenumber)02d',
'%(seasonnumber)02dx%(episodenumber)02d')
sports_ep_type = ('%(seasonnumber)dx%(episodenumber)02d',
's%(seasonnumber)02de%(episodenumber)02d',
'S%(seasonnumber)02dE%(episodenumber)02d',
'%(seasonnumber)02dx%(episodenumber)02d')
naming_ep_type_text = ('1x02', 's01e02', 'S01E02', '01x02')
naming_multi_ep_type = {0: ['-%(episodenumber)02d'] * len(naming_ep_type),
1: [' - ' + x for x in naming_ep_type],
2: [x + '%(episodenumber)02d' for x in ('x', 'e', 'E', 'x')]}
naming_multi_ep_type_text = ('extend', 'duplicate', 'repeat')
naming_sep_type = (' - ', ' ')
naming_sep_type_text = (' - ', 'space')
def change_HTTPS_CERT(https_cert):
"""
Replace HTTPS Certificate file path.
:param https_cert: path to the new certificate file
:return: True on success, False on failure
"""
if not https_cert:
app._HTTPS_CERT = ''
return True
app_https_cert = os.path.normpath(app._HTTPS_CERT) if app._HTTPS_CERT else None
if app_https_cert != os.path.normpath(https_cert):
if helpers.make_dir(os.path.dirname(os.path.abspath(https_cert))):
app._HTTPS_CERT = os.path.normpath(https_cert)
log.info(u'Changed https cert path to {cert_path}', {u'cert_path': https_cert})
else:
return False
return True
def change_HTTPS_KEY(https_key):
"""
Replace HTTPS Key file path.
:param https_key: path to the new key file
:return: True on success, False on failure
"""
if not https_key:
app._HTTPS_KEY = ''
return True
app_https_key = os.path.normpath(app._HTTPS_KEY) if app._HTTPS_KEY else None
if app_https_key != os.path.normpath(https_key):
if helpers.make_dir(os.path.dirname(os.path.abspath(https_key))):
app._HTTPS_KEY = os.path.normpath(https_key)
log.info(u'Changed https key path to {key_path}', {u'key_path': https_key})
else:
return False
return True
def change_LOG_DIR(log_dir):
"""
Change logging directory for application and webserver.
:param log_dir: Path to new logging directory
:return: True on success, False on failure
"""
if not log_dir:
app._LOG_DIR = ''
return True
abs_log_dir = os.path.normpath(os.path.join(app.DATA_DIR, log_dir))
app_log_dir = os.path.normpath(app._LOG_DIR) if app._LOG_DIR else None
if app_log_dir != abs_log_dir:
if not helpers.make_dir(abs_log_dir):
return False
app.ACTUAL_LOG_DIR = os.path.normpath(log_dir)
app._LOG_DIR = abs_log_dir
return True
def change_NZB_DIR(nzb_dir):
"""
Change NZB Folder
:param nzb_dir: New NZB Folder location
:return: True on success, False on failure
"""
if not nzb_dir:
app._NZB_DIR = ''
return True
app_nzb_dir = os.path.normpath(app._NZB_DIR) if app._NZB_DIR else None
if app_nzb_dir != os.path.normpath(nzb_dir):
if helpers.make_dir(nzb_dir):
app._NZB_DIR = os.path.normpath(nzb_dir)
log.info(u'Changed NZB folder to {nzb_dir}', {'nzb_dir': nzb_dir})
else:
return False
return True
def change_TORRENT_DIR(torrent_dir):
"""
Change torrent directory
:param torrent_dir: New torrent directory
:return: True on success, False on failure
"""
if not torrent_dir:
app._TORRENT_DIR = ''
return True
app_torrent_dir = os.path.normpath(app._TORRENT_DIR) if app._TORRENT_DIR else None
if app_torrent_dir != os.path.normpath(torrent_dir):
if helpers.make_dir(torrent_dir):
app._TORRENT_DIR = os.path.normpath(torrent_dir)
log.info(u'Changed torrent folder to {torrent_dir}', {u'torrent_dir': torrent_dir})
else:
return False
return True
def change_RSS_DIR(rss_dir):
"""
Change rss directory
:param: New rss directory
:return: Bool representing success
"""
if not rss_dir:
app._RSS_DIR = ''
return True
app_rss_dir = os.path.normpath(app._RSS_DIR) if app._RSS_DIR else None
if app_rss_dir != os.path.normpath(rss_dir):
if helpers.make_dir(rss_dir):
app._RSS_DIR = os.path.normpath(rss_dir)
log.info(u'Changed rss dir to {0}', rss_dir)
else:
return False
return True
def change_TV_DOWNLOAD_DIR(tv_download_dir):
"""
Change TV_DOWNLOAD directory (used by postprocessor)
:param tv_download_dir: New tv download directory
:return: True on success, False on failure
"""
if not tv_download_dir:
app._TV_DOWNLOAD_DIR = ''
return True
app_tv_download_dir = os.path.normpath(app._TV_DOWNLOAD_DIR) if app._TV_DOWNLOAD_DIR else None
if app_tv_download_dir != os.path.normpath(tv_download_dir):
if helpers.make_dir(tv_download_dir):
app._TV_DOWNLOAD_DIR = os.path.normpath(tv_download_dir)
log.info(u'Changed TV download folder to {tv_download_dir}', {u'tv_download_dir': tv_download_dir})
else:
return False
return True
def change_AUTOPOSTPROCESSOR_FREQUENCY(freq):
"""
Change frequency of automatic postprocessing thread.
TODO: Make all thread frequency changers in config.py return True/False status
:param freq: New frequency
"""
if app._AUTOPOSTPROCESSOR_FREQUENCY == freq:
return
app._AUTOPOSTPROCESSOR_FREQUENCY = try_int(freq, 10)
if app._AUTOPOSTPROCESSOR_FREQUENCY < app.MIN_AUTOPOSTPROCESSOR_FREQUENCY:
app._AUTOPOSTPROCESSOR_FREQUENCY = app.MIN_AUTOPOSTPROCESSOR_FREQUENCY
if app.post_processor_scheduler:
app.post_processor_scheduler.cycleTime = datetime.timedelta(minutes=app._AUTOPOSTPROCESSOR_FREQUENCY)
def change_DOWNLOAD_HANDLER_FREQUENCY(freq):
"""
Change frequency of Download Handler thread.
:param freq: New frequency
"""
if app._DOWNLOAD_HANDLER_FREQUENCY == freq:
return
app._DOWNLOAD_HANDLER_FREQUENCY = try_int(freq, app.DEFAULT_DOWNLOAD_HANDLER_FREQUENCY)
if app._DOWNLOAD_HANDLER_FREQUENCY < app.MIN_DOWNLOAD_HANDLER_FREQUENCY:
app._DOWNLOAD_HANDLER_FREQUENCY = app.MIN_DOWNLOAD_HANDLER_FREQUENCY
if app.download_handler_scheduler:
app.download_handler_scheduler.cycleTime = datetime.timedelta(minutes=app._DOWNLOAD_HANDLER_FREQUENCY)
def change_DAILYSEARCH_FREQUENCY(freq):
"""
Change frequency of daily search thread.
:param freq: New frequency
"""
if app._DAILYSEARCH_FREQUENCY == freq:
return
app._DAILYSEARCH_FREQUENCY = try_int(freq, app.DEFAULT_DAILYSEARCH_FREQUENCY)
if app._DAILYSEARCH_FREQUENCY < app.MIN_DAILYSEARCH_FREQUENCY:
app._DAILYSEARCH_FREQUENCY = app.MIN_DAILYSEARCH_FREQUENCY
if app.daily_search_scheduler:
app.daily_search_scheduler.cycleTime = datetime.timedelta(minutes=app._DAILYSEARCH_FREQUENCY)
def change_BACKLOG_FREQUENCY(freq):
"""
Change frequency of backlog thread.
:param freq: New frequency
"""
if app._BACKLOG_FREQUENCY == freq:
return
app._BACKLOG_FREQUENCY = try_int(freq, app.DEFAULT_BACKLOG_FREQUENCY)
app.MIN_BACKLOG_FREQUENCY = app.instance.get_backlog_cycle_time()
if app._BACKLOG_FREQUENCY < app.MIN_BACKLOG_FREQUENCY:
app._BACKLOG_FREQUENCY = app.MIN_BACKLOG_FREQUENCY
if app.backlog_search_scheduler:
app.backlog_search_scheduler.cycleTime = datetime.timedelta(minutes=app._BACKLOG_FREQUENCY)
def change_CHECK_PROPERS_INTERVAL(check_propers_interval):
"""
Change frequency of backlog thread.
:param freq: New frequency
"""
if not app._DOWNLOAD_PROPERS:
return
if app._CHECK_PROPERS_INTERVAL == check_propers_interval:
return
if check_propers_interval in app.PROPERS_SEARCH_INTERVAL:
update_interval = datetime.timedelta(minutes=app.PROPERS_SEARCH_INTERVAL[check_propers_interval])
else:
update_interval = datetime.timedelta(hours=1)
app._CHECK_PROPERS_INTERVAL = check_propers_interval
if app.proper_finder_scheduler:
app.proper_finder_scheduler.cycleTime = update_interval
def change_UPDATE_FREQUENCY(freq):
"""
Change frequency of daily updater thread.
:param freq: New frequency
"""
if app._UPDATE_FREQUENCY == freq:
return
app._UPDATE_FREQUENCY = try_int(freq, app.DEFAULT_UPDATE_FREQUENCY)
if app._UPDATE_FREQUENCY < app.MIN_UPDATE_FREQUENCY:
app._UPDATE_FREQUENCY = app.MIN_UPDATE_FREQUENCY
if app.version_check_scheduler:
app.version_check_scheduler.cycleTime = datetime.timedelta(hours=app._UPDATE_FREQUENCY)
def change_SHOWUPDATE_HOUR(freq):
"""
Change frequency of show updater thread.
:param freq: New frequency
"""
if app._SHOWUPDATE_HOUR == freq:
return
app._SHOWUPDATE_HOUR = try_int(freq, app.DEFAULT_SHOWUPDATE_HOUR)
if app._SHOWUPDATE_HOUR > 23:
app._SHOWUPDATE_HOUR = 0
elif app._SHOWUPDATE_HOUR < 0:
app._SHOWUPDATE_HOUR = 0
if app.show_update_scheduler:
app.show_update_scheduler.start_time = datetime.time(hour=app._SHOWUPDATE_HOUR)
def change_RECOMMENDED_SHOW_UPDATE_HOUR(freq):
"""
Change frequency of show updater thread.
:param freq: New frequency
"""
if app._RECOMMENDED_SHOW_UPDATE_HOUR == freq:
return
app._RECOMMENDED_SHOW_UPDATE_HOUR = try_int(freq, app.DEFAULT_RECOMMENDED_SHOW_UPDATE_HOUR)
if app._RECOMMENDED_SHOW_UPDATE_HOUR > 23:
app._RECOMMENDED_SHOW_UPDATE_HOUR = 0
elif app._RECOMMENDED_SHOW_UPDATE_HOUR < 0:
app._RECOMMENDED_SHOW_UPDATE_HOUR = 0
if app.show_update_scheduler:
app.show_update_scheduler.start_time = datetime.time(hour=app._RECOMMENDED_SHOW_UPDATE_HOUR)
def change_SUBTITLES_FINDER_FREQUENCY(subtitles_finder_frequency):
"""
Change frequency of subtitle thread.
:param subtitles_finder_frequency: New frequency
"""
if app._SUBTITLES_FINDER_FREQUENCY == subtitles_finder_frequency:
return
if subtitles_finder_frequency == '' or subtitles_finder_frequency is None:
subtitles_finder_frequency = 1
app._SUBTITLES_FINDER_FREQUENCY = try_int(subtitles_finder_frequency, 1)
def change_VERSION_NOTIFY(version_notify):
"""
Change frequency of versioncheck thread.
:param version_notify: New frequency
"""
if app._VERSION_NOTIFY == version_notify:
return
old_setting = app._VERSION_NOTIFY
app._VERSION_NOTIFY = bool(version_notify)
if not version_notify:
app.NEWEST_VERSION_STRING = None
if app.version_check_scheduler and old_setting is False and version_notify is True:
app.version_check_scheduler.forceRun()
def change_GIT_PATH(path):
"""
Recreate the version_check scheduler when GIT_PATH is changed.
Force a run to clear or set any error messages.
"""
if app._GIT_PATH == path:
return
app._GIT_PATH = path
if app.version_check_scheduler:
app.version_check_scheduler.stop.set()
app.version_check_scheduler.join(10)
app.version_check_scheduler = None
app.version_check_scheduler = scheduler.Scheduler(
CheckVersion(),
cycleTime=datetime.timedelta(hours=app._UPDATE_FREQUENCY),
threadName='CHECKVERSION',
silent=False)
app.version_check_scheduler.enable = True
app.version_check_scheduler.start()
app.version_check_scheduler.forceRun()
def change_theme(theme_name):
"""
Hot-swap theme.
:param theme_name: New theme name
"""
if theme_name == app.THEME_NAME:
return False
old_theme_name = app.THEME_NAME
old_data_root = os.path.join(app.DATA_ROOT, old_theme_name)
app.THEME_NAME = theme_name
app.THEME_DATA_ROOT = os.path.join(app.DATA_ROOT, theme_name)
static_file_handlers = app.instance.web_server.app.static_file_handlers
log.info('Switching theme from "{old}" to "{new}"', {'old': old_theme_name, 'new': theme_name})
for rule in static_file_handlers.target.rules:
if not rule.target_kwargs['path'] or old_data_root not in rule.target_kwargs['path']:
# Skip other static file handlers
continue
old_path = rule.target_kwargs['path']
new_path = old_path.replace(old_data_root, app.THEME_DATA_ROOT)
rule.target_kwargs['path'] = new_path
log.debug('Changed {old} to {new}', {'old': old_path, 'new': new_path})
# Reset cache
StaticFileHandler.reset()
return True
def CheckSection(CFG, sec):
""" Check if INI section exists, if not create it."""
if sec in CFG:
return True
CFG[sec] = {}
return False
def checkbox_to_value(option, value_on=1, value_off=0):
"""
Turns checkbox option 'on' or 'true' to value_on (1).
any other value returns value_off (0)
"""
if isinstance(option, list):
option = option[-1]
if option in ('on', 'true'):
return value_on
return value_off
def clean_host(host, default_port=None):
"""
Returns host or host:port or empty string from a given url or host.
If no port is found and default_port is given use host:default_port
"""
host = host.strip()
if host:
match_host_port = re.search(r'(?:http.*://)?(?P<host>[^:/]+).?(?P<port>[0-9]*).*', host)
cleaned_host = match_host_port.group('host')
cleaned_port = match_host_port.group('port')
if cleaned_host:
if cleaned_port:
host = cleaned_host + ':' + cleaned_port
elif default_port:
host = cleaned_host + ':' + str(default_port)
else:
host = cleaned_host
else:
host = ''
return host
def clean_hosts(hosts, default_port=None):
"""
Returns list of cleaned hosts by clean_host.
:param hosts: list of hosts
:param default_port: default port to use
:return: list of cleaned hosts
"""
cleaned_hosts = []
for cur_host in [host.strip() for host in hosts.split(',') if host.strip()]:
cleaned_host = clean_host(cur_host, default_port)
if cleaned_host:
cleaned_hosts.append(cleaned_host)
cleaned_hosts = cleaned_hosts or []
return cleaned_hosts
def clean_url(url):
"""
Returns an cleaned url starting with a scheme and folder with trailing or an empty string.
"""
if url and url.strip():
url = url.strip()
if '://' not in url:
url = '//' + url
scheme, netloc, path, query, fragment = urlsplit(url, 'http')
if not path:
path += '/'
cleaned_url = urlunsplit((scheme, netloc, path, query, fragment))
else:
cleaned_url = ''
return cleaned_url
def convert_csv_string_to_list(value, delimiter=',', trim=False):
"""
Convert comma or other character delimited strings to a list.
:param value: The value to convert.f
:param delimiter: Optionally Change the default delimiter ',' if required.
:param trim: Optionally trim the individual list items.
:return: The delimited value as a list.
"""
if not isinstance(value, (string_types, text_type)):
return value
with suppress(AttributeError, ValueError):
value = value.split(delimiter) if value else []
if trim:
value = [_.strip() for _ in value]
return value
################################################################################
# Check_setting_int #
################################################################################
def minimax(val, default, low, high):
"""Return value forced within range."""
val = try_int(val, default)
if val < low:
return low
if val > high:
return high
return val
################################################################################
# Check_setting_int #
################################################################################
def check_setting_int(config, cfg_name, item_name, def_val, silent=True):
try:
my_val = config[cfg_name][item_name]
if str(my_val).lower() == 'true':
my_val = 1
elif str(my_val).lower() == 'false':
my_val = 0
my_val = int(my_val)
if str(my_val) == str(None):
raise Exception
except Exception:
my_val = def_val
try:
config[cfg_name][item_name] = my_val
except Exception:
config[cfg_name] = {}
config[cfg_name][item_name] = my_val
if not silent:
log.debug(u'{item} -> {value}', {u'item': item_name, u'value': my_val})
return my_val
################################################################################
# Check_setting_bool #
################################################################################
def check_setting_bool(config, cfg_name, item_name, def_val, silent=True):
return bool(check_setting_int(config=config, cfg_name=cfg_name, item_name=item_name, def_val=def_val, silent=silent))
################################################################################
# Check_setting_float #
################################################################################
def check_setting_float(config, cfg_name, item_name, def_val, silent=True):
try:
my_val = float(config[cfg_name][item_name])
if str(my_val) == str(None):
raise Exception
except Exception:
my_val = def_val
try:
config[cfg_name][item_name] = my_val
except Exception:
config[cfg_name] = {}
config[cfg_name][item_name] = my_val
if not silent:
log.debug(u'{item} -> {value}', {u'item': item_name, u'value': my_val})
return my_val
################################################################################
# Check_setting_str #
################################################################################
def check_setting_str(config, cfg_name, item_name, def_val, silent=True, censor_log=False, valid_values=None, encrypted=False):
# For passwords you must include the word `password` in the item_name or pass `encrypted=True`
# and add `helpers.encrypt(ITEM_NAME, ENCRYPTION_VERSION)` in save_config()
if not censor_log:
censor_level = common.privacy_levels['stupid']
else:
censor_level = common.privacy_levels[censor_log]
privacy_level = common.privacy_levels[app.PRIVACY_LEVEL]
if bool(item_name.find('password') + 1) or encrypted:
encryption_version = app.ENCRYPTION_VERSION
else:
encryption_version = 0
try:
my_val = helpers.decrypt(config[cfg_name][item_name], encryption_version)
if str(my_val) == str(None):
raise Exception
except Exception:
my_val = def_val
try:
config[cfg_name][item_name] = helpers.encrypt(my_val, encryption_version)
except Exception:
config[cfg_name] = {}
config[cfg_name][item_name] = helpers.encrypt(my_val, encryption_version)
if privacy_level >= censor_level or (cfg_name, item_name) in iteritems(logger.censored_items):
if not item_name.endswith('custom_url'):
logger.censored_items[cfg_name, item_name] = my_val
if not silent:
log.debug(u'{item} -> {value}', {u'item': item_name, u'value': my_val})
if valid_values and my_val not in valid_values:
return def_val
return my_val
################################################################################
# Check_setting_list #
################################################################################
def check_setting_list(config, cfg_name, item_name, default=None, silent=True, censor_log=False, transform=None,
transform_default=0, split_value=False):
"""Check a setting, using the settings section and item name. Expect to return a list."""
default = default or []
if not censor_log:
censor_level = common.privacy_levels['stupid']
else:
censor_level = common.privacy_levels[censor_log]
privacy_level = common.privacy_levels[app.PRIVACY_LEVEL]
try:
my_val = config[cfg_name][item_name]
except Exception:
my_val = default
try:
config[cfg_name][item_name] = my_val
except Exception:
config[cfg_name] = {}
config[cfg_name][item_name] = my_val
if privacy_level >= censor_level or (cfg_name, item_name) in iteritems(logger.censored_items):
if not item_name.endswith('custom_url'):
logger.censored_items[cfg_name, item_name] = my_val
if split_value:
if isinstance(my_val, string_types):
my_val = split_and_strip(my_val, split_value)
# Make an attempt to cast the lists values.
if isinstance(my_val, list) and transform:
for index, value in enumerate(my_val):
try:
my_val[index] = transform(value)
except ValueError:
my_val[index] = transform_default
if not silent:
log.debug(u'{item} -> {value!r}', {u'item': item_name, u'value': my_val})
return my_val
################################################################################
# Check_setting #
################################################################################
def check_setting(config, section, attr_type, attr, default=None, silent=True, **kwargs):
"""
Check setting from config file
"""
func = {
'string': check_setting_str,
'int': check_setting_int,
'float': check_setting_float,
'bool': check_setting_bool,
'list': check_setting_list,
}
return func[attr_type](config, section, attr, default, silent, **kwargs)
################################################################################
# Check_setting #
################################################################################
def check_provider_setting(config, provider, attr_type, attr, default=None, silent=True, **kwargs):
"""
Check setting from config file
"""
name = provider.get_id()
section = name.upper()
attr = '{name}_{attr}'.format(name=name, attr=attr)
return check_setting(config, section, attr_type, attr, default, silent, **kwargs)
################################################################################
# Load Provider Setting #
################################################################################
def load_provider_setting(config, provider, attr_type, attr, default=None, silent=True, **kwargs):
if hasattr(provider, attr):
value = check_provider_setting(config, provider, attr_type, attr, default, silent, **kwargs)
setattr(provider, attr, value)
################################################################################
# Save Provider Setting #
################################################################################
def save_provider_setting(config, provider, attr, **kwargs):
if hasattr(provider, attr):
section = kwargs.pop('section', provider.get_id().upper())
setting = '{name}_{attr}'.format(name=provider.get_id(), attr=attr)
value = kwargs.pop('value', getattr(provider, attr))
if value in [True, False]:
value = int(value)
config[section][setting] = value
class ConfigMigrator(object):
def __init__(self, config_obj):
"""
Initializes a config migrator that can take the config from the version indicated in the config
file up to the version required by Medusa
"""
self.config_obj = config_obj
# check the version of the config
self.config_version = check_setting_int(config_obj, 'General', 'config_version', app.CONFIG_VERSION)
self.expected_config_version = app.CONFIG_VERSION
self.migration_names = {
1: 'Custom naming',
2: 'Sync backup number with version number',
3: 'Rename omgwtfnzb variables',
4: 'Add newznab cat_ids',
5: 'Metadata update',
6: 'Convert from XBMC to new KODI variables',
7: 'Use version 2 for password encryption',
8: 'Convert Plex setting keys',
9: 'Added setting "enable_manualsearch" for providers (dynamic setting)',
10: 'Convert all csv config items to lists',
11: 'Convert provider ratio type string to int',
12: 'Add new metadata option overwrite_nfo'
}
def migrate_config(self):
"""
Calls each successive migration until the config is the same version as the app expects
"""
if self.config_version > self.expected_config_version:
logger.log_error_and_exit(
u"""Your config version (%i) has been incremented past what this version of the application supports (%i).
If you have used other forks or a newer version of the application, your config file may be unusable due to their modifications.""" %
(self.config_version, self.expected_config_version)
)
app.CONFIG_VERSION = self.config_version
while self.config_version < self.expected_config_version:
next_version = self.config_version + 1
if next_version in self.migration_names:
migration_name = f': {self.migration_names[next_version]}'
else:
migration_name = ''
log.info(u'Backing up config before upgrade')
if not helpers.backup_versioned_file(app.CONFIG_FILE, self.config_version):
logger.log_error_and_exit(u'Config backup failed, abort upgrading config')
else:
log.info(u'Proceeding with upgrade')
# do the migration, expect a method named _migrate_v<num>
log.info(u'Migrating config up to version {version} {migration_name}',
{'version': next_version, 'migration_name': migration_name})
getattr(self, '_migrate_v' + str(next_version))()
self.config_version = next_version
# save new config after migration
app.CONFIG_VERSION = self.config_version
log.info(u'Saving config file to disk')
app.instance.save_config()
# Migration v1: Custom naming
def _migrate_v1(self):
"""
Reads in the old naming settings from your config and generates a new config template from them.
"""
app.NAMING_PATTERN = self._name_to_pattern()
log.info(u"Based on your old settings I'm setting your new naming pattern to: {pattern}",
{'pattern': app.NAMING_PATTERN})
app.NAMING_CUSTOM_ABD = bool(check_setting_int(self.config_obj, 'General', 'naming_dates', 0))
if app.NAMING_CUSTOM_ABD:
app.NAMING_ABD_PATTERN = self._name_to_pattern(True)
log.info(u'Adding a custom air-by-date naming pattern to your config: {pattern}',
{'pattern': app.NAMING_ABD_PATTERN})
else:
app.NAMING_ABD_PATTERN = naming.name_abd_presets[0]
app.NAMING_MULTI_EP = int(check_setting_int(self.config_obj, 'General', 'naming_multi_ep_type', 1))
# see if any of their shows used season folders
main_db_con = db.DBConnection()
season_folder_shows = main_db_con.select('SELECT indexer_id FROM tv_shows WHERE flatten_folders = 0 LIMIT 1')
# if any shows had season folders on then prepend season folder to the pattern
if season_folder_shows:
old_season_format = check_setting_str(self.config_obj, 'General', 'season_folders_format', 'Season %02d')
if old_season_format:
try:
new_season_format = old_season_format % 9
new_season_format = str(new_season_format).replace('09', '%0S')
new_season_format = new_season_format.replace('9', '%S')
log.info(
u'Changed season folder format from {old_season_format} to {new_season_format}, '
u'prepending it to your naming config',
{'old_season_format': old_season_format, 'new_season_format': new_season_format}
)
app.NAMING_PATTERN = new_season_format + os.sep + app.NAMING_PATTERN
except (TypeError, ValueError):
log.error(u"Can't change {old_season_format} to new season format",
{'old_season_format': old_season_format})
# if no shows had it on then don't flatten any shows and don't put season folders in the config
else:
log.info(u"No shows were using season folders before so I'm disabling flattening on all shows")
# don't flatten any shows at all
main_db_con.action('UPDATE tv_shows SET flatten_folders = 0')
app.NAMING_FORCE_FOLDERS = naming.check_force_season_folders()
def _name_to_pattern(self, abd=False):
# get the old settings from the file
use_periods = bool(check_setting_int(self.config_obj, 'General', 'naming_use_periods', 0))
ep_type = check_setting_int(self.config_obj, 'General', 'naming_ep_type', 0)
sep_type = check_setting_int(self.config_obj, 'General', 'naming_sep_type', 0)
use_quality = bool(check_setting_int(self.config_obj, 'General', 'naming_quality', 0))
use_show_name = bool(check_setting_int(self.config_obj, 'General', 'naming_show_name', 1))
use_ep_name = bool(check_setting_int(self.config_obj, 'General', 'naming_ep_name', 1))
# make the presets into templates
naming_ep_type = ('%Sx%0E',
's%0Se%0E',
'S%0SE%0E',
'%0Sx%0E')
# set up our data to use
if use_periods:
show_name = '%S.N'
ep_name = '%E.N'
ep_quality = '%Q.N'
abd_string = '%A.D'
else:
show_name = '%SN'
ep_name = '%EN'
ep_quality = '%QN'
abd_string = '%A-D'
if abd and abd_string:
ep_string = abd_string
else:
ep_string = naming_ep_type[ep_type]
finalName = ''
# start with the show name
if use_show_name and show_name:
finalName += show_name + naming_sep_type[sep_type]
# add the season/ep stuff
finalName += ep_string
# add the episode name
if use_ep_name and ep_name:
finalName += naming_sep_type[sep_type] + ep_name
# add the quality
if use_quality and ep_quality:
finalName += naming_sep_type[sep_type] + ep_quality
if use_periods:
finalName = re.sub(r'\s+', '.', finalName)
return finalName