-
Notifications
You must be signed in to change notification settings - Fork 277
/
handler.py
2377 lines (2013 loc) · 102 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 builtins import str
from datetime import date, datetime
from medusa import (
app,
config,
db,
helpers,
logger,
name_cache,
notifiers,
providers,
subtitles,
ui,
)
from medusa.black_and_white_list import (
BlackAndWhiteList,
)
from medusa.clients import torrent
from medusa.clients.nzb import (
nzbget,
sab,
)
from medusa.common import (
ARCHIVED,
DOWNLOADED,
FAILED,
IGNORED,
Overview,
Quality,
SKIPPED,
SNATCHED,
SNATCHED_BEST,
SNATCHED_PROPER,
UNAIRED,
WANTED,
cpu_presets,
statusStrings,
)
from medusa.failed_history import prepare_failed_name
from medusa.helper.common import (
enabled_providers,
pretty_file_size,
try_int,
)
from medusa.helper.exceptions import (
AnidbAdbaConnectionException,
CantRefreshShowException,
CantUpdateShowException,
ShowDirectoryNotFoundException,
ex,
)
from medusa.helpers.anidb import get_release_groups_for_anime, short_group_names
from medusa.indexers.indexer_api import indexerApi
from medusa.indexers.indexer_exceptions import (
IndexerException,
IndexerShowNotFoundInLanguage,
)
from medusa.indexers.utils import indexer_id_to_name, indexer_name_to_id
from medusa.providers.generic_provider import GenericProvider
from medusa.sbdatetime import sbdatetime
from medusa.scene_exceptions import (
get_all_scene_exceptions,
get_scene_exceptions,
update_scene_exceptions,
)
from medusa.scene_numbering import (
get_scene_absolute_numbering,
get_scene_absolute_numbering_for_show,
get_scene_numbering,
get_scene_numbering_for_show,
get_xem_absolute_numbering_for_show,
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,
get_provider_cache_results,
update_finished_search_queue_item,
)
from medusa.search.queue import (
BacklogQueueItem,
FailedQueueItem,
ForcedSearchQueueItem,
SnatchQueueItem,
)
from medusa.server.web.core import (
PageTemplate,
WebRoot,
)
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.tv.series import Series, SeriesIdentifier
from medusa.version_checker import CheckVersion
from requests.compat import (
quote_plus,
unquote_plus,
)
from six import iteritems
from tornroutes import route
from traktor import (
MissingTokenException,
TokenExpiredException,
TraktApi,
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):
t = PageTemplate(rh=self, filename='home.mako')
selected_root = int(app.SELECTED_ROOT)
shows_dir = None
if selected_root is not None and app.ROOT_DIRS:
backend_pieces = app.ROOT_DIRS
backend_dirs = backend_pieces[1:]
try:
shows_dir = backend_dirs[selected_root] if selected_root != -1 else None
except IndexError:
# If user have a root selected in /home and remove the root folder a IndexError is raised
shows_dir = None
app.SELECTED_ROOT = -1
series = []
if app.ANIME_SPLIT_HOME:
anime = []
for show in app.showList:
if shows_dir and not show._location.startswith(shows_dir):
continue
if show.is_anime:
anime.append(show)
else:
series.append(show)
show_lists = [[order, {'Series': series, 'Anime': anime}[order]] for order in app.SHOW_LIST_ORDER]
else:
for show in app.showList:
if shows_dir and not show._location.startswith(shows_dir):
continue
series.append(show)
show_lists = [['Series', series]]
stats = self.show_statistics()
return t.render(show_lists=show_lists, show_stat=stats[0],
max_download_count=stats[1], controller='home', action='index')
@staticmethod
def show_statistics():
main_db_con = db.DBConnection()
snatched = [SNATCHED, SNATCHED_PROPER, SNATCHED_BEST]
downloaded = [DOWNLOADED, ARCHIVED]
# FIXME: This inner join is not multi indexer friendly.
sql_result = main_db_con.select(
"""
SELECT showid, indexer,
(SELECT COUNT(*) FROM tv_episodes
WHERE showid=tv_eps.showid AND
indexer=tv_eps.indexer AND
season > 0 AND
episode > 0 AND
airdate > 1 AND
status IN {status_quality}
) AS ep_snatched,
(SELECT COUNT(*) FROM tv_episodes
WHERE showid=tv_eps.showid AND
indexer=tv_eps.indexer AND
season > 0 AND
episode > 0 AND
airdate > 1 AND
status IN {status_download}
) AS ep_downloaded,
(SELECT COUNT(*) FROM tv_episodes
WHERE showid=tv_eps.showid AND
indexer=tv_eps.indexer AND
season > 0 AND
episode > 0 AND
airdate > 1 AND
((airdate <= {today} AND (status = {skipped} OR
status = {wanted} OR
status = {failed})) OR
(status IN {status_quality}) OR
(status IN {status_download}))
) 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,
(SELECT SUM(file_size) FROM tv_episodes
WHERE showid=tv_eps.showid AND
indexer=tv_eps.indexer
) AS show_size
FROM tv_episodes tv_eps
GROUP BY showid, indexer
""".format(status_quality='({statuses})'.format(statuses=','.join([str(x) for x in snatched])),
status_download='({statuses})'.format(statuses=','.join([str(x) for x in downloaded])),
skipped=SKIPPED, wanted=WANTED, unaired=UNAIRED, failed=FAILED,
today=date.today().toordinal())
)
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
# @TODO: Replace with /api/v2/config/kodi, check if enabled === true
def haveKODI():
return app.USE_KODI and app.KODI_UPDATE_LIBRARY
@staticmethod
# @TODO: Replace with /api/v2/config/plex, check if enabled === true
def havePLEX():
return app.USE_PLEX_SERVER and app.PLEX_UPDATE_LIBRARY
@staticmethod
# @TODO: Replace with /api/v2/config/emby, check if enabled === true
def haveEMBY():
return app.USE_EMBY
@staticmethod
# @TODO: Replace with /api/v2/config/torrents, check if enabled === true
def haveTORRENT():
return bool(app.USE_TORRENTS and app.TORRENT_METHOD != 'blackhole' and
(app.ENABLE_HTTPS and app.TORRENT_HOST[:5] == 'https' or not
app.ENABLE_HTTPS and app.TORRENT_HOST[:5] == 'http:'))
@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 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
final_result = ''
for curHost in [x.strip() for x in host.split(',')]:
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(curHost))
ui.notifications.message('Tested Plex Home Theater(s): ', unquote_plus(host.replace(',', ', ')))
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
final_result = ''
cur_result = notifiers.plex_notifier.test_notify_pms(unquote_plus(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(host.replace(',', ', ')))
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(host.replace(',', ', ')))
ui.notifications.message('Tested Plex Media Server host(s): ', unquote_plus(host.replace(',', ', ')))
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 getTraktToken(trakt_pin=None):
trakt_settings = {'trakt_api_key': app.TRAKT_API_KEY,
'trakt_api_secret': app.TRAKT_API_SECRET}
trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT, **trakt_settings)
response = None
try:
(access_token, refresh_token) = trakt_api.get_token(app.TRAKT_REFRESH_TOKEN, trakt_pin=trakt_pin)
if access_token and refresh_token:
app.TRAKT_ACCESS_TOKEN = access_token
app.TRAKT_REFRESH_TOKEN = refresh_token
response = trakt_api.validate_account()
except MissingTokenException:
ui.notifications.error('You need to get a PIN and authorize Medusa app')
return 'You need to get a PIN and authorize Medusa app'
except TokenExpiredException:
# Clear existing tokens
app.TRAKT_ACCESS_TOKEN = ''
app.TRAKT_REFRESH_TOKEN = ''
ui.notifications.error('TOKEN expired. Reload page, get a new PIN and authorize Medusa app')
return 'TOKEN expired. Reload page, get a new PIN and authorize Medusa app'
except TraktException:
ui.notifications.error("Connection error. Click 'Authorize Medusa' button again")
return "Connection error. Click 'Authorize Medusa' button again"
if response:
ui.notifications.message('Trakt Authorized')
return 'Trakt Authorized'
ui.notifications.error('Connection error. Reload the page to get new token!')
return 'Trakt Not Authorized!'
@staticmethod
def testTrakt(username=None, blacklist_name=None):
return notifiers.trakt_notifier.test_notify(username, 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):
entries = {'emails': '', 'prowlAPIs': ''}
series_identifier = SeriesIdentifier.from_slug(show)
series_obj = Series.find_by_identifier(series_identifier)
if series_obj:
if series_obj.notify_list:
entries = series_obj.notify_list
if emails is not None:
entries['emails'] = emails
series_obj.notify_list = entries
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):
tv_dir_free = helpers.get_disk_space_usage(app.TV_DOWNLOAD_DIR)
root_dir = {}
if app.ROOT_DIRS:
backend_pieces = app.ROOT_DIRS
backend_dirs = backend_pieces[1:]
else:
backend_dirs = []
if backend_dirs:
for subject in backend_dirs:
root_dir[subject] = helpers.get_disk_space_usage(subject)
t = PageTemplate(rh=self, filename='status.mako')
return t.render(title='Status', header='Status',
tvdirFree=tv_dir_free, rootDir=root_dir,
controller='home', action='status')
def shutdown(self, pid=None):
if not Shutdown.stop(pid):
return self.redirect('/{page}/'.format(page=app.DEFAULT_PAGE))
title = 'Shutting down'
message = 'Medusa is shutting down...'
return self._genericMessage(title, message)
def restart(self, pid=None):
if not Restart.restart(pid):
return self.redirect('/{page}/'.format(page=app.DEFAULT_PAGE))
t = PageTemplate(rh=self, filename='restart.mako')
return t.render(title='Home', header='Restarting Medusa',
controller='home', action='restart')
def updateCheck(self, pid=None):
if str(pid) != str(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 update(self, pid=None, branch=None):
if str(pid) != str(app.PID):
return self.redirect('/home/')
checkversion = CheckVersion()
backup = checkversion.updater and checkversion._runbackup() # pylint: disable=protected-access
if backup is True:
if branch:
checkversion.updater.branch = branch
# @FIXME: Pre-render the restart page. This is a workaround to stop errors on updates.
t = PageTemplate(rh=self, filename='restart.mako')
restart_rendered = t.render(title='Home', header='Restarting Medusa',
controller='home', action='restart')
if checkversion.updater.need_update() and checkversion.updater.update():
# do a hard restart
app.events.put(app.events.SystemEvent.RESTART)
return restart_rendered
else:
return self._genericMessage('Update Failed',
'Update wasn\'t successful, not restarting. Check your log for more information.')
else:
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, ):
# @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 series ID: {seriesid}'.format(seriesid=seriesid))
if series_obj is None:
return self._genericMessage('Error', 'Show not in show list')
main_db_con = db.DBConnection()
season_results = main_db_con.select(
'SELECT DISTINCT season '
'FROM tv_episodes '
'WHERE indexer = ? AND showid = ? AND season IS NOT NULL '
'ORDER BY season DESC',
[series_obj.indexer, series_obj.series_id]
)
min_season = 0 if app.DISPLAY_SHOW_SPECIALS else 1
sql_results = main_db_con.select(
'SELECT * '
'FROM tv_episodes '
'WHERE indexer = ? AND showid = ? AND season >= ? '
'ORDER BY season DESC, episode DESC',
[series_obj.indexer, series_obj.series_id, min_season]
)
t = PageTemplate(rh=self, filename='displayShow.mako')
submenu = [{
'title': 'Edit',
'path': 'home/editShow?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'icon': 'ui-icon ui-icon-pencil',
}]
try:
show_loc = (series_obj.location, True)
except ShowDirectoryNotFoundException:
show_loc = (series_obj._location, False) # pylint: disable=protected-access
show_message = ''
if app.show_queue_scheduler.action.isBeingAdded(series_obj):
show_message = 'This show is in the process of being downloaded - the info below is incomplete.'
elif app.show_queue_scheduler.action.isBeingUpdated(series_obj):
show_message = 'The information on this page is in the process of being updated.'
elif app.show_queue_scheduler.action.isBeingRefreshed(series_obj):
show_message = 'The episodes below are currently being refreshed from disk'
elif app.show_queue_scheduler.action.isBeingSubtitled(series_obj):
show_message = 'Currently downloading subtitles for this show'
elif app.show_queue_scheduler.action.isInRefreshQueue(series_obj):
show_message = 'This show is queued to be refreshed.'
elif app.show_queue_scheduler.action.isInUpdateQueue(series_obj):
show_message = 'This show is queued and awaiting an update.'
elif app.show_queue_scheduler.action.isInSubtitleQueue(series_obj):
show_message = 'This show is queued and awaiting subtitles download.'
if not app.show_queue_scheduler.action.isBeingAdded(series_obj):
if not app.show_queue_scheduler.action.isBeingUpdated(series_obj):
submenu.append({
'title': 'Resume' if series_obj.paused else 'Pause',
'path': 'home/togglePause?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'icon': 'ui-icon ui-icon-{state}'.format(state='play' if series_obj.paused else 'pause'),
})
submenu.append({
'title': 'Remove',
'path': 'home/deleteShow?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'class': 'removeshow',
'confirm': True,
'icon': 'ui-icon ui-icon-trash',
})
submenu.append({
'title': 'Re-scan files',
'path': 'home/refreshShow?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'icon': 'ui-icon ui-icon-refresh',
})
submenu.append({
'title': 'Force Full Update',
'path': 'home/updateShow?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'icon': 'ui-icon ui-icon-transfer-e-w',
})
submenu.append({
'title': 'Update show in KODI',
'path': 'home/updateKODI?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'requires': self.haveKODI(),
'icon': 'menu-icon-kodi',
})
submenu.append({
'title': 'Update show in Emby',
'path': 'home/updateEMBY?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'requires': self.haveEMBY(),
'icon': 'menu-icon-emby',
})
submenu.append({
'title': 'Preview Rename',
'path': 'home/testRename?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'icon': 'ui-icon ui-icon-tag',
})
if app.USE_SUBTITLES and not app.show_queue_scheduler.action.isBeingSubtitled(
series_obj) and series_obj.subtitles:
submenu.append({
'title': 'Download Subtitles',
'path': 'home/subtitleShow?indexername={series_obj.indexer_name}&seriesid={series_obj.series_id}'.format(series_obj=series_obj),
'icon': 'menu-icon-backlog',
})
ep_counts = {
Overview.SKIPPED: 0,
Overview.WANTED: 0,
Overview.QUAL: 0,
Overview.GOOD: 0,
Overview.UNAIRED: 0,
Overview.SNATCHED: 0,
Overview.SNATCHED_PROPER: 0,
Overview.SNATCHED_BEST: 0
}
ep_cats = {}
for cur_result in sql_results:
cur_ep_cat = series_obj.get_overview(cur_result['status'], cur_result['quality'], manually_searched=cur_result['manually_searched'])
if cur_ep_cat:
ep_cats['s{season}e{episode}'.format(season=cur_result['season'], episode=cur_result['episode'])] = cur_ep_cat
ep_counts[cur_ep_cat] += 1
bwl = None
if series_obj.is_anime:
bwl = series_obj.release_groups
series_obj.exceptions = get_scene_exceptions(series_obj)
indexer_id = int(series_obj.indexer)
series_id = int(series_obj.series_id)
# Delete any previous occurrances
indexer_name = indexer_id_to_name(indexer_id)
for index, recentShow in enumerate(app.SHOWS_RECENT):
if recentShow['indexerName'] == indexer_name and recentShow['showId'] == series_id:
del app.SHOWS_RECENT[index]
# Only track 5 most recent shows
del app.SHOWS_RECENT[4:]
# Insert most recent show
app.SHOWS_RECENT.insert(0, {
'indexerName': indexer_name,
'showId': series_id,
'name': series_obj.name,
})
return t.render(
submenu=submenu[::-1], showLoc=show_loc, show_message=show_message,
show=series_obj, sql_results=sql_results, season_results=season_results,
bwl=bwl, ep_counts=ep_counts,
ep_cats=ep_cats, all_scene_exceptions=' | '.join(series_obj.exceptions),
scene_numbering=get_scene_numbering_for_show(series_obj),
xem_numbering=get_xem_numbering_for_show(series_obj, refresh_data=False),
scene_absolute_numbering=get_scene_absolute_numbering_for_show(series_obj),
xem_absolute_numbering=get_xem_absolute_numbering_for_show(series_obj),
title=series_obj.name, controller='home', action='displayShow',
)
def pickManualSearch(self, provider=None, rowid=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 rowid: The provider's cache table's rowid. (currently the implicit sqlites rowid is used, needs to be replaced in future)
@return: A json with a {'success': true} or false.
"""
# Try to retrieve the cached result from the providers cache table.
# @TODO: the implicit sqlite rowid is used, should be replaced with an explicit PK column
try:
main_db_con = db.DBConnection('cache.db')
cached_result = main_db_con.action(
'SELECT * '
'FROM \'{provider}\' '
'WHERE rowid = ?'.format(provider=provider),
[rowid],
fetchone=True
)
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, '