-
Notifications
You must be signed in to change notification settings - Fork 276
/
Copy pathhandler.py
1818 lines (1516 loc) · 75.9 KB
/
handler.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
from __future__ import unicode_literals
import json
import os
import time
from datetime import date
from textwrap import dedent
from medusa import (
app,
config,
db,
helpers,
logger,
notifiers,
providers,
subtitles,
ui,
)
from medusa.clients import torrent
from medusa.clients.nzb import (
nzbget,
sab,
)
from medusa.common import (
ARCHIVED,
DOWNLOADED,
FAILED,
IGNORED,
Quality,
SKIPPED,
SNATCHED,
SNATCHED_BEST,
SNATCHED_PROPER,
UNAIRED,
WANTED,
cpu_presets,
statusStrings,
)
from medusa.helper.common import enabled_providers
from medusa.helper.exceptions import (
AnidbAdbaConnectionException,
CantRefreshShowException,
CantUpdateShowException,
ShowDirectoryNotFoundException,
ex,
)
from medusa.helpers.anidb import get_release_groups_for_anime
from medusa.indexers.api import indexerApi
from medusa.indexers.utils import indexer_name_to_id
from medusa.scene_exceptions import (
get_all_scene_exceptions
)
from medusa.scene_numbering import (
get_scene_absolute_numbering,
get_scene_numbering,
get_xem_numbering_for_show,
set_scene_numbering,
xem_refresh,
)
from medusa.search import SearchType
from medusa.search.manual import (
SEARCH_STATUS_FINISHED,
SEARCH_STATUS_QUEUED,
SEARCH_STATUS_SEARCHING,
collect_episodes_from_search_thread,
update_finished_search_queue_item,
)
from medusa.search.queue import (
BacklogQueueItem,
FailedQueueItem,
SnatchQueueItem,
)
from medusa.server.web.core import (
PageTemplate,
WebRoot,
)
from medusa.show.show import Show
from medusa.tv.cache import Cache
from medusa.tv.series import Series, SeriesIdentifier
from medusa.updater.version_checker import CheckVersion
from requests.compat import (
quote_plus,
unquote_plus,
)
from six import iteritems, text_type
from six.moves import map
from tornroutes import route
import trakt
from trakt.errors import TraktException
@route('/home(/?.*)')
class Home(WebRoot):
def __init__(self, *args, **kwargs):
super(Home, self).__init__(*args, **kwargs)
def _genericMessage(self, subject, message):
t = PageTemplate(rh=self, filename='genericMessage.mako')
return t.render(message=message, subject=subject, title='')
def index(self):
"""
Render the home page.
[Converted to VueRouter]
"""
t = PageTemplate(rh=self, filename='index.mako')
return t.render()
@staticmethod
def show_statistics():
pre_today = [SKIPPED, WANTED, FAILED]
snatched = [SNATCHED, SNATCHED_PROPER, SNATCHED_BEST]
downloaded = [DOWNLOADED, ARCHIVED]
def query_in(items):
return '({0})'.format(','.join(map(text_type, items)))
query = dedent("""\
SELECT showid, indexer,
SUM(
season > 0 AND
episode > 0 AND
airdate > 1 AND
status IN {status_quality}
) AS ep_snatched,
SUM(
season > 0 AND
episode > 0 AND
airdate > 1 AND
status IN {status_download}
) AS ep_downloaded,
SUM(
season > 0 AND
episode > 0 AND
airdate > 1 AND (
(airdate <= {today} AND status IN {status_pre_today})
OR status IN {status_both}
)
) AS ep_total,
(SELECT airdate FROM tv_episodes
WHERE showid=tv_eps.showid AND
indexer=tv_eps.indexer AND
airdate >= {today} AND
(status = {unaired} OR status = {wanted})
ORDER BY airdate ASC
LIMIT 1
) AS ep_airs_next,
(SELECT airdate FROM tv_episodes
WHERE showid=tv_eps.showid AND
indexer=tv_eps.indexer AND
airdate > 1 AND
status <> {unaired}
ORDER BY airdate DESC
LIMIT 1
) AS ep_airs_prev,
SUM(file_size) AS show_size
FROM tv_episodes tv_eps
GROUP BY showid, indexer
""").format(status_quality=query_in(snatched), status_download=query_in(downloaded),
status_pre_today=query_in(pre_today), status_both=query_in(snatched + downloaded),
skipped=SKIPPED, wanted=WANTED, unaired=UNAIRED, today=date.today().toordinal())
main_db_con = db.DBConnection()
sql_result = main_db_con.select(query)
show_stat = {}
max_download_count = 1000
for cur_result in sql_result:
show_stat[(cur_result['indexer'], cur_result['showid'])] = cur_result
if cur_result['ep_total'] > max_download_count:
max_download_count = cur_result['ep_total']
max_download_count *= 100
return show_stat, max_download_count
def is_alive(self, *args, **kwargs):
self.set_header('Content-Type', 'application/json; charset=UTF-8')
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', 'x-requested-with')
return json.dumps({
'pid': app.PID if app.started else ''
})
@staticmethod
def testSABnzbd(host=None, username=None, password=None, apikey=None):
host = config.clean_url(host)
try:
connection, acces_msg = sab.get_sab_access_method(host)
except Exception as error:
logger.log('Error while testing SABnzbd connection: {error}'.format(error=error), logger.WARNING)
return 'Error while testing connection. Check warning logs.'
if connection:
authed, auth_msg = sab.test_authentication(host, username, password, apikey) # @UnusedVariable
if authed:
return 'Success. Connected and authenticated'
else:
return 'Authentication failed. SABnzbd expects {access!r} as authentication method, {auth}'.format(
access=acces_msg, auth=auth_msg)
else:
return 'Unable to connect to host'
@staticmethod
def testNZBget(host=None, username=None, password=None, use_https=False):
try:
connected_status = nzbget.testNZB(host, username, password, config.checkbox_to_value(use_https))
except Exception as error:
logger.log('Error while testing NZBget connection: {error}'.format(error=error), logger.WARNING)
return 'Error while testing connection. Check warning logs.'
if connected_status:
return 'Success. Connected and authenticated'
else:
return 'Unable to connect to host'
@staticmethod
def testTorrent(torrent_method=None, host=None, username=None, password=None):
# @TODO: Move this to the validation section of each PATCH/PUT method for torrents
host = config.clean_url(host)
try:
client = torrent.get_client_class(torrent_method)
_, acces_msg = client(host, username, password).test_authentication()
except Exception as error:
logger.log('Error while testing {torrent} connection: {error}'.format(
torrent=torrent_method or 'torrent', error=error), logger.WARNING)
return 'Error while testing connection. Check warning logs.'
return acces_msg
@staticmethod
def testFreeMobile(freemobile_id=None, freemobile_apikey=None):
result, message = notifiers.freemobile_notifier.test_notify(freemobile_id, freemobile_apikey)
if result:
return 'SMS sent successfully'
else:
return 'Problem sending SMS: {msg}'.format(msg=message)
@staticmethod
def testTelegram(telegram_id=None, telegram_apikey=None):
result, message = notifiers.telegram_notifier.test_notify(telegram_id, telegram_apikey)
if result:
return 'Telegram notification succeeded. Check your Telegram clients to make sure it worked'
else:
return 'Error sending Telegram notification: {msg}'.format(msg=message)
@staticmethod
def testDiscord(discord_webhook=None, discord_tts=False):
result, message = notifiers.discord_notifier.test_notify(discord_webhook, config.checkbox_to_value(discord_tts))
if result:
return 'Discord notification succeeded. Check your Discord channels to make sure it worked'
else:
return 'Error sending Discord notification: {msg}'.format(msg=message)
@staticmethod
def testslack(slack_webhook=None):
result = notifiers.slack_notifier.test_notify(slack_webhook)
if result:
return 'Slack notification succeeded. Check your Slack channel to make sure it worked'
else:
return 'Error sending Slack notification'
@staticmethod
def testGrowl(host=None, password=None):
success = 'Registered and Tested growl successfully'
failure = 'Registration and Testing of growl failed'
host = config.clean_host(host, default_port=23053)
result = notifiers.growl_notifier.test_notify(host, password)
return '{message} {host}{password}'.format(
message=success if result else failure,
host=unquote_plus(host),
password=' with password: {pwd}'.format(pwd=password) if password else ''
)
@staticmethod
def testProwl(prowl_api=None, prowl_priority=0):
result = notifiers.prowl_notifier.test_notify(prowl_api, prowl_priority)
if result:
return 'Test prowl notice sent successfully'
else:
return 'Test prowl notice failed'
@staticmethod
def testBoxcar2(accesstoken=None):
result = notifiers.boxcar2_notifier.test_notify(accesstoken)
if result:
return 'Boxcar2 notification succeeded. Check your Boxcar2 clients to make sure it worked'
else:
return 'Error sending Boxcar2 notification'
@staticmethod
def testPushover(userKey=None, apiKey=None):
result = notifiers.pushover_notifier.test_notify(userKey, apiKey)
if result:
return 'Pushover notification succeeded. Check your Pushover clients to make sure it worked'
else:
return 'Error sending Pushover notification'
@staticmethod
def twitterStep1():
return notifiers.twitter_notifier._get_authorization() # pylint: disable=protected-access
@staticmethod
def twitterStep2(key):
result = notifiers.twitter_notifier._get_credentials(key) # pylint: disable=protected-access
logger.log(u'result: {result}'.format(result=result))
return 'Key verification successful' if result else 'Unable to verify key'
@staticmethod
def testTwitter():
result = notifiers.twitter_notifier.test_notify()
return 'Tweet successful, check your twitter to make sure it worked' if result else 'Error sending tweet'
@staticmethod
def testKODI(host=None, username=None, password=None):
host = config.clean_hosts(host)
final_result = ''
for curHost in [x.strip() for x in host if x.strip()]:
cur_result = notifiers.kodi_notifier.test_notify(unquote_plus(curHost), username, password)
if len(cur_result.split(':')) > 2 and 'OK' in cur_result.split(':')[2]:
final_result += 'Test KODI notice sent successfully to {host}<br>\n'.format(host=unquote_plus(curHost))
else:
final_result += 'Test KODI notice failed to {host}<br>\n'.format(host=unquote_plus(curHost))
return final_result
def testPHT(self, host=None, username=None, password=None):
self.set_header('Cache-Control', 'max-age=0,no-cache,no-store')
if None is not password and set('*') == set(password):
password = app.PLEX_CLIENT_PASSWORD
host = config.clean_hosts(host)
final_result = ''
for curHost in [x.strip() for x in host if x.strip()]:
cur_result = notifiers.plex_notifier.test_notify_pht(unquote_plus(curHost), username, password)
if len(cur_result.split(':')) > 2 and 'OK' in cur_result.split(':')[2]:
final_result += 'Successful test notice sent to Plex Home Theater ... {host}<br>\n'.format(host=unquote_plus(curHost))
else:
final_result += 'Test failed for Plex Home Theater ... {host}<br>\n'.format(host=unquote_plus(cur_result))
ui.notifications.message('Tested Plex Home Theater(s)', final_result)
return final_result
def testPMS(self, host=None, username=None, password=None, plex_server_token=None):
self.set_header('Cache-Control', 'max-age=0,no-cache,no-store')
if password is not None and set('*') == set(password):
password = app.PLEX_SERVER_PASSWORD
host = config.clean_hosts(host)
final_result = ''
cur_result = notifiers.plex_notifier.test_notify_pms(host, username, password, plex_server_token)
if cur_result is None:
final_result += 'Successful test of Plex Media Server(s) ... {host}<br>\n'.format(host=unquote_plus(', '.join(host)))
elif cur_result is False:
final_result += 'Test failed, No Plex Media Server host specified<br>\n'
else:
final_result += 'Test failed for Plex Media Server(s) ... {host}<br>\n'.format(host=unquote_plus(cur_result))
ui.notifications.message('Tested Plex Media Server(s)', final_result)
return final_result
@staticmethod
def testLibnotify():
if notifiers.libnotify_notifier.test_notify():
return 'Tried sending desktop notification via libnotify'
else:
return notifiers.libnotify.diagnose()
@staticmethod
def testEMBY(host=None, emby_apikey=None):
host = config.clean_host(host)
result = notifiers.emby_notifier.test_notify(unquote_plus(host), emby_apikey)
if result:
return 'Test notice sent successfully to {host}'.format(host=unquote_plus(host))
else:
return 'Test notice failed to {host}'.format(host=unquote_plus(host))
@staticmethod
def testNMJ(host=None, database=None, mount=None):
host = config.clean_host(host)
result = notifiers.nmj_notifier.test_notify(unquote_plus(host), database, mount)
if result:
return 'Successfully started the scan update'
else:
return 'Test failed to start the scan update'
@staticmethod
def settingsNMJ(host=None):
host = config.clean_host(host)
result = notifiers.nmj_notifier.notify_settings(unquote_plus(host))
if result:
return json.dumps({
'message': 'Got settings from {host}'.format(host=host),
'database': app.NMJ_DATABASE,
'mount': app.NMJ_MOUNT,
})
else:
return json.dumps({
'message': 'Failed! Make sure your Popcorn is on and NMJ is running. '
'(see Log & Errors -> Debug for detailed info)',
'database': '',
'mount': '',
})
@staticmethod
def testNMJv2(host=None):
host = config.clean_host(host)
result = notifiers.nmjv2_notifier.test_notify(unquote_plus(host))
if result:
return 'Test notice sent successfully to {host}'.format(host=unquote_plus(host))
else:
return 'Test notice failed to {host}'.format(host=unquote_plus(host))
@staticmethod
def settingsNMJv2(host=None, dbloc=None, instance=None):
host = config.clean_host(host)
result = notifiers.nmjv2_notifier.notify_settings(unquote_plus(host), dbloc, instance)
if result:
return json.dumps({
'message': 'NMJ Database found at: {host}'.format(host=host),
'database': app.NMJv2_DATABASE,
})
else:
return json.dumps({
'message': 'Unable to find NMJ Database at location: {db_loc}. '
'Is the right location selected and PCH running?'.format(db_loc=dbloc),
'database': ''
})
@staticmethod
def requestTraktDeviceCodeOauth():
"""Start Trakt OAuth device auth. Send request."""
logger.log('Start a new Oauth device authentication request. Request is valid for 60 minutes.', logger.INFO)
try:
app.TRAKT_DEVICE_CODE = trakt.get_device_code(app.TRAKT_API_KEY, app.TRAKT_API_SECRET)
except TraktException as error:
logger.log('Unable to get trakt device code. Error: {error!r}'.format(error=error), logger.WARNING)
return json.dumps({'result': False})
return json.dumps(app.TRAKT_DEVICE_CODE)
@staticmethod
def checkTrakTokenOauth():
"""Check if the Trakt device OAuth request has been authenticated."""
logger.log('Start Trakt token request', logger.INFO)
if not app.TRAKT_DEVICE_CODE.get('requested'):
logger.log('You need to request a token before checking authentication', logger.WARNING)
return json.dumps({'result': 'need to request first', 'error': True})
if (app.TRAKT_DEVICE_CODE.get('requested') + app.TRAKT_DEVICE_CODE.get('requested')) < time.time():
logger.log('Trakt token Request expired', logger.INFO)
return json.dumps({'result': 'request expired', 'error': True})
if not app.TRAKT_DEVICE_CODE.get('device_code'):
logger.log('You need to request a token before checking authentication. Missing device code.', logger.WARNING)
return json.dumps({'result': 'need to request first', 'error': True})
try:
response = trakt.get_device_token(
app.TRAKT_DEVICE_CODE.get('device_code'), app.TRAKT_API_KEY, app.TRAKT_API_SECRET, store=True
)
except TraktException as error:
logger.log('Unable to get trakt device token. Error: {error!r}'.format(error=error), logger.WARNING)
return json.dumps({'result': 'Trakt error while retrieving device token', 'error': True})
if response.ok:
response_json = response.json()
app.TRAKT_ACCESS_TOKEN, app.TRAKT_REFRESH_TOKEN = \
response_json.get('access_token'), response_json.get('refresh_token')
return json.dumps({'result': 'succesfully updated trakt access and refresh token', 'error': False})
else:
if response.status_code == 400:
return json.dumps({'result': 'device code has not been activated yet', 'error': True})
if response.status_code == 409:
return json.dumps({'result': 'already activated this code', 'error': False})
logger.log(u'Something went wrong', logger.DEBUG)
return json.dumps({'result': 'Something went wrong'})
@staticmethod
def testTrakt(blacklist_name=None):
return notifiers.trakt_notifier.test_notify(blacklist_name)
@staticmethod
def forceTraktSync():
"""Force a trakt sync, depending on the notification settings, library is synced with watchlist and/or collection."""
return json.dumps({'result': ('Could not start sync', 'Sync Started')[app.trakt_checker_scheduler.forceRun()]})
@staticmethod
def loadShowNotifyLists():
data = {}
size = 0
for show in app.showList:
notify_list = {
'emails': '',
'prowlAPIs': '',
}
if show.notify_list:
notify_list = show.notify_list
data[show.identifier.slug] = {
'id': show.show_id,
'name': show.name,
'slug': show.identifier.slug,
'list': notify_list['emails'],
'prowl_notify_list': notify_list['prowlAPIs']
}
size += 1
data['_size'] = size
return json.dumps(data)
@staticmethod
def saveShowNotifyList(show=None, emails=None, prowlAPIs=None):
series_identifier = SeriesIdentifier.from_slug(show)
series_obj = Series.find_by_identifier(series_identifier)
# Create a new dict, to force the "dirty" flag on the Series object.
entries = {'emails': '', 'prowlAPIs': ''}
if not series_obj:
return 'show missing'
if series_obj.notify_list:
entries.update(series_obj.notify_list)
if emails is not None:
entries['emails'] = emails
if prowlAPIs is not None:
entries['prowlAPIs'] = prowlAPIs
series_obj.notify_list = entries
series_obj.save_to_db()
return 'OK'
@staticmethod
def testEmail(host=None, port=None, smtp_from=None, use_tls=None, user=None, pwd=None, to=None):
host = config.clean_host(host)
if notifiers.email_notifier.test_notify(host, port, smtp_from, use_tls, user, pwd, to):
return 'Test email sent successfully! Check inbox.'
else:
return 'ERROR: {error}'.format(error=notifiers.email_notifier.last_err)
@staticmethod
def testPushalot(authorizationToken=None):
result = notifiers.pushalot_notifier.test_notify(authorizationToken)
if result:
return 'Pushalot notification succeeded. Check your Pushalot clients to make sure it worked'
else:
return 'Error sending Pushalot notification'
@staticmethod
def testPushbullet(api=None):
result = notifiers.pushbullet_notifier.test_notify(api)
if result.get('success'):
return 'Pushbullet notification succeeded. Check your device to make sure it worked'
else:
return 'Error sending Pushbullet notification: {0}'.format(result.get('error'))
@staticmethod
def testJoin(api=None, device=None):
result = notifiers.join_notifier.test_notify(api, device)
if result.get('success'):
return 'Join notification succeeded. Check your device to make sure it worked'
else:
return 'Error sending Join notification: {0}'.format(result.get('error'))
@staticmethod
def getPushbulletDevices(api=None):
result = notifiers.pushbullet_notifier.get_devices(api)
if result:
return result
else:
return 'Error sending Pushbullet notification'
def status(self):
"""
Render the status page.
[Converted to VueRouter]
"""
return PageTemplate(rh=self, filename='index.mako').render()
def restart(self):
"""
Render the restart page.
[Converted to VueRouter]
"""
return PageTemplate(rh=self, filename='index.mako').render()
def shutdown(self):
"""
Render the shutdown page.
[Converted to VueRouter]
"""
return PageTemplate(rh=self, filename='index.mako').render()
def update(self):
"""
Render the update page.
[Converted to VueRouter]
"""
return PageTemplate(rh=self, filename='index.mako').render()
def updateCheck(self, pid=None):
if text_type(pid) != text_type(app.PID):
return self.redirect('/home/')
app.version_check_scheduler.action.check_for_new_version(force=True)
app.version_check_scheduler.action.check_for_new_news(force=True)
return self.redirect('/{page}/'.format(page=app.DEFAULT_PAGE))
def branchCheckout(self, branch):
if app.BRANCH != branch:
app.BRANCH = branch
ui.notifications.message('Checking out branch: ', branch)
return self.update(app.PID, branch)
else:
ui.notifications.message('Already on branch: ', branch)
return self.redirect('/{page}/'.format(page=app.DEFAULT_PAGE))
def branchForceUpdate(self):
return {
'currentBranch': app.BRANCH,
'resetBranches': app.GIT_RESET_BRANCHES,
'branches': [branch for branch in app.version_check_scheduler.action.list_remote_branches()
if branch not in app.GIT_RESET_BRANCHES]
}
@staticmethod
def getDBcompare():
checkversion = CheckVersion() # @TODO: replace with settings var
db_status = checkversion.getDBcompare()
if db_status == 'upgrade':
logger.log(u'Checkout branch has a new DB version - Upgrade', logger.DEBUG)
return json.dumps({
'status': 'success',
'message': 'upgrade',
})
elif db_status == 'equal':
logger.log(u'Checkout branch has the same DB version - Equal', logger.DEBUG)
return json.dumps({
'status': 'success',
'message': 'equal',
})
elif db_status == 'downgrade':
logger.log(u'Checkout branch has an old DB version - Downgrade', logger.DEBUG)
return json.dumps({
'status': 'success',
'message': 'downgrade',
})
else:
logger.log(u"Checkout branch couldn't compare DB version.", logger.WARNING)
return json.dumps({
'status': 'error',
'message': 'General exception',
})
def getSeasonSceneExceptions(self, indexername, seriesid):
"""Get show name scene exceptions per season
:param indexer: The shows indexer
:param indexer_id: The shows indexer_id
:return: A json with the scene exceptions per season.
"""
indexer_id = indexer_name_to_id(indexername)
series_obj = Show.find_by_id(app.showList, indexer_id, seriesid)
return json.dumps({
'seasonExceptions': {season: list(exception_name) for season, exception_name
in iteritems(get_all_scene_exceptions(series_obj))},
'xemNumbering': {tvdb_season_ep[0]: anidb_season_ep[0]
for (tvdb_season_ep, anidb_season_ep)
in iteritems(get_xem_numbering_for_show(series_obj, refresh_data=False))}
})
def displayShow(self, indexername=None, seriesid=None, ):
"""
Render the home page.
[Converted to VueRouter]
"""
try:
indexer_id = indexer_name_to_id(indexername)
series_obj = Show.find_by_id(app.showList, indexer_id, seriesid)
except (ValueError, TypeError):
return self._genericMessage('Error', 'Invalid series ID: {seriesid}'.format(seriesid=seriesid))
if series_obj is None:
return self._genericMessage('Error', 'Show not in show list')
t = PageTemplate(rh=self, filename='index.mako')
return t.render(
controller='home', action='displayShow',
)
def pickManualSearch(self, provider=None, identifier=None):
"""
Tries to Perform the snatch for a manualSelected episode, episodes or season pack.
@param provider: The provider id, passed as usenet_crawler and not the provider name (Usenet-Crawler)
@param identifier: The provider's cache table's identifier (unique).
@return: A json with a {'success': true} or false.
"""
# Try to retrieve the cached result from the providers cache table.
provider_obj = providers.get_provider_class(provider)
try:
cached_result = Cache(provider_obj).load_from_row(identifier)
except Exception as msg:
error_message = "Couldn't read cached results. Error: {error}".format(error=msg)
logger.log(error_message)
return self._genericMessage('Error', error_message)
if not cached_result or not all([cached_result['url'],
cached_result['quality'],
cached_result['name'],
cached_result['indexer'],
cached_result['indexerid'],
cached_result['season'] is not None,
provider]):
return self._genericMessage('Error', "Cached result doesn't have all needed info to snatch episode")
try:
series_obj = Show.find_by_id(app.showList, cached_result['indexer'], cached_result['indexerid'])
except (ValueError, TypeError):
return self._genericMessage('Error', 'Invalid show ID: {0}'.format(cached_result['indexerid']))
if not series_obj:
return self._genericMessage('Error', 'Could not find a show with id {0} in the list of shows, '
'did you remove the show?'.format(cached_result['indexerid']))
search_result = provider_obj.get_result(series=series_obj, cache=cached_result)
search_result.search_type = SearchType.MANUAL_SEARCH
# Create the queue item
snatch_queue_item = SnatchQueueItem(search_result.series, search_result.episodes, search_result)
# Add the queue item to the queue
app.manual_snatch_scheduler.action.add_item(snatch_queue_item)
while snatch_queue_item.success is not False:
if snatch_queue_item.started and snatch_queue_item.success:
# If the snatch was successfull we'll need to update the original searched segment,
# with the new status: SNATCHED (2)
update_finished_search_queue_item(snatch_queue_item)
return json.dumps({
'result': 'success',
})
time.sleep(1)
return json.dumps({
'result': 'failure',
})
def manualSearchCheckCache(self, indexername, seriesid, season=None, episode=None, manual_search_type='episode', **last_prov_updates):
""" Periodic check if the searchthread is still running for t he selected show/season/ep
and if there are new results in the cache.db
"""
refresh_results = 'refresh'
indexer_id = indexer_name_to_id(indexername)
series_obj = Show.find_by_id(app.showList, indexer_id, seriesid)
try:
int(episode)
int(season)
except ValueError:
return {'result': 'error'}
# To prevent it from keeping searching when no providers have been enabled
if not enabled_providers('manualsearch'):
return {'result': SEARCH_STATUS_FINISHED}
main_db_con = db.DBConnection('cache.db')
episodes_in_search = collect_episodes_from_search_thread(series_obj)
# Check if the requested ep is in a search thread
searched_item = [ep for ep in episodes_in_search
if all([ep['show']['indexer'] == series_obj.identifier.indexer.id,
ep['show']['series_id'] == series_obj.identifier.id,
text_type(ep['episode']['season']) == season,
text_type(ep['episode']['episode']) == episode])]
# # No last_prov_updates available, let's assume we need to refresh until we get some
# if not last_prov_updates:
# return {'result': REFRESH_RESULTS}
sql_episode = '' if manual_search_type == 'season' else episode
for provider, last_update in iteritems(last_prov_updates):
table_exists = main_db_con.select(
'SELECT name '
'FROM sqlite_master '
"WHERE type='table' AND name=?",
[provider]
)
if not table_exists:
continue
# Check if the cache table has a result for this show + season + ep wich has a later timestamp, then last_update
# FIXME: This will need to be adjusted when indexer field is added to the providers.
needs_update = main_db_con.select(
'SELECT * '
"FROM '{provider}' "
'WHERE episodes LIKE ? AND season = ? AND indexer = ? AND indexerid = ? AND time > ?'.format(provider=provider),
['%|{episodes}|%'.format(episodes=sql_episode), season, series_obj.indexer, series_obj.series_id, int(last_update)]
)
if needs_update:
return {'result': refresh_results}
# If the item is queued multiple times (don't know if this is possible),
# but then check if as soon as a search has finished
# Move on and show results
# Return a list of queues the episode has been found in
search_status = [item['search']['status'] for item in searched_item]
if not searched_item or all([last_prov_updates,
SEARCH_STATUS_QUEUED not in search_status,
SEARCH_STATUS_SEARCHING not in search_status,
SEARCH_STATUS_FINISHED in search_status]):
# If the ep not anymore in the QUEUED or SEARCHING Thread, and it has the status finished,
# return it as finished
return {'result': SEARCH_STATUS_FINISHED}
# Force a refresh when the last_prov_updates is empty due to the tables not existing yet.
# This can be removed if we make sure the provider cache tables always exist prior to the
# start of the first search
if not last_prov_updates and SEARCH_STATUS_FINISHED in search_status:
return {'result': refresh_results}
return {'result': searched_item[0]['search']['status']}
def snatchSelection(self, indexername, seriesid, season=None, episode=None, manual_search_type='episode',
perform_search=0, down_cur_quality=0, show_all_results=0):
"""
Render the home page.
[Converted to VueRouter]
"""
# @TODO: add more comprehensive show validation
try:
indexer_id = indexer_name_to_id(indexername)
series_obj = Show.find_by_id(app.showList, indexer_id, seriesid)
except (ValueError, TypeError):
return self._genericMessage('Error', 'Invalid show ID: {series}'.format(series=seriesid))
if series_obj is None:
return self._genericMessage('Error', 'Show not in show list')
t = PageTemplate(rh=self, filename='index.mako')
return t.render(
controller='home', action='snatchSelection'
)
@staticmethod
def sceneExceptions(indexername, seriesid):
# @TODO: Replace with plot from GET /api/v2/show/{id}
indexer_id = indexer_name_to_id(indexername)
series_obj = Show.find_by_id(app.showList, indexer_id, seriesid)
exceptions_list = get_all_scene_exceptions(series_obj)
if not exceptions_list:
return 'No scene exceptions'
out = []
for season, names in iter(sorted(iteritems(exceptions_list))):
if season == -1:
season = '*'
out.append('S{season}: {names}'.format(season=season, names=', '.join(names)))
return '<br>'.join(out)
@staticmethod
def check_show_for_language(series_obj, language):
"""
Request the show in a specific language from the indexer.
:param series_obj: (Series) Show object
:param language: Language two-letter country code. For ex: 'en'
:returns: True if show is found in language else False
"""
# Get the Indexer used by the show
show_indexer = indexerApi(series_obj.indexer)
# Add the language to the show indexer's parameters
params = show_indexer.api_params.copy()
params.update({
'language': language,
'episodes': False,
})
# Create an indexer with the updated parameters
indexer = show_indexer.indexer(**params)
if language in indexer.config['valid_languages']:
return True
def massEditShow(
self, indexername=None, seriesid=None, location=None, allowed_qualities=None, preferred_qualities=None,
season_folders=None, paused=None, air_by_date=None, sports=None, dvd_order=None, subtitles=None,
anime=None, scene=None, defaultEpStatus=None
):
"""
A variation of the original `editShow`, where `directCall` is always true.
This route as been added specifically for the usage in the massEditSubmit route.
It's called when trying to mass edit show configurations.
This route should be removed after vueifying manage_massEdit.mako.
"""
allowed_qualities = allowed_qualities or []
preferred_qualities = preferred_qualities or []
errors = 0
if not indexername or not seriesid:
logger.log('No show was selected (indexer: {indexer}, show: {show})'.format(
indexer=indexername, show=seriesid), logger.WARNING)
errors += 1
return errors
series_obj = Show.find_by_id(app.showList, indexer_name_to_id(indexername), seriesid)
if not series_obj:
logger.log('Unable to find the specified show: {indexer}{show}'.format(
indexer=indexername, show=seriesid), logger.WARNING)
errors += 1
return errors
season_folders = config.checkbox_to_value(season_folders)
dvd_order = config.checkbox_to_value(dvd_order)
paused = config.checkbox_to_value(paused)
air_by_date = config.checkbox_to_value(air_by_date)
scene = config.checkbox_to_value(scene)
sports = config.checkbox_to_value(sports)
anime = config.checkbox_to_value(anime)
subtitles = config.checkbox_to_value(subtitles)
do_update_scene_numbering = not (scene == series_obj.scene and anime == series_obj.anime)
if not isinstance(allowed_qualities, list):
allowed_qualities = [allowed_qualities]
if not isinstance(preferred_qualities, list):
preferred_qualities = [preferred_qualities]
with series_obj.lock:
new_quality = Quality.combine_qualities([int(q) for q in allowed_qualities],
[int(q) for q in preferred_qualities])
series_obj.quality = new_quality
# reversed for now
if bool(series_obj.season_folders) != bool(season_folders):
series_obj.season_folders = season_folders
try:
app.show_queue_scheduler.action.refreshShow(series_obj)
except CantRefreshShowException as error:
errors += 1
logger.log("Unable to refresh show '{show}': {error!r}".format
(show=series_obj.name, error=error), logger.WARNING)
# Check if we should erase parsed cached results for that show
do_erase_parsed_cache = False
for item in [('scene', scene), ('anime', anime), ('sports', sports),
('air_by_date', air_by_date), ('dvd_order', dvd_order)]:
if getattr(series_obj, item[0]) != item[1]:
do_erase_parsed_cache = True
# Break if at least one setting was changed
break
series_obj.paused = paused
series_obj.scene = scene