-
Notifications
You must be signed in to change notification settings - Fork 278
/
episode.py
2211 lines (1871 loc) · 85.6 KB
/
episode.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
"""Episode classes."""
from __future__ import unicode_literals
import logging
import os.path
import re
import time
import traceback
import warnings
from builtins import str
from datetime import date, datetime
import knowit
from medusa import (
app,
db,
helpers,
network_timezones,
notifiers,
post_processor,
subtitles,
ws
)
from medusa.common import (
ARCHIVED,
DOWNLOADED,
FAILED,
NAMING_DUPLICATE,
NAMING_EXTEND,
NAMING_LIMITED_EXTEND,
NAMING_LIMITED_EXTEND_E_LOWER_PREFIXED,
NAMING_LIMITED_EXTEND_E_UPPER_PREFIXED,
NAMING_SEPARATED_REPEAT,
Quality,
SKIPPED,
SNATCHED,
SNATCHED_BEST,
SNATCHED_PROPER,
UNAIRED,
UNSET,
WANTED,
statusStrings,
)
from medusa.helper.common import (
dateFormat,
dateTimeFormat,
episode_num,
remove_extension,
replace_extension,
sanitize_filename,
try_int,
)
from medusa.helper.exceptions import (
EpisodeDeletedException,
EpisodeNotFoundException,
MultipleEpisodesInDatabaseException,
NoNFOException,
ex,
)
from medusa.indexers.api import indexerApi
from medusa.indexers.config import indexerConfig
from medusa.indexers.exceptions import (
IndexerEpisodeNotFound,
IndexerError,
IndexerSeasonNotFound,
)
from medusa.logger.adapters.style import BraceAdapter
from medusa.name_parser.parser import (
InvalidNameException,
InvalidShowException,
NameParser,
)
from medusa.sbdatetime import sbdatetime
from medusa.scene_numbering import (
get_scene_absolute_numbering,
get_scene_numbering,
)
from medusa.search.queue import FailedQueueItem
from medusa.tv.base import Identifier, TV
from six import itervalues, viewitems
try:
import xml.etree.cElementTree as ETree
except ImportError:
import xml.etree.ElementTree as ETree
log = BraceAdapter(logging.getLogger(__name__))
log.logger.addHandler(logging.NullHandler())
class EpisodeNumber(Identifier):
"""Episode Number: season/episode, absolute or air by date."""
date_fmt = '%Y-%m-%d'
regex = re.compile(r'\b(?:(?P<air_date>\d{4}-\d{2}-\d{2})|'
r'(?:s(?P<season>\d{1,4}))(?:e(?P<episode>\d{1,4}))|'
r'(?:e(?P<abs_episode>\d{1,4})))\b', re.IGNORECASE)
@classmethod
def from_slug(cls, slug):
"""Create episode number from slug. E.g.: s01e02."""
match = cls.regex.match(slug)
if match:
try:
result = {k: int(v) if k != 'air_date' else datetime.strptime(v, cls.date_fmt)
for k, v in viewitems(match.groupdict()) if v is not None}
if result:
if 'air_date' in result:
return AirByDateNumber(**result)
if 'season' in result and 'episode' in result:
return RelativeNumber(**result)
if 'abs_episode' in result:
return AbsoluteNumber(**result)
except ValueError:
pass
class RelativeNumber(Identifier):
"""Regular episode number: season and episode."""
def __init__(self, season, episode):
"""Constructor.
:param season:
:type season: int
:param episode:
:type episode: int
"""
self.season = season
self.episode = episode
def __bool__(self):
"""Magic method."""
return self.season is not None and self.episode is not None
def __repr__(self):
"""Magic method."""
return '<RelativeNumber [s{0:02d}e{1:02d}]>'.format(self.season, self.episode)
def __str__(self):
"""Magic method."""
return 's{0:02d}e{1:02d}'.format(self.season, self.episode)
def __hash__(self):
"""Magic method."""
return hash((self.season, self.episode))
def __eq__(self, other):
"""Magic method."""
return isinstance(other, RelativeNumber) and (
self.season == other.season and self.episode == other.episode)
class AbsoluteNumber(EpisodeNumber):
"""Episode number class that handles absolute episode numbers."""
def __init__(self, abs_episode):
"""Constructor.
:param abs_episode:
:type abs_episode: int
"""
self.episode = abs_episode
def __bool__(self):
"""Magic method."""
return self.episode is not None
def __repr__(self):
"""Magic method."""
return '<AbsoluteNumber [e{0:02d}]>'.format(self.episode)
def __str__(self):
"""Magic method."""
return 'e{0:02d}'.format(self.episode)
def __hash__(self):
"""Magic method."""
return hash(self.episode)
def __eq__(self, other):
"""Magic method."""
return isinstance(other, AbsoluteNumber) and self.episode == other.episode
class AirByDateNumber(EpisodeNumber):
"""Episode number class that handles air-by-date episode numbers."""
def __init__(self, air_date):
"""Constructor.
:param air_date:
:type air_date: datetime
"""
self.air_date = air_date
def __bool__(self):
"""Magic method."""
return self.air_date is not None
def __repr__(self):
"""Magic method."""
return '<AirByDateNumber [{0!r}]>'.format(self.air_date)
def __str__(self):
"""Magic method."""
return self.air_date.strftime(self.date_fmt)
def __hash__(self):
"""Magic method."""
return hash(self.air_date)
def __eq__(self, other):
"""Magic method."""
return isinstance(other, AirByDateNumber) and self.air_date == other.air_date
class Episode(TV):
"""Represent a TV Show episode."""
__refactored = {
'show': 'series',
}
def __init__(self, series, season, episode, filepath=''):
"""Instantiate a Episode with database information."""
super(Episode, self).__init__(
int(series.indexer) if series else 0,
int(series.indexerid) if series else 0,
{'series', 'related_episodes', 'wanted_quality'})
self.series = series
self.name = ''
self.season = season
self.episode = episode
self.slug = 's{season:02d}e{episode:02d}'.format(season=self.season, episode=self.episode)
self.absolute_number = 0
self.description = ''
self.subtitles = []
self.subtitles_searchcount = 0
self.subtitles_lastsearch = str(datetime.min)
self.airdate = date.fromordinal(1)
self.hasnfo = False
self.hastbn = False
self._status = UNSET
self.quality = Quality.NA
self.file_size = 0
self.release_name = ''
self.is_proper = False
self.version = 0
self.release_group = ''
self._location = filepath
self._scene_season = None
self._scene_episode = 0
self._scene_absolute_number = 0
self.manually_searched = False
self.related_episodes = []
self.wanted_quality = []
self.watched = False
if series:
self._specify_episode(self.season, self.episode)
self.check_for_meta_files()
def __getattr__(self, item):
"""Get attribute values for deprecated attributes."""
try:
return super(Episode, self).__getattribute__(item)
except AttributeError as error:
try:
refactor = self.__refactored[item]
except KeyError:
raise error
else:
warnings.warn(
'{item} is deprecated, use {refactor} instead \n{trace}'.format(
item=item, refactor=refactor, trace=traceback.print_stack(),
),
DeprecationWarning
)
return super(Episode, self).__getattribute__(refactor)
def __eq__(self, other):
"""Override default equalize implementation."""
return all([self.series.identifier == other.series.identifier,
self.season == other.season,
self.episode == other.episode])
@classmethod
def find_by_series_and_episode(cls, series, episode_number):
"""Find Episode based on series and episode number.
:param series:
:type series: medusa.tv.series.Series
:param episode_number:
:type episode_number: EpisodeNumber
:return:
:rtype: medusa.tv.Episode
"""
if isinstance(episode_number, RelativeNumber):
episode = series.get_episode(season=episode_number.season, episode=episode_number.episode)
elif isinstance(episode_number, AbsoluteNumber):
episode = series.get_episode(absolute_number=episode_number.episode)
elif isinstance(episode_number, AirByDateNumber):
episode = series.get_episode(air_date=episode_number.air_date)
else:
# if this happens then it's a bug!
raise ValueError
if episode:
return episode
@staticmethod
def from_filepath(filepath):
"""Return an Episode for the given filepath.
IMPORTANT: The filepath is not kept in the Episode.location
Episode.location should only be set after it's post-processed and it's in the correct location.
As of now, Episode is also not cached in Series.episodes since this method is only used during postpone PP.
Goal here is to slowly move to use this method to create TVEpisodes. New parameters might be introduced.
:param filepath:
:type filepath: str
:return:
:rtype: Episode
"""
try:
parse_result = NameParser().parse(filepath, cache_result=True)
results = []
if parse_result.series.is_anime and parse_result.ab_episode_numbers:
episodes = (parse_result.series.get_episode(absolute_number=episode_number, should_cache=False)
for episode_number in parse_result.ab_episode_numbers)
results = [ep for ep in episodes if ep is not None]
if not parse_result.series.is_anime and parse_result.episode_numbers:
episodes = (parse_result.series.get_episode(season=parse_result.season_number,
episode=episode_number, should_cache=False)
for episode_number in parse_result.episode_numbers)
results = [ep for ep in episodes if ep is not None]
for episode in results:
episode.related_episodes = list(results[1:])
return episode # only root episode has related_episodes
except (InvalidNameException, InvalidShowException):
log.warning('Cannot create Episode from path {path}',
{'path': filepath})
@property
def identifier(self):
"""Return the episode identifier.
:return:
:rtype: string
"""
if self.series.air_by_date and self.airdate != date.fromordinal(1):
return self.airdate.strftime(dateFormat)
if self.series.is_anime and self.absolute_number is not None:
return 'e{0:02d}'.format(self.absolute_number)
return 's{0:02d}e{1:02d}'.format(self.season, self.episode)
@property
def location(self):
"""Return the location.
:return:
:rtype: location
"""
return self._location
@location.setter
def location(self, value):
old_location = os.path.normpath(self._location)
new_location = os.path.normpath(value)
if value and self.is_location_valid(new_location):
self.file_size = os.path.getsize(new_location)
else:
self._location = ''
self.file_size = 0
return
if new_location == old_location:
return
log.debug('{id}: Setter sets location to {location}',
{'id': self.series.series_id, 'location': new_location})
self._location = new_location
@property
def indexer_name(self):
"""Return the indexer name identifier. Example: tvdb."""
return indexerConfig[self.indexer].get('identifier')
@property
def air_date(self):
"""Return air date from the episode."""
if self.airdate == date.min:
return None
date_parsed = sbdatetime.convert_to_setting(
network_timezones.parse_date_time(
date.toordinal(self.airdate),
self.series.airs,
self.series.network)
)
return date_parsed.isoformat()
@property
def status(self):
"""Return the episode status."""
return self._status
@status.setter
def status(self, value):
self._status = value
@property
def status_name(self):
"""Return the status name."""
return statusStrings[self.status]
@property
def scene_season(self):
"""Return the scene season."""
if self._scene_season is None:
return self.season
return self._scene_season
@scene_season.setter
def scene_season(self, value):
"""Set the scene season."""
self._scene_season = try_int(value, None)
@property
def scene_episode(self):
"""Return the scene episode."""
if not self._scene_episode:
return self.episode
return self._scene_episode
@scene_episode.setter
def scene_episode(self, value):
"""Set the scene episode."""
self._scene_episode = try_int(value, 0)
@property
def scene_absolute_number(self):
"""Return the scene absolute number."""
if not self._scene_absolute_number:
return self.absolute_number
return self._scene_absolute_number
@scene_absolute_number.setter
def scene_absolute_number(self, value):
"""Set the scene absolute number."""
self._scene_absolute_number = try_int(value, 0)
@property
def quality_name(self):
"""Return the status name."""
return Quality.qualityStrings[self.quality]
def is_location_valid(self, location=None):
"""Whether the location is a valid file.
:param location:
:type location: str
:return:
:rtype: bool
"""
return os.path.isfile(location or self._location)
def metadata(self):
"""Return the video metadata."""
try:
return knowit.know(self.location)
except knowit.KnowitException as error:
log.warning(
'An error occurred while parsing: {path}\n'
'KnowIt reported:\n{report}', {
'path': self.location,
'report': error,
})
return {}
def refresh_subtitles(self):
"""Look for subtitles files and refresh the subtitles property."""
current_subtitles = subtitles.get_current_subtitles(self)
ep_num = (episode_num(self.season, self.episode) or
episode_num(self.season, self.episode, numbering='absolute'))
if self.subtitles == current_subtitles:
log.debug(
'{id}: No changed subtitles for {series} {ep}. Current subtitles: {subs}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': ep_num,
'subs': current_subtitles
}
)
else:
log.debug(
'{id}: Subtitle changes detected for {series} {ep}.'
' Current subtitles: {subs}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': ep_num,
'subs': current_subtitles
}
)
self.subtitles = current_subtitles if current_subtitles else []
log.debug('{id}: Saving subtitles changes to database',
{'id': self.series.series_id})
self.save_to_db()
def download_subtitles(self, lang=None):
"""Download subtitles.
:param lang:
:type lang: string
"""
if not self.is_location_valid():
log.debug(
'{id}: {series} {ep} does not exist, unable to download subtitles', {
'id': self.series.series_id,
'series': self.series.name,
'ep': (episode_num(self.season, self.episode) or
episode_num(self.season, self.episode, numbering='absolute')),
}
)
return
new_subtitles = subtitles.download_subtitles(self, lang=lang)
if new_subtitles:
self.subtitles = subtitles.merge_subtitles(self.subtitles, new_subtitles)
self.subtitles_searchcount += 1 if self.subtitles_searchcount else 1
self.subtitles_lastsearch = datetime.now().strftime(dateTimeFormat)
log.debug('{id}: Saving last subtitles search to database',
{'id': self.series.series_id})
self.save_to_db()
if new_subtitles:
subtitle_list = ', '.join([subtitles.name_from_code(code) for code in new_subtitles])
log.info(
'{id}: Downloaded {subs} subtitles for {series} {ep}', {
'id': self.series.series_id,
'subs': subtitle_list,
'series': self.series.name,
'ep': (episode_num(self.season, self.episode) or
episode_num(self.season, self.episode, numbering='absolute')),
}
)
notifiers.notify_subtitle_download(self, subtitle_list)
else:
log.info(
'{id}: No subtitles found for {series} {ep}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': (episode_num(self.season, self.episode) or
episode_num(self.season, self.episode, numbering='absolute')),
}
)
return new_subtitles
def check_for_meta_files(self):
"""Check Whether metadata files has changed. And write the current set self.hasnfo and set.hastbn.
:return: Whether a database update should be done on the episode.
:rtype: bool
"""
oldhasnfo = self.hasnfo
oldhastbn = self.hastbn
all_nfos = []
all_tbns = []
# check for nfo and tbn
if not self.is_location_valid():
return False
for metadata_provider in itervalues(app.metadata_provider_dict):
if metadata_provider.episode_metadata:
new_result = metadata_provider.has_episode_metadata(self)
else:
new_result = False
all_nfos.append(new_result)
if metadata_provider.episode_thumbnails:
new_result = metadata_provider.has_episode_thumb(self)
else:
new_result = False
all_tbns.append(new_result)
self.hasnfo = any(all_nfos)
self.hastbn = any(all_tbns)
changed = oldhasnfo != self.hasnfo or oldhastbn != self.hastbn
if changed:
self.save_to_db()
return changed
def _specify_episode(self, season, episode):
sql_results = self.load_from_db(season, episode)
if not sql_results:
# only load from NFO if we didn't load from DB
if self.is_location_valid():
try:
self.__load_from_nfo(self.location)
except NoNFOException:
log.error(
'{id}: There was an error loading the NFO for {series} {ep}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
}
)
# if we tried loading it from NFO and didn't find the NFO, try the Indexers
if not self.hasnfo:
try:
result = self.load_from_indexer(season, episode)
except EpisodeDeletedException:
result = False
# if we failed SQL *and* NFO, Indexers then fail
if not result:
raise EpisodeNotFoundException('{id}: Unable to find {series} {ep}'.format
(id=self.series.series_id, series=self.series.name,
ep=episode_num(season, episode)))
def load_from_db(self, season, episode):
"""Load episode information from database.
:param season:
:type season: int
:param episode:
:type episode: int
:return:
:rtype: bool
"""
if not self.dirty:
return True
main_db_con = db.DBConnection()
sql_results = main_db_con.select(
'SELECT '
' * '
'FROM '
' tv_episodes '
'WHERE '
' indexer = ? '
' AND showid = ? '
' AND season = ? '
' AND episode = ?', [self.series.indexer, self.series.series_id, season, episode])
if len(sql_results) > 1:
raise MultipleEpisodesInDatabaseException('Your DB has two records for the same series somehow.')
elif not sql_results:
log.debug(
'{id}: {series} {ep} not found in the database', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(self.season, self.episode),
}
)
return False
else:
self.name = sql_results[0]['name'] or ''
self.season = season
self.episode = episode
self.absolute_number = sql_results[0]['absolute_number']
self.description = sql_results[0]['description'] or ''
if sql_results[0]['subtitles']:
self.subtitles = sql_results[0]['subtitles'].split(',')
self.subtitles_searchcount = sql_results[0]['subtitles_searchcount']
self.subtitles_lastsearch = sql_results[0]['subtitles_lastsearch']
self.airdate = date.fromordinal(int(sql_results[0]['airdate']))
self.status = int(sql_results[0]['status'] or UNSET)
self.quality = int(sql_results[0]['quality'] or Quality.NA)
self.file_size = int(sql_results[0]['file_size'] or 0)
if sql_results[0]['release_name'] is not None:
self.release_name = sql_results[0]['release_name']
if sql_results[0]['is_proper']:
self.is_proper = int(sql_results[0]['is_proper'])
if sql_results[0]['version']:
self.version = int(sql_results[0]['version'])
if sql_results[0]['release_group'] is not None:
self.release_group = sql_results[0]['release_group']
if sql_results[0]['location']:
self._location = sql_results[0]['location']
self.manually_searched = bool(sql_results[0]['manually_searched'])
self.watched = bool(sql_results[0]['watched'])
self.indexerid = int(sql_results[0]['indexerid'])
self.indexer = int(sql_results[0]['indexer'])
self.scene_season = sql_results[0]['scene_season']
self.scene_episode = sql_results[0]['scene_episode']
self.scene_absolute_number = sql_results[0]['scene_absolute_number']
if self.scene_absolute_number == 0:
self.scene_absolute_number = get_scene_absolute_numbering(
self.series,
self.absolute_number
)
if self.series.is_scene:
self._load_scene_numbering()
self.reset_dirty()
return True
def _load_scene_numbering(self):
scene_mapping = get_scene_numbering(
self.series, self.season, self.episode
)
if all([scene_mapping[0] is not None, scene_mapping[1]]):
self.scene_season = scene_mapping[0]
self.scene_episode = scene_mapping[1]
def set_indexer_data(self, season=None, indexer_api=None):
"""Set episode information from indexer.
:param season:
:param indexer_api:
:rtype: bool
"""
if season is None:
season = self.season
if indexer_api is None or indexer_api.indexer != self.series.indexer_api.indexer:
api = self.series.indexer_api
else:
api = indexer_api
try:
api._get_episodes(self.series.series_id, aired_season=season)
except IndexerError as error:
log.warning(
'{id}: {indexer} threw up an error: {error_msg}', {
'id': self.series.series_id,
'indexer': indexerApi(self.indexer).name,
'error_msg': ex(error),
}
)
return False
return True
def load_from_indexer(self, season=None, episode=None, tvapi=None, cached_season=None):
"""Load episode information from indexer.
:param season:
:type season: int
:param episode:
:type episode: int
:param tvapi:
:param cached_season:
:return:
:rtype: bool
"""
if season is None:
season = self.season
if episode is None:
episode = self.episode
try:
if cached_season:
my_ep = cached_season[episode]
else:
series = self.series.indexer_api[self.series.series_id]
my_ep = series[season][episode]
except (IndexerError, IOError) as error:
log.warning(
'{id}: {indexer} threw up an error: {error_msg}', {
'id': self.series.series_id,
'indexer': indexerApi(self.indexer).name,
'error_msg': ex(error),
}
)
# if the episode is already valid just log it, if not throw it up
if self.name:
log.debug(
'{id}: {indexer} timed out but we have enough info from other sources, allowing the error', {
'id': self.series.series_id,
'indexer': indexerApi(self.indexer).name,
}
)
return
else:
log.warning(
'{id}: {indexer} timed out, unable to create the episode', {
'id': self.series.series_id,
'indexer': indexerApi(self.indexer).name,
}
)
return False
except (IndexerEpisodeNotFound, IndexerSeasonNotFound):
log.debug(
'{id}: Unable to find the episode on {indexer}. Deleting it from db', {
'id': self.series.series_id,
'indexer': indexerApi(self.indexer).name,
}
)
# if I'm no longer on the Indexers but I once was then delete myself from the DB
if self.indexerid != -1:
self.delete_episode()
return
if getattr(my_ep, 'episodename', None) is None:
log.info(
'{id}: {series} {ep} has no name on {indexer}. Setting to an empty string', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'indexer': indexerApi(self.indexer).name,
}
)
setattr(my_ep, 'episodename', '')
if getattr(my_ep, 'absolute_number', None) is None:
log.debug(
'{id}: {series} {ep} has no absolute number on {indexer}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'indexer': indexerApi(self.indexer).name,
}
)
else:
self.absolute_number = int(my_ep['absolute_number'])
log.debug(
'{id}: {series} {ep} has absolute number: {absolute} ', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'absolute': self.absolute_number,
}
)
self.name = getattr(my_ep, 'episodename', '')
self.season = season
self.episode = episode
self.scene_absolute_number = get_scene_absolute_numbering(
self.series,
self.absolute_number
)
# TODO: Just me not understanding. If we're getting the show info from the indexer.
# Why are we trying to get the scene_season and scene_episode from the db?
self._load_scene_numbering()
self.description = getattr(my_ep, 'overview', '')
firstaired = getattr(my_ep, 'firstaired', None)
if not firstaired or firstaired == '0000-00-00':
firstaired = str(date.fromordinal(1))
raw_airdate = [int(x) for x in firstaired.split('-')]
try:
self.airdate = date(raw_airdate[0], raw_airdate[1], raw_airdate[2])
except (ValueError, IndexError):
log.warning(
'{id}: Malformed air date of {aired} retrieved from {indexer} for {series} {ep}', {
'id': self.series.series_id,
'aired': firstaired,
'indexer': indexerApi(self.indexer).name,
'series': self.series.name,
'ep': episode_num(season, episode),
}
)
# if I'm incomplete on the indexer but I once was complete then just delete myself from the DB for now
if self.indexerid != -1:
self.delete_episode()
return False
# early conversion to int so that episode doesn't get marked dirty
self.indexerid = getattr(my_ep, 'id', None)
if self.indexerid is None:
log.error(
'{id}: Failed to retrieve ID from {indexer}', {
'id': self.series.series_id,
'aired': firstaired,
'indexer': indexerApi(self.indexer).name,
}
)
if self.indexerid != -1:
self.delete_episode()
return False
if self.location:
log.debug(
'{id}: {series} {ep} status is {status!r}. Location: {location}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'status': statusStrings[self.status],
'location': self.location,
}
)
if not os.path.isfile(self.location):
if (self.airdate >= date.today() or self.airdate == date.fromordinal(1)) and \
self.status in (UNSET, UNAIRED, WANTED):
# Need to check if is UNAIRED otherwise code will step into second 'IF'
# and make episode as default_ep_status
# If is a leaked episode and user manually snatched, it will respect status
# If is a fake (manually snatched), when user set as FAILED, status will be WANTED
# and code below will make it UNAIRED again
self.status = UNAIRED
log.debug(
'{id}: {series} {ep} airs in the future or has no air date, marking it {status}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'status': statusStrings[self.status],
}
)
elif self.status in (UNSET, UNAIRED):
# Only do UNAIRED/UNSET, it could already be snatched/ignored/skipped,
# or downloaded/archived to disconnected media
self.status = self.series.default_ep_status if self.season > 0 else SKIPPED # auto-skip specials
log.debug(
'{id}: {series} {ep} has already aired, marking it {status}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'status': statusStrings[self.status],
}
)
else:
log.debug(
'{id}: {series} {ep} status untouched: {status}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'status': statusStrings[self.status],
}
)
# Update the episode's status/quality if a file exists and the status is not SNATCHED|DOWNLOADED|ARCHIVED
elif helpers.is_media_file(self.location):
if self.status not in [SNATCHED, SNATCHED_PROPER, SNATCHED_BEST, DOWNLOADED, ARCHIVED]:
self.update_status_quality(self.location)
else:
log.debug(
'{id}: {series} {ep} status untouched: {status}', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'status': statusStrings[self.status],
}
)
# shouldn't get here probably
else:
log.warning(
'{id}: {series} {ep} status changed from {old_status} to UNSET', {
'id': self.series.series_id,
'series': self.series.name,
'ep': episode_num(season, episode),
'old_status': statusStrings[self.status],
}
)
self.status = UNSET
self.save_to_db()
def __load_from_nfo(self, location):
if not self.series.is_location_valid():
log.warning('{id}: The series location {location} is missing, unable to load metadata',
{'id': self.series.series_id, 'location': location})
return
log.debug('{id}: Loading episode details from the NFO file associated with {location}',