-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathPreferenceParser.py
More file actions
executable file
·1395 lines (1141 loc) · 53.3 KB
/
Copy pathPreferenceParser.py
File metadata and controls
executable file
·1395 lines (1141 loc) · 53.3 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
from collections import namedtuple
from pathlib import Path
from sys import exit as sys_exit
from typing import Any, Iterator, Literal, Optional, Union, overload
from num2words import CONVERTER_CLASSES as SUPPORTED_LANGUAGE_CODES
from tqdm import tqdm
from modules.CleanPath import CleanPath
from modules.Debug import log, TQDM_KWARGS
from modules.EmbyInterface import EmbyInterface
from modules.Font import Font
from modules.ImageMagickInterface import ImageMagickInterface
from modules.ImageMaker import ImageMaker
from modules.JellyfinInterface import JellyfinInterface
from modules.Manager import Manager
from modules.PlexInterface import PlexInterface
from modules.SeriesInfo import SeriesInfo
from modules.SeriesYamlWriter import SeriesYamlWriter
from modules.Show import Show
from modules.SonarrInterface import SonarrInterface
from modules.StandardSummary import StandardSummary
from modules.StyleSet import StyleSet
from modules.StylizedSummary import StylizedSummary
from modules.TautulliInterface import TautulliInterface
from modules.Template import Template
from modules.TitleCard import TitleCard
from modules.TMDbInterface import TMDbInterface
from modules.Version import Version
from modules.YamlReader import YamlReader
YamlWriterSet = namedtuple(
'YamlWriterSet', ('interface_id', 'writer', 'update_args')
)
class PreferenceParser(YamlReader):
"""
This class describes a preference parser that reads a given
preference YAML file and parses it into individual attributes.
"""
"""Valid image source identifiers"""
VALID_IMAGE_SOURCES = ('emby', 'jellyfin', 'plex', 'tmdb')
"""Valid episode data source identifiers"""
VALID_EPISODE_DATA_SOURCES = ('emby', 'jellyfin', 'sonarr', 'plex', 'tmdb')
DEFAULT_EPISODE_DATA_SOURCE = 'sonarr'
"""Default season folder format string"""
DEFAULT_SEASON_FOLDER_FORMAT = 'Season {season}'
"""Default directory for temporary database objects"""
DEFAULT_TEMP_DIR = Path(__file__).parent / '.objects'
"""File containing the executing version of TitleCardMaker"""
VERSION_FILE = Path(__file__).parent / 'ref' / 'version'
def __init__(self, file: Path, is_docker: bool = False) -> None:
"""
Constructs a new instance of this object. This reads the given
file, errors and exits if any required options are missing, and
then parses the preferences into object attributes.
Args:
file: The file to parse for preferences.
is_docker: Whether executing within a Docker container.
Raises:
SystemExit (1): Any required YAML options are missing from
`file`.
"""
# Initialize parent YamlReader object - errors are critical
super().__init__(log_function=log.critical)
self.valid = True
self.version = Version(self.VERSION_FILE.read_text().strip())
self.is_docker = is_docker
# Store and read file
self.file = file
self.read_file()
# Database object directory, create if DNE
self.DEFAULT_TEMP_DIR.mkdir(parents=True, exist_ok=True)
if is_docker:
self.database_directory = self.file.parent / '.objects'
else:
self.database_directory = self.DEFAULT_TEMP_DIR
self.database_directory.mkdir(parents=True, exist_ok=True)
# Check for required source directory
if (value := self.get('options', 'source', type_=str)) is None:
log.critical(f'Preference file missing required options/source '
f'attribute')
sys_exit(1)
self.source_directory = CleanPath(value).sanitize()
# Setup default values that can be overwritten by YAML
self.series_files = []
self.execution_mode = Manager.DEFAULT_EXECUTION_MODE
self.card_class = self._parse_card_type(TitleCard.DEFAULT_CARD_TYPE)
self.card_filename_format = TitleCard.DEFAULT_FILENAME_FORMAT
self.card_extension = TitleCard.DEFAULT_CARD_EXTENSION
self.card_dimensions = TitleCard.DEFAULT_CARD_DIMENSIONS
self.image_source_priority = ('tmdb', 'plex', 'emby', 'jellyfin')
self.episode_data_source = self.DEFAULT_EPISODE_DATA_SOURCE
self.validate_fonts = True
self.season_folder_format = self.DEFAULT_SEASON_FOLDER_FORMAT
self.sync_specials = True
self.supported_language_codes = ['en']
self.archive_directory = None
self.create_archive = False
self.archive_all_variations = True
self.create_summaries = True
self.summary_class = StylizedSummary
self.summary_background = self.summary_class.BACKGROUND_COLOR
self.summary_minimum_episode_count = 3
self.summary_created_by = None
self.summary_ignore_specials = False
self.use_emby = False
self.emby_url = None
self.emby_api_key = None
self.emby_username = None
self.emby_verify_ssl = True
self.emby_filesize_limit = self.filesize_as_bytes(
EmbyInterface.DEFAULT_FILESIZE_LIMIT
)
self.emby_style_set = StyleSet()
self.emby_yaml_writers = []
self.emby_yaml_update_args = []
self.use_jellyfin = False
self.jellyfin_url = None
self.jellyfin_api_key = None
self.jellyfin_username = None
self.jellyfin_verify_ssl = True
self.jellyfin_filesize_limit = self.filesize_as_bytes(
JellyfinInterface.DEFAULT_FILESIZE_LIMIT
)
self.jellyfin_style_set = StyleSet()
self.jellyfin_yaml_writers = []
self.jellyfin_yaml_update_args = []
self.use_plex = False
self.plex_url = None
self.plex_token = 'NA'
self.plex_verify_ssl = True
self.integrate_with_kometa = False
self.plex_filesize_limit = self.filesize_as_bytes(
PlexInterface.DEFAULT_FILESIZE_LIMIT
)
self.plex_timeout = PlexInterface.DEFAULT_TIMEOUT
self.plex_style_set = StyleSet()
self.plex_yaml_writers = []
self.plex_yaml_update_args = []
self.sonarr_kwargs = []
self.sonarr_yaml_writers = []
self.use_tmdb = False
self.tmdb_api_key = None
self.tmdb_retry_count = TMDbInterface.BLACKLIST_THRESHOLD
self.tmdb_minimum_resolution = {'width': 0, 'height': 0}
self.tmdb_skip_localized_images = False
self.tmdb_logo_language_priority = ['en']
self.use_tautulli = False
self.tautulli_url = None
self.tautulli_api_key = None
self.tautulli_verify_ssl = True
self.tautulli_username = None
self.tautulli_update_script = None
self.tautulli_agent_name = TautulliInterface.DEFAULT_AGENT_NAME
self.tautulli_script_timeout = TautulliInterface.DEFAULT_SCRIPT_TIMEOUT
self.imagemagick_container = None
self.imagemagick_timeout = ImageMagickInterface.COMMAND_TIMEOUT_SECONDS
# Determine default media server
if (not self._is_specified('emby')
and not self._is_specified('plex')
and not self._is_specified('jellyfin')):
log.warning(f'No Media Servers indicated - TitleCardMaker will not '
f'automatically load any cards')
self.default_media_server = 'plex'
if (self._is_specified('emby')
and not self._is_specified('plex')
and not self._is_specified('jellyfin')):
self.default_media_server = 'emby'
elif (self._is_specified('jellyfin')
and not self._is_specified('emby')
and not self._is_specified('plex')):
self.default_media_server = 'jellyfin'
elif (self._is_specified('plex')
and not self._is_specified('emby')
and not self._is_specified('jellyfin')):
self.default_media_server = 'plex'
else:
self.default_media_server = None
# Modify object attributes based off YAML, updating validiry
self.__parse_yaml()
self.__parse_sync()
# Whether to use magick prefix
self.use_magick_prefix = False
self.__determine_imagemagick_prefix()
def __repr__(self) -> str:
"""Returns an unambiguous string representation of the object."""
attributes = ', '.join(
f'{attr}={getattr(self, attr)!r}' for attr in self.__dict__
if not attr.startswith('_')
)
return f'<PreferenceParser {attributes}>'
def __determine_imagemagick_prefix(self) -> None:
"""
Determine whether to use the "magick " prefix for ImageMagick
commands. If a prefix cannot be determined, a critical message
is logged and this object's validity is set to False.
"""
# Try variations of the font list command with/out the "magick " prefix
for prefix, use_magick in zip(('', 'magick '), (False, True)):
# Create ImageMagickInterface and verify validity
interface = ImageMagickInterface(
self.imagemagick_container, use_magick, self.imagemagick_timeout
)
if interface.validate_interface():
self.use_magick_prefix = use_magick
log.debug(f'Using "{prefix}" ImageMagick command prefix')
return None
# If none of the font commands worked, IM might not be installed
log.critical(f"ImageMagick doesn't appear to be installed")
interface.print_command_history()
self.valid = False
return None
def __parse_sync(self) -> None:
"""
Parse the YAML sync sections of this preference file. This
updates the lists of SeriesYamlWriter objects for each
applicable interface.
"""
# Inner function to create and add SeriesYamlWriter objects (and)
# their update args dictionaries to this object's lists
def append_writer_and_args(sync_type, interface_id, sync, static):
# Combine static and given sync YAML
sync_yaml = YamlReader(static | sync, log_function=log.warning)
# Skip if file wasn't specified
if (file := sync_yaml.get('file', type_=CleanPath)) is None:
return None
# Create SeriesYamlWriter with this config
file = file.sanitize()
writer = SeriesYamlWriter(
file,
sync_yaml.get('mode', type_=str, default='append'),
sync_yaml.get('compact_mode', type_=bool, default=True),
sync_yaml.get('volumes', type_=dict, default={}),
sync_yaml.get('add_template', type_=str, default=None),
sync_yaml.get('card_directory', type_=CleanPath, default=None),
)
# If invalid after initialization, error and exit
if not writer.valid:
log.error(f'Cannot sync to "{file.resolve()}" - invalid sync')
return None
# Parse args applicable to all interfaces
update_args = {}
if (value := sync_yaml.get('exclusions', type_=list)) is not None:
update_args['exclusions'] = value
if (value := sync_yaml.get('required_tags', type_=list)) is not None:
update_args['required_tags'] = value
# Parse args applicable only to specific interfaces
if sync_type in ('emby', 'jellyfin', 'plex'):
if (value := sync_yaml.get('libraries', type_=list)) is not None:
update_args['filter_libraries'] = value
elif sync_type == 'sonarr':
value = sync_yaml.get(
'libraries',
type_=dict,
default=sync_yaml.get('plex_libraries', type_=dict),
)
if value is not None:
update_args['libraries'] = value
if (value := sync_yaml.get('monitored_only', type_=bool)) is not None:
update_args['monitored_only'] = value
if (value := sync_yaml.get('downloaded_only', type_=bool)) is not None:
update_args['downloaded_only'] = value
if (value := sync_yaml.get('series_type', type_=str)) is not None:
if value in SonarrInterface.VALID_SERIES_TYPES:
update_args['series_type'] = value
else:
vals = ", ".join(SonarrInterface.VALID_SERIES_TYPES)
log.error(f'Cannot filter by series_type "{value}" - '
f'must be one of {vals}')
sync_yaml.valid = False
# Skip if YAML was invalidated at any point
if not sync_yaml.valid:
log.error(f'Cannot sync to "{file.resolve()}" - invalid sync')
return None
# Add to either Plex or Sonarr lists
if sync_type == 'emby':
self.emby_yaml_writers.append(writer)
self.emby_yaml_update_args.append(update_args)
elif sync_type == 'jellyfin':
self.jellyfin_yaml_writers.append(writer)
self.jellyfin_yaml_update_args.append(update_args)
elif sync_type == 'plex':
self.plex_yaml_writers.append(writer)
self.plex_yaml_update_args.append(update_args)
else:
self.sonarr_yaml_writers.append(
YamlWriterSet(interface_id, writer, update_args)
)
return None
# Create Emby SeriesYamlWriter objects
if (emby_sync := self.get('emby', 'sync')) is not None:
# Singular sync specification
if isinstance(emby_sync, dict):
append_writer_and_args('emby', 0, emby_sync, {})
# List of syncs
elif isinstance(emby_sync, list) and len(emby_sync) > 0:
base_sync = emby_sync[0]
for sync in emby_sync:
append_writer_and_args('emby', 0, sync, base_sync)
else:
log.error(f'Invalid Emby sync: {emby_sync}')
# Create Jellyfin SeriesYamlWriter objects
if (jellyfin_sync := self.get('jellyfin', 'sync')) is not None:
# Singular sync specification
if isinstance(jellyfin_sync, dict):
append_writer_and_args('jellyfin', 0, jellyfin_sync, {})
# List of syncs
elif isinstance(jellyfin_sync, list) and len(jellyfin_sync) > 0:
base_sync = jellyfin_sync[0]
for sync in jellyfin_sync:
append_writer_and_args('jellyfin', 0, sync, base_sync)
else:
log.error(f'Invalid Jellyfin sync: {jellyfin_sync}')
# Create Plex SeriesYamlWriter objects
if (plex_sync := self.get('plex', 'sync')) is not None:
# Singular sync specification
if isinstance(plex_sync, dict):
append_writer_and_args('plex', 0, plex_sync, {})
# List of syncs
elif isinstance(plex_sync, list) and len(plex_sync) > 0:
base_sync = plex_sync[0]
for sync in plex_sync:
append_writer_and_args('plex', 0, sync, base_sync)
else:
log.error(f'Invalid Plex sync: {plex_sync}')
# Create Sonarr SeriesYamlWriter objects
if self._is_specified('sonarr'):
# Singular server
if (isinstance(self.get('sonarr'), dict)
and (sonarr_sync := self.get('sonarr', 'sync')) is not None):
# Singular sync specification
if isinstance(sonarr_sync, dict):
append_writer_and_args('sonarr', 0, sonarr_sync, {})
# List of syncs
elif isinstance(sonarr_sync, list) and len(sonarr_sync) > 0:
base_sync = sonarr_sync[0]
for sync in sonarr_sync:
append_writer_and_args('sonarr', 0, sync, base_sync)
else:
log.error(f'Invalid Sonarr sync: {sonarr_sync}')
# Multiple sonarr interfaces, check for sync on each
elif isinstance(self.get('sonarr'), list):
for interface_id, server in enumerate(self.get('sonarr')):
reader = YamlReader(server)
# Singular sync for this server
if isinstance((sync := reader.get('sync')), dict):
append_writer_and_args('sonarr', interface_id, sync, {})
# List of syncs for this server
elif isinstance(sync, list) and len(sync) > 0:
base_sync = sync[0]
for sub_sync in sync:
append_writer_and_args(
'sonarr', interface_id, sub_sync, base_sync
)
def __parse_yaml_options(self) -> None:
"""
Parse the 'options' section of the raw YAML dictionary into
attributes.
"""
# Skip if sections omitted
if not self._is_specified('options'):
return None
if (value := self.get('options', 'execution_mode',
type_=self.TYPE_LOWER_STR)) is not None:
if value in Manager.VALID_EXECUTION_MODES:
self.execution_mode = value
else:
log.critical(f'Execution mode "{value}" is invalid')
self.valid = False
if (value := self.get('options', 'series')) is not None:
if isinstance(value, list):
self.series_files = value
else:
self.series_files = [value]
else:
log.warning(f'No series YAML files indicated, no cards will be '
f'created')
if (value := self.get('options', 'card_type', type_=str)) is not None:
self.card_class = self._parse_card_type(value)
if (value := self.get('options', 'card_extension', type_=str)) is not None:
extension = ('' if value[0] == '.' else '.') + value
if extension in ImageMaker.VALID_IMAGE_EXTENSIONS:
self.card_extension = extension
else:
log.critical(f'Card extension "{extension}" is invalid')
self.valid = False
if (value := self.get('options', 'card_dimensions', type_=str)) is not None:
try:
width, height = map(int, value.lower().split('x'))
assert width > 0 and height > 0
if not (16 / 9 - 0.1) <= width / height <= (16 / 9 + 0.1):
log.warning(f'Card dimensions aspect ratio is not 16:9')
if width < 200 or height < 200:
log.warning(f'Card dimensions are very small')
self.card_dimensions = value
except ValueError:
log.critical(f'Invalid card dimensions - specify as WIDTHxHEIGHT')
self.valid = False
except AssertionError:
log.critical(f'Invalid card dimensions - both dimensions must '
f'be larger than 0px')
self.valid = False
if (value := self.get('options', 'filename_format', type_=str)) is not None:
if TitleCard.validate_card_format_string(value):
self.card_filename_format = value
else:
self.valid = False
if (value := self.get('options', 'image_source_priority',
type_=self.TYPE_LOWER_STR)) is not None:
if (sources := self.parse_image_source_priority(value)) is None:
log.critical(f'Image source priority "{value}" is invalid')
self.valid = False
else:
self.image_source_priority = sources
if (value := self.get('options', 'episode_data_source',
type_=self.TYPE_LOWER_STR)) is not None:
if value in self.VALID_EPISODE_DATA_SOURCES:
self.episode_data_source = value
else:
log.critical(f'Episode data source "{value}" is invalid')
self.valid = False
if (value := self.get('options', 'validate_fonts', type_=bool)) is not None:
self.validate_fonts = value
if (value := self.get('options', 'season_folder_format',
type_=str)) is not None:
self.season_folder_format = value
self.get_season_folder(1)
if (value := self.get('options', 'sync_specials', type_=bool)) is not None:
self.sync_specials = value
if (value := self.get('options', 'language_codes', type_=list)) is not None:
value = set(value) | set(('en', ))
if all(code in SUPPORTED_LANGUAGE_CODES for code in value):
self.supported_language_codes = value
else:
codes = ', '.join(SUPPORTED_LANGUAGE_CODES)
log.critical(f'Not all language codes are recognized')
log.info(f'Must be one of {codes}')
self.valid = False
return None
def __parse_yaml_archive(self) -> None:
"""
Parse the 'archive' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('archive'):
return None
if (value := self.get('archive', 'path', type_=Path)) is not None:
self.archive_directory = value
self.create_archive = True
if (value := self.get('archive', 'all_variations', type_=bool)) is not None:
self.archive_all_variations = value
if (value := self.get('archive', 'summary', 'create',
type_=bool)) is not None:
self.create_summaries = value
if (value := self.get('archive', 'summary', 'type',
type_=self.TYPE_LOWER_STR)) is not None:
if value == 'standard':
self.summary_class = StandardSummary
self.summary_background = self.summary_class.BACKGROUND_COLOR
elif value == 'stylized':
self.summary_class = StylizedSummary
self.summary_background = self.summary_class.BACKGROUND_COLOR
else:
log.critical(f'Summary type "{value}" is invalid - must be '
f'"standard" or "stylized"')
self.valid = False
if (value := self.get('archive', 'summary', 'created_by',
type_=str)) is not None:
self.summary_created_by = value
if (value := self.get('archive', 'summary', 'background',
type_=str)) is not None:
self.summary_background = value
if (value := self.get('archive', 'summary', 'minimum_episodes',
type_=int)) is not None:
self.summary_minimum_episode_count = value
if (value := self.get('archive', 'summary', 'ignore_specials',
type_=bool)) is not None:
self.summary_ignore_specials = value
return None
def __parse_yaml_emby(self) -> None:
"""
Parse the 'emby' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('emby'):
return None
if (not self._is_specified('emby', 'url')
or not self._is_specified('emby', 'api_key')
or not self._is_specified('emby', 'username')):
log.critical(f'Must specify Emby "url", "api_key", and "username"')
self.valid = False
if (value := self.get('emby', 'url', type_=str)) is not None:
self.emby_url = value
self.use_emby = True
if (value := self.get('emby', 'api_key', type_=str)) is not None:
self.emby_api_key = value
if (value := self.get('emby', 'username', type_=str)) is not None:
self.emby_username = value
if (value := self.get('emby', 'verify_ssl', type_=bool)) is not None:
self.emby_verify_ssl = value
if (value := self.get('emby', 'filesize_limit',
type_=self.filesize_as_bytes)) is not None:
self.emby_filesize_limit = value
self.emby_style_set = StyleSet(
self.get('emby', 'watched_style', type_=str, default='unique'),
self.get('emby', 'unwatched_style', type_=str, default='unique'),
)
self.valid &= self.emby_style_set.valid
return None
def __parse_yaml_jellyfin(self) -> None:
"""
Parse the 'jellyfin' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('jellyfin'):
return None
if (not self._is_specified('jellyfin', 'url')
or not self._is_specified('jellyfin', 'api_key')
or not self._is_specified('jellyfin', 'username')):
log.critical(f'Must specify Jellyfin "url", "api_key", and '
f'"username"')
self.valid = False
if (value := self.get('jellyfin', 'url', type_=str)) is not None:
self.jellyfin_url = value
self.use_jellyfin = True
if (value := self.get('jellyfin', 'api_key', type_=str)) is not None:
self.jellyfin_api_key = value
if (value := self.get('jellyfin', 'username', type_=str)) is not None:
self.jellyfin_username = value
if (value := self.get('jellyfin', 'verify_ssl', type_=bool)) is not None:
self.jellyfin_verify_ssl = value
if (value := self.get('jellyfin', 'filesize_limit',
type_=self.filesize_as_bytes)) is not None:
self.jellyfin_filesize_limit = value
self.jellyfin_style_set = StyleSet(
self.get('jellyfin', 'watched_style', type_=str, default='unique'),
self.get('jellyfin', 'unwatched_style', type_=str, default='unique'),
)
self.valid &= self.jellyfin_style_set.valid
return None
def __parse_yaml_plex(self) -> None:
"""
Parse the 'plex' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('plex'):
return None
if (value := self.get('plex', 'url', type_=str)) is not None:
self.plex_url = value
self.use_plex = True
if (value := self.get('plex', 'token', type_=str)) is not None:
self.plex_token = value
if (value := self.get('plex', 'verify_ssl', type_=bool)) is not None:
self.plex_verify_ssl = value
integrate = self.get(
'plex', 'integrate_with_kometa',
type_=bool,
default=self.get('plex', 'integrate_with_pmm_overlays', type_=bool)
)
if integrate is not None:
self.integrate_with_kometa = value
if (value := self.get('plex', 'filesize_limit',
type_=self.filesize_as_bytes)) is not None:
self.plex_filesize_limit = value
if value > self.filesize_as_bytes('10 MB'):
log.warning(f'Plex will reject all images larger than 10 MB')
if (value := self.get('plex', 'timeout', type_=int)) is not None:
if value < 1:
log.critical(f'Plex timeout must be at least 1')
self.valid = False
self.plex_timeout = value
self.plex_style_set = StyleSet(
self.get('plex', 'watched_style', type_=str, default='unique'),
self.get('plex', 'unwatched_style', type_=str, default='unique'),
)
self.valid &= self.plex_style_set.valid
return None
def __parse_yaml_sonarr(self) -> None:
"""
Parse the 'sonarr' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('sonarr'):
return None
# Inner function to parse a single instance of server YAML
def parse_server(yaml: dict[str, Any]):
reader = YamlReader(yaml)
# Server must provide URL and API key
if ((url := reader.get('url', type_=str)) is None or
(api_key := reader.get('api_key', type_=str)) is None):
log.critical(f'Sonarr server must contain "url" and "api_key"')
self.valid = False
else:
self.sonarr_kwargs.append({
'url': url,
'api_key': api_key,
'verify_ssl': reader.get(
'verify_ssl', type_=bool, default=True
),
'downloaded_only': reader.get(
'downloaded_only', type_=bool, default=True
),
})
# If multiple servers were specified, parse all specifications
if isinstance(self.get('sonarr'), list):
for server in self.get('sonarr'):
parse_server(server)
# Single server specification
elif isinstance(self.get('sonarr'), dict):
parse_server(self.get('sonarr'))
else:
log.critical(f'Invalid Sonarr preferences')
self.valid = False
return None
def __parse_yaml_tmdb(self) -> None:
"""
Parse the 'tmdb' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('tmdb'):
return None
if (value := self.get('tmdb', 'api_key', type_=str)) is not None:
self.tmdb_api_key = value
self.use_tmdb = True
if (value := self.get('tmdb', 'retry_count', type_=int)) is not None:
if value < 0:
log.critical(f'Cannot have a negative TMDb retry count')
self.valid = False
else:
self.tmdb_retry_count = value
if (value := self.get('tmdb', 'minimum_resolution', type_=str)) is not None:
try:
width, height = map(int, value.lower().split('x'))
self.tmdb_minimum_resolution = {'width': width, 'height':height}
except Exception:
log.critical(f'Invalid minimum resolution - specify as '
f'WIDTHxHEIGHT')
self.valid = False
if (value := self.get('tmdb', 'skip_localized_images',
type_=bool)) is not None:
self.tmdb_skip_localized_images = value
if (value := self.get('tmdb', 'logo_language_priority', type_=str)):
codes = list(map(str.strip, value.split(',')))
if all(code in TMDbInterface.LANGUAGE_CODES for code in codes):
self.tmdb_logo_language_priority = codes
else:
opts = '"' + '", "'.join(TMDbInterface.LANGUAGE_CODES) + '"'
log.critical(f'Invalid TMDb logo language codes - must be comma'
f'-separated list of any of the following: {opts}')
self.valid = False
return None
def __parse_yaml_tautulli(self) -> None:
"""
Parse the 'tautulli' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('tautulli'):
return None
# Parse required attributes
if ((url := self.get('tautulli', 'url', type_=str)) is not None
and (api_key := self.get('tautulli', 'api_key', type_=str)) is not None
and (script := self.get('tautulli', 'update_script',
type_=Path)) is not None):
self.tautulli_url = url
self.tautulli_api_key = api_key
self.tautulli_update_script = script
self.use_tautulli = True
else:
log.critical(f'tautulli preferences must contain "url", "api_key", '
f'and "update_script"')
self.valid = False
if (value := self.get('tautulli', 'verify_ssl', type_=bool)) is not None:
self.tautulli_verify_ssl = value
if (value := self.get('tautulli', 'username', type_=str)) is not None:
self.tautulli_username = value
if (value := self.get('tautulli', 'agent_name', type_=str)) is not None:
self.tautulli_agent_name = value
if (value := self.get('tautulli', 'script_timeout',type_=int)) is not None:
self.tautulli_script_timeout = value
return None
def __parse_yaml_imagemagick(self) -> None:
"""
Parse the 'imagemagick' section of the raw YAML dictionary into
attributes.
"""
# Skip if section omitted
if not self._is_specified('imagemagick'):
return None
# Warn if ImageMagick provided in a Docker environment
if self.is_docker:
log.warning(f'Specifying the "imagemagick" section is not '
f'recommended when using TitleCardMaker in Docker')
if (value := self.get('imagemagick', 'container', type_=str)):
self.imagemagick_container = value
if (value := self.get('imagemagick', 'timeout', type_=int)):
self.imagemagick_timeout = value
return None
def __parse_yaml(self) -> None:
"""
Parse the raw YAML dictionary into object attributes. This also
errors to the user if any provided values are overtly invalid
(i.e. missing where necessary, fails type conversion).
"""
# Parse each section
self.__parse_yaml_options()
self.__parse_yaml_archive()
self.__parse_yaml_emby()
self.__parse_yaml_jellyfin()
self.__parse_yaml_plex()
self.__parse_yaml_sonarr()
self.__parse_yaml_tmdb()
self.__parse_yaml_tautulli()
self.__parse_yaml_imagemagick()
# Warn for renamed settings
def __validate_libraries(self,
library_yaml: dict[str, str],
file: Path,
) -> bool:
"""
Validate the given libraries YAML.
Args:
library_yaml: YAML from the 'libraries' key to validate.
file: File whose YAML is being evaluated - for logging only.
Returns:
True if the given YAML is valid, False otherwise.
"""
err = f'in series YAML file "{file.resolve()}"'
# Libraries must be a dictionary
if not isinstance(library_yaml, dict):
log.error(f'Invalid library specification {err}')
return False
# Validate all given libraries
for name, spec in library_yaml.items():
# All libraries must be dictionaries
if not isinstance(spec, dict):
log.error(f'Library "{name}" is invalid {err}')
return False
# All libraries must provide paths
if spec.get('path') is None:
log.error(f'Library "{name}" is missing required "path" {err}')
return False
# Libraries must specify a media server if there is no default
if (self.default_media_server is None
and spec.get('media_server') is None):
log.error(f'Library "{name}" is missing required "media_server"'
f' {err}')
return False
# Media server must be Plex or Emby
if (spec.get('media_server', self.default_media_server)
not in ('emby', 'jellyfin', 'plex')):
log.error(f'Library "{name}" specifies an invalid media_server')
return False
return True
def __validate_fonts(self,
font_yaml: dict[str, Union[str, float]],
file: Path
) -> bool:
"""
Validate the given font YAML.
Args:
font_yaml: Font map YAML to validate.
file: File whose YAML is being evaluated - for logging only.
Returns:
True if the given YAML is valid, False otherwise.
"""
# Font map must be a dictionary
if not isinstance(font_yaml, dict):
log.error(f'Invalid font specification for series file '
f'"{file.resolve()}"')
return False
# Validate all given fonts
for name, spec in font_yaml.items():
# All fonts must be dictionaries
if not isinstance(spec, dict):
log.error(f'Font "{name}" is invalid for series file '
f'"{file.resolve()}"')
return False
# All fonts must provide valid font attributes
for attrib in spec.keys():
if attrib not in Font.VALID_ATTRIBUTES:
log.error(f'Font "{name}" has unrecognized attribute '
f'"{attrib}"')
return False
return True
def __apply_template(self,
templates: dict[str, Template],
series_yaml: dict[str, Any],
series_name: str) -> bool:
"""
Apply the correct Template object (if indicated) to the given
series YAML. This effectively "fill out" the indicated template,
and updates the series YAML directly.
Args:
templates: Dictionary of Template objects to potentially
apply.
series_yaml: The YAML of the series to modify.
series_name: The name of the series being modified.
Returns:
True if the given series contained all the required template
variables for application, False if it did not.
"""
# No templates defined for this series, skip
if 'template' not in series_yaml:
return True
# Get the indicated template YAML
series_template = series_yaml['template']
# If directly specified as a key, add to series YAML
if isinstance(series_template, str):
template_name = series_template
series_template = {'template_name': series_template}
series_yaml['template'] = series_template
elif isinstance(series_template, dict):
if 'name' not in series_template:
log.error(f'Missing template name for "{series_name}"')
return False
template_name = series_template['name']
else:
log.error(f'Template specification for "{series_name}" is invalid')
return False