-
Notifications
You must be signed in to change notification settings - Fork 278
/
series.py
2943 lines (2494 loc) · 115 KB
/
series.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
"""Series classes."""
from __future__ import unicode_literals
import copy
import datetime
import glob
import json
import logging
import os.path
import re
import shutil
import stat
import traceback
import warnings
from builtins import map
from builtins import str
from collections import (
OrderedDict, namedtuple
)
from itertools import chain, groupby
from medusa import (
app,
db,
helpers,
image_cache,
network_timezones,
notifiers,
post_processor,
ui,
)
from medusa.black_and_white_list import BlackAndWhiteList
from medusa.common import (
ARCHIVED,
DOWNLOADED,
FAILED,
IGNORED,
Overview,
Quality,
SKIPPED,
SNATCHED,
SNATCHED_BEST,
SNATCHED_PROPER,
UNAIRED,
UNSET,
WANTED,
countryList,
qualityPresets,
statusStrings,
)
from medusa.helper.common import episode_num, pretty_file_size, sanitize_filename, try_int
from medusa.helper.exceptions import (
CantRefreshShowException,
CantRemoveShowException,
EpisodeDeletedException,
EpisodeNotFoundException,
MultipleShowObjectsException,
ShowDirectoryNotFoundException,
ShowNotFoundException,
ex,
)
from medusa.helpers import make_dir
from medusa.helpers.anidb import short_group_names
from medusa.helpers.externals import check_existing_shows, get_externals, load_externals_from_db
from medusa.helpers.utils import dict_to_array, safe_get, to_camel_case
from medusa.imdb import Imdb
from medusa.indexers.api import indexerApi
from medusa.indexers.config import (
EXTERNAL_MAPPINGS,
INDEXER_IMDB,
INDEXER_TVRAGE,
STATUS_MAP,
indexerConfig
)
from medusa.indexers.exceptions import (
IndexerAttributeNotFound, IndexerException, IndexerSeasonNotFound, IndexerShowAlreadyInLibrary
)
from medusa.indexers.imdb.api import ImdbIdentifier
from medusa.indexers.tmdb.api import Tmdb
from medusa.indexers.utils import (
indexer_id_to_slug,
mappings,
reverse_mappings,
slug_to_indexer_id
)
from medusa.logger.adapters.style import CustomBraceAdapter
from medusa.media.banner import ShowBanner
from medusa.media.fan_art import ShowFanArt
from medusa.media.network_logo import ShowNetworkLogo
from medusa.media.poster import ShowPoster
from medusa.name_cache import build_name_cache
from medusa.name_parser.parser import (
InvalidNameException,
InvalidShowException,
NameParser,
)
from medusa.sbdatetime import sbdatetime
from medusa.scene_exceptions import get_all_scene_exceptions, get_scene_exceptions, refresh_exceptions_cache, update_scene_exceptions
from medusa.scene_numbering import (
get_scene_absolute_numbering_for_show, get_scene_numbering_for_show,
get_xem_absolute_numbering_for_show, get_xem_numbering_for_show,
numbering_tuple_to_dict, xem_refresh
)
from medusa.search import FORCED_SEARCH
from medusa.search_templates import SearchTemplates
from medusa.show.show import Show
from medusa.subtitles import (
code_from_code,
from_country_code_to_name,
)
from medusa.tv.base import Identifier, TV
from medusa.tv.episode import Episode
from medusa.tv.indexer import Indexer
from six import ensure_text, iteritems, itervalues, string_types, text_type, viewitems
import ttl_cache
try:
from send2trash import send2trash
except ImportError:
app.TRASH_REMOVE_SHOW = 0
MILLIS_YEAR_1900 = datetime.datetime(year=1900, month=1, day=1).toordinal()
log = CustomBraceAdapter(logging.getLogger(__name__))
log.logger.addHandler(logging.NullHandler())
class SaveSeriesException(Exception):
"""Generic exception used for adding a new series."""
class ChangeIndexerException(Exception):
"""Generic exception used for changing a shows indexer."""
class SeriesIdentifier(Identifier):
"""Series identifier with indexer and indexer id."""
def __init__(self, indexer, identifier):
"""Constructor.
:param indexer:
:type indexer: Indexer or int
:param identifier:
:type identifier: int
"""
self.indexer = indexer if isinstance(indexer, Indexer) else Indexer.from_id(indexer)
self.id = identifier
@classmethod
def from_slug(cls, slug):
"""Create SeriesIdentifier from slug. E.g.: tvdb1234."""
result = slug_to_indexer_id(slug)
if result is not None:
indexer, indexer_id = result
if indexer is not None and indexer_id is not None:
return SeriesIdentifier(Indexer(indexer), indexer_id)
@classmethod
def from_id(cls, indexer, indexer_id):
"""Create SeriesIdentifier from tuple (indexer, indexer_id)."""
return SeriesIdentifier(indexer, indexer_id)
@property
def slug(self):
"""Slug."""
return text_type(self)
def get_indexer_api(self, options=None):
"""Return an indexer api for this show."""
indexer_api = indexerApi(self.indexer.id)
indexer_api_params = indexer_api.api_params.copy()
if options and options.get('lang') is not None:
indexer_api_params['language'] = options['lang']
log.debug('{indexer_name}: {indexer_params!r}', {
'indexer_name': indexerApi(self.indexer.id).name,
'indexer_params': indexer_api_params
})
return indexer_api.indexer(**indexer_api_params)
def __bool__(self):
"""Magic method."""
return self.indexer is not None and self.id is not None
def __repr__(self):
"""Magic method."""
return '<SeriesIdentifier [{0!r} - {1}]>'.format(self.indexer, self.id)
def __str__(self):
"""Magic method."""
return '{0}{1}'.format(self.indexer, self.id)
def __hash__(self):
"""Magic method."""
return hash((self.indexer, self.id))
def __eq__(self, other):
"""Magic method."""
return isinstance(other, SeriesIdentifier) and self.indexer == other.indexer and self.id == other.id
class Series(TV):
"""Represent a TV Show."""
YEAR_MATCH = re.compile(r'.*\(\d{4}\)$')
def __init__(self, indexer, indexerid, lang='', quality=None,
season_folders=None, enabled_subtitles=None):
"""Instantiate a Series with database information based on indexerid.
:param indexer:
:type indexer: int
:param indexerid:
:type indexerid: int
:param lang:
:type lang: str
"""
super(Series, self).__init__(
indexer, indexerid,
{'episodes', 'next_aired', 'release_groups', 'imdb_info'})
self.show_id = None
self.name = ''
self.imdb_id = ''
self.network = ''
self.genre = ''
self.classification = ''
self.runtime = 0
self.plot = None
self.imdb_info = {}
self.quality = quality or int(app.QUALITY_DEFAULT)
self.season_folders = season_folders or int(app.SEASON_FOLDERS_DEFAULT)
self.status = 'Unknown'
self._airs = ''
# Amount of hours we want to start searching early (-1) or late (1) for new episodes
self.airdate_offset = 0
self.start_year = 0
self.paused = 0
self.air_by_date = 0
self.subtitles = enabled_subtitles or int(app.SUBTITLES_DEFAULT)
self.notify_list = {}
self.dvd_order = 0
self.lang = lang
self._last_update_indexer = 1
self.sports = 0
self.anime = 0
self.scene = 0
self._release_required_words = ''
self._release_ignored_words = ''
self.release_ignored_exclude = 0
self.release_required_exclude = 0
self.default_ep_status = SKIPPED
self._location = ''
self.episodes = {}
self._prev_aired = 0
self._next_aired = 0
self._release_groups = None
self._aliases = set()
self.externals = {}
self._indexer_api = None
self._show_lists = ''
self._templates = None
self._search_templates = None
other_show = Show.find_by_id(app.showList, self.indexer, self.series_id)
if other_show is not None:
raise MultipleShowObjectsException("Can't create a show if it already exists")
self._load_from_db()
@classmethod
def find_series(cls, predicate=None):
"""Find series based on given predicate."""
return [s for s in app.showList if s and (not predicate or predicate(s))]
@classmethod
def find_by_identifier(cls, identifier, predicate=None):
"""Find series by its identifier and predicate.
:param identifier:
:type identifier: medusa.tv.series.SeriesIdentifier
:param predicate:
:type predicate: callable
:return:
:rtype:
"""
result = Show.find_by_id(app.showList, identifier.indexer.id, identifier.id)
if result and (not predicate or predicate(result)):
return result
@classmethod
def from_identifier(cls, identifier):
"""Create a series object from its identifier."""
return Series(identifier.indexer.id, identifier.id)
@property
def title(self):
"""Get show's title.
The shows title is displayed in the UI and used for creating the shows folder and episodes.
The title is set for searches.
"""
if all([app.ADD_TITLE_WITH_YEAR, self.start_year and not Series.YEAR_MATCH.match(self.name)]):
return '{name} ({year})'.format(name=self.name, year=self.start_year)
return self.name
@property
def identifier(self):
"""Return a series identifier object."""
return SeriesIdentifier(self.indexer, self.series_id)
@property
def slug(self):
"""Slug."""
return self.identifier.slug
@property
def indexer_api(self):
"""Get an Indexer API instance."""
if not self._indexer_api:
self.create_indexer()
return self._indexer_api
@indexer_api.setter
def indexer_api(self, value):
"""Set an Indexer API instance."""
self._indexer_api = value
def create_indexer(self, banners=False, actors=False, dvd_order=False, episodes=True):
"""Force the creation of a new Indexer API."""
api = indexerApi(self.indexer)
params = api.api_params.copy()
if self.lang:
params['language'] = self.lang
log.debug('{id}: Using language from show settings: {lang}',
{'id': self.series_id, 'lang': self.lang})
if self.dvd_order != 0 or dvd_order:
params['dvdorder'] = True
params['actors'] = actors
params['banners'] = banners
params['episodes'] = episodes
self.indexer_api = api.indexer(**params)
@property
def is_anime(self):
"""Check if the show is Anime."""
return bool(self.anime)
@property
def use_templates(self):
"""Check if the show uses advanced templates."""
return bool(self.templates)
def is_location_valid(self, location=None):
"""
Check if the location is valid.
:param location: Path to check
:return: True if the given path is a directory
"""
return os.path.isdir(location or self._location)
@property
def is_recently_deleted(self):
"""
Check if the show was recently deleted.
Can be used to suppress error messages such as attempting to use the
show object just after being removed.
"""
return self.indexer_slug in app.RECENTLY_DELETED
@property
def is_scene(self):
"""Check if this ia a scene show."""
return bool(self.scene)
@property
def is_sports(self):
"""Check if this is a sport show."""
return bool(self.sports)
@property
def network_logo_name(self):
"""Get the network logo name."""
def sanitize_network_names(str):
dict = ({
u'\u010C': 'C', # Č
u'\u00E1': 'a', # á
u'\u00E9': 'e', # é
u'\u00F1': 'n', # ñ
u'\u00C9': 'e', # É
u'\u05E7': 'q', # ק
u'\u05E9': 's', # ש
u'\u05EA': 't', # ת
' ': '-'})
for key in dict:
str = str.replace(key, dict[key])
return str.lower()
return sanitize_network_names(self.network)
@property
def validate_location(self):
"""Legacy call to location with a validation when ADD_SHOWS_WO_DIR is set."""
if app.CREATE_MISSING_SHOW_DIRS or self.is_location_valid():
return self._location
raise ShowDirectoryNotFoundException('Show folder does not exist.')
@property
def location(self):
"""Get the show location."""
return self._location
@location.setter
def location(self, value):
old_location = os.path.normpath(self._location)
new_location = os.path.normpath(value)
if new_location == old_location:
return
log.debug(
u'{indexer} {id}: Setting location: {location}', {
'indexer': indexerApi(self.indexer).name,
'id': self.series_id,
'location': new_location,
}
)
# Don't validate directory if user wants to add shows without creating a dir
if app.ADD_SHOWS_WO_DIR or self.is_location_valid(value):
self._location = new_location
return
changed_location = True
log.info('Changing show location to: {new}', {'new': new_location})
if not os.path.isdir(new_location):
if app.CREATE_MISSING_SHOW_DIRS:
log.info(u"Show directory doesn't exist, creating it")
try:
os.mkdir(new_location)
except OSError as error:
changed_location = False
log.warning(u"Unable to create the show directory '{location}'. Error: {msg}",
{'location': new_location, 'msg': error})
else:
log.info('New show directory created')
helpers.chmod_as_parent(new_location)
else:
changed_location = False
log.warning(
"New location '{location}' does not exist. "
"Enable setting '(Config - Postprocessing) Create missing show dirs'",
{'location': new_location})
# Save new location only if we changed it
if changed_location:
self._location = new_location
if changed_location and os.path.isdir(new_location):
try:
app.show_queue_scheduler.action.refreshShow(self)
except CantRefreshShowException as error:
log.warning("Unable to refresh show '{show}'. Error: {error}",
{'show': self.name, 'error': error})
@property
def indexer_name(self):
"""Return the indexer name identifier. Example: tvdb."""
return indexerConfig[self.indexer].get('identifier')
@property
def indexer_slug(self):
"""Return the slug name of the series. Example: tvdb1234."""
return indexer_id_to_slug(self.indexer, self.series_id)
@property
def current_qualities(self):
"""
Get the show qualities.
:returns: A tuple of allowed and preferred qualities
"""
return Quality.split_quality(int(self.quality))
@property
def using_preset_quality(self):
"""Check if a preset is used."""
return self.quality in qualityPresets
@property
def default_ep_status_name(self):
"""Get the default episode status name."""
return statusStrings[self.default_ep_status]
@default_ep_status_name.setter
def default_ep_status_name(self, status_name):
"""Set the default episode status using its name."""
self.default_ep_status = next((status for status, name in iteritems(statusStrings)
if name.lower() == status_name.lower()),
self.default_ep_status)
@property
def size(self):
"""Size of the show on disk."""
return helpers.get_size(self.location)
def show_size(self, pretty=False):
"""
Get the size of the show on disk (deprecated).
:param pretty: True if you want a pretty size. (e.g. 3 GB)
:return: Size of the show on disk.
"""
warnings.warn(
u'Method show_size is deprecated. Use size property instead.',
DeprecationWarning,
)
return pretty_file_size(self.size) if pretty else self.size
@property
def subtitle_flag(self):
"""Subtitle flag."""
return code_from_code(self.lang) if self.lang else ''
@property
def show_type(self):
"""Return show type."""
return 'sports' if self.is_sports else ('anime' if self.is_anime else 'series')
@property
def imdb_year(self):
"""Return series year."""
return self.imdb_info.get('year')
@property
def imdb_runtime(self):
"""Return series runtime."""
return self.imdb_info.get('runtimes')
@property
def imdb_akas(self):
"""Return genres akas dict."""
akas = {}
for x in [v for v in (self.imdb_info.get('akas') or '').split('|') if v]:
if '::' in x:
val, key = x.split('::')
akas[key] = val
return akas
@property
def imdb_countries(self):
"""Return country codes."""
return [v for v in (self.imdb_info.get('country_codes') or '').split('|') if v]
@property
def imdb_plot(self):
"""Return series plot."""
return self.imdb_info.get('plot') or ''
@property
def imdb_genres(self):
"""Return series genres."""
return self.imdb_info.get('genres') or ''
@property
def imdb_votes(self):
"""Return series votes."""
return self.imdb_info.get('votes')
@property
def imdb_rating(self):
"""Return series rating."""
return self.imdb_info.get('rating')
@property
def imdb_certificates(self):
"""Return series certificates."""
return self.imdb_info.get('certificates')
@property
def last_update_indexer(self):
"""Return last indexer update as epoch."""
update_date = datetime.date.fromordinal(self._last_update_indexer)
epoch_date = update_date - datetime.date.fromtimestamp(0)
return int(epoch_date.total_seconds())
@last_update_indexer.setter
def last_update_indexer(self, value):
"""Set last indexer update (datetime.date.today().toordinal())."""
self._last_update_indexer = value
@property
def prev_aired(self):
"""Return last aired episode ordinal."""
self._prev_aired = self.prev_episode()
return self._prev_aired
@property
def next_aired(self):
"""Return next aired episode ordinal."""
today = datetime.date.today().toordinal()
if not self._next_aired or self._next_aired < today:
self._next_aired = self.next_episode()
return self._next_aired
@property
@ttl_cache(21600.0)
def prev_airdate(self):
"""Return last aired episode airdate."""
return (
sbdatetime.convert_to_setting(network_timezones.parse_date_time(self.prev_aired, self.airs, self.network))
if self.prev_aired > MILLIS_YEAR_1900 else None
)
@property
@ttl_cache(21600.0)
def next_airdate(self):
"""Return next aired episode airdate."""
return (
sbdatetime.convert_to_setting(network_timezones.parse_date_time(self.next_aired, self.airs, self.network))
if self.next_aired > MILLIS_YEAR_1900 else None
)
@property
def countries(self):
"""Return countries."""
return [v for v in (self.imdb_info.get('countries') or '').split('|') if v]
@property
def genres(self):
"""Return genres list."""
return list({
i for i in (self.genre or '').split('|') if i}
| {i for i in self.imdb_genres.replace('Sci-Fi', 'Science-Fiction').split('|') if i})
@property
def airs(self):
"""Return episode time that series usually airs."""
return self._airs
@airs.setter
def airs(self, value):
"""Set episode time that series usually airs."""
if value is None or not network_timezones.test_timeformat(value):
self._airs = ''
else:
self._airs = text_type(value).replace('am', ' AM').replace('pm', ' PM').replace(' ', ' ').strip()
@property
def poster(self):
"""Return poster path."""
img_type = image_cache.POSTER
return image_cache.get_artwork(img_type, self)
@property
def banner(self):
"""Return banner path."""
img_type = image_cache.BANNER
return image_cache.get_artwork(img_type, self)
@property
def aliases(self):
"""Return series aliases."""
if self._aliases:
return self._aliases
return set(chain(*itervalues(get_all_scene_exceptions(self))))
@aliases.setter
def aliases(self, exceptions):
"""
Set the series aliases.
:param exceptions: Array of dictionaries.
"""
update_scene_exceptions(self, exceptions)
self._aliases = set(chain(*itervalues(get_all_scene_exceptions(self))))
# If we added or removed aliases, we need to make sure these are reflected in the search templates.
self._search_templates.templates = self._search_templates.generate()
build_name_cache(self)
@property
def aliases_to_json(self):
"""Return aliases as a dict."""
return [{
'season': alias.season,
'title': alias.title,
'custom': alias.custom
} for alias in self.aliases]
@property
@ttl_cache(25200.0) # Caching as this is requested for the /home page.
def xem_numbering(self):
"""Return series episode xem numbering."""
return get_xem_numbering_for_show(self, refresh_data=False)
@property
def xem_absolute_numbering(self):
"""Return series xem absolute numbering."""
return get_xem_absolute_numbering_for_show(self)
@property
def scene_absolute_numbering(self):
"""Return series scene absolute numbering."""
return get_scene_absolute_numbering_for_show(self)
@property
def scene_numbering(self):
"""Return series scene numbering."""
return get_scene_numbering_for_show(self)
@property
def release_ignored_words(self):
"""Return release ignore words."""
return [v for v in self._release_ignored_words.split(',') if v]
@release_ignored_words.setter
def release_ignored_words(self, value):
self._release_ignored_words = value if isinstance(value, string_types) else ','.join(value)
@property
def release_required_words(self):
"""Return release ignore words."""
return [v for v in (self._release_required_words or '').split(',') if v]
@release_required_words.setter
def release_required_words(self, value):
self._release_required_words = value if isinstance(value, string_types) else ','.join(value)
@property
def release_groups(self):
"""Return the BlackAndWhiteList object."""
if not self._release_groups:
self._release_groups = BlackAndWhiteList(self)
return self._release_groups
@property
def blacklist(self):
"""Return the anime's blacklisted release groups."""
return self.release_groups.blacklist
@blacklist.setter
def blacklist(self, group_names):
"""
Set the anime's blacklisted release groups.
:param group_names: A list of blacklist release group names.
"""
self.release_groups.set_black_keywords(short_group_names(group_names))
@property
def whitelist(self):
"""Return the anime's whitelisted release groups."""
return self.release_groups.whitelist
@whitelist.setter
def whitelist(self, group_names):
"""
Set the anime's whitelisted release groups.
:param group_names: A list of whitelist release group names.
"""
self.release_groups.set_white_keywords(short_group_names(group_names))
@staticmethod
def normalize_status(status):
"""Return a normalized status given current indexer status."""
for medusa_status, indexer_mappings in viewitems(STATUS_MAP):
if status.lower() in indexer_mappings:
return medusa_status
return 'Unknown'
def flush_episodes(self):
"""Delete references to anything that's not in the internal lists."""
for cur_season in self.episodes:
for cur_ep in self.episodes[cur_season]:
my_ep = self.episodes[cur_season][cur_ep]
self.episodes[cur_season][cur_ep] = None
del my_ep
def erase_cached_parse(self):
"""Erase parsed cached results."""
NameParser().erase_cached_parse(self.indexer, self.series_id)
def get_all_seasons(self, last_airdate=False):
"""Retrieve a dictionary of seasons with the number of episodes, using the episodes table.
:param last_airdate: Option to pass the airdate of the last aired episode for the season in stead of the number
of episodes
:type last_airdate: bool
:return:
:rtype: dictionary of seasons (int) and count(episodes) (int)
"""
sql_selection = 'SELECT season, {0} AS number_of_episodes FROM tv_episodes ' \
'WHERE showid = ? GROUP BY season'.format('count(*)' if not last_airdate else 'max(airdate)')
main_db_con = db.DBConnection()
results = main_db_con.select(sql_selection, [self.series_id])
return {int(x['season']): int(x['number_of_episodes']) for x in results}
def get_all_episodes(self, season=None, has_location=False):
"""Retrieve all episodes for this show given the specified filter.
:param season:
:type season: int or list of int
:param has_location:
:type has_location: bool
:return:
:rtype: list of Episode
"""
# subselection to detect multi-episodes early, share_location > 0
# If a multi-episode release has been downloaded. For example my.show.S01E1E2.1080p.WEBDL.mkv, you'll find the same location
# in the database for those episodes (S01E01 and S01E02). The query is to mark that the location for each episode is shared with another episode.
sql_selection = ('SELECT season, episode, (SELECT '
' COUNT (*) '
'FROM '
' tv_episodes '
'WHERE '
' indexer = tve.indexer AND showid = tve.showid '
' AND season = tve.season '
" AND location != '' "
' AND location = tve.location '
' AND episode != tve.episode) AS share_location '
'FROM tv_episodes tve WHERE indexer = ? AND showid = ?'
)
sql_args = [self.indexer, self.series_id]
if season is not None:
season = helpers.ensure_list(season)
sql_selection += ' AND season IN (?)'
sql_args.append(','.join(map(text_type, season)))
if has_location:
sql_selection += " AND location != ''"
# need ORDER episode ASC to rename multi-episodes in order S01E01-02
sql_selection += ' ORDER BY season ASC, episode ASC'
main_db_con = db.DBConnection()
results = main_db_con.select(sql_selection, sql_args)
ep_list = []
for cur_result in results:
cur_ep = self.get_episode(cur_result['season'], cur_result['episode'])
if not cur_ep:
continue
cur_ep.related_episodes = []
if cur_ep.location:
# if there is a location, check if it's a multi-episode (share_location > 0)
# and put them in related_episodes
if cur_result['share_location'] > 0:
related_eps_result = main_db_con.select(
'SELECT '
' season, episode '
'FROM '
' tv_episodes '
'WHERE '
' showid = ? '
' AND season = ? '
' AND location = ? '
' AND episode != ? '
'ORDER BY episode ASC',
[self.series_id, cur_ep.season, cur_ep.location, cur_ep.episode])
for cur_related_ep in related_eps_result:
related_ep = self.get_episode(cur_related_ep['season'], cur_related_ep['episode'])
if related_ep and related_ep not in cur_ep.related_episodes:
cur_ep.related_episodes.append(related_ep)
ep_list.append(cur_ep)
return ep_list
def get_episode(self, season=None, episode=None, filepath=None, no_create=False, absolute_number=None,
air_date=None, should_cache=True):
"""Return TVEpisode given the specified filter.
:param season:
:type season: int
:param episode:
:type episode: int
:param filepath:
:type filepath: str
:param no_create:
:type no_create: bool
:param absolute_number:
:type absolute_number: int
:param air_date:
:type air_date: datetime.datetime
:param should_cache:
:type should_cache: bool
:return:
:rtype: Episode
"""
season = try_int(season, None)
episode = try_int(episode, None)
absolute_number = try_int(absolute_number, None)
# if we get an anime get the real season and episode
if season is None and not episode:
main_db_con = db.DBConnection()
sql = None
sql_args = None
if self.is_anime and absolute_number:
sql = (
'SELECT season, episode '
'FROM tv_episodes '
'WHERE indexer = ? '
'AND showid = ? '
'AND absolute_number = ?'
)
sql_args = [self.indexer, self.series_id, absolute_number]
log.debug('{id}: Season and episode lookup for {show} using absolute number {absolute}',
{'id': self.series_id, 'absolute': absolute_number, 'show': self.name})
elif air_date:
sql = (
'SELECT season, episode '
'FROM tv_episodes '
'WHERE indexer = ? '
'AND showid = ? '
'AND airdate = ?'
)
sql_args = [self.indexer, self.series_id, air_date.toordinal()]
log.debug('{id}: Season and episode lookup for {show} using air date {air_date}',
{'id': self.series_id, 'air_date': air_date, 'show': self.name})
sql_results = main_db_con.select(sql, sql_args) if sql else []
if len(sql_results) == 1:
episode = int(sql_results[0]['episode'])
season = int(sql_results[0]['season'])
log.debug(
u'{id}: Found season and episode which is {show} {ep}', {
'id': self.series_id,
'show': self.name,
'ep': episode_num(season, episode)
}
)
elif len(sql_results) > 1:
log.error('{id}: Multiple entries found in show: {show} ',
{'id': self.series_id, 'show': self.name})
return None
else:
log.debug('{id}: No entries found in show: {show}',
{'id': self.series_id, 'show': self.name})
return None
if season not in self.episodes:
self.episodes[season] = {}
if episode in self.episodes[season] and self.episodes[season][episode] is not None:
return self.episodes[season][episode]
elif no_create:
return None
if filepath:
ep = Episode(self, season, episode, filepath)
else:
ep = Episode(self, season, episode)
if ep is not None and should_cache:
self.episodes[season][episode] = ep
return ep
def show_words(self):
"""Return all related words to show: preferred, undesired, ignore, require."""
words = namedtuple('show_words', ['preferred_words', 'undesired_words', 'ignored_words', 'required_words'])
preferred_words = app.PREFERRED_WORDS
undesired_words = app.UNDESIRED_WORDS
global_ignore = app.IGNORE_WORDS
global_require = app.REQUIRE_WORDS
show_ignore = self.release_ignored_words
show_require = self.release_required_words
# If word is in global ignore and also in show require, then remove it from global ignore
# Join new global ignore with show ignore
if not self.release_ignored_exclude:
final_ignore = show_ignore + [i for i in global_ignore if i.lower() not in [r.lower() for r in show_require]]
else: