forked from SNAPflix/salts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.py
1880 lines (1643 loc) · 92.7 KB
/
default.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
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import os
import re
import datetime
import time
import xbmcplugin
import xbmcgui
import xbmc
import xbmcvfs
import urllib2
from addon.common.addon import Addon
from salts_lib.db_utils import DB_Connection
from salts_lib.url_dispatcher import URL_Dispatcher
from salts_lib.srt_scraper import SRT_Scraper
from salts_lib.trakt_api import Trakt_API, TransientTraktError
from salts_lib import utils
from salts_lib import log_utils
from salts_lib.constants import *
from scrapers import * # import all scrapers into this namespace
from scrapers import ScraperVideo
_SALTS = Addon('plugin.video.salts', sys.argv)
ICON_PATH = os.path.join(_SALTS.get_path(), 'icon.png')
username=_SALTS.get_setting('username')
password=_SALTS.get_setting('password')
TOKEN=utils.get_trakt_token()
use_https=_SALTS.get_setting('use_https')=='true'
trakt_timeout=int(_SALTS.get_setting('trakt_timeout'))
list_size=int(_SALTS.get_setting('list_size'))
trakt_api=Trakt_API(username,password, TOKEN, use_https, list_size, trakt_timeout)
url_dispatcher=URL_Dispatcher()
db_connection=DB_Connection()
global urlresolver
@url_dispatcher.register(MODES.MAIN)
def main_menu():
db_connection.init_database()
if not TOKEN:
remind_count = int(_SALTS.get_setting('remind_count'))
remind_max=5
if remind_count<remind_max:
remind_count += 1
log_utils.log('Showing Config reminder')
builtin = 'XBMC.Notification(%s,(%s/%s) Configure Trakt Account for more options, 7500, %s)'
xbmc.executebuiltin(builtin % (_SALTS.get_name(), remind_count, remind_max, ICON_PATH))
_SALTS.set_setting('remind_count', str(remind_count))
else:
_SALTS.set_setting('remind_count', '0')
if _SALTS.get_setting('auto-disable') != DISABLE_SETTINGS.OFF:
utils.do_disable_check()
_SALTS.add_directory({'mode': MODES.BROWSE, 'section': SECTIONS.MOVIES}, {'title': 'Movies'}, img=utils.art('movies.png'), fanart=utils.art('fanart.jpg'))
_SALTS.add_directory({'mode': MODES.BROWSE, 'section': SECTIONS.TV}, {'title': 'TV Shows'}, img=utils.art('television.png'), fanart=utils.art('fanart.jpg'))
_SALTS.add_directory({'mode': MODES.SETTINGS}, {'title': 'Settings'}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=False)
@url_dispatcher.register(MODES.SETTINGS)
def settings_menu():
_SALTS.add_directory({'mode': MODES.SCRAPERS}, {'title': 'Scraper Sort Order'}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
_SALTS.add_directory({'mode': MODES.RES_SETTINGS}, {'title': 'Url Resolver Settings'}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
_SALTS.add_directory({'mode': MODES.ADDON_SETTINGS}, {'title': 'Add-on Settings'}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
_SALTS.add_directory({'mode': MODES.SHOW_VIEWS}, {'title': 'Set Default Views'}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
_SALTS.add_directory({'mode': MODES.BROWSE_URLS}, {'title': 'Remove Cached Url(s)'}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.SHOW_VIEWS)
def show_views():
for content_type in ['movies', 'tvshows', 'seasons', 'episodes']:
_SALTS.add_directory({'mode': MODES.BROWSE_VIEW, 'content_type': content_type}, {'title': 'Set Default %s View' % (content_type.capitalize())}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.BROWSE_VIEW, ['content_type'])
def browse_view(content_type):
_SALTS.add_directory({'mode': MODES.SET_VIEW, 'content_type': content_type}, {'title': 'Set a view then select this item to set the default %s view' % (content_type.capitalize())}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
utils.set_view(content_type, False)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.SET_VIEW, ['content_type'])
def set_default_view(content_type):
current_view = utils.get_current_view()
if current_view:
_SALTS.set_setting('%s_view' % (content_type), current_view)
view_name = xbmc.getInfoLabel('Container.Viewmode')
builtin = "XBMC.Notification(Import,%s View Set to: %s,2000, %s)" % (content_type.capitalize(), view_name, ICON_PATH)
xbmc.executebuiltin(builtin)
@url_dispatcher.register(MODES.BROWSE_URLS)
def browse_urls():
urls = db_connection.get_all_urls(order_matters=True)
_SALTS.add_directory({'mode': MODES.FLUSH_CACHE}, {'title': '***Delete [B][COLOR red]ENTIRE[/COLOR][/B] Url Cache***'}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
for url in urls:
_SALTS.add_directory({'mode': MODES.DELETE_URL, 'url': url[0]}, {'title': url[0]}, img=utils.art('settings.png'), fanart=utils.art('fanart.jpg'))
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.DELETE_URL, ['url'])
def delete_url(url):
db_connection.delete_cached_url(url)
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.RES_SETTINGS)
def resolver_settings():
global urlresolver
import urlresolver
urlresolver.display_settings()
@url_dispatcher.register(MODES.ADDON_SETTINGS)
def addon_settings():
_SALTS.show_settings()
@url_dispatcher.register(MODES.BROWSE, ['section'])
def browse_menu(section):
if section==SECTIONS.TV:
section_label='TV Shows'
search_img='television_search.png'
else:
section_label='Movies'
search_img='movies_search.png'
if utils.menu_on('trending'): _SALTS.add_directory({'mode': MODES.TRENDING, 'section': section}, {'title': 'Trending %s' % (section_label)}, img=utils.art('trending.png'), fanart=utils.art('fanart.jpg'))
if utils.menu_on('popular'): _SALTS.add_directory({'mode': MODES.POPULAR, 'section': section}, {'title': 'Popular %s' % (section_label)}, img=utils.art('popular.png'), fanart=utils.art('fanart.jpg'))
if utils.menu_on('recent'): _SALTS.add_directory({'mode': MODES.RECENT, 'section': section}, {'title': 'Recently Updated %s' % (section_label)}, img=utils.art('recent.png'), fanart=utils.art('fanart.jpg'))
if TOKEN:
if utils.menu_on('recommended'): _SALTS.add_directory({'mode': MODES.RECOMMEND, 'section': section}, {'title': 'Recommended %s' % (section_label)}, img=utils.art('recommended.png'), fanart=utils.art('fanart.jpg'))
if utils.menu_on('collection'): add_refresh_item({'mode': MODES.SHOW_COLLECTION, 'section': section}, 'My %s Collection' % (section_label[:-1]), utils.art('collection.png'), utils.art('fanart.jpg'))
if utils.menu_on('favorites'): _SALTS.add_directory({'mode': MODES.SHOW_FAVORITES, 'section': section}, {'title': 'My Favorites'}, img=utils.art('my_favorites.png'), fanart=utils.art('fanart.jpg'))
if utils.menu_on('subscriptions'): _SALTS.add_directory({'mode': MODES.MANAGE_SUBS, 'section': section}, {'title': 'My Subscriptions'}, img=utils.art('my_subscriptions.png'), fanart=utils.art('fanart.jpg'))
if utils.menu_on('watchlist'): _SALTS.add_directory({'mode': MODES.SHOW_WATCHLIST, 'section': section}, {'title': 'My Watchlist'}, img=utils.art('my_watchlist.png'), fanart=utils.art('fanart.jpg'))
if utils.menu_on('my_lists'): _SALTS.add_directory({'mode': MODES.MY_LISTS, 'section': section}, {'title': 'My Lists'}, img=utils.art('my_lists.png'), fanart=utils.art('fanart.jpg'))
if utils.menu_on('other_lists'): _SALTS.add_directory({'mode': MODES.OTHER_LISTS, 'section': section}, {'title': 'Other Lists'}, img=utils.art('other_lists.png'), fanart=utils.art('fanart.jpg'))
if section==SECTIONS.TV:
if TOKEN:
if utils.menu_on('progress'): add_refresh_item({'mode': MODES.SHOW_PROGRESS}, 'My Next Episodes', utils.art('my_progress.png'), utils.art('fanart.jpg'))
if utils.menu_on('my_cal'): add_refresh_item({'mode': MODES.MY_CAL}, 'My Calendar', utils.art('my_calendar.png'), utils.art('fanart.jpg'))
if utils.menu_on('general_cal'): add_refresh_item({'mode': MODES.CAL}, 'General Calendar', utils.art('calendar.png'), utils.art('fanart.jpg'))
if utils.menu_on('premiere_cal'): add_refresh_item({'mode': MODES.PREMIERES}, 'Premiere Calendar', utils.art('premiere_calendar.png'), utils.art('fanart.jpg'))
if TOKEN:
if utils.menu_on('friends'): add_refresh_item({'mode': MODES.FRIENDS_EPISODE, 'section': section}, 'Friends Episode Activity [COLOR red][I](Temporarily Broken)[/I][/COLOR]', utils.art('friends_episode.png'), utils.art('fanart.jpg'))
if TOKEN:
if utils.menu_on('friends'): add_refresh_item({'mode': MODES.FRIENDS, 'section': section}, 'Friends Activity [COLOR red][I](Temporarily Broken)[/I][/COLOR]', utils.art('friends.png'), utils.art('fanart.jpg'))
if utils.menu_on('search'): _SALTS.add_directory({'mode': MODES.SEARCH, 'section': section}, {'title': 'Search'}, img=utils.art(search_img), fanart=utils.art('fanart.jpg'))
if utils.menu_on('search'): _SALTS.add_directory({'mode': MODES.RECENT_SEARCH, 'section': section}, {'title': 'Recent Searches'}, img=utils.art(search_img), fanart=utils.art('fanart.jpg'))
if utils.menu_on('search'): _SALTS.add_directory({'mode': MODES.SAVED_SEARCHES, 'section': section}, {'title': 'Saved Searches'}, img=utils.art(search_img), fanart=utils.art('fanart.jpg'))
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def add_refresh_item(queries, label, thumb, fanart):
liz = xbmcgui.ListItem(label, iconImage=thumb, thumbnailImage=thumb)
liz.setProperty('fanart_image', fanart)
menu_items = []
refresh_queries = {'mode': MODES.FORCE_REFRESH, 'refresh_mode': queries['mode']}
if 'section' in queries: refresh_queries.update({'section': queries['section']})
menu_items.append(('Force Refresh', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(refresh_queries))), )
liz.addContextMenuItems(menu_items)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), _SALTS.build_plugin_url(queries), liz, isFolder=True)
@url_dispatcher.register(MODES.FORCE_REFRESH, ['refresh_mode'], ['section', 'slug', 'username'])
def force_refresh(refresh_mode, section=None, slug=None, username=None):
builtin = "XBMC.Notification(%s,Forcing Refresh, 2000, %s)" % (_SALTS.get_name(), ICON_PATH)
xbmc.executebuiltin(builtin)
log_utils.log('Forcing refresh for mode: |%s|%s|%s|%s|' % (refresh_mode, section, slug, username))
now = datetime.datetime.now()
offset = int(_SALTS.get_setting('calendar-day'))
start_date = now + datetime.timedelta(days=offset)
start_date = datetime.datetime.strftime(start_date,'%Y-%m-%d')
if refresh_mode == MODES.SHOW_COLLECTION:
trakt_api.get_collection(section, cached=False)
elif refresh_mode == MODES.SHOW_PROGRESS:
get_progress(cache_override = True)
elif refresh_mode == MODES.MY_CAL:
trakt_api.get_my_calendar(start_date, cached=False)
elif refresh_mode == MODES.CAL:
trakt_api.get_calendar(start_date, cached=False)
elif refresh_mode == MODES.PREMIERES:
trakt_api.get_premieres(start_date, cached=False)
elif refresh_mode == MODES.FRIENDS_EPISODE:
trakt_api.get_friends_activity(section, True)
elif refresh_mode == MODES.FRIENDS:
trakt_api.get_friends_activity(section)
elif refresh_mode == MODES.SHOW_LIST:
trakt_api.show_list(slug, section, username, cached=False)
else:
log_utils.log('Force refresh on unsupported mode: |%s|' % (refresh_mode))
return
log_utils.log('Force refresh complete: |%s|%s|%s|%s|' % (refresh_mode, section, slug, username))
builtin = "XBMC.Notification(%s,Force Refresh Complete, 2000, %s)" % (_SALTS.get_name(), ICON_PATH)
xbmc.executebuiltin(builtin)
@url_dispatcher.register(MODES.SCRAPERS)
def scraper_settings():
scrapers=utils.relevant_scrapers(None, True, True)
if _SALTS.get_setting('toggle_enable')=='true':
label='**Enable All Scrapers**'
else:
label='**Disable All Scrapers**'
_SALTS.add_directory({'mode': MODES.TOGGLE_ALL}, {'title': label}, img=utils.art('scraper.png'), fanart=utils.art('fanart.jpg'))
for i, cls in enumerate(scrapers):
label = '%s (Provides: %s)' % (cls.get_name(), str(list(cls.provides())).replace("'", ""))
label = '%s (Success: %s%%)' % (label, utils.calculate_success(cls.get_name()))
if not utils.scraper_enabled(cls.get_name()):
label = '[COLOR darkred]%s[/COLOR]' % (label)
toggle_label='Enable Scraper'
else:
toggle_label='Disable Scraper'
liz = xbmcgui.ListItem(label=label, iconImage=utils.art('scraper.png'), thumbnailImage=utils.art('scraper.png'))
liz.setProperty('fanart_image', utils.art('fanart.jpg'))
liz.setProperty('IsPlayable', 'false')
liz.setInfo('video', {'title': label})
liz_url = _SALTS.build_plugin_url({'mode': MODES.TOGGLE_SCRAPER, 'name': cls.get_name()})
menu_items=[]
if i>0:
queries = {'mode': MODES.MOVE_SCRAPER, 'name': cls.get_name(), 'direction': DIRS.UP, 'other': scrapers[i-1].get_name()}
menu_items.append(('Move Up', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
if i<len(scrapers)-1:
queries = {'mode': MODES.MOVE_SCRAPER, 'name': cls.get_name(), 'direction': DIRS.DOWN, 'other': scrapers[i+1].get_name()}
menu_items.append(('Move Down', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries = {'mode': MODES.MOVE_TO, 'name': cls.get_name()}
menu_items.append(('Move To...', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries = {'mode': MODES.TOGGLE_SCRAPER, 'name': cls.get_name()}
menu_items.append((toggle_label, 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
liz.addContextMenuItems(menu_items, replaceItems=True)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz, isFolder=False)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.MOVE_TO, ['name'])
def move_to(name):
dialog = xbmcgui.Dialog()
sort_key = utils.make_source_sort_key()
new_pos = dialog.numeric(0, 'Enter New Position (1 - %s)' % (len(sort_key)))
if new_pos:
new_pos = int(new_pos)
old_key = sort_key[name]
new_key=-new_pos+1
if (new_pos<=0 or new_pos>len(sort_key)) or old_key==new_key:
return
for key in sort_key:
this_key = sort_key[key]
# moving scraper up
if new_key>old_key:
# move everything between the old and new down
if this_key>old_key and this_key<=new_key:
sort_key[key] -= 1
# moving scraper down
else:
# move everything between the old and new up
if this_key>new_key and this_key<=new_key:
sort_key[key] += 1
sort_key[name]=new_key
_SALTS.set_setting('source_sort_order', utils.make_source_sort_string(sort_key))
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.MOVE_SCRAPER, ['name', 'direction', 'other'])
def move_scraper(name, direction, other):
sort_key = utils.make_source_sort_key()
if direction == DIRS.UP:
sort_key[name] +=1
sort_key[other] -= 1
elif direction == DIRS.DOWN:
sort_key[name] -= 1
sort_key[other] += 1
_SALTS.set_setting('source_sort_order', utils.make_source_sort_string(sort_key))
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.TOGGLE_ALL)
def toggle_scrapers():
cur_toggle = _SALTS.get_setting('toggle_enable')
scrapers=utils.relevant_scrapers(None, True, True)
for scraper in scrapers:
_SALTS.set_setting('%s-enable' % (scraper.get_name()), cur_toggle)
new_toggle = 'false' if cur_toggle=='true' else 'true'
_SALTS.set_setting('toggle_enable', new_toggle)
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.TOGGLE_SCRAPER, ['name'])
def toggle_scraper(name):
if utils.scraper_enabled(name):
setting='false'
else:
setting='true'
_SALTS.set_setting('%s-enable' % (name), setting)
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.TRENDING, ['section'], ['page'])
def browse_trending(section, page = 1):
list_data = trakt_api.get_trending(section, page)
make_dir_from_list(section, list_data, query = {'mode': MODES.TRENDING, 'section': section}, page = page)
@url_dispatcher.register(MODES.POPULAR, ['section'], ['page'])
def browse_popular(section, page = 1):
list_data = trakt_api.get_popular(section, page)
make_dir_from_list(section, list_data, query = {'mode': MODES.POPULAR, 'section': section}, page = page)
@url_dispatcher.register(MODES.RECENT, ['section'], ['page'])
def browse_recent(section, page = 1):
now = datetime.datetime.now()
start_date = now - datetime.timedelta(days=7)
start_date = datetime.datetime.strftime(start_date,'%Y-%m-%d')
list_data = trakt_api.get_recent(section, start_date, page)
make_dir_from_list(section, list_data, query = {'mode': MODES.RECENT, 'section': section}, page = page)
@url_dispatcher.register(MODES.RECOMMEND, ['section'])
def browse_recommendations(section):
list_data = trakt_api.get_recommendations(section)
make_dir_from_list(section, list_data)
@url_dispatcher.register(MODES.FRIENDS, ['mode', 'section'])
@url_dispatcher.register(MODES.FRIENDS_EPISODE, ['mode', 'section'])
def browse_friends(mode, section):
section_params=utils.get_section_params(section)
activities=trakt_api.get_friends_activity(section, mode==MODES.FRIENDS_EPISODE)
totalItems=len(activities)
for activity in activities['activity']:
if 'episode' in activity:
show=activity['show']
liz, liz_url = make_episode_item(show, activity['episode'], show_subs=False)
folder=(liz.getProperty('isPlayable')!='true')
label=liz.getLabel()
label = '%s (%s) - %s' % (show['title'], show['year'], label.decode('utf-8', 'replace'))
liz.setLabel(label)
else:
liz, liz_url = make_item(section_params, activity[TRAKT_SECTIONS[section][:-1]])
folder = section_params['folder']
label=liz.getLabel()
action = ' [[COLOR blue]%s[/COLOR] [COLOR green]%s' % (activity['user']['username'], activity['action'])
if activity['action']=='rating': action += ' - %s' % (activity['rating'])
action += '[/COLOR]]'
label = '%s %s' % (action, label.decode('utf-8', 'replace'))
liz.setLabel(label)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz,isFolder=folder,totalItems=totalItems)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.MY_CAL, ['mode'], ['start_date'])
@url_dispatcher.register(MODES.CAL, ['mode'], ['start_date'])
@url_dispatcher.register(MODES.PREMIERES, ['mode'], ['start_date'])
def browse_calendar(mode, start_date=None):
if start_date is None:
now = datetime.datetime.now()
offset = int(_SALTS.get_setting('calendar-day'))
start_date = now + datetime.timedelta(days=offset)
start_date = datetime.datetime.strftime(start_date,'%Y-%m-%d')
if mode == MODES.MY_CAL:
days=trakt_api.get_my_calendar(start_date)
elif mode == MODES.CAL:
days=trakt_api.get_calendar(start_date)
elif mode == MODES.PREMIERES:
days=trakt_api.get_premieres(start_date)
make_dir_from_cal(mode, start_date, days)
@url_dispatcher.register(MODES.MY_LISTS, ['section'])
def browse_lists(section):
lists = trakt_api.get_lists()
lists.insert(0, {'name': 'watchlist', 'ids': {'slug': utils.WATCHLIST_SLUG}})
totalItems=len(lists)
for user_list in lists:
ids = user_list['ids']
liz = xbmcgui.ListItem(label=user_list['name'], iconImage=utils.art('list.png'), thumbnailImage=utils.art('list.png'))
liz.setProperty('fanart_image', utils.art('fanart.jpg'))
queries = {'mode': MODES.SHOW_LIST, 'section': section, 'slug': ids['slug']}
liz_url = _SALTS.build_plugin_url(queries)
menu_items=[]
queries={'mode': MODES.SET_FAV_LIST, 'slug': ids['slug'], 'section': section}
menu_items.append(('Set as Favorites List', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries={'mode': MODES.SET_SUB_LIST, 'slug': ids['slug'], 'section': section}
menu_items.append(('Set as Subscription List', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries={'mode': MODES.COPY_LIST, 'slug': COLLECTION_SLUG, 'section': section, 'target_slug': ids['slug']}
menu_items.append(('Import from Collection', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
liz.addContextMenuItems(menu_items, replaceItems=True)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz,isFolder=True,totalItems=totalItems)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.OTHER_LISTS, ['section'])
def browse_other_lists(section):
liz = xbmcgui.ListItem(label='Add another user\'s list', iconImage=utils.art('add_other.png'), thumbnailImage=utils.art('add_other.png'))
liz.setProperty('fanart_image', utils.art('fanart.jpg'))
liz_url = _SALTS.build_plugin_url({'mode': MODES.ADD_OTHER_LIST, 'section': section})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz, isFolder=False)
lists = db_connection.get_other_lists(section)
totalItems=len(lists)
for other_list in lists:
try:
header = trakt_api.get_list_header(other_list[1], other_list[0])
except urllib2.HTTPError as e:
if e.code == 404:
header = None
else:
raise
if header:
found=True
if other_list[2]:
name=other_list[2]
else:
name=header['name']
else:
name = other_list[1]
found=False
label = '[[COLOR blue]%s[/COLOR]] %s' % (other_list[0], name)
liz = xbmcgui.ListItem(label=label, iconImage=utils.art('list.png'), thumbnailImage=utils.art('list.png'))
liz.setProperty('fanart_image', utils.art('fanart.jpg'))
if found:
queries = {'mode': MODES.SHOW_LIST, 'section': section, 'slug': other_list[1], 'username': other_list[0]}
else:
queries = {'mode': MODES.OTHER_LISTS, 'section': section}
liz_url = _SALTS.build_plugin_url(queries)
menu_items=[]
if found:
queries = {'mode': MODES.FORCE_REFRESH, 'refresh_mode': MODES.SHOW_LIST, 'section': section, 'slug': other_list[1], 'username': other_list[0]}
menu_items.append(('Force Refresh', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries={'mode': MODES.COPY_LIST, 'section': section, 'slug': other_list[1], 'username': other_list[0]}
menu_items.append(('Copy to My List', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries={'mode': MODES.ADD_OTHER_LIST, 'section': section, 'username': other_list[0]}
menu_items.append(('Add more from %s' % (other_list[0]), 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries={'mode': MODES.REMOVE_LIST, 'section': section, 'slug': other_list[1], 'username': other_list[0]}
menu_items.append(('Remove List', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
queries={'mode': MODES.RENAME_LIST, 'section': section, 'slug': other_list[1], 'username': other_list[0], 'name': name}
menu_items.append(('Rename List', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(queries))), )
liz.addContextMenuItems(menu_items, replaceItems=True)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz,isFolder=True,totalItems=totalItems)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.REMOVE_LIST, ['section', 'username', 'slug'])
def remove_list(section, username, slug):
db_connection.delete_other_list(section, username, slug)
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.RENAME_LIST, ['section', 'slug', 'username', 'name'])
def rename_list(section, slug, username, name):
keyboard = xbmc.Keyboard()
keyboard.setHeading('Enter the new name (blank to reset)')
keyboard.setDefault(name)
keyboard.doModal()
if keyboard.isConfirmed():
new_name=keyboard.getText()
db_connection.rename_other_list(section, username, slug, new_name)
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.ADD_OTHER_LIST, ['section'], ['username'])
def add_other_list(section, username=None):
if username is None:
keyboard = xbmc.Keyboard()
keyboard.setHeading('Enter username of list owner')
keyboard.doModal()
if keyboard.isConfirmed():
username=keyboard.getText()
slug=pick_list(None, section, username)
if slug:
db_connection.add_other_list(section, username, slug)
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.SHOW_LIST, ['section', 'slug'], ['username'])
def show_list(section, slug, username=None):
if slug == utils.WATCHLIST_SLUG:
items = trakt_api.show_watchlist(section)
else:
items = trakt_api.show_list(slug, section, username)
make_dir_from_list(section, items, slug)
@url_dispatcher.register(MODES.SHOW_WATCHLIST, ['section'])
def show_watchlist(section):
show_list(section, utils.WATCHLIST_SLUG)
@url_dispatcher.register(MODES.SHOW_COLLECTION, ['section'])
def show_collection(section):
items = trakt_api.get_collection(section, cached=_SALTS.get_setting('cache_collection')=='true')
sort_key = int(_SALTS.get_setting('sort_collection'))
if sort_key == 1:
items.reverse()
elif sort_key > 0:
items.sort(key=lambda x:x[['title', 'year'][sort_key - 2]])
make_dir_from_list(section, items, COLLECTION_SLUG)
def get_progress(cache_override=False):
cached = _SALTS.get_setting('cache_watched') =='true' and not cache_override
max_progress = int(_SALTS.get_setting('progress_size'))
watched_list = trakt_api.get_watched(SECTIONS.TV, full=True, cached = cached)
episodes = []
for i, watched in enumerate(watched_list):
if i != 0 and i >= max_progress:
break
progress = trakt_api.get_show_progress(watched['show']['ids']['slug'], full=True, cached = cached)
if 'next_episode' in progress and progress['next_episode']:
episode = {'show': watched['show'], 'episode': progress['next_episode']}
episode['last_watched_at']=watched['last_watched_at']
episode['percent_completed'] = (progress['completed'] * 100) / progress['aired'] if progress['aired']>0 else 0
episode['completed']=progress['completed']
episodes.append(episode)
return utils.sort_progress(episodes, sort_order=SORT_MAP[int(_SALTS.get_setting('sort_progress'))])
@url_dispatcher.register(MODES.SHOW_PROGRESS)
def show_progress():
for episode in get_progress():
log_utils.log('Episode: Sort Keys: Tile: |%s| Last Watched: |%s| Percent: |%s%%| Completed: |%s|' % (episode['show']['title'], episode['last_watched_at'], episode['percent_completed'], episode['completed']), xbmc.LOGDEBUG)
first_aired_utc = utils.iso_2_utc(episode['episode']['first_aired'])
if _SALTS.get_setting('show_unaired_next')=='true' or first_aired_utc <=time.time():
show=episode['show']
fanart=show['images']['fanart']['full']
date=utils.make_day(time.strftime('%Y-%m-%d', time.localtime(first_aired_utc)))
menu_items=[]
queries = {'mode': MODES.SEASONS, 'slug': show['ids']['slug'], 'fanart': fanart}
menu_items.append(('Browse Seasons', 'Container.Update(%s)' % (_SALTS.build_plugin_url(queries))), )
liz, liz_url = make_episode_item(show, episode['episode'], menu_items=menu_items)
label=liz.getLabel()
label = '[[COLOR deeppink]%s[/COLOR]] %s - %s' % (date, show['title'], label.decode('utf-8', 'replace'))
liz.setLabel(label)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz,isFolder=(liz.getProperty('isPlayable')!='true'))
xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=False)
@url_dispatcher.register(MODES.MANAGE_SUBS, ['section'])
def manage_subscriptions(section):
slug=_SALTS.get_setting('%s_sub_slug' % (section))
if slug:
next_run = utils.get_next_run(MODES.UPDATE_SUBS)
label = 'Update Subscriptions: (Next Run: [COLOR %s]%s[/COLOR])'
if _SALTS.get_setting('auto-'+MODES.UPDATE_SUBS) == 'true':
color = 'green'
run_str = next_run.strftime("%Y-%m-%d %I:%M:%S %p")
else:
color = 'red'
run_str = 'DISABLED'
label = label % (color, run_str)
liz = xbmcgui.ListItem(label=label, iconImage=utils.art('update_subscriptions.png'), thumbnailImage=utils.art('update_subscriptions.png'))
liz.setProperty('fanart_image', utils.art('fanart.jpg'))
liz_url = _SALTS.build_plugin_url({'mode': MODES.UPDATE_SUBS, 'section': section})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz, isFolder=False)
if section == SECTIONS.TV:
liz = xbmcgui.ListItem(label='Clean-Up Subscriptions', iconImage=utils.art('clean_up.png'), thumbnailImage=utils.art('clean_up.png'))
liz.setProperty('fanart_image', utils.art('fanart.jpg'))
liz_url = _SALTS.build_plugin_url({'mode': MODES.CLEAN_SUBS})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz, isFolder=False)
show_pickable_list(slug, 'Pick a list to use for Subscriptions', MODES.PICK_SUB_LIST, section)
@url_dispatcher.register(MODES.SHOW_FAVORITES, ['section'])
def show_favorites(section):
slug=_SALTS.get_setting('%s_fav_slug' % (section))
show_pickable_list(slug, 'Pick a list to use for Favorites', MODES.PICK_FAV_LIST, section)
@url_dispatcher.register(MODES.PICK_SUB_LIST, ['mode', 'section'])
@url_dispatcher.register(MODES.PICK_FAV_LIST, ['mode', 'section'])
def pick_list(mode, section, username=None):
slug=utils.choose_list(username)
if slug:
if mode == MODES.PICK_FAV_LIST:
set_list(MODES.SET_FAV_LIST, slug, section)
elif mode == MODES.PICK_SUB_LIST:
set_list(MODES.SET_SUB_LIST, slug, section)
else:
return slug
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.SET_SUB_LIST, ['mode', 'slug', 'section'])
@url_dispatcher.register(MODES.SET_FAV_LIST, ['mode', 'slug', 'section'])
def set_list(mode, slug, section):
if mode == MODES.SET_FAV_LIST:
setting='%s_fav_slug' % (section)
elif mode == MODES.SET_SUB_LIST:
setting='%s_sub_slug' % (section)
_SALTS.set_setting(setting, slug)
@url_dispatcher.register(MODES.SEARCH, ['section'])
def search(section, search_text=None):
keyboard = xbmc.Keyboard()
keyboard.setHeading('Search %s' % (section))
while True:
keyboard.doModal()
if keyboard.isConfirmed():
search_text = keyboard.getText()
if not search_text:
msg = 'Blank Searches are not allowed'
builtin = 'XBMC.Notification(%s,%s, 5000, %s)'
xbmc.executebuiltin(builtin % (_SALTS.get_name(), msg, ICON_PATH))
return
else:
break
else:
break
if keyboard.isConfirmed():
search_text = keyboard.getText()
utils.keep_search(section, search_text)
queries = {'mode': MODES.SEARCH_RESULTS, 'section': section, 'query': search_text}
pluginurl = _SALTS.build_plugin_url(queries)
builtin = 'Container.Update(%s)' %(pluginurl)
xbmc.executebuiltin(builtin)
@url_dispatcher.register(MODES.RECENT_SEARCH, ['section'])
def recent_searches(section):
if section==SECTIONS.TV:
search_img='television_search.png'
else:
search_img='movies_search.png'
head = int(_SALTS.get_setting('%s_search_head' % (section)))
for i in reversed(range(0,SEARCH_HISTORY)):
index = (i + head + 1) % SEARCH_HISTORY
search_text =db_connection.get_setting('%s_search_%s' % (section, index))
if not search_text:
break
label = '[%s Search] %s' % (section, search_text)
liz = xbmcgui.ListItem(label=label, iconImage=utils.art(search_img), thumbnailImage=utils.art(search_img))
liz.setProperty('fanart_image', utils.art('fanart.png'))
menu_items = []
refresh_queries = {'mode': MODES.SAVE_SEARCH, 'section': section, 'query': search_text}
menu_items.append(('Save Search', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(refresh_queries))), )
liz.addContextMenuItems(menu_items)
queries = {'mode': MODES.SEARCH_RESULTS, 'section': section, 'query': search_text}
xbmcplugin.addDirectoryItem(int(sys.argv[1]), _SALTS.build_plugin_url(queries), liz, isFolder=True)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.SAVED_SEARCHES, ['section'])
def saved_searches(section):
if section==SECTIONS.TV:
search_img='television_search.png'
else:
search_img='movies_search.png'
for search in db_connection.get_searches(section, order_matters=True):
label = '[%s Search] %s' % (section, search[1])
liz = xbmcgui.ListItem(label=label, iconImage=utils.art(search_img), thumbnailImage=utils.art(search_img))
liz.setProperty('fanart_image', utils.art('fanart.png'))
menu_items = []
refresh_queries = {'mode': MODES.DELETE_SEARCH, 'search_id': search[0]}
menu_items.append(('Delete Search', 'RunPlugin(%s)' % (_SALTS.build_plugin_url(refresh_queries))), )
liz.addContextMenuItems(menu_items)
queries = {'mode': MODES.SEARCH_RESULTS, 'section': section, 'query': search[1]}
xbmcplugin.addDirectoryItem(int(sys.argv[1]), _SALTS.build_plugin_url(queries), liz, isFolder=True)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.SAVE_SEARCH, ['section', 'query'])
def save_search(section, query):
db_connection.save_search(section, query)
@url_dispatcher.register(MODES.DELETE_SEARCH, ['search_id'])
def delete_search(search_id):
db_connection.delete_search(search_id)
xbmc.executebuiltin("XBMC.Container.Refresh")
@url_dispatcher.register(MODES.SEARCH_RESULTS, ['section', 'query'], ['page'])
def search_results(section, query, page = 1):
results = trakt_api.search(section, query, page)
make_dir_from_list(section, results, query = {'mode': MODES.SEARCH_RESULTS, 'section': section, 'query': query}, page = page)
@url_dispatcher.register(MODES.SEASONS, ['slug', 'fanart'])
def browse_seasons(slug, fanart):
seasons=trakt_api.get_seasons(slug)
info={}
if TOKEN:
progress = trakt_api.get_show_progress(slug, cached=_SALTS.get_setting('cache_watched')=='true')
info = utils.make_seasons_info(progress)
totalItems=len(seasons)
for season in seasons:
if _SALTS.get_setting('show_season0') == 'true' or season['number'] != 0:
liz=make_season_item(season, info.get(str(season['number']), {'season': season['number']}), slug, fanart)
queries = {'mode': MODES.EPISODES, 'slug': slug, 'season': season['number']}
liz_url = _SALTS.build_plugin_url(queries)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz,isFolder=True,totalItems=totalItems)
utils.set_view(CONTENT_TYPES.SEASONS, False)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.EPISODES, ['slug', 'season'])
def browse_episodes(slug, season):
show=trakt_api.get_show_details(slug)
episodes=trakt_api.get_episodes(slug, season)
if TOKEN:
progress = trakt_api.get_show_progress(slug, cached=_SALTS.get_setting('cache_watched')=='true')
episodes = utils.make_episodes_watched(episodes, progress)
totalItems=len(episodes)
now=time.time()
for episode in episodes:
utc_air_time = utils.iso_2_utc(episode['first_aired'])
if _SALTS.get_setting('show_unaired')=='true' or utc_air_time <= now:
if _SALTS.get_setting('show_unknown')=='true' or utc_air_time:
liz, liz_url =make_episode_item(show, episode)
xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, liz,isFolder=(liz.getProperty('isPlayable')!='true'),totalItems=totalItems)
utils.set_view(CONTENT_TYPES.EPISODES, False)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
@url_dispatcher.register(MODES.GET_SOURCES, ['mode', 'video_type', 'title', 'year', 'slug'], ['season', 'episode', 'ep_title', 'dialog'])
@url_dispatcher.register(MODES.SELECT_SOURCE, ['mode', 'video_type', 'title', 'year', 'slug'], ['season', 'episode', 'ep_title'])
@url_dispatcher.register(MODES.DOWNLOAD_SOURCE, ['mode', 'video_type', 'title', 'year', 'slug'], ['season', 'episode', 'ep_title'])
def get_sources(mode, video_type, title, year, slug, season='', episode='', ep_title='', dialog=None):
timeout = max_timeout = int(_SALTS.get_setting('source_timeout'))
if max_timeout == 0: timeout=None
max_results = int(_SALTS.get_setting('source_results'))
worker_count=0
hosters=[]
workers=[]
video=ScraperVideo(video_type, title, year, slug, season, episode, ep_title)
if utils.P_MODE != P_MODES.NONE: q = utils.Queue()
begin = time.time()
fails={}
got_timeouts = False
for cls in utils.relevant_scrapers(video_type):
if utils.P_MODE == P_MODES.NONE:
hosters += cls(max_timeout).get_sources(video)
if max_results> 0 and len(hosters) >= max_results:
break
else:
worker=utils.start_worker(q, utils.parallel_get_sources, [cls, video])
utils.increment_setting('%s_try' % (cls.get_name()))
worker_count+=1
workers.append(worker)
fails[cls.get_name()]=True
# collect results from workers
if utils.P_MODE != P_MODES.NONE:
while worker_count>0:
try:
log_utils.log('Calling get with timeout: %s' %(timeout), xbmc.LOGDEBUG)
result = q.get(True, timeout)
log_utils.log('Got %s Source Results' %(len(result['hosters'])), xbmc.LOGDEBUG)
worker_count -=1
hosters += result['hosters']
del fails[result['name']]
if max_timeout>0:
timeout = max_timeout - (time.time() - begin)
if timeout<0: timeout=0
except utils.Empty:
log_utils.log('Get Sources Process Timeout', xbmc.LOGWARNING)
utils.record_timeouts(fails)
got_timeouts=True
break
if max_results> 0 and len(hosters) >= max_results:
log_utils.log('Exceeded max results: %s/%s' % (max_results, len(hosters)))
break
else:
got_timeouts = False
log_utils.log('All source results received')
total = len(workers)
timeouts = len(fails)
workers=utils.reap_workers(workers)
try:
timeout_msg = 'Scraper Timeouts: %s/%s' % (timeouts, total) if got_timeouts and timeouts else ''
if not hosters:
log_utils.log('No Sources found for: |%s|' % (video))
msg = ' (%s)' % timeout_msg if timeout_msg else ''
builtin = 'XBMC.Notification(%s,No Sources Found%s, 5000, %s)'
xbmc.executebuiltin(builtin % (_SALTS.get_name(), msg, ICON_PATH))
return False
if timeout_msg:
builtin = 'XBMC.Notification(%s,%s, 5000, %s)'
xbmc.executebuiltin(builtin % (_SALTS.get_name(), timeout_msg, ICON_PATH))
hosters = utils.filter_exclusions(hosters)
hosters = utils.filter_quality(video_type, hosters)
if _SALTS.get_setting('enable_sort')=='true':
if _SALTS.get_setting('filter-unknown')=='true':
hosters = utils.filter_unknown_hosters(hosters)
SORT_KEYS['source'] = utils.make_source_sort_key()
hosters.sort(key = utils.get_sort_key)
global urlresolver
import urlresolver
hosters = filter_unusable_hosters(hosters)
if not hosters:
log_utils.log('No Useable Sources found for: |%s|' % (video))
msg = ' (%s)' % timeout_msg if timeout_msg else ''
builtin = 'XBMC.Notification(%s,No Useable Sources Found%s, 5000, %s)'
xbmc.executebuiltin(builtin % (_SALTS.get_name(), msg, ICON_PATH))
return False
pseudo_tv = xbmcgui.Window(10000).getProperty('PseudoTVRunning')
if pseudo_tv=='True' or (mode == MODES.GET_SOURCES and _SALTS.get_setting('auto-play')=='true'):
auto_play_sources(hosters, video_type, slug, season, episode)
else:
if dialog or (dialog is None and _SALTS.get_setting('source-win') == 'Dialog'):
stream_url = pick_source_dialog(hosters)
return play_source(mode, stream_url, video_type, slug, season, episode)
else:
pick_source_dir(mode, hosters, video_type, slug, season, episode)
finally:
utils.reap_workers(workers, None)
def filter_unusable_hosters(hosters):
filtered_hosters=[]
filter_max = int(_SALTS.get_setting('filter_unusable'))
for i, hoster in enumerate(hosters):
if i<filter_max and 'direct' in hoster and hoster['direct']==False:
hmf = urlresolver.HostedMediaFile(host=hoster['host'], media_id='dummy') # use dummy media_id to force host validation
if not hmf:
log_utils.log('Unusable source %s (%s) from %s' % (hoster['url'], hoster['host'], hoster['class'].get_name()), xbmc.LOGINFO)
continue
filtered_hosters.append(hoster)
return filtered_hosters
@url_dispatcher.register(MODES.RESOLVE_SOURCE, ['mode', 'class_url', 'video_type', 'slug', 'class_name'], ['season', 'episode'])
@url_dispatcher.register(MODES.DIRECT_DOWNLOAD, ['mode', 'class_url', 'video_type', 'slug', 'class_name'], ['season', 'episode'])
def resolve_source(mode, class_url, video_type, slug, class_name, season='', episode=''):
for cls in utils.relevant_scrapers(video_type):
if cls.get_name() == class_name:
scraper_instance=cls()
break
else:
log_utils.log('Unable to locate scraper with name: %s' % (class_name))
return False
hoster_url = scraper_instance.resolve_link(class_url)
if mode == MODES.DIRECT_DOWNLOAD:
_SALTS.end_of_directory()
return play_source(mode, hoster_url, video_type, slug, season, episode)
@url_dispatcher.register(MODES.PLAY_TRAILER,['stream_url'])
def play_trailer(stream_url):
xbmc.Player().play(stream_url)
def download_subtitles(language, title, year, season, episode):
srt_scraper=SRT_Scraper()
tvshow_id=srt_scraper.get_tvshow_id(title, year)
if tvshow_id is None:
return
subs=srt_scraper.get_episode_subtitles(language, tvshow_id, season, episode)
sub_labels=[]
for sub in subs:
sub_labels.append(utils.format_sub_label(sub))
index=0
if len(sub_labels)>1:
dialog = xbmcgui.Dialog()
index = dialog.select('Choose a subtitle to download', sub_labels)
if subs and index > -1:
return srt_scraper.download_subtitle(subs[index]['url'])
def play_source(mode, hoster_url, video_type, slug, season='', episode=''):
global urlresolver
import urlresolver
if hoster_url is None:
return False
hmf = urlresolver.HostedMediaFile(url=hoster_url)
if not hmf:
log_utils.log('hoster_url not supported by urlresolver: %s' % (hoster_url))
stream_url = hoster_url
else:
stream_url = hmf.resolve()
if not stream_url or not isinstance(stream_url, basestring):
# commenting out as it hides urlresolver notifications
#builtin = 'XBMC.Notification(%s,Could not Resolve Url: %s, 5000, %s)'
#xbmc.executebuiltin(builtin % (_SALTS.get_name(), hoster_url, ICON_PATH))
return False
resume_point = 0
if mode not in [MODES.DOWNLOAD_SOURCE, MODES.DIRECT_DOWNLOAD]:
if utils.bookmark_exists(slug, season, episode):
if utils.get_resume_choice(slug, season, episode):
resume_point = utils.get_bookmark(slug, season, episode)
log_utils.log('Resume Point: %s' % (resume_point), xbmc.LOGDEBUG)
try:
win = xbmcgui.Window(10000)
win.setProperty('salts.playing', 'True')
win.setProperty('salts.playing.slug', slug)
win.setProperty('salts.playing.season', str(season))
win.setProperty('salts.playing.episode', str(episode))
if _SALTS.get_setting('trakt_bookmark')=='true':
win.setProperty('salts.playing.trakt_resume', str(resume_point))
art={'thumb': '', 'fanart': ''}
info={}
if video_type == VIDEO_TYPES.EPISODE:
path = _SALTS.get_setting('tv-download-folder')
file_name = utils.filename_from_title(slug, VIDEO_TYPES.TVSHOW)
file_name = file_name % ('%02d' % int(season), '%02d' % int(episode))
ep_meta = trakt_api.get_episode_details(slug, season, episode)
show_meta = trakt_api.get_show_details(slug)
people = trakt_api.get_people(SECTIONS.TV, slug) if _SALTS.get_setting('include_people')=='true' else None
info = utils.make_info(ep_meta, show_meta, people)
images={}
images['images']=show_meta['images']
images['images'].update(ep_meta['images'])
art=utils.make_art(images)
path = make_path(path, VIDEO_TYPES.TVSHOW, show_meta['title'], season=season)
file_name = utils.filename_from_title(show_meta['title'], VIDEO_TYPES.TVSHOW)
file_name = file_name % ('%02d' % int(season), '%02d' % int(episode))
else:
path = _SALTS.get_setting('movie-download-folder')
file_name = utils.filename_from_title(slug, video_type)
item = trakt_api.get_movie_details(slug)
people = trakt_api.get_people(SECTIONS.MOVIES, slug) if _SALTS.get_setting('include_people')=='true' else None
info = utils.make_info(item, people=people)
art=utils.make_art(item)
path = make_path(path, video_type, item['title'], item['year'])
file_name = utils.filename_from_title(item['title'], video_type, item['year'])
except TransientTraktError as e:
log_utils.log('During Playback: %s' % (str(e)), xbmc.LOGWARNING) # just log warning if trakt calls fail and leave meta and art blank
if mode in [MODES.DOWNLOAD_SOURCE, MODES.DIRECT_DOWNLOAD]:
utils.download_media(stream_url, path, file_name)
return True
if video_type == VIDEO_TYPES.EPISODE and utils.srt_download_enabled():
srt_path = download_subtitles(_SALTS.get_setting('subtitle-lang'), show_meta['title'], show_meta['year'], season, episode)
if utils.srt_show_enabled() and srt_path:
log_utils.log('Setting srt path: %s' % (srt_path), xbmc.LOGDEBUG)
win.setProperty('salts.playing.srt', srt_path)
listitem = xbmcgui.ListItem(path=stream_url, iconImage=art['thumb'], thumbnailImage=art['thumb'])
if _SALTS.get_setting('trakt_bookmark')!='true':
listitem.setProperty('ResumeTime', str(resume_point))
listitem.setProperty('Totaltime', str(99999)) # dummy value to force resume to work
listitem.setProperty('fanart_image', art['fanart'])
try: listitem.setArt(art)
except:pass
listitem.setProperty('IsPlayable', 'true')
listitem.setPath(stream_url)
listitem.setInfo('video', info)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
return True
def auto_play_sources(hosters, video_type, slug, season, episode):
for item in hosters:
if item['multi-part']:
continue
hoster_url=item['class'].resolve_link(item['url'])
log_utils.log('Auto Playing: %s' % (hoster_url), xbmc.LOGDEBUG)
if play_source(MODES.GET_SOURCES, hoster_url, video_type, slug, season, episode):
return True
else:
msg = 'All sources failed to play'
log_utils.log(msg, xbmc.LOGERROR)
builtin = 'XBMC.Notification(%s,%s, 5000, %s)'
xbmc.executebuiltin(builtin % (_SALTS.get_name(), msg, ICON_PATH))
def pick_source_dialog(hosters):
for item in hosters:
if item['multi-part']:
continue
label = item['class'].format_source_label(item)
label = '[%s] %s' % (item['class'].get_name(),label)
item['label']=label
dialog = xbmcgui.Dialog()
index = dialog.select('Choose your stream', [item['label'] for item in hosters if 'label' in item])
if index>-1:
try:
if hosters[index]['url']:
hoster_url=hosters[index]['class'].resolve_link(hosters[index]['url'])
log_utils.log('Attempting to play url: %s' % hoster_url)
return hoster_url
except Exception as e:
log_utils.log('Error (%s) while trying to resolve %s' % (str(e), hosters[index]['url']), xbmc.LOGERROR)
def pick_source_dir(mode, hosters, video_type, slug, season='', episode=''):