-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnakamori.py
1864 lines (1654 loc) · 79.8 KB
/
nakamori.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import resources.lib.TagBlacklist as TagFilter
import resources.lib.util as util
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
from resources.lib.util import *
from collections import defaultdict
from distutils.version import LooseVersion
try:
import pydevd
except ImportError:
pass
handle = int(sys.argv[1])
__addon__ = xbmcaddon.Addon(id='plugin.video.nakamori-legacy')
__addonversion__ = __addon__.getAddonInfo('version')
__addonid__ = __addon__.getAddonInfo('id')
def valid_user():
"""
Logs into the server and stores the apikey, then checks if the userid is valid
:return: bool True if all completes successfully
"""
version = get_version()
if version == 'legacy' or version == '3.6.1.0':
return valid_userid()
# reset apikey if user enters new login info
if __addon__.getSetting("apikey") != "" and __addon__.getSetting("login") == "":
# ignore what we put in for userid, the api sets it
set_userid()
return valid_userid()
else:
xbmc.log('-- apikey empty --')
# password can be empty as JMM Default account have blank password
try:
if __addon__.getSetting("login") != "" and __addon__.getSetting("device") != "":
body = '{"user":"' + __addon__.getSetting("login") + '",' + \
'"device":"' + __addon__.getSetting("device") + '",' + \
'"pass":"' + __addon__.getSetting("password") + '"}'
postd = post_data("http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port") +
"/api/auth", body)
auth = json.loads(postd)
if "apikey" in auth:
xbmc.log('-- save apikey and reset user credentials --')
__addon__.setSetting(id='apikey', value=str(auth["apikey"]))
__addon__.setSetting(id='login', value='')
__addon__.setSetting(id='password', value='')
set_userid()
return valid_userid()
else:
raise Exception('Error Getting apikey')
else:
xbmc.log('-- Login and Device Empty --')
return False
except Exception as exc:
error('Error in Valid_User', str(exc))
return False
def set_userid():
"""
Set userid that is assign to current user via jmm3.7+ api
Returns: bool True if set assign was successful
"""
uid = json.loads(get_json("http://" + __addon__.getSetting("ipaddress") + ":" +
__addon__.getSetting("port") + "/api/myid/get"))
if "userid" in uid:
__addon__.setSetting(id='userid', value=str(uid['userid']))
return True
else:
return False
def valid_userid():
"""
Checks if the set userid is valid
Returns: bool True if valid
"""
xml_file = get_xml("http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port") +
"/jmmserverkodi/getusers")
if xml_file is not None:
data = xml(xml_file)
for user_data in data.findall('User'):
user_id = user_data.get('id', '')
if user_id == __addon__.getSetting("userid"):
return True
return False
return False
def refresh():
"""
Refresh and re-request data from server
"""
# refresh watch status as we now mark episode and refresh list so it show real status not kodi_cached
xbmc.executebuiltin('Container.Refresh')
# Allow time for the ui to reload (this may need to be tweaked, I am running on localhost)
xbmc.sleep(int(__addon__.getSetting('refresh_wait')))
# use episode number for position
def move_position_on_list(control_list, position=0):
"""
Move to the position in a list
Args:
control_list: the list control
position: the index of the item not including settings
"""
if position < 0:
position = 0
if __addon__.getSetting('show_continue') == 'true':
position = int(position + 1)
if get_kodi_setting_bool("filelists.showparentdiritems"):
position = int(position + 1)
try:
control_list.selectItem(position)
except:
try:
control_list.selectItem(position - 1)
except Exception as e:
error('Unable to reselect item', str(e))
xbmc.log('control_list: ' + str(control_list.getId()), xbmc.LOGWARNING)
xbmc.log('position: ' + str(position), xbmc.LOGWARNING)
def set_window_heading(var_tree):
"""
Sets the window titles
Args:
var_tree: details dict
"""
window_obj = xbmcgui.Window(xbmcgui.getCurrentWindowId())
try:
window_obj.setProperty("heading", var_tree.get('title1'))
except Exception as e:
error('set_window_heading Exception', str(e))
window_obj.clearProperty("heading")
try:
window_obj.setProperty("heading2", var_tree.get('title2'))
except Exception as e:
error('set_window_heading2 Exception', str(e))
window_obj.clearProperty("heading2")
def filter_gui_item_by_tag(title):
"""
Remove list items from the tag group filter by the tag blacklist in settings
Args:
title: the title of the list item
Returns: Whether or not to remove it (true is yes)
:rtype: bool
"""
str1 = [title]
str1 = TagFilter.processTags(__addon__, str1)
return len(str1) > 0
def add_gui_item(url, details, extra_data, context=None, folder=True, index=0):
"""Adds an item to the menu and populates its info labels
:param url:The URL of the menu or file this item links to
:param details:Data such as info labels
:param extra_data:Data such as stream info
:param context:The context menu
:param folder:Is it a folder or file
:param index:Index in the list
:type url:str
:type details:Union[str,object]
:type extra_data:Union[str,object]
:type context:
:type folder:bool
:type index:int
:rtype:bool
:return: Did the item successfully add
"""
try:
tbi = ""
tp = 'Video'
link_url = ""
# handle short urls to work with seriesid and epid
if extra_data.get('key', '') != '':
url_in = str(extra_data.get('key'))
if folder:
if not url_in.lower().startswith("http://" + __addon__.getSetting("ipaddress") + ":" +
__addon__.getSetting("port")):
if url_in.lower().startswith('/jmmserverkodi'):
extra_data['key'] = "http://" + __addon__.getSetting("ipaddress") + ":" + \
__addon__.getSetting("port") + url_in
# do this before so it'll log
# use the year as a fallback in case the date is unavailable
if details.get('date', '') == '':
if details.get('year', '') != '' and details['year'] != 0:
details['date'] = '01.01.' + str(details['year'])
details['aired'] = details['date']
# details['aired'] = str(details['year'])+'-01-01'
if __addon__.getSetting("spamLog") == 'true':
xbmc.log("add_gui_item - url: " + url, xbmc.LOGWARNING)
if details is not None:
xbmc.log("add_gui_item - details", xbmc.LOGWARNING)
for i in details:
temp_log = ""
a = details.get(encode(i))
if a is None:
temp_log = "\'unset\'"
elif isinstance(a, list) or isinstance(a, dict):
for b in a:
temp_log = str(b) if temp_log == "" else temp_log + " | " + str(b)
else:
temp_log = str(a)
xbmc.log("-" + str(i) + "- " + temp_log, xbmc.LOGWARNING)
if extra_data is not None:
xbmc.log("add_gui_item - extra_data", xbmc.LOGWARNING)
for i in extra_data:
temp_log = ""
a = extra_data.get(encode(i))
if a is None:
temp_log = "\'unset\'"
elif isinstance(a, list) or isinstance(a, dict):
for b in a:
temp_log = str(b) if temp_log == "" else temp_log + " | " + str(b)
else:
temp_log = str(a)
xbmc.log("-" + str(i) + "- " + temp_log, xbmc.LOGWARNING)
if extra_data is not None and len(extra_data) > 0:
if extra_data.get('parameters'):
for argument, value in extra_data.get('parameters').items():
link_url = "%s&%s=%s" % (link_url, argument, urllib.quote(value))
tbi = extra_data.get('thumb', '')
tp = extra_data.get('type', 'Video')
if details.get('parenttitle', '').lower() == 'tags':
if not filter_gui_item_by_tag(details.get('title', '')):
return
liz = xbmcgui.ListItem(details.get('title', 'Unknown'))
if tbi is not None and len(tbi) > 0:
liz.setArt({'thumb': tbi})
liz.setArt({'poster': get_poster(tbi)})
if extra_data is not None and len(extra_data) > 0:
actors = extra_data.get('actors', None)
if actors is not None:
if len(actors) > 0:
try:
liz.setCast(actors)
details.pop('cast', None)
details.pop('castandrole', None)
except:
pass
# Set the properties of the item, such as summary, name, season, etc
liz.setInfo(type=tp, infoLabels=details)
# For all video items
if not folder:
liz.setProperty('IsPlayable', 'true')
if extra_data and len(extra_data) > 0:
if extra_data.get('type', 'video').lower() == "video":
liz.setProperty('TotalTime', str(extra_data.get('duration')))
liz.setProperty('ResumeTime', str(extra_data.get('resume')))
liz.setProperty('VideoResolution', str(extra_data.get('xVideoResolution', '')))
liz.setProperty('VideoCodec', extra_data.get('xVideoCodec', ''))
liz.setProperty('AudioCodec', extra_data.get('xAudioCodec', ''))
liz.setProperty('AudioChannels', str(extra_data.get('xAudioChannels', '')))
liz.setProperty('VideoAspect', str(extra_data.get('xVideoAspect', '')))
video_codec = {}
if extra_data.get('VideoCodec'):
video_codec['codec'] = extra_data.get('VideoCodec')
if extra_data.get('height'):
video_codec['height'] = int(extra_data.get('height'))
if extra_data.get('width'):
video_codec['width'] = int(extra_data.get('width'))
if extra_data.get('xVideoAspect'):
video_codec['aspect'] = float(extra_data.get('xVideoAspect'))
if extra_data.get('duration'):
video_codec['duration'] = extra_data.get('duration')
if __addon__.getSetting("spamLog") == 'true':
xbmc.log("add_gui_item - video codec", xbmc.LOGWARNING)
for i in video_codec:
temp_log = ""
a = video_codec.get(encode(i))
if a is None:
temp_log = "\'unset\'"
elif isinstance(a, list):
for b in a:
temp_log = str(b) if temp_log == "" else temp_log + " | " + str(b)
else:
temp_log = str(a)
xbmc.log("-" + str(i) + "- " + temp_log, xbmc.LOGWARNING)
liz.addStreamInfo('video', video_codec)
if extra_data.get('AudioStreams'):
for stream in extra_data['AudioStreams']:
liz.setProperty('AudioCodec.' + str(stream), str(extra_data['AudioStreams'][stream]
['AudioCodec']))
liz.setProperty('AudioChannels.' + str(stream), str(extra_data['AudioStreams'][stream]
['AudioChannels']))
audio_codec = dict()
audio_codec['codec'] = str(extra_data['AudioStreams'][stream]['AudioCodec'])
audio_codec['channels'] = int(extra_data['AudioStreams'][stream]['AudioChannels'])
audio_codec['language'] = str(extra_data['AudioStreams'][stream]['AudioLanguage'])
if __addon__.getSetting("spamLog") == 'true':
xbmc.log("add_gui_item - audio codec", xbmc.LOGWARNING)
for i in audio_codec:
temp_log = ""
a = audio_codec.get(encode(i))
if a is None:
temp_log = "\'unset\'"
elif isinstance(a, list):
for b in a:
temp_log = str(b) if temp_log == "" else temp_log + " | " + str(b)
else:
temp_log = str(a)
xbmc.log("-" + str(i) + "- " + temp_log, xbmc.LOGWARNING)
liz.addStreamInfo('audio', audio_codec)
if extra_data.get('SubStreams'):
for stream2 in extra_data['SubStreams']:
liz.setProperty('SubtitleLanguage.' + str(stream2), str(extra_data['SubStreams'][stream2]
['SubtitleLanguage']))
subtitle_codec = dict()
subtitle_codec['language'] = str(extra_data['SubStreams'][stream2]['SubtitleLanguage'])
liz.addStreamInfo('subtitle', subtitle_codec)
# UMS/PSM Jumpy plugin require 'path' to play video
partemp = util.parseParameters(input_string=url)
liz.setProperty('path', str(partemp.get('file', 'empty')))
if extra_data and len(extra_data) > 0:
if extra_data.get('source') == 'AnimeGroup' or extra_data.get('source') == 'AnimeSerie':
# Then set the number of watched and unwatched, which will be displayed per season
liz.setProperty('TotalEpisodes', str(extra_data['TotalEpisodes']))
liz.setProperty('WatchedEpisodes', str(extra_data['WatchedEpisodes']))
liz.setProperty('UnWatchedEpisodes', str(extra_data['UnWatchedEpisodes']))
# Hack to show partial flag for TV shows and seasons
if extra_data.get('partialTV') == 1:
liz.setProperty('TotalTime', '100')
liz.setProperty('ResumeTime', '50')
if extra_data.get('fanart_image'):
liz.setArt({"fanart": extra_data.get('fanart_image', '')})
if extra_data.get('banner'):
liz.setArt({'banner': extra_data.get('banner', '')})
if extra_data.get('season_thumb'):
liz.setArt({'seasonThumb': extra_data.get('season_thumb', '')})
if context is None:
if extra_data and len(extra_data) > 0:
if extra_data.get('type', 'video').lower() == "video":
context = []
url_peep_base = sys.argv[2]
my_len = len(
"http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port")
+ __addon__.getSetting("userid"))
if extra_data.get('source', 'none') == 'AnimeSerie':
series_id = extra_data.get('key')[(my_len + 30):]
url_peep = url_peep_base + "&anime_id=" + series_id + "&cmd=voteSer"
if __addon__.getSetting('context_show_info') == 'true':
context.append(('More Info', 'Action(Info)'))
if __addon__.getSetting('context_show_vote_Series') == 'true':
context.append(('Vote (Shoko)', 'RunScript(plugin.video.nakamori, %s, %s)' %
(sys.argv[1], url_peep)))
url_peep = url_peep_base + "&anime_id=" + series_id
context.append(('Mark as Watched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=watched)'
% (sys.argv[1], url_peep)))
context.append(('Mark as Unwatched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=unwatched)'
% (sys.argv[1], url_peep)))
elif extra_data.get('source', 'none') == 'AnimeGroup':
series_id = extra_data.get('key')[(my_len + 30):]
if __addon__.getSetting('context_show_info') == 'true':
context.append(('More Info', 'Action(Info)'))
url_peep = url_peep_base + "&group_id=" + series_id
context.append(('Mark as Watched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=watched)'
% (sys.argv[1], url_peep)))
context.append(('Mark as Unwatched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=unwatched)'
% (sys.argv[1], url_peep)))
elif extra_data.get('source', 'none') == 'tvepisodes':
series_id = extra_data.get('parentKey')[(my_len + 30):]
url_peep = url_peep_base + "&anime_id=" + series_id + \
"&ep_id=" + extra_data.get('jmmepisodeid') + '&ui_index=' + str(index)
if not extra_data.get('unsorted', False):
if __addon__.getSetting('context_show_play_no_watch') == 'true':
context.append(('Play (Do not Mark as Watched (Shoko))',
'RunScript(plugin.video.nakamori, %s, %s&cmd=no_mark)'
% (sys.argv[1], url_peep)))
if __addon__.getSetting('context_show_info') == 'true':
context.append(('More Info', 'Action(Info)'))
if __addon__.getSetting('context_show_vote_Series') == 'true' and not extra_data.get('unsorted',
False):
if series_id != '':
context.append(
('Vote for Series (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=voteSer)'
% (sys.argv[1], url_peep)))
if __addon__.getSetting('context_show_vote_Episode') == 'true' and not extra_data.get(
'unsorted', False):
if extra_data.get('jmmepisodeid') != '':
context.append(
('Vote for Episode (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=voteEp)'
% (sys.argv[1], url_peep)))
if extra_data.get('jmmepisodeid') != '' and not extra_data.get('unsorted', False):
if __addon__.getSetting('context_krypton_watched') == 'true':
if details.get('playcount', 0) == 0:
context.append(
('Mark as Watched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=watched)'
% (sys.argv[1], url_peep)))
else:
context.append(
('Mark as Unwatched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=unwatched)'
% (sys.argv[1], url_peep)))
else:
context.append(
('Mark as Watched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=watched)'
% (sys.argv[1], url_peep)))
context.append(
('Mark as Unwatched (Shoko)',
'RunScript(plugin.video.nakamori, %s, %s&cmd=unwatched)'
% (sys.argv[1], url_peep)))
if extra_data.get('unsorted', False):
context.append(
('Rescan File',
'RunScript(plugin.video.nakamori, %s, %s&cmd=rescan)'
% (sys.argv[1], url_peep)))
context.append(
('Rehash File',
'RunScript(plugin.video.nakamori, %s, %s&cmd=rehash)'
% (sys.argv[1], url_peep)))
liz.addContextMenuItems(context)
return xbmcplugin.addDirectoryItem(handle, url, listitem=liz, isFolder=folder)
except Exception as e:
error("Error during add_gui_item", str(e))
def remove_anidb_links(data=""):
"""
Remove anidb links from descriptions
Args:
data: the strong to remove links from
Returns: new string without links
"""
# search for string with 1 to 3 letters and 1 to 7 numbers
p = re.compile('http://anidb.net/[a-z]{1,3}[0-9]{1,7}[ ]')
data2 = p.sub('', data)
# remove '[' and ']' that included link to anidb.net
p = re.compile('(\[|\])')
return p.sub('', data2)
def get_poster(data=""):
"""
Convert a thumb to a poster if needed and return
Args:
data: The url of the image
Returns: the new url of the image
"""
if data is not None:
result = data
if len(data) > 0 and "getthumb" in data.lower():
p = data.lower().replace('getthumb', 'getimage')
s = p.split("/")
last_word = ""
for chunk in s:
last_word = chunk
result = p.replace(last_word, '')[:-1]
return result
return data
def gen_image_url(data=""):
"""
Perform conversion of url if necessary
Args:
data: URL of the image
Returns: the new URL of the image
"""
if __addon__.getSetting('useOriginalThumbnailRatio') == 'true':
ratio = '0'
else:
ratio = '1.7778'
if data is not None:
if data.startswith("http"):
if data.endswith("0.6667"):
data = data.replace("0.6667", ratio)
elif data.endswith("0,6667"):
data = data.replace("0,6667", ratio)
if 'getsupportimage' in data.lower():
data = data.replace("/0.6667", '')
data = data.replace("/0,6667", '')
return data
if data.endswith("0.6667"):
return ("http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port")
+ "/JMMServerREST/GetThumb/" + data).replace("0.6667", ratio)
elif data.endswith("0,6667"):
return ("http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port")
+ "/JMMServerREST/GetThumb/" + data).replace("0,6667", ratio)
else:
return ("http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port")
+ "/JMMServerREST/GetImage/" + data)
return data
def set_watch_flag(extra_data, details):
"""
Set the flag icon for the list item to the desired state based on watched episodes
Args:
extra_data: the extra_data dict
details: the details dict
"""
# TODO: Real watch progress instead of 0,50,100%
# Set up overlays for watched and unwatched episodes
if extra_data['WatchedEpisodes'] == 0:
details['playcount'] = 0
elif extra_data['UnWatchedEpisodes'] == 0:
details['playcount'] = 1
else:
extra_data['partialTV'] = 1
def get_legacy_title(data):
"""
Get the legacy title format
Args:
data: the xml node containing the title
Returns: string of the desired title
"""
lang = __addon__.getSetting("displaylang")
title_type = __addon__.getSetting("title_type")
temp_title = encode(data.get('original_title', 'Unknown'))
titles = temp_title.split('|')
try:
for title in titles:
stripped = title[title.index('}') + 1:]
if ('{' + title_type.lower() + ':' + lang.lower() + '}') in title:
return stripped
for title in titles:
# fallback on language
stripped = title[title.index('}') + 1:]
if (':' + lang.lower() + '}') in title:
return stripped
for title in titles:
# fallback on x-jat
stripped = title[title.index('}') + 1:]
if '{main:x-jat}' in title:
return stripped
except:
pass
return encode(data.get('title', 'Unknown'))
def get_title(data):
"""
Get the new title
Args:
data: the xml node containing the title
Returns: string of the desired title
"""
try:
if __addon__.getSetting('use_server_title') == 'true':
return encode(data.get('title', 'Unknown'))
# xbmc.log(data.get('title', 'Unknown'))
title = encode(data.get('title', '')).lower()
if title == 'ova' or title == 'ovas' \
or title == 'episode' or title == 'episodes' \
or title == 'special' or title == 'specials' \
or title == 'parody' or title == 'parodies' \
or title == 'credit' or title == 'credits' \
or title == 'trailer' or title == 'trailers' \
or title == 'other' or title == 'others':
return encode(data.get('title', 'Error'))
if data.get('original_title', '') != '':
return get_legacy_title(data)
lang = __addon__.getSetting("displaylang")
title_type = __addon__.getSetting("title_type")
try:
for titleTag in data.findall('AnimeTitle'):
if titleTag.find('Type').text.lower() == title_type.lower():
if titleTag.find('Language').text.lower() == lang.lower():
return encode(titleTag.find('Title').text)
# fallback on language any title
for titleTag in data.findall('AnimeTitle'):
if titleTag.find('Type').text.lower() != 'short':
if titleTag.find('Language').text.lower() == lang.lower():
return encode(titleTag.find('Title').text)
# fallback on x-jat main title
for titleTag in data.findall('AnimeTitle'):
if titleTag.find('Type').text.lower() == 'main':
if titleTag.find('Language').text.lower() == 'x-jat':
return encode(titleTag.find('Title').text)
# fallback on directory title
return encode(data.get('title', 'Unknown'))
except Exception as expc:
error('Error thrown on getting title', str(expc))
return encode(data.get('title', 'Error'))
except Exception as exw:
error("get_title Exception", str(exw))
return 'Error'
def get_legacy_tags(tag_xml):
"""
Get the tags from the legacy style
Args:
tag_xml: the xml node containing the tags
Returns: a string of all of the tags formatted
"""
temp_genre = ""
tag = tag_xml.find("Tag")
if tag is not None:
temp_genre = tag.get('tag', '')
temp_genres = str.split(temp_genre, ",")
temp_genres = TagFilter.processTags(__addon__, temp_genres)
temp_genre = ""
for a in temp_genres:
a = " ".join(w.capitalize() for w in a.split())
temp_genre = encode(a) if temp_genre == "" else temp_genre + " | " + encode(a)
return temp_genre
def get_tags(tag_xml):
"""
Get the tags from the new style
Args:
tag_xml: the xml node containing the tags
Returns: a string of all of the tags formatted
"""
try:
if tag_xml.find('Tag') is not None:
return get_legacy_tags(tag_xml)
temp_genres = []
for tag in tag_xml.findall("Genre"):
if tag is not None:
temp_genre = encode(tag.get('tag', '')).strip()
temp_genres.append(temp_genre)
temp_genres = TagFilter.processTags(__addon__, temp_genres)
temp_genre = " | ".join(temp_genres)
return temp_genre
except Exception as exc:
error('Error generating tags', str(exc))
return ''
def get_cast_and_role(data):
"""
Get cast from the xml and arrange in the new setCast format
Args:
data: xml node containing the cast
Returns: a list of dictionaries for the cast
"""
result_list = []
if data is not None:
character_tag = 'Role'
if data.find('Characters') is not None:
data = data.find('Characters')
character_tag = 'Character'
for char in data.findall(character_tag):
# Don't init any variables we don't need right now
# char_id = char.get('charID')
if character_tag == 'Role':
char_charname = char.get('role', '')
char_seiyuuname = char.get('tag', 'Unknown')
char_seiyuupic = char.get('rolePicture', 'err404')
else:
char_charname = char.get('charname', '')
# char_desc=char.get('description','')
char_seiyuuname = char.get('tag', 'Unknown')
char_seiyuupic = char.get('seiyuupic', 'err404')
# only add it if it has data
# reorder these to match the convention (Actor is cast, character is role, in that order)
if len(char_charname) != 0:
actor = {
'name': char_seiyuuname,
'role': char_charname,
'thumbnail': char_seiyuupic
}
result_list.append(actor)
if len(result_list) == 0:
return None
return result_list
def convert_cast_and_role_to_legacy(list_of_dicts):
result_list = []
list_cast = []
list_cast_and_role = []
if len(list_of_dicts) > 0:
for actor in list_of_dicts:
seiyuu = actor.get('name', '')
role = actor.get('role', '')
if len(role) != 0:
list_cast.append(role)
if len(seiyuu) != 0:
list_cast_and_role.append((seiyuu, role))
result_list.append(list_cast)
result_list.append(list_cast_and_role)
return result_list
def get_cast_and_role_legacy(data):
"""
Get cast from the xml
Args:
data: xml node containing the cast
Returns: a list of the cast
"""
if data is not None:
result_list = []
list_cast = []
list_cast_and_role = []
character_tag = 'Role'
if data.find('Characters') is not None:
data = data.find('Characters')
character_tag = 'Character'
for char in data.findall(character_tag):
# Don't init any variables we don't need right now
# char_id = char.get('charID')
if character_tag == 'Role':
char_charname = char.get('role', '')
else:
char_charname = char.get('charname', '')
# char_picture=char.get('picture','')
# char_desc=char.get('description','')
if character_tag == 'Role':
char_seiyuuname = char.get('seiyuuname', 'Unknown')
else:
char_seiyuuname = char.get('tag', 'Unknown')
# char_seiyuupic=char.get('seiyuupic', 'err404')
# only add it if it has data
# reorder these to match the convention (Actor is cast, character is role, in that order)
if len(char_charname) != 0:
list_cast.append(str(char_charname))
if len(char_seiyuuname) != 0:
list_cast_and_role.append((str(char_seiyuuname), str(char_charname)))
result_list.append(list_cast)
result_list.append(list_cast_and_role)
return result_list
# Adding items to list/menu:
def build_main_menu():
"""
Builds the list of items in the Main Menu
"""
xbmcplugin.setContent(handle, content='tvshows')
try:
# http://127.0.0.1:8111/jmmserverkodi/getfilters/1
e = xml(get_xml("http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port") +
"/jmmserverkodi/getfilters/" + __addon__.getSetting("userid")))
set_window_heading(e)
try:
for atype in e.findall('Directory'):
title = atype.get('title')
use_mode = 4
key = atype.get('key', '')
if title == 'Continue Watching (SYSTEM)':
title = 'Continue Watching'
elif title == 'Unsort':
title = 'Unsorted'
use_mode = 6
key = "http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port") \
+ "/JMMServerKodi/GetMetadata/" + __addon__.getSetting("userid") + "/1/0"
if __addon__.getSetting("spamLog") == "true":
xbmc.log("build_main_menu - key = " + key)
if __addon__.getSetting('request_nocast') == 'true' and title != 'Unsorted':
key += '/nocast'
url = key
thumb = gen_image_url(atype.get('thumb'))
fanart = gen_image_url(atype.get('art', thumb))
u = sys.argv[0]
u = set_parameter(u, 'url', url)
u = set_parameter(u, 'mode', str(use_mode))
u = set_parameter(u, 'name', urllib.quote_plus(title))
u = set_parameter(u, 'filterid', atype.get('GenericId', ''))
liz = xbmcgui.ListItem(label=title, label2=title, path=url)
liz.setArt({'thumb': thumb, 'fanart': fanart, 'poster': get_poster(thumb), 'icon': 'DefaultVideo.png'})
liz.setInfo(type="Video", infoLabels={"Title": title, "Plot": title})
xbmcplugin.addDirectoryItem(handle, url=u, listitem=liz, isFolder=True)
except Exception as e:
error("Error during build_main_menu", str(e))
except Exception as e:
# get_html now catches, so an XML error is the only thing this will catch
error("Invalid XML Received in build_main_menu", str(e))
# Start Add_Search
url = "http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port") \
+ "/jmmserverkodi/search/" + __addon__.getSetting("userid") + "/" + __addon__.getSetting("maxlimit") + "/"
title = "Search"
thumb = "http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port") \
+ "/jmmserverkodi/GetSupportImage/plex_others.png"
liz = xbmcgui.ListItem(label=title, label2=title, path=url)
liz.setArt({'thumb': thumb, 'poster': get_poster(thumb), 'icon': 'DefaultVideo.png'})
liz.setInfo(type="Video", infoLabels={"Title": title, "Plot": title})
u = sys.argv[0]
u = set_parameter(u, 'url', url)
u = set_parameter(u, 'mode', str(3))
u = set_parameter(u, 'name', urllib.quote_plus(title))
xbmcplugin.addDirectoryItem(handle, url=u, listitem=liz, isFolder=True)
# End Add_Search
xbmcplugin.endOfDirectory(handle, True, False, False)
def build_tv_shows(params, extra_directories=None):
"""
Builds the list of items for Filters and Groups
Args:
params:
extra_directories:
Returns:
"""
# xbmcgui.Dialog().ok('MODE=4','IN')
# xbmcgui.Dialog().ok('MODE=4', str(params['url']))
xbmcplugin.setContent(handle, 'tvshows')
if __addon__.getSetting('use_server_sort') == 'false' and extra_directories is None:
xbmcplugin.addSortMethod(handle, 27) # video title ignore THE
xbmcplugin.addSortMethod(handle, 3) # date
xbmcplugin.addSortMethod(handle, 18) # rating
xbmcplugin.addSortMethod(handle, 17) # year
xbmcplugin.addSortMethod(handle, 28) # by MPAA
try:
html = encode(decode(get_xml(params['url'])))
if __addon__.getSetting("spamLog") == "true":
xbmc.log(params['url'])
xbmc.log(html)
e = xml(html)
set_window_heading(e)
try:
parent_title = ''
try:
parent_title = e.get('title1', '')
except Exception as exc:
error("Unable to get parent title in buildTVShows", str(exc))
if extra_directories is not None:
e.extend(extra_directories)
directory_list = e.findall('Directory')
if len(directory_list) <= 0:
if e.find('Video') is not None:
build_tv_episodes(params)
return
error("No directory listing")
for directory in directory_list:
temp_genre = get_tags(directory)
watched = int(directory.get('viewedLeafCount', 0))
# TODO: Decide about future of cast_and_role in ALL
# This is not used here because JMM don't present this data because of the size in 'ALL'
# but we will leave this here to future support if we shrink the data flow
list_cast = []
list_cast_and_role = []
actors = []
if len(list_cast) == 0:
result_list = get_cast_and_role(directory)
actors = result_list
if result_list is not None:
result_list = convert_cast_and_role_to_legacy(result_list)
list_cast = result_list[0]
list_cast_and_role = result_list[1]
if __addon__.getSetting("local_total") == "true":
total = int(directory.get('totalLocal', 0))
else:
total = int(directory.get('leafCount', 0))
title = get_title(directory)
details = {
'title': title,
'parenttitle': encode(parent_title),
'genre': temp_genre,
'year': int(directory.get('year', 0)),
'episode': total,
'season': int(directory.get('season', 1)),
# 'count' : count,
# 'size' : size,
# 'Date' : date,
'rating': float(str(directory.get('rating', 0.0)).replace(',', '.')),
# 'playcount' : int(atype.get('viewedLeafCount')),
# overlay : integer (2, - range is 0..8. See GUIListItem.h for values
'cast': list_cast, # cast : list (Michal C. Hall,
'castandrole': list_cast_and_role,
# This also does nothing. Those gremlins.
# 'cast' : list([("Actor1", "Character1"),("Actor2","Character2")]),
# 'castandrole' : list([("Actor1", "Character1"),("Actor2","Character2")]),
# director : string (Dagur Kari,
'mpaa': directory.get('contentRating', ''),
'plot': remove_anidb_links(encode(directory.get('summary', ''))),
# 'plotoutline' : plotoutline,
'originaltitle': encode(directory.get('original_title', '')),
'sorttitle': title,
# 'Duration' : duration,
# 'Studio' : studio, < ---
# 'Tagline' : tagline,
# 'Writer' : writer,
# 'tvshowtitle' : tvshowtitle,
'tvshowname': title,
# 'premiered' : premiered,
# 'Status' : status,
# code : string (tt0110293, - IMDb code
'aired': directory.get('originallyAvailableAt', ''),
# credits : string (Andy Kaufman, - writing credits
# 'Lastplayed' : lastplayed,
'votes': directory.get('votes'),
# trailer : string (/home/user/trailer.avi,
'dateadded': directory.get('addedAt')
}
temp_date = str(details['aired']).split('-')
if len(temp_date) == 3: # format is 2016-01-24, we want it 24.01.2016
details['date'] = temp_date[1] + '.' + temp_date[2] + '.' + temp_date[0]
directory_type = directory.get('AnimeType', '')
key = directory.get('key', '')
filterid = ''
if get_version() > LooseVersion(
'3.6.1.0') and directory_type != 'AnimeType' and directory_type != 'AnimeSerie':
if params.get('filterid', '') != '':
filterid = params.get('filterid', '')
if directory_type == 'AnimeGroupFilter':
filterid = directory.get('GenericId', '')
# length = len("http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port")
# + "/JMMServerKodi/GetMetadata/" + __addon__.getSetting("userid") + "/") + 2
#key = key[length:]
#key = "http://" + __addon__.getSetting("ipaddress") + ":" + __addon__.getSetting("port") \
# + "/JMMServerKodi/GetMetadata/" + __addon__.getSetting("userid") + '/0/' + key
thumb = gen_image_url(directory.get('thumb'))
fanart = gen_image_url(directory.get('art', thumb))
banner = gen_image_url(directory.get('banner', ''))
extra_data = {
'type': 'video',
'source': directory_type,
'UnWatchedEpisodes': int(details['episode']) - watched,
'WatchedEpisodes': watched,
'TotalEpisodes': details['episode'],
'thumb': thumb,
'fanart_image': fanart,