-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.py
1855 lines (1763 loc) · 66.4 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
from json import dumps, loads
from random import choice
from sys import argv
from time import time
from urllib.parse import parse_qsl, quote, urlencode, urlparse
import inputstreamhelper # type: ignore
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
from requests import HTTPError, Session
from resources.lib.myvodka import login as myvodka_login
from resources.lib.myvodka import vtv
from resources.lib.utils import static as utils_static
from resources.lib.utils import unix_to_date, voda_to_epg_time
from resources.lib.utils.dns_resolver import resolve_domain
from resources.lib.vodka import (
devices,
enums,
login,
media_list,
misc,
recording,
static,
)
from resources.lib.vodka.playback import (
PlaybackException,
get_playback_obj,
get_recording_playback_object,
)
addon = xbmcaddon.Addon()
addon_name = addon.getAddonInfo("name")
HOME_ID = 10000 # https://kodi.wiki/view/Window_IDs
def add_item(plugin_prefix, handle, name, action, is_directory, **kwargs) -> None:
"""
Adds an item to the Kodi listing
"""
url = f"{plugin_prefix}?action={action}"
item = xbmcgui.ListItem(label=name)
info_labels = {}
if kwargs.get("description"):
info_labels.update({"plot": kwargs["description"]})
arts = {}
if kwargs.get("icon"):
arts.update({"thumb": kwargs["icon"], "icon": kwargs["icon"]})
if kwargs.get("fanart"):
arts.update({"fanart": kwargs["fanart"]})
item.setProperty("Fanart_Image", kwargs["fanart"])
if kwargs.get("type"):
info_labels.update({"mediatype": kwargs["type"]})
if kwargs.get("id"):
url += "&id=%s" % (kwargs["id"])
if kwargs.get("year"):
info_labels.update({"year": kwargs["year"]})
if kwargs.get("episode"):
info_labels.update({"episode": kwargs["episode"]})
if kwargs.get("season"):
info_labels.update({"season": kwargs["season"]})
if kwargs.get("show_name"):
info_labels.update({"tvshowtitle": kwargs["show_name"]})
if kwargs.get("genre"):
info_labels.update({"genre": kwargs["genre"]})
if kwargs.get("country"):
info_labels.update({"country": kwargs["country"]})
if kwargs.get("director"):
info_labels.update({"director": kwargs["director"]})
if kwargs.get("cast"):
info_labels.update({"cast": kwargs["cast"]})
if kwargs.get("mpaa"):
info_labels.update({"mpaa": kwargs["mpaa"]})
if kwargs.get("duration"):
info_labels.update({"duration": kwargs["duration"]})
if kwargs.get("extra"):
url += "&extra=%s" % (kwargs["extra"])
if kwargs.get("is_livestream"):
# see https://forum.kodi.tv/showthread.php?pid=2743328#pid2743328 to understand this hack
# useful for livestreams to not to mark the item as watched + adds switch to channel context menu item
# NOTE: MUST BE THE LAST PARAMETER in the URL
url += "&pvr=.pvr"
if not is_directory:
item.setProperty("IsPlayable", "true")
item.setArt(arts)
item.setInfo(type="Video", infoLabels=info_labels)
try:
item.setContentLookup(False)
except:
pass # if it's a local dir, no need for it
ctx_menu = []
if kwargs.get("refresh"):
ctx_menu.append((addon.getLocalizedString(30036), "Container.Refresh"))
if kwargs.get("ctx_menu"):
ctx_menu.extend(kwargs["ctx_menu"])
item.addContextMenuItems(ctx_menu)
xbmcplugin.addDirectoryItem(int(handle), url, item, is_directory)
def prepare_session() -> Session:
"""
Prepare a requests session for use within the addon. Also sets
the user agent to a random desktop user agent if it is not set.
:return: The prepared session.
"""
user_agent = addon.getSetting("useragent")
if not user_agent:
addon.setSetting("useragent", choice(utils_static.desktop_user_agents))
user_agent = addon.getSetting("useragent")
session = Session()
session.headers.update({"User-Agent": user_agent})
return session
def authenticate(session: Session, addon_from_thread: xbmcaddon.Addon = None) -> None:
"""
Handles initial login, device registration and token refresh.
Also generates the device key if it is not set.
:param session: The requests session.
:return: None
"""
addon_local = addon_from_thread or addon
if not all(
[addon_local.getSetting("username"), addon_local.getSetting("password")]
):
return
if not addon_local.getSetting("devicekey"):
device_id = misc.generate_ud_id()
addon_local.setSetting("devicekey", device_id)
ks_expiry = addon_local.getSetting("ksexpiry")
if ks_expiry and int(ks_expiry) > int(time()):
return # KS token is valid so no need to reauthenticate
prog_dialog = xbmcgui.DialogProgress()
prog_dialog.create(addon_name)
# KS login
# refresh KS token if it expired
if ks_expiry and int(ks_expiry) < time():
try:
prog_dialog.update(85, addon_local.getLocalizedString(30016))
(
access_token,
refresh_token,
expiration_date,
refresh_expiration_date,
) = login.refresh_access_token(
session,
addon_local.getSetting("jsonpostgw"),
addon_local.getSetting("ksrefreshtoken"),
ud_id=addon_local.getSetting("devicekey"),
api_user=addon_local.getSetting("apiuser"),
api_pass=addon_local.getSetting("apipass"),
platform=addon_local.getSetting("platform"),
device_brand_id=enums.DeviceBrandId.PCMAC.value,
token=addon_local.getSetting("kstoken"),
domain_id=addon_local.getSetting("domainid"),
site_guid=addon_local.getSetting("siteguid"),
)
prog_dialog.close()
except HTTPError as e:
# check if the error is 403
# if it is, then the refresh token is invalid
# so we need to reauthenticate
if e.response.status_code == 403:
addon_local.setSetting("ksexpiry", "")
authenticate(session, addon_local)
return
else:
raise e
# fresh login
else:
# reset MyVodka expiry
xbmcgui.Window(HOME_ID).setProperty("kodi.vodka.myvodka_expiry", "")
prog_dialog.update(50, addon_local.getLocalizedString(30022))
pkey, vodka_config = login.get_config(
session, addon_local.getSetting("devicekey")
)
json_post_gw = next(
(
item["JsonGW"]
for item in vodka_config["params"]["Gateways"]
if item.get("JsonGW")
),
None,
)
phoenix_gw = next(
(
item["JsonGW"]
for item in vodka_config["params"]["GatewaysPhoenix"]
if item.get("JsonGW")
),
None,
)
license_url_base = next(
(
item["SSPLicenseServerUrl"]
for item in vodka_config["params"]["NagraSettings"]
if item.get("SSPLicenseServerUrl")
),
None,
)
tenant_id = next(
(
item["TenantID"]
for item in vodka_config["params"]["NagraSettings"]
if item.get("TenantID")
),
None,
)
init_obj = vodka_config["params"]["InitObj"]
api_user = next(
(item["ApiUser"] for item in init_obj if item.get("ApiUser")), None
)
api_pass = next(
(item["ApiPass"] for item in init_obj if item.get("ApiPass")), None
)
platform = next(
(item["Platform"] for item in init_obj if item.get("Platform")), None
)
if not all(
[
json_post_gw,
phoenix_gw,
license_url_base,
tenant_id,
api_user,
api_pass,
platform,
]
):
prog_dialog.close()
raise ValueError("Missing required parameters.")
addon_local.setSetting("jsonpostgw", json_post_gw)
addon_local.setSetting("phoenixgw", phoenix_gw)
addon_local.setSetting("licenseurlbase", license_url_base)
addon_local.setSetting("tenantid", tenant_id)
addon_local.setSetting("apiuser", api_user)
addon_local.setSetting("apipass", api_pass)
addon_local.setSetting("platform", platform)
# we don't store the public key as it's not needed after a login
prog_dialog.update(75, addon_local.getLocalizedString(30023))
try:
login_response, access_token, refresh_token = login.sign_in(
session,
json_post_gw,
addon_local.getSetting("devicekey"),
api_user,
api_pass,
platform,
addon_local.getSetting("username"),
addon_local.getSetting("password"),
pkey,
)
except login.LoginError as e:
prog_dialog.close()
dialog = xbmcgui.Dialog()
dialog.ok(
addon_name,
addon_local.getLocalizedString(30025).format(message=e.message),
)
return
# NOTE: tokens have a pipe character and the expiration date appended to them here
access_token, expiration_date = access_token.split("|")
refresh_token, refresh_expiration_date = refresh_token.split("|")
site_guid = login_response["SiteGuid"]
domain_id = login_response["DomainID"]
addon_local.setSetting("domainid", str(domain_id))
addon_local.setSetting("siteguid", site_guid)
# register device
prog_dialog.update(90, addon_local.getLocalizedString(30024))
try:
devices.register_device(
session,
json_post_gw,
addon_local.getSetting("devicenick"),
ud_id=addon_local.getSetting("devicekey"),
api_user=api_user,
api_pass=api_pass,
platform=platform,
device_brand_id=enums.DeviceBrandId.PCMAC.value,
token=access_token,
domain_id=domain_id,
site_guid=site_guid,
)
except devices.DeviceRegistrationError as e:
prog_dialog.close()
dialog = xbmcgui.Dialog()
dialog.ok(
addon_name,
addon_local.getLocalizedString(30025).format(message=e.message),
)
return
prog_dialog.close()
# show success dialog
dialog = xbmcgui.Dialog()
dialog.ok(addon_name, addon_local.getLocalizedString(30026))
addon_local.setSetting("kstoken", access_token)
addon_local.setSetting("ksrefreshtoken", refresh_token)
addon_local.setSetting("ksexpiry", str(expiration_date))
addon_local.setSetting("ksrefreshexpiry", str(refresh_expiration_date))
def main_menu() -> None:
"""
Renders the main menu of the addon.
:return: None
"""
# channel list
add_item(
plugin_prefix=argv[0],
handle=argv[1],
name=addon.getLocalizedString(30027),
action="channel_list",
is_directory=True,
)
# recordings
add_item(
plugin_prefix=argv[0],
handle=argv[1],
name=addon.getLocalizedString(30096),
action="recordings",
is_directory=True,
extra="0", # page number
)
# device list (kaltura)
add_item(
plugin_prefix=argv[0],
handle=argv[1],
name=addon.getLocalizedString(30043),
action="device_list",
is_directory=True,
)
# device list (MyVodka)
add_item(
plugin_prefix=argv[0],
handle=argv[1],
name=addon.getLocalizedString(30128),
action="myvodka_device_list",
is_directory=True,
)
# settings
add_item(
plugin_prefix=argv[0],
handle=argv[1],
name=addon.getLocalizedString(30112),
action="settings",
is_directory=True,
)
# about
add_item(
plugin_prefix=argv[0],
handle=argv[1],
name=addon.getLocalizedString(30053),
action="about",
is_directory=True,
)
xbmcplugin.endOfDirectory(int(argv[1]))
def get_available_files(session: Session, file_ids: list) -> list:
"""
Get the list of available file IDs.
:param session: The requests session.
:param file_ids: The list of file IDs.
:return: The list of available file IDs.
"""
# split the list of channels into chunks of 100 in the for loop
# to avoid sending too many requests at once
available_channels = []
for i in range(0, len(file_ids), 100):
# NOTE: original app does this in chunks of 10
# but that seems to be too slow, so we do it in chunks of 100
chunk = file_ids[i : min(i + 100, len(file_ids))]
response = media_list.product_price_list(
session,
addon.getSetting("phoenixgw"),
chunk,
addon.getSetting("kstoken"),
)
for product in response:
# NOTE: values here are only guesses
if product.get("purchaseStatus") in [
"subscription_purchased",
"free",
"ppv_purchased",
"collection_purchased",
"pre_paid_purchased",
"subscription_purchased_wrong_currency",
]:
available_channels.append(product.get("fileId"))
return available_channels
def replace_image(image_url: str) -> str:
image_url = urlparse(image_url)
hostname = image_url.hostname
scheme = image_url.scheme
image_url = image_url._replace(scheme="http")._replace(
netloc=f"127.0.0.1:{addon.getSetting('webport')}"
)
params = {
"h": hostname,
"s": scheme,
}
return image_url.geturl() + "?" + urlencode(params)
def channel_list(session: Session) -> None:
"""
Renders the list of live channels.
:param session: The requests session.
:return: None
"""
channels = media_list.get_channel_list(
session, addon.getSetting("phoenixgw"), addon.getSetting("kstoken")
)
# sort channels by channel number
channels.sort(
key=lambda x: int(
next(
(
value.get("value", 0)
for key, value in x.get("metas", {}).items()
if key == "Channel number"
),
0,
)
)
)
potential_file_ids = {}
no_epg_list = []
for channel in channels:
media_files = [
media_file
for media_file in channel.get("mediaFiles")
if media_file.get("type") in static.media_file_ids
]
# sort media files that contain 'HD' earlier
media_files.sort(key=lambda x: x.get("type").lower().find("hd"), reverse=True)
if not media_files:
continue
media_file = media_files[0]["id"]
epg_id = channel.get("metas", {}).get("EPG_GUID_ID", {}).get("value")
if not epg_id:
no_epg_list.append(str(media_file))
else:
potential_file_ids[epg_id] = str(media_file)
# check which channels are available also from non-EPG sources
available_file_ids = get_available_files(
session, list(potential_file_ids.values()) + no_epg_list
)
epgs = []
if addon.getSettingInt("epgonchannels") != 4: # EPG is enabled
if not addon.getSettingBool("showallchannels"):
# drop channels that are not available
for channel_id, media_file_id in list(potential_file_ids.items()):
if int(media_file_id) not in available_file_ids:
potential_file_ids.pop(channel_id)
# get EPG data in bulk
chunk_size = addon.getSettingInt("epgfetchinonereq")
for i in range(0, len(potential_file_ids), chunk_size):
chunk = list(potential_file_ids.keys())[i : i + chunk_size]
channel_programs = media_list.get_epg_by_channel_ids(
session,
addon.getSetting("jsonpostgw"),
chunk,
0,
1,
2,
api_user=addon.getSetting("apiuser"),
api_pass=addon.getSetting("apipass"),
domain_id=addon.getSetting("domainid"),
site_guid=addon.getSetting("siteguid"),
platform=addon.getSetting("platform"),
ud_id=addon.getSetting("devicekey"),
)
# append the programs to the EPG list
epgs.extend(channel_programs)
# TODO: get API version
for channel in channels:
channel_id = channel.get("id")
if not channel_id:
continue
name = channel.get("name")
images = channel.get("images")
image = None
if images:
image = next(
(image for image in images if image.get("ratio") == "16:10"),
images[0],
)["url"]
if addon.getSettingBool("webenabled"):
image = replace_image(image)
# get media file id
media_files = [
media_file
for media_file in channel.get("mediaFiles")
if media_file.get("type") in static.media_file_ids
and media_file.get("id") in available_file_ids
]
# sort media files that contain 'HD' earlier
media_files.sort(key=lambda x: x.get("type").lower().find("hd"), reverse=True)
playable = False
if not media_files and not addon.getSettingBool("showallchannels"):
continue
elif not media_files and addon.getSettingBool("showallchannels"):
name = f"[COLOR red]{name}[/COLOR]" # channel not subscribed
else:
playable = True
media_file = media_files[0]["id"]
epg_id = channel.get("metas", {}).get("EPG_GUID_ID", {}).get("value")
description = ""
if addon.getSettingInt("epgonchannels") != 4: # EPG is enabled
epg = next(
(
epg.get("EPGChannelProgrammeObject", {})
for epg in epgs
if epg.get("EPG_CHANNEL_ID") == str(epg_id)
),
None,
)
if epg and addon.getSettingInt("epgonchannels") == 0:
# current program description and
# all next programs with start time and title
# find current program
current_program = next(
(
program
for program in epg
if voda_to_epg_time(program.get("START_DATE"))[1]
< time()
< voda_to_epg_time(program.get("END_DATE"))[1]
),
None,
)
if current_program:
name += f"[CR][COLOR gray]{current_program.get('NAME')}[/COLOR]"
description += current_program.get("DESCRIPTION") + "\n\n"
# find next programs
next_programs = [
program
for program in epg
if voda_to_epg_time(program.get("START_DATE"))[1] > time()
]
for program in next_programs:
# add start time in bold and title
description += (
"[B]"
+ unix_to_date(voda_to_epg_time(program.get("START_DATE"))[1])
+ "[/B] "
+ program.get("NAME")
+ "\n"
)
elif (
epg and addon.getSettingInt("epgonchannels") == 1
): # next programs first, then current
# find next programs
next_programs = [
program
for program in epg
if voda_to_epg_time(program.get("START_DATE"))[1] > time()
]
for program in next_programs:
# add start time in bold and title
description += (
"[B]"
+ unix_to_date(voda_to_epg_time(program.get("START_DATE"))[1])
+ "[/B] "
+ program.get("NAME")
+ "\n"
)
description += "\n"
# find current program
current_program = next(
(
program
for program in epg
if voda_to_epg_time(program.get("START_DATE"))[1]
< time()
< voda_to_epg_time(program.get("END_DATE"))[1]
),
None,
)
if current_program:
name += f"[CR][COLOR gray]{current_program.get('NAME')}[/COLOR]"
description += current_program.get("DESCRIPTION") + "\n"
elif (
epg and addon.getSettingInt("epgonchannels") == 2
): # only current program
# find current program
current_program = next(
(
program
for program in epg
if voda_to_epg_time(program.get("START_DATE"))[1]
< time()
< voda_to_epg_time(program.get("END_DATE"))[1]
),
None,
)
if current_program:
name += f"[CR][COLOR gray]{current_program.get('NAME')}[/COLOR]"
description += current_program.get("DESCRIPTION")
elif (
epg and addon.getSettingInt("epgonchannels") == 3
): # only next programs
# find next programs
next_programs = [
program
for program in epg
if voda_to_epg_time(program.get("START_DATE"))[1] > time()
]
for program in next_programs:
# add start time in bold and title
description += (
"[B]"
+ unix_to_date(voda_to_epg_time(program.get("START_DATE"))[1])
+ "[/B] "
+ program.get("NAME")
+ "\n"
)
add_item(
plugin_prefix=argv[0],
handle=argv[1],
name=name,
action="play_channel" if playable else "dummy",
is_directory=False,
id=channel_id,
icon=image,
is_livestream=True,
refresh=True,
extra=media_file if playable else None,
description=description,
)
xbmcplugin.endOfDirectory(int(argv[1]))
xbmcplugin.setContent(int(argv[1]), "videos")
def try_register_device(session: Session) -> None:
"""
Tries to register the device if it is not registered for playback.
:param session: The requests session.
:return: None
"""
try:
devices.register_device(
session,
addon.getSetting("jsonpostgw"),
addon.getSetting("devicenick"),
ud_id=addon.getSetting("devicekey"),
api_user=addon.getSetting("apiuser"),
api_pass=addon.getSetting("apipass"),
platform=addon.getSetting("platform"),
device_brand_id=enums.DeviceBrandId.PCMAC.value,
token=addon.getSetting("kstoken"),
domain_id=addon.getSetting("domainid"),
site_guid=addon.getSetting("siteguid"),
)
except devices.DeviceRegistrationError as e:
dialog = xbmcgui.Dialog()
dialog.ok(addon_name, addon.getLocalizedString(30025).format(message=e.message))
def _gen_mgr_params(playback_obj: list, asset_type: str) -> str:
"""
Generates the parameters for playback manager's statistics report.
:param playback_obj: playback object
:return: parameters for playback manager
"""
try:
params = {
"id": playback_obj["id"],
"assetId": playback_obj["assetId"],
}
if asset_type == "media":
params["assetType"] = "MEDIA"
elif asset_type == "epg":
params["assetType"] = "CATCHUP"
elif asset_type == "recording":
params["assetType"] = "NPVR"
except (KeyError, IndexError):
return ""
return urlencode(params)
def get_tag(tags: list, key: str) -> str:
"""
Gets the tag value from the list of tags.
:param tags: The list of tags.
:param key: The tag key.
:return: The tag value.
"""
tag = next(
(tag["Value"] for tag in tags if tag["Key"] == key),
None,
)
return tag
def play(
session: Session, media_id: int, asset_file_id: int, asset_type: str = "media"
) -> None:
"""
Fetches the playback object and attempts to start the playback
using the chosen DRM system.
:param session: The requests session.
:param media_id: The media ID.
:param asset_file_id: The asset file ID.
:return: None
"""
try:
playback_obj = get_playback_obj(
session,
addon.getSetting("phoenixgw"),
addon.getSetting("kstoken"),
media_id,
asset_file_id,
asset_type=asset_type,
)
except PlaybackException as e:
if e.code == "1003": # Device not in household
try_register_device(session)
return
elif e.code == "3037": # catchup buffer limit reached
dialog = xbmcgui.Dialog()
dialog.ok(
addon_name,
addon.getLocalizedString(30095),
)
return
else:
dialog = xbmcgui.Dialog()
dialog.ok(
addon_name, addon.getLocalizedString(30025).format(message=e.message)
)
return
# get the first source object
playback_obj = next(
(source for source in playback_obj.get("sources", [])),
None,
)
if not playback_obj:
xbmcgui.Dialog().ok(addon_name, addon.getLocalizedString(30030))
return
# get the first entry with scheme=CUSTOM_DRM from the drm list
drm = next(
(
drm
for drm in playback_obj.get("drm", [])
if drm.get("scheme") == "CUSTOM_DRM"
),
None,
)
if not drm:
xbmcgui.Dialog().ok(
addon_name,
addon.getLocalizedString(30031),
)
return
nv_authorizations = drm.get("data")
if not nv_authorizations:
xbmcgui.Dialog().ok(
addon_name,
addon.getLocalizedString(30032),
)
return
# construct 'trailer' parameters for playback manager
trailer_params = _gen_mgr_params(playback_obj, asset_type)
manifest_url = urlparse(playback_obj.get("url"))
headers = {}
if addon.getSettingBool("usedoh"):
# extract host from domain
hostname = manifest_url.hostname
ip = resolve_domain(addon.getSetting("dohaddress"), hostname)
if not ip:
xbmcgui.Dialog().ok(
addon_name,
addon.getLocalizedString(30035).format(url=manifest_url.geturl()),
)
return
# replace hostname with IP and specify port 80
manifest_url = manifest_url._replace(netloc=f"{ip}:80")
# replace https with http
manifest_url = manifest_url._replace(scheme="http")
headers["Host"] = hostname
else:
# replace https with http
manifest_url = manifest_url._replace(scheme="http")
# replace port 443 with 80
manifest_url = manifest_url._replace(
netloc=manifest_url.netloc.replace("443", "80")
)
# handle redirect as Kodi's player can't
response = session.head(
manifest_url.geturl(), allow_redirects=False, headers=headers
)
manifest_url = response.headers.get("Location")
drm_system = addon.getSettingInt("drmsystem")
# construct playback item
is_helper = inputstreamhelper.Helper("mpd", drm="com.widevine.alpha")
play_item = xbmcgui.ListItem(path=manifest_url)
play_item.setContentLookup(False)
play_item.setInfo("video", {"trailer": argv[0] + "?" + trailer_params})
play_item.setMimeType("application/dash+xml")
play_item.setProperty("inputstream", is_helper.inputstream_addon)
play_item.setProperty("inputstream.adaptive.manifest_type", "mpd")
play_item.setProperty(
"inputstream.adaptive.manifest_headers",
urlencode({"User-Agent": addon.getSetting("useragent")}),
)
if drm_system == 0: # Widevine
if not is_helper.check_inputstream():
xbmcgui.Dialog().ok(
addon_name,
addon.getLocalizedString(30050),
)
return
license_headers = {
"User-Agent": addon.getSetting("useragent"),
"Content-Type": "application/octet-stream", # NOTE: important
"nv-authorizations": nv_authorizations,
}
license_url = f"{addon.getSetting('licenseurlbase')}/{addon.getSetting('tenantid')}/wvls/contentlicenseservice/v1/licenses|{urlencode(license_headers)}|R{{SSM}}|"
play_item.setProperty("inputstream.adaptive.license_type", "com.widevine.alpha")
elif drm_system == 1: # PlayReady
license_headers = {
"User-Agent": addon.getSetting("useragent"),
"Content-Type": "text/xml",
"SOAPAction": "http://schemas.microsoft.com/DRM/2007/03/protocols/AcquireLicense",
"nv-authorizations": nv_authorizations,
}
license_url = f"{addon.getSetting('licenseurlbase')}/{addon.getSetting('tenantid')}/prls/contentlicenseservice/v1/licenses|{urlencode(license_headers)}|R{{SSM}}|"
play_item.setProperty(
"inputstream.adaptive.license_type", "com.microsoft.playready"
)
play_item.setProperty(
"inputstream.adaptive.license_key",
license_url,
)
xbmcplugin.setResolvedUrl(int(argv[1]), True, listitem=play_item)
def play_recording(session: Session, recording_id: int, media_id: list) -> None:
"""
Method used to play recordings. Unfortunately works very differently from
live streams and catchups.
:param session: The requests session.
:param recording_id: The recording ID.
:param media_id: The media ID.
:return: None
"""
media_id, media_type = loads(media_id.replace("'", '"'))
referrer = static.npvr_types.get(media_type, list(static.npvr_types.keys())[0])
try:
playback_object = get_recording_playback_object(
session,
addon.getSetting("jsonpostgw"),
recording_id,
int(media_id),
referrer=referrer,
api_user=addon.getSetting("apiuser"),
api_pass=addon.getSetting("apipass"),
domain_id=addon.getSetting("domainid"),
site_guid=addon.getSetting("siteguid"),
platform=addon.getSetting("platform"),
ud_id=addon.getSetting("devicekey"),
token=addon.getSetting("kstoken"),
)
except PlaybackException as e:
drm_token = xbmcgui.Window(xbmcgui.getCurrentWindowId()).setProperty(
"kodi.vodka.drm_token", ""
)
try_register_device(session)
dialog = xbmcgui.Dialog()
dialog.ok(
addon_name,
e.message,
)
return
main_url = playback_object.get("mainUrl")
if not main_url:
dialog = xbmcgui.Dialog()
dialog.ok(
addon_name,
addon.getLocalizedString(30030),
)
return
# check if we have a cached DRM token and if it's still valid
drm_token = xbmcgui.Window(xbmcgui.getCurrentWindowId()).getProperty(
"kodi.vodka.drm_token"
)
if not drm_token or misc.get_token_exp(drm_token) < time():
# get DRM token
device_info = devices.get_device(
session,
addon.getSetting("phoenixgw"),
addon.getSetting("kstoken"),
)
drm_token = device_info.get("drm", {}).get("data")
if not drm_token:
dialog = xbmcgui.Dialog()
dialog.ok(
addon_name,
addon.getLocalizedString(30032),
)
return
xbmcgui.Window(xbmcgui.getCurrentWindowId()).setProperty(
"kodi.vodka.drm_token", drm_token
)
trailer_data = {
"id": recording_id,
"assetId": media_id,
}
trailer_params = _gen_mgr_params(trailer_data, "recording")
manifest_url = urlparse(main_url)
headers = {}
if addon.getSettingBool("usedoh"):
# extract host from domain
hostname = manifest_url.hostname
ip = resolve_domain(addon.getSetting("dohaddress"), hostname)
if not ip:
xbmcgui.Dialog().ok(
addon_name,
addon.getLocalizedString(30035).format(url=manifest_url.geturl()),
)
return
# replace hostname with IP and specify port 80
manifest_url = manifest_url._replace(netloc=f"{ip}:80")
# replace https with http
manifest_url = manifest_url._replace(scheme="http")
headers["Host"] = hostname
else:
# replace https with http
manifest_url = manifest_url._replace(scheme="http")
# replace port 443 with 80
manifest_url = manifest_url._replace(
netloc=manifest_url.netloc.replace("443", "80")
)
# handle redirect as Kodi's player can't
response = session.head(
manifest_url.geturl(), allow_redirects=False, headers=headers
)
manifest_url = response.headers.get("Location")
drm_system = addon.getSettingInt("drmsystem")
# construct playback item
is_helper = inputstreamhelper.Helper("mpd", drm="com.widevine.alpha")
play_item = xbmcgui.ListItem(path=manifest_url)
play_item.setContentLookup(False)
play_item.setInfo("video", {"trailer": argv[0] + "?" + trailer_params})
play_item.setMimeType("application/dash+xml")
play_item.setProperty("inputstream", is_helper.inputstream_addon)
play_item.setProperty("inputstream.adaptive.manifest_type", "mpd")
play_item.setProperty(
"inputstream.adaptive.manifest_headers",
urlencode({"User-Agent": addon.getSetting("useragent")}),
)
if drm_system == 0: # Widevine
if not is_helper.check_inputstream():
xbmcgui.Dialog().ok(
addon_name,
addon.getLocalizedString(30050),
)
return
license_headers = {
"User-Agent": addon.getSetting("useragent"),
"Content-Type": "application/octet-stream", # NOTE: important
"nv-authorizations": drm_token,
}
license_url = f"{addon.getSetting('licenseurlbase')}/{addon.getSetting('tenantid')}/wvls/contentlicenseservice/v1/licenses|{urlencode(license_headers)}|R{{SSM}}|"
play_item.setProperty("inputstream.adaptive.license_type", "com.widevine.alpha")
elif drm_system == 1: # PlayReady
license_headers = {
"User-Agent": addon.getSetting("useragent"),
"Content-Type": "text/xml",
"SOAPAction": "http://schemas.microsoft.com/DRM/2007/03/protocols/AcquireLicense",
"nv-authorizations": drm_token,
}
license_url = f"{addon.getSetting('licenseurlbase')}/{addon.getSetting('tenantid')}/prls/contentlicenseservice/v1/licenses|{urlencode(license_headers)}|R{{SSM}}|"
play_item.setProperty(
"inputstream.adaptive.license_type", "com.microsoft.playready"
)
play_item.setProperty(
"inputstream.adaptive.license_key",
license_url,
)
xbmcplugin.setResolvedUrl(int(argv[1]), True, listitem=play_item)
def get_recordings(session: Session, page_num: int) -> None: