/
core.py
2862 lines (2357 loc) · 111 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Author: Dennis Lutter <lad1337@gmail.com>
# Author: Jonathon Saine <thezoggy@gmail.com>
#
# This file is part of Medusa.
#
# Medusa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Medusa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Medusa. If not, see <http://www.gnu.org/licenses/>.
# TODO: break this up into separate files
# pylint: disable=line-too-long,too-many-lines,abstract-method
# pylint: disable=no-member,method-hidden,missing-docstring,invalid-name
import json
import logging
import os
import time
from collections import OrderedDict
from datetime import date, datetime
from medusa import (
app, classes, db, helpers, image_cache, network_timezones,
process_tv, sbdatetime, subtitles, ui,
)
from medusa.common import ARCHIVED, DOWNLOADED, FAILED, IGNORED, Overview, Quality, SKIPPED, SNATCHED, SNATCHED_PROPER, \
UNAIRED, UNKNOWN, WANTED, \
statusStrings
from medusa.helper.common import (
dateFormat, dateTimeFormat, pretty_file_size, sanitize_filename,
timeFormat, try_int,
)
from medusa.helper.exceptions import CantUpdateShowException, ShowDirectoryNotFoundException
from medusa.helpers.quality import get_quality_string
from medusa.indexers.indexer_api import indexerApi
from medusa.indexers.indexer_config import INDEXER_TVDBV2
from medusa.indexers.indexer_exceptions import IndexerError, IndexerShowIncomplete, IndexerShowNotFound
from medusa.logger import LOGGING_LEVELS, filter_logline, read_loglines
from medusa.logger.adapters.style import BraceAdapter
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.search.queue import BacklogQueueItem, ForcedSearchQueueItem
from medusa.show.coming_episodes import ComingEpisodes
from medusa.show.history import History
from medusa.show.show import Show
from medusa.system.restart import Restart
from medusa.system.shutdown import Shutdown
from medusa.version_checker import CheckVersion
from requests.compat import unquote_plus
from six import iteritems, text_type
from tornado.web import RequestHandler
log = BraceAdapter(logging.getLogger(__name__))
log.logger.addHandler(logging.NullHandler())
INDEXER_IDS = ('indexerid', 'tvdbid', 'tvmazeid', 'tmdbid')
# basically everything except RESULT_SUCCESS / success is bad
RESULT_SUCCESS = 10 # only use inside the run methods
RESULT_FAILURE = 20 # only use inside the run methods
RESULT_TIMEOUT = 30 # not used yet :(
RESULT_ERROR = 40 # only use outside of the run methods !
RESULT_FATAL = 50 # only use in Api.default() ! this is the "we encountered an internal error" error
RESULT_DENIED = 60 # only use in Api.default() ! this is the access denied error
result_type_map = {
RESULT_DENIED: 'denied',
RESULT_ERROR: 'error',
RESULT_FATAL: 'fatal',
RESULT_FAILURE: 'failure',
RESULT_SUCCESS: 'success',
RESULT_TIMEOUT: 'timeout',
}
class ApiHandler(RequestHandler):
""" api class that returns json results """
version = 5 # use an int since float-point is unpredictable
def __init__(self, *args, **kwargs):
super(ApiHandler, self).__init__(*args, **kwargs)
# def set_default_headers(self):
# self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
def get(self, *args, **kwargs):
kwargs = self.request.arguments
for arg, value in iteritems(kwargs):
if len(value) == 1:
kwargs[arg] = value[0]
args = args[1:]
# set the output callback
# default json
output_callback_dict = {
'default': self._out_as_json,
'image': self._out_as_image,
}
access_msg = u'API :: {0} - gave correct API KEY. ACCESS GRANTED'.format(self.request.remote_ip)
log.debug(access_msg)
# set the original call_dispatcher as the local _call_dispatcher
_call_dispatcher = self.call_dispatcher
# if profile was set wrap "_call_dispatcher" in the profile function
if 'profile' in kwargs:
from profilehooks import profile
_call_dispatcher = profile(_call_dispatcher, immediate=True)
del kwargs['profile']
try:
out_dict = _call_dispatcher(args, kwargs)
except Exception as error: # real internal error oohhh nooo :(
log.exception(u'API :: {0!r}', error.message)
error_data = {
'error_msg': error.message,
'args': args,
'kwargs': kwargs
}
out_dict = _responds(RESULT_FATAL, error_data,
'Medusa encountered an internal error! Please report to the Devs')
if 'outputType' in out_dict:
output_callback = output_callback_dict[out_dict['outputType']]
else:
output_callback = output_callback_dict['default']
try:
self.finish(output_callback(out_dict))
except Exception:
pass
def _out_as_image(self, _dict):
self.set_header('Content-Type', _dict['image'].get_media_type())
return _dict['image'].get_media()
def _out_as_json(self, _dict):
self.set_header('Content-Type', 'application/json;charset=UTF-8')
try:
out = json.dumps(_dict, ensure_ascii=False, sort_keys=True)
callback = self.get_query_argument('callback', None) or self.get_query_argument('jsonp', None)
if callback:
out = '{0}({1});'.format(callback, out) # wrap with JSONP call if requested
except Exception as error: # if we fail to generate the output fake an error
log.exception(u'API :: Traceback')
out = '{{"result": "{0}", "message": "error while composing output: {1!r}"}}'.format(
result_type_map[RESULT_ERROR], error.message
)
return out
def call_dispatcher(self, args, kwargs): # pylint:disable=too-many-branches
""" calls the appropriate CMD class
looks for a cmd in args and kwargs
or calls the TVDBShorthandWrapper when the first args element is a number
or returns an error that there is no such cmd
"""
log.debug(u'API :: all args: {0!r}', args)
log.debug(u'API :: all kwargs: {0!r}', kwargs)
commands = None
if args:
commands, args = args[0], args[1:]
commands = kwargs.pop('cmd', commands)
out_dict = {}
if commands:
commands = commands.split('|')
multi_commands = len(commands) > 1
for cmd in commands:
cur_args, cur_kwargs = self.filter_params(cmd, args, kwargs)
if len(cmd.split('_')) > 1:
cmd, cmd_index = cmd.split('_')
log.debug(u'API :: {0}: {1}', cmd, cur_kwargs)
if not (cmd in ('show.getbanner', 'show.getfanart', 'show.getnetworklogo', 'show.getposter') and
multi_commands): # skip these cmd while chaining
try:
if cmd in function_mapper:
func = function_mapper.get(cmd) # map function
func.rh = self # add request handler to function
cur_out_dict = func(cur_args, cur_kwargs).run() # call function and get response
elif _is_int(cmd):
cur_out_dict = TVDBShorthandWrapper(cur_args, cur_kwargs, cmd).run()
else:
cur_out_dict = _responds(RESULT_ERROR, 'No such cmd: {0!r}'.format(cmd))
except ApiError as error: # Api errors that we raised, they are harmless
cur_out_dict = _responds(RESULT_ERROR, msg=error.message)
else: # if someone chained one of the forbidden commands they will get an error for this one cmd
cur_out_dict = _responds(RESULT_ERROR, msg='The cmd {0!r} is not supported while chaining'.format(cmd))
if multi_commands:
# note: if duplicate commands are issued and one has an index defined it will override
# all others or the other way around, depending on the command order
# THIS IS NOT A BUG!
if cmd_index: # do we need an index dict for this cmd ?
if cmd not in out_dict:
out_dict[cmd] = {}
out_dict[cmd][cmd_index] = cur_out_dict
else:
out_dict[cmd] = cur_out_dict
else:
out_dict = cur_out_dict
if multi_commands: # if we had multiple commands we have to wrap it in a response dict
out_dict = _responds(RESULT_SUCCESS, out_dict)
else: # index / no cmd given
out_dict = CMD_(args, kwargs).run()
return out_dict
@staticmethod
def filter_params(cmd, args, kwargs):
""" return only params kwargs that are for cmd
and rename them to a clean version (remove "<cmd>_")
args are shared across all commands
all args and kwargs are lowered
cmd are separated by "|" e.g. &cmd=shows|future
kwargs are name-spaced with "." e.g. show.indexerid=101501
if a kwarg has no namespace asking it anyways (global)
full e.g.
/api?apikey=1234&cmd=show.seasonlist_asd|show.seasonlist_2&show.seasonlist_asd.indexerid=101501&show.seasonlist_2.indexerid=79488&sort=asc
two calls of show.seasonlist
one has the index "asd" the other one "2"
the "indexerid" kwargs / params have the indexed cmd as a namespace
and the kwarg / param "sort" is a used as a global
"""
cur_args = []
for arg in args:
cur_args.append(arg.lower())
cur_args = tuple(cur_args)
cur_kwargs = {}
for kwarg in kwargs:
if kwarg.find(cmd + '.') == 0:
clean_key = kwarg.rpartition('.')[2]
cur_kwargs[clean_key] = kwargs[kwarg].lower()
elif '.' not in kwarg: # the kwarg was not name-spaced therefore a "global"
cur_kwargs[kwarg] = kwargs[kwarg]
return cur_args, cur_kwargs
class ApiCall(ApiHandler):
_help = {'desc': 'This command is not documented. Please report this to the developers.'}
def __init__(self, args, kwargs):
# missing
if hasattr(self, '_missing') and self._missing:
self.run = self.return_missing
# help
if 'help' in kwargs:
self.run = self.return_help
def run(self):
# override with real output function in subclass
return {}
def return_help(self):
try:
if self._requiredParams:
pass
except AttributeError:
self._requiredParams = []
try:
if self._optionalParams:
pass
except AttributeError:
self._optionalParams = []
for paramDict, paramType in [(self._requiredParams, 'requiredParameters'),
(self._optionalParams, 'optionalParameters')]:
if paramType in self._help:
for paramName in paramDict:
if paramName not in self._help[paramType]:
self._help[paramType][paramName] = {}
if paramDict[paramName]['allowedValues']:
self._help[paramType][paramName]['allowedValues'] = paramDict[paramName]['allowedValues']
else:
self._help[paramType][paramName]['allowedValues'] = 'see desc'
self._help[paramType][paramName]['defaultValue'] = paramDict[paramName]['defaultValue']
self._help[paramType][paramName]['type'] = paramDict[paramName]['type']
elif paramDict:
for paramName in paramDict:
self._help[paramType] = {}
self._help[paramType][paramName] = paramDict[paramName]
else:
self._help[paramType] = {}
msg = 'No description available'
if 'desc' in self._help:
msg = self._help['desc']
return _responds(RESULT_SUCCESS, self._help, msg)
def return_missing(self):
if len(self._missing) == 1:
msg = 'The required parameter: {0!r} was not set'.format(self._missing[0])
else:
msg = 'The required parameters: {0!r} were not set'.format("','".join(self._missing))
return _responds(RESULT_ERROR, msg=msg)
def check_params(self, args, kwargs, key, default, required, arg_type, allowed_values):
""" function to check passed params for the shorthand wrapper
and to detect missing/required params
"""
# auto-select indexer
if key in INDEXER_IDS:
if 'tvdbid' in kwargs:
key = 'tvdbid'
self.indexer = INDEXER_IDS.index(key)
missing = True
org_default = default
if arg_type == 'bool':
allowed_values = [0, 1]
if args:
default = args[0]
missing = False
args = args[1:]
if kwargs.get(key):
default = kwargs.get(key)
missing = False
if required:
if hasattr(self, '_requiredParams') and isinstance(self._requiredParams, list):
self._requiredParams.append(key)
else:
self._missing = []
self._requiredParams = {key: {'allowedValues': allowed_values,
'defaultValue': org_default,
'type': arg_type}}
if missing and key not in self._missing:
self._missing.append(key)
else:
try:
self._optionalParams[key] = {'allowedValues': allowed_values,
'defaultValue': org_default,
'type': arg_type}
except AttributeError:
self._optionalParams = {key: {'allowedValues': allowed_values,
'defaultValue': org_default,
'type': arg_type}}
if default:
default = self._check_param_type(default, key, arg_type)
self._check_param_value(default, key, allowed_values)
return default, args
def _check_param_type(self, value, name, arg_type):
""" checks if value can be converted / parsed to arg_type
will raise an error on failure
or will convert it to arg_type and return new converted value
can check for:
- int: will be converted into int
- bool: will be converted to False / True
- list: will always return a list
- string: will do nothing for now
- ignore: will ignore it, just like "string"
"""
error = False
if arg_type == 'int':
if _is_int(value):
value = int(value)
else:
error = True
elif arg_type == 'bool':
if value in ('0', '1'):
value = bool(int(value))
elif value in ('true', 'True', 'TRUE'):
value = True
elif value in ('false', 'False', 'FALSE'):
value = False
elif value not in (True, False):
error = True
elif arg_type == 'list':
value = value.split('|')
elif arg_type == 'string':
pass
elif arg_type == 'ignore':
pass
else:
log.error(u'API :: Invalid param type: {0!r} can not be checked. Ignoring it.', arg_type)
if error:
# this is a real ApiError !!
raise ApiError(
u'param {0!r} with given value {1!r} could not be parsed into {2!r}'.format(name, value, arg_type)
)
return value
def _check_param_value(self, value, name, allowed_values):
""" will check if value (or all values in it ) are in allowed values
will raise an exception if value is "out of range"
if bool(allowed_value) is False a check is not performed and all values are excepted
"""
if allowed_values:
error = False
if isinstance(value, list):
for item in value:
if item not in allowed_values:
error = True
else:
if value not in allowed_values:
error = True
if error:
# this is kinda a ApiError but raising an error is the only way of quitting here
raise ApiError(
u'param: {0!r} with given value {1!r} is out of allowed range {2!r}'.format(
name, value, allowed_values
)
)
class TVDBShorthandWrapper(ApiCall):
_help = {'desc': 'This is an internal function wrapper. Call the help command directly for more information.'}
def __init__(self, args, kwargs, sid):
self.origArgs = args
self.kwargs = kwargs
self.sid = sid
self.s, args = self.check_params(args, kwargs, 's', None, False, 'ignore', [])
self.e, args = self.check_params(args, kwargs, 'e', None, False, 'ignore', [])
self.args = args
ApiCall.__init__(self, args, kwargs)
def run(self):
""" internal function wrapper """
args = (self.sid,) + self.origArgs
if self.e:
return CMD_Episode(args, self.kwargs).run()
elif self.s:
return CMD_ShowSeasons(args, self.kwargs).run()
else:
return CMD_Show(args, self.kwargs).run()
# ###############################
# helper functions #
# ###############################
def _is_int(data):
try:
int(data)
except (TypeError, ValueError, OverflowError):
return False
else:
return True
def _rename_element(dict_obj, old_key, new_key):
try:
dict_obj[new_key] = dict_obj[old_key]
del dict_obj[old_key]
except (ValueError, TypeError, NameError):
pass
return dict_obj
def _responds(result_type, data=None, msg=''):
"""
result is a string of given "type" (success/failure/timeout/error)
message is a human readable string, can be empty
data is either a dict or a array, can be a empty dict or empty array
"""
return {'result': result_type_map[result_type],
'message': msg,
'data': {} if not data else data}
def _ordinal_to_date(ordinal, date_format):
x = int(ordinal)
return date.fromordinal(x).strftime(date_format) if x >= 1 else ''
def _ordinal_to_date_form(ordinal):
return _ordinal_to_date(ordinal, dateFormat)
def _ordinal_to_datetime_form(ordinal):
# workaround for episodes with no air date
return _ordinal_to_date(ordinal, dateTimeFormat)
quality_map = OrderedDict((
('sdtv', Quality.SDTV),
('sddvd', Quality.SDDVD),
('hdtv', Quality.HDTV),
('rawhdtv', Quality.RAWHDTV),
('fullhdtv', Quality.FULLHDTV),
('hdwebdl', Quality.HDWEBDL),
('fullhdwebdl', Quality.FULLHDWEBDL),
('hdbluray', Quality.HDBLURAY),
('fullhdbluray', Quality.FULLHDBLURAY),
('uhd_4k_tv', Quality.UHD_4K_TV),
('uhd_4k_webdl', Quality.UHD_4K_WEBDL),
('uhd_4k_bluray', Quality.UHD_4K_BLURAY),
('uhd_8k_tv', Quality.UHD_8K_TV),
('uhd_8k_webdl', Quality.UHD_8K_WEBDL),
('uhd_8k_bluray', Quality.UHD_8K_BLURAY),
('unknown', Quality.UNKNOWN),
))
def _map_quality(show_obj):
mapped_quality = {v: k for k, v in quality_map.items()}
allowed_qualities = []
preferred_qualities = []
i_quality_id, a_quality_id = Quality.split_quality(int(show_obj))
if i_quality_id:
for quality in i_quality_id:
allowed_qualities.append(mapped_quality[quality])
if a_quality_id:
for quality in a_quality_id:
preferred_qualities.append(mapped_quality[quality])
return allowed_qualities, preferred_qualities
def _get_root_dirs():
if app.ROOT_DIRS == '':
return {}
root_dir = {}
root_dirs = app.ROOT_DIRS
default_index = int(app.ROOT_DIRS[0])
root_dir['default_index'] = int(app.ROOT_DIRS[0])
# remove default_index value from list (this fixes the offset)
root_dirs.pop(0)
if len(root_dirs) < default_index:
return {}
# clean up the list - replace %xx escapes by their single-character equivalent
root_dirs = [unquote_plus(x) for x in root_dirs]
default_dir = root_dirs[default_index]
dir_list = []
for root_dir in root_dirs:
valid = 1
try:
os.listdir(root_dir)
except Exception:
valid = 0
default = 0
if root_dir is default_dir:
default = 1
cur_dir = {
'valid': valid,
'location': root_dir,
'default': default
}
dir_list.append(cur_dir)
return dir_list
class ApiError(Exception):
"""
Generic API error
"""
class IntParseError(Exception):
"""
A value could not be parsed into an int, but should be parse-able to an int
"""
# -------------------------------------------------------------------------------------#
class CMD_Help(ApiCall):
_help = {
'desc': 'Get help about a given command',
'optionalParameters': {
'subject': {'desc': 'The name of the command to get the help of'},
}
}
def __init__(self, args, kwargs):
# required
# optional
self.subject, args = self.check_params(args, kwargs, 'subject', 'help', False, 'string', function_mapper.keys())
ApiCall.__init__(self, args, kwargs)
def run(self):
""" Get help about a given command """
if self.subject in function_mapper:
out = _responds(RESULT_SUCCESS, function_mapper.get(self.subject)((), {'help': 1}).run())
else:
out = _responds(RESULT_FAILURE, msg='No such cmd')
return out
class CMD_ComingEpisodes(ApiCall):
_help = {
'desc': 'Get the coming episodes',
'optionalParameters': {
'sort': {'desc': 'Change the sort order'},
'type': {'desc': 'One or more categories of coming episodes, separated by |'},
'paused': {
'desc': '0 to exclude paused shows, 1 to include them, or omitted to use Medusa default value'
},
}
}
def __init__(self, args, kwargs):
# required
# optional
self.sort, args = self.check_params(args, kwargs, 'sort', 'date', False, 'string', ComingEpisodes.sorts.keys())
self.type, args = self.check_params(args, kwargs, 'type', '|'.join(ComingEpisodes.categories), False, 'list',
ComingEpisodes.categories)
self.paused, args = self.check_params(args, kwargs, 'paused', bool(app.COMING_EPS_DISPLAY_PAUSED), False,
'bool', [])
# super, missing, help
ApiCall.__init__(self, args, kwargs)
def run(self):
""" Get the coming episodes """
grouped_coming_episodes = ComingEpisodes.get_coming_episodes(self.type, self.sort, True, self.paused)
data = {section: [] for section in grouped_coming_episodes.keys()}
for section, coming_episodes in iteritems(grouped_coming_episodes):
for coming_episode in coming_episodes:
data[section].append({
'airdate': coming_episode['airdate'],
'airs': coming_episode['airs'],
'ep_name': coming_episode['name'],
'ep_plot': coming_episode['description'],
'episode': coming_episode['episode'],
'indexerid': coming_episode['indexer_id'],
'network': coming_episode['network'],
'paused': coming_episode['paused'],
'quality': coming_episode['quality'],
'season': coming_episode['season'],
'show_name': coming_episode['show_name'],
'show_status': coming_episode['status'],
'tvdbid': coming_episode['tvdbid'],
'weekday': coming_episode['weekday']
})
return _responds(RESULT_SUCCESS, data)
class CMD_Episode(ApiCall):
_help = {
'desc': 'Get detailed information about an episode',
'requiredParameters': {
'indexerid': {'desc': 'Unique ID of a show'},
'season': {'desc': 'The season number'},
'episode': {'desc': 'The episode number'},
},
'optionalParameters': {
'tvdbid': {'desc': 'thetvdb.com unique ID of a show'},
'full_path': {
'desc': 'Return the full absolute show location (if valid, and True), or the relative show location'
},
}
}
def __init__(self, args, kwargs):
# required
self.indexerid, args = self.check_params(args, kwargs, 'indexerid', None, True, 'int', [])
self.s, args = self.check_params(args, kwargs, 'season', None, True, 'int', [])
self.e, args = self.check_params(args, kwargs, 'episode', None, True, 'int', [])
# optional
self.full_path, args = self.check_params(args, kwargs, 'full_path', False, False, 'bool', [])
# super, missing, help
ApiCall.__init__(self, args, kwargs)
def run(self):
"""Get detailed information about an episode."""
show_obj = Show.find(app.showList, int(self.indexerid))
if not show_obj:
return _responds(RESULT_FAILURE, msg='Show not found')
main_db_con = db.DBConnection(row_type='dict')
sql_results = main_db_con.select(
'SELECT name, description, airdate, status, location, file_size, release_name, subtitles '
'FROM tv_episodes WHERE showid = ? AND episode = ? AND season = ?',
[self.indexerid, self.e, self.s])
if not len(sql_results) == 1:
raise ApiError('Episode not found')
episode = sql_results[0]
# handle path options
# absolute vs relative vs broken
show_path = None
try:
show_path = show_obj.location
except ShowDirectoryNotFoundException:
pass
if not show_path: # show dir is broken ... episode path will be empty
episode['location'] = ''
elif not self.full_path:
# using the length because lstrip() removes to much
show_path_length = len(show_path) + 1 # the / or \ yeah not that nice i know
episode['location'] = episode['location'][show_path_length:]
# convert stuff to human form
if try_int(episode['airdate'], 1) > 693595: # 1900
episode['airdate'] = sbdatetime.sbdatetime.sbfdate(sbdatetime.sbdatetime.convert_to_setting(
network_timezones.parse_date_time(int(episode['airdate']), show_obj.airs, show_obj.network)),
d_preset=dateFormat)
else:
episode['airdate'] = 'Never'
status, quality = Quality.split_composite_status(int(episode['status']))
episode['status'] = statusStrings[status]
episode['quality'] = get_quality_string(quality)
episode['file_size_human'] = pretty_file_size(episode['file_size'])
return _responds(RESULT_SUCCESS, episode)
class CMD_EpisodeSearch(ApiCall):
_help = {
'desc': 'Search for an episode. The response might take some time.',
'requiredParameters': {
'indexerid': {'desc': 'Unique ID of a show'},
'season': {'desc': 'The season number'},
'episode': {'desc': 'The episode number'},
},
'optionalParameters': {
'tvdbid': {'desc': 'thetvdb.com unique ID of a show'},
}
}
def __init__(self, args, kwargs):
# required
self.indexerid, args = self.check_params(args, kwargs, 'indexerid', None, True, 'int', [])
self.s, args = self.check_params(args, kwargs, 'season', None, True, 'int', [])
self.e, args = self.check_params(args, kwargs, 'episode', None, True, 'int', [])
# optional
# super, missing, help
ApiCall.__init__(self, args, kwargs)
def run(self):
""" Search for an episode """
show_obj = Show.find(app.showList, int(self.indexerid))
if not show_obj:
return _responds(RESULT_FAILURE, msg='Show not found')
# retrieve the episode object and fail if we can't get one
ep_obj = show_obj.get_episode(self.s, self.e)
if isinstance(ep_obj, str):
return _responds(RESULT_FAILURE, msg='Episode not found')
# make a queue item for it and put it on the queue
ep_queue_item = ForcedSearchQueueItem(show_obj, [ep_obj])
app.forced_search_queue_scheduler.action.add_item(ep_queue_item) # @UndefinedVariable
# wait until the queue item tells us whether it worked or not
while ep_queue_item.success is None: # @UndefinedVariable
time.sleep(1)
# return the correct json value
if ep_queue_item.success:
_, quality = Quality.split_composite_status(ep_obj.status)
# TODO: split quality and status?
return _responds(RESULT_SUCCESS, {'quality': get_quality_string(quality)},
'Snatched ({0})'.format(get_quality_string(quality)))
return _responds(RESULT_FAILURE, msg='Unable to find episode')
class CMD_EpisodeSetStatus(ApiCall):
_help = {
'desc': 'Set the status of an episode or a season (when no episode is provided)',
'requiredParameters': {
'indexerid': {'desc': 'Unique ID of a show'},
'season': {'desc': 'The season number'},
'status': {'desc': 'The status of the episode or season'}
},
'optionalParameters': {
'episode': {'desc': 'The episode number'},
'force': {'desc': 'True to replace existing downloaded episode or season, False otherwise'},
'tvdbid': {'desc': 'thetvdb.com unique ID of a show'},
}
}
def __init__(self, args, kwargs):
# required
self.indexerid, args = self.check_params(args, kwargs, 'indexerid', None, True, 'int', [])
self.s, args = self.check_params(args, kwargs, 'season', None, True, 'int', [])
self.status, args = self.check_params(args, kwargs, 'status', None, True, 'string',
['wanted', 'skipped', 'ignored', 'failed'])
# optional
self.e, args = self.check_params(args, kwargs, 'episode', None, False, 'int', [])
self.force, args = self.check_params(args, kwargs, 'force', False, False, 'bool', [])
# super, missing, help
ApiCall.__init__(self, args, kwargs)
def run(self):
""" Set the status of an episode or a season (when no episode is provided) """
show_obj = Show.find(app.showList, int(self.indexerid))
if not show_obj:
return _responds(RESULT_FAILURE, msg='Show not found')
# convert the string status to a int
for status in statusStrings:
if str(statusStrings[status]).lower() == str(self.status).lower():
self.status = status
break
else: # if we don't break out of the for loop we got here.
# the allowed values has at least one item that could not be matched against the internal status strings
raise ApiError('The status string could not be matched to a status. Report to Devs!')
if self.e:
ep_obj = show_obj.get_episode(self.s, self.e)
if not ep_obj:
return _responds(RESULT_FAILURE, msg='Episode not found')
ep_list = [ep_obj]
else:
# get all episode numbers from self, season
ep_list = show_obj.get_all_episodes(season=self.s)
def _ep_result(result_code, ep, msg=''):
return {'season': ep.season, 'episode': ep.episode, 'status': statusStrings[ep.status],
'result': result_type_map[result_code], 'message': msg}
ep_results = []
failure = False
start_backlog = False
segments = {}
sql_l = []
for ep_obj in ep_list:
with ep_obj.lock:
if self.status == WANTED:
# figure out what episodes are wanted so we can backlog them
if ep_obj.season in segments:
segments[ep_obj.season].append(ep_obj)
else:
segments[ep_obj.season] = [ep_obj]
# don't let them mess up UN-AIRED episodes
if ep_obj.status == UNAIRED:
if self.e is not None: # setting the status of an un-aired is only considered a failure if we directly wanted this episode, but is ignored on a season request
ep_results.append(
_ep_result(RESULT_FAILURE, ep_obj, 'Refusing to change status because it is UN-AIRED'))
failure = True
continue
if self.status == FAILED and not app.USE_FAILED_DOWNLOADS:
ep_results.append(_ep_result(RESULT_FAILURE, ep_obj,
'Refusing to change status to FAILED because failed download handling is disabled'))
failure = True
continue
# allow the user to force setting the status for an already downloaded episode
if ep_obj.status in Quality.DOWNLOADED + Quality.ARCHIVED and not self.force:
ep_results.append(_ep_result(RESULT_FAILURE, ep_obj,
'Refusing to change status because it is already marked as DOWNLOADED'))
failure = True
continue
ep_obj.status = self.status
sql_l.append(ep_obj.get_sql())
if self.status == WANTED:
start_backlog = True
ep_results.append(_ep_result(RESULT_SUCCESS, ep_obj))
if sql_l:
main_db_con = db.DBConnection()
main_db_con.mass_action(sql_l)
extra_msg = ''
if start_backlog:
for season, segment in iteritems(segments):
cur_backlog_queue_item = BacklogQueueItem(show_obj, segment)
app.search_queue_scheduler.action.add_item(cur_backlog_queue_item) # @UndefinedVariable
log.info(u'API :: Starting backlog for {0} season {1} because some episodes were set to WANTED',
show_obj.name, season)
extra_msg = ' Backlog started'
if failure:
return _responds(RESULT_FAILURE, ep_results, 'Failed to set all or some status. Check data. {0}'.format(extra_msg))
else:
return _responds(RESULT_SUCCESS, msg='All status set successfully. {0}'.format(extra_msg))
class CMD_SubtitleSearch(ApiCall):
_help = {
'desc': 'Search for an episode subtitles. The response might take some time.',
'requiredParameters': {
'indexerid': {'desc': 'Unique ID of a show'},
'season': {'desc': 'The season number'},
'episode': {'desc': 'The episode number'},
},
'optionalParameters': {
'tvdbid': {'desc': 'thetvdb.com unique ID of a show'},
}
}
def __init__(self, args, kwargs):
# required
self.indexerid, args = self.check_params(args, kwargs, 'indexerid', None, True, 'int', [])
self.s, args = self.check_params(args, kwargs, 'season', None, True, 'int', [])
self.e, args = self.check_params(args, kwargs, 'episode', None, True, 'int', [])
# optional
# super, missing, help
ApiCall.__init__(self, args, kwargs)
def run(self):
""" Search for an episode subtitles """
show_obj = Show.find(app.showList, int(self.indexerid))
if not show_obj:
return _responds(RESULT_FAILURE, msg='Show not found')
# retrieve the episode object and fail if we can't get one
ep_obj = show_obj.get_episode(self.s, self.e)
if isinstance(ep_obj, str):
return _responds(RESULT_FAILURE, msg='Episode not found')
try:
new_subtitles = ep_obj.download_subtitles()
except Exception:
return _responds(RESULT_FAILURE, msg='Unable to find subtitles')
if new_subtitles:
new_languages = [subtitles.name_from_code(code) for code in new_subtitles]
status = 'New subtitles downloaded: {0}'.format(', '.join(new_languages))
response = _responds(RESULT_SUCCESS, msg='New subtitles found')
else:
status = 'No subtitles downloaded'
response = _responds(RESULT_FAILURE, msg='Unable to find subtitles')
ui.notifications.message('Subtitles Search', status)
return response
class CMD_Exceptions(ApiCall):
_help = {
'desc': 'Get the scene exceptions for all or a given show',
'optionalParameters': {
'indexerid': {'desc': 'Unique ID of a show'},
'tvdbid': {'desc': 'thetvdb.com unique ID of a show'},
}
}
def __init__(self, args, kwargs):
# required
# optional
self.indexerid, args = self.check_params(args, kwargs, 'indexerid', None, False, 'int', [])
# super, missing, help
ApiCall.__init__(self, args, kwargs)
def run(self):
""" Get the scene exceptions for all or a given show """
cache_db_con = db.DBConnection('cache.db', row_type='dict')
if self.indexerid is None:
sql_results = cache_db_con.select("SELECT show_name, indexer_id AS 'indexerid' FROM scene_exceptions")
scene_exceptions = {}
for row in sql_results:
indexerid = row['indexerid']
if indexerid not in scene_exceptions:
scene_exceptions[indexerid] = []
scene_exceptions[indexerid].append(row['show_name'])
else: