This repository has been archived by the owner on Sep 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
default.py
610 lines (505 loc) · 24.3 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
# -*- coding: utf-8 -*-
"""
A Kodi addon/skin for NFL Game Pass
"""
import sys
import urllib.request
import urllib.parse
import urllib.error
from traceback import format_exc
from datetime import timedelta
import logging
import time
import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
from resources.lib.pigskin.pigskin import pigskin
from resources.lib import kodilogging
dialog = xbmcgui.Dialog()
# Addon Init
addon = xbmcaddon.Addon()
language = addon.getLocalizedString
ADDON_PATH = xbmcvfs.translatePath(addon.getAddonInfo('path'))
ADDON_PROFILE = xbmcvfs.translatePath(addon.getAddonInfo('profile'))
# Default Window IDs
WINDOW_FULLSCREEN_VIDEO = 12005
# Logging Init
logger = logging.getLogger(addon.getAddonInfo('id'))
kodilogging.config()
# Create addon_data directory
if not xbmcvfs.exists(ADDON_PROFILE):
xbmcvfs.mkdir(ADDON_PROFILE)
def get_credentials():
username = addon.getSetting('email')
password = addon.getSetting('password')
if not username or not password:
answer = dialog.ok(language(30021), language(30050))
if answer:
addon.openSettings()
username = addon.getSetting('email')
password = addon.getSetting('password')
else:
sys.exit(0)
return username, password
def build_proxy_url():
try:
protocol = addon.getSetting('proxy_scheme') + '://'
auth = ''
if addon.getSetting('proxy_auth') == 'true':
username = addon.getSetting('proxy_username').strip()
password = addon.getSetting('proxy_password')
if not username or not password:
return ''
auth = '%s:%s@' % (urllib.parse.quote(username), urllib.parse.quote(password))
host = addon.getSetting('proxy_host').strip()
if not host:
return ''
port = addon.getSetting('proxy_port').strip()
if port:
host = host + ':' + port
proxy_url = protocol + auth + host
return proxy_url
except Exception as e:
logger.debug('Failed building proxy url, using none')
logger.debug('Trace Message:\n{}'.format(format_exc()))
return None
def has_inputstream_adaptive():
"""Checks if InputStream Adaptive is installed and enabled."""
adaptive_available = xbmc.getCondVisibility('System.HasAddon("inputstream.adaptive")')
if adaptive_available:
logger.debug('InputStream Adaptive is installed and enabled.')
return True
else:
logger.debug('InputStream Adaptive is not installed and/or enabled.')
return False
def select_version(game_versions):
"""Selects a game version and returns the video ID while honoring the user's /preference/."""
preferred_version = int(addon.getSetting('preferred_game_version'))
if preferred_version == 0:
selected_version = 'Game video'
elif preferred_version == 1:
selected_version = 'Condensed game'
elif preferred_version == 2:
selected_version = 'Coach film'
else:
selected_version = None
# user wants to be asked to select version
# bring up selection when preferred game version is unavailable
if not selected_version or selected_version not in game_versions:
versions = list(game_versions.keys())
answer = dialog.select(language(30016), versions)
if answer > -1:
selected_version = versions[answer]
logger.debug('Selected version: %s' % selected_version)
else:
logger.debug('Select version dialog was cancelled.')
return None
return game_versions[selected_version]
def coloring(text, meaning):
"""Return the text wrapped in appropriate color markup."""
if meaning == "disabled":
color = "FF000000"
elif meaning == "disabled-info":
color = "FF111111"
colored_text = "[COLOR=%s]%s[/COLOR]" % (color, text)
return colored_text
class GamepassGUI(xbmcgui.WindowXML):
def __init__(self, *args, **kwargs):
self.gp = None
self.season_list = None
self.season_items = []
self.clicked_season = -1
self.weeks_list = None
self.weeks_items = []
self.clicked_week = -1
self.games_list = None
self.games_items = []
self.clicked_game = -1
self.live_list = None
self.live_items = []
self.selected_season = ''
self.selected_week = ''
self.main_selection = None
self.player = None
self.list_refill = False
self.focusId = 100
self.seasons = None
self.has_inputstream_adaptive = has_inputstream_adaptive()
self.window = None
self.selected_season_type = None
xbmcgui.WindowXML.__init__(self, *args, **kwargs)
self.action_previous_menu = (9, 10, 92, 216, 247, 257, 275, 61467, 61448)
def pigskin_login(self):
# Build proxy if needed
proxy_url = build_proxy_url()
self.gp = pigskin(proxy_url)
try:
username, password = get_credentials()
login_success = self.gp.login(username, password)
if not login_success:
dialog.ok(language(30021), language(30023))
sys.exit(0)
except Exception as e:
logger.debug('Trace Message:\n{}'.format(format_exc()))
dialog.ok('Epic Failure', language(30024))
sys.exit(0)
def onInit(self): # pylint: disable=invalid-name
self.window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
self.season_list = self.window.getControl(210)
self.weeks_list = self.window.getControl(220)
self.games_list = self.window.getControl(230)
self.live_list = self.window.getControl(240)
if self.list_refill:
self.season_list.reset()
self.season_list.addItems(self.season_items)
self.weeks_list.reset()
self.weeks_list.addItems(self.weeks_items)
self.games_list.reset()
self.games_list.addItems(self.games_items)
self.live_list.reset()
self.live_list.addItems(self.live_items)
else:
self.window.setProperty('NW_clicked', 'false')
self.window.setProperty('GP_clicked', 'false')
logger.debug('Initiate Game Pass Login')
self.pigskin_login()
self.seasons = self.gp.get_seasons()
try:
self.setFocus(self.window.getControl(self.focusId))
except Exception as e:
logger.debug('Focus not possible: %s' % self.focusId)
logger.debug('Trace Message:\n{}'.format(format_exc()))
def display_seasons(self):
"""List seasons"""
self.season_items = []
for season in self.seasons:
listitem = xbmcgui.ListItem(season)
self.season_items.append(listitem)
self.season_list.addItems(self.season_items)
def display_nfln_seasons(self):
"""List seasons"""
self.season_items = []
self.seasons = set([year for show in self.gp.nfln_shows for year in self.gp.nfln_shows[show]])
for season in sorted(self.seasons, reverse=True):
listitem = xbmcgui.ListItem(season)
self.season_items.append(listitem)
self.season_list.addItems(self.season_items)
def display_nfl_network_archive(self):
"""List shows for a given season"""
self.weeks_items = []
shows = self.gp.get_shows(self.selected_season)
for show_name in shows:
listitem = xbmcgui.ListItem(show_name)
self.weeks_items.append(listitem)
self.weeks_list.addItems(self.weeks_items)
def display_weeks_games(self):
"""Show games for a given season/week"""
self.games_items = []
games = self.gp.get_games(self.selected_season, self.selected_season_type, self.selected_week)
for game in games:
if not game['visitorCityState']:
game['visitorCityState'] = self.get_team_citystate(game, game['visitorTeamAbbr'])
if not game['homeCityState']:
game['homeCityState'] = self.get_team_citystate(game, game['homeTeamAbbr'])
game_id = '{0}-{1}-{2}'.format(
game['visitorNickName'].lower(),
game['homeNickName'].lower(),
str(game['gameId']))
game_name_shrt = '[B]%s[/B] at [B]%s[/B]' % (game['visitorNickName'], game['homeNickName'])
if game['visitorCityState'] == '' or game['homeCityState'] == '':
game_name_full = game_name_shrt
else:
game_name_full = '[B]%s %s[/B] at [B]%s %s[/B]' % (
game['visitorCityState'],
game['visitorNickName'],
game['homeCityState'],
game['homeNickName'])
listitem = xbmcgui.ListItem(game_name_shrt, game_name_full)
listitem.setProperty('is_game', 'true')
listitem.setProperty('is_show', 'false')
if addon.getSetting('time_notation') == '0': # 12-hour clock
datetime_format = '%A, %b %d - %I:%M %p'
else: # 24-hour clock
datetime_format = '%A, %b %d - %H:%M'
datetime_obj = self.gp.nfldate_to_datetime(game['gameDateTimeUtc'], True)
if game['phase'] == 'FINAL' or game['phase'] == 'FINAL_OVERTIME':
# show game duration only if user wants to see it
if addon.getSetting('hide_game_length') == 'false' and game['video']:
if game['video']['videoDuration'] == '':
game['video']['videoDuration'] = '0'
game_info = '%s [CR] Duration: %s' % (
game['phase'],
str(timedelta(seconds=int(float(game['video']['videoDuration'].replace(',', '.'))))))
else:
if addon.getSetting('display_datetime') == 'true':
if addon.getSetting('hide_game_length') == 'true' and game['phase'] != 'FINAL':
game_info = 'FINAL' + '\n' + '(' + datetime_obj.strftime(datetime_format) +')'
else:
game_info = game['phase'] + '\n' + '(' + datetime_obj.strftime(datetime_format) +')'
else:
game_info = game['phase']
if addon.getSetting('hide_game_length') == 'true' and game['phase'] != 'FINAL':
game_info = 'FINAL'
else:
game_info = datetime_obj.strftime(datetime_format)
if game['videoStatus'] == 'SCHEDULED':
isPlayable = 'false'
isBlackedOut = 'false'
elif game['videoStatus'] == 'LIVE':
game_info += '[CR]» Live «'
video_id = str(game['video']['videoId'])
isPlayable = 'true'
isBlackedOut = 'false'
listitem.setProperty('live_video_id', video_id)
else: # ONDEMAND
isPlayable = 'true'
isBlackedOut = 'false'
listitem.setProperty('isPlayable', isPlayable)
listitem.setProperty('isBlackedOut', isBlackedOut)
listitem.setProperty('game_id', game_id)
listitem.setProperty('game_info', game_info)
listitem.setProperty('away_thumb',
'https://static.www.nfl.com/t_thumb_squared/f_auto/league/api/clubs/logos/%s' %
game['visitorTeamAbbr'])
listitem.setProperty('home_thumb',
'https://static.www.nfl.com/t_thumb_squared/f_auto/league/api/clubs/logos/%s'
% game['homeTeamAbbr'])
self.games_items.append(listitem)
self.games_list.addItems(self.games_items)
@staticmethod
def get_team_citystate(game, team_abbr):
"""Parse video tags and retrieve team city/state"""
citystate = ''
if isinstance(game['video'], dict) and 'tags' in game['video']:
for tag in game['video']['tags']:
try:
if tag['extraData']['abbr'] == team_abbr:
citystate = tag['extraData']['cityState']
break
except (KeyError, TypeError):
continue
return citystate
def display_seasons_weeks(self):
"""List weeks for a given season"""
weeks_dict = self.gp.get_weeks(self.selected_season)
for season_type in weeks_dict:
for week_num in sorted(weeks_dict[season_type], key=int):
if season_type == 'pre':
title = language(30047).format(week_num)
elif season_type == 'reg':
title = language(30048).format(week_num)
elif season_type == 'post':
title = weeks_dict[season_type][week_num].upper()
else:
raise RuntimeError(f'Unsupported season type {season_type} detected.')
future = 'false'
listitem = xbmcgui.ListItem(title)
listitem.setProperty('week', week_num)
listitem.setProperty('season_type', season_type)
listitem.setProperty('future', future)
self.weeks_items.append(listitem)
self.weeks_list.addItems(self.weeks_items)
def display_shows_episodes(self, show_name, season):
"""Show episodes for a given season/show"""
self.games_items = []
episodes = self.gp.get_shows_episodes(show_name, season)
episode_title = ''
for episode in episodes:
try:
listitem = xbmcgui.ListItem('[B]%s[/B]' % show_name)
for episode_title, episode_videoId_thumbnail in list(episode.items()):
listitem.setProperty('game_info', episode_title)
for episode_videoId, episode_thumbnail in list(episode_videoId_thumbnail.items()):
listitem.setProperty('id', episode_videoId)
listitem.setProperty('away_thumb',
episode_thumbnail.replace('{formatInstructions}', 'c_thumb,q_auto,f_png'))
listitem.setProperty('is_game', 'false')
listitem.setProperty('is_show', 'true')
listitem.setProperty('isPlayable', 'true')
self.games_items.append(listitem)
except Exception as e:
logger.debug(f'Exception adding archive directory: {episode_title}')
logger.debug('Trace Message:\n{}'.format(format_exc()))
self.games_list.addItems(self.games_items)
def play_url(self, url):
if not self.has_inputstream_adaptive:
logger.debug('Fatal: Inputstream Adaptive is not installed or enabled. Please install and/or enable the '
'inputstream.adaptive add-on!')
dialog.ok(language(30021), language(30051))
return
self.list_refill = True
playitem = xbmcgui.ListItem(path=url)
playitem.setProperty('inputstream', 'inputstream.adaptive')
playitem.setProperty('inputstream.adaptive.manifest_type', 'hls')
playitem.setProperty('inputstream.adaptive.stream_headers', url.split('|')[1])
xbmc.Player().play(item=url, listitem=playitem)
# Show a busy dialog until playing starts.
# Kodi deinits busy dialog on player start.
# TODO Make timeout time an add-on variable
# Note: Overrides playlisttimeout kodi setting (default 20s)
calculatedTimeout = time.time() + 10
while True:
if xbmcgui.getCurrentWindowId() == WINDOW_FULLSCREEN_VIDEO:
break
if time.time() > calculatedTimeout:
logger.debug('Player took too long to start')
break
# Sleep to avoid hogging CPU
xbmc.sleep(100)
def init(self, level):
if level == 'season':
self.weeks_items = []
self.weeks_list.reset()
self.games_list.reset()
self.clicked_week = -1
self.clicked_game = -1
if self.clicked_season > -1: # unset previously selected season
self.season_list.getListItem(self.clicked_season).setProperty('clicked', 'false')
self.season_list.getSelectedItem().setProperty('clicked', 'true')
self.clicked_season = self.season_list.getSelectedPosition()
elif level in {'week', 'show'}:
self.games_list.reset()
self.clicked_game = -1
if self.clicked_week > -1: # unset previously selected week/show
self.weeks_list.getListItem(self.clicked_week).setProperty('clicked', 'false')
self.weeks_list.getSelectedItem().setProperty('clicked', 'true')
self.clicked_week = self.weeks_list.getSelectedPosition()
elif level in {'game', 'episode'}:
if self.clicked_game > -1: # unset previously selected game/episode
self.games_list.getListItem(self.clicked_game).setProperty('clicked', 'false')
self.games_list.getSelectedItem().setProperty('clicked', 'true')
self.clicked_game = self.games_list.getSelectedPosition()
def select_stream_url(self, streams):
"""Determine which stream URL to use."""
if not streams:
logger.debug('no streams list was provided!')
dialog.ok(language(30043), language(30045))
return False
# prefer chromecast streams (as they're of higher quality) but fallback
# to HLS when they're not present
try:
url = streams['chromecast']
except KeyError:
url = streams['hls']
return url
def onFocus(self, controlId): # pylint: disable=invalid-name
# save currently focused list
if controlId in [210, 220, 230, 240]:
self.focusId = controlId
def onClick(self, controlId): # pylint: disable=invalid-name
try:
if controlId in [110, 120, 130]:
self.games_list.reset()
self.weeks_list.reset()
self.season_list.reset()
self.live_list.reset()
self.games_items = []
self.weeks_items = []
self.live_items = []
self.clicked_game = -1
self.clicked_week = -1
self.clicked_season = -1
if controlId in [110, 120]:
self.main_selection = 'GamePass'
self.window.setProperty('NW_clicked', 'false')
self.window.setProperty('GP_clicked', 'true')
# display games of current week for usability purposes
cur_s_w = self.gp.get_current_season_and_week()
self.selected_season = cur_s_w['season']
self.selected_season_type = cur_s_w['season_type']
self.selected_week = cur_s_w['week']
self.display_seasons()
try:
self.display_seasons_weeks()
if addon.getSetting('display_current_week') == 'true':
self.display_weeks_games()
except Exception as e:
logger.debug('Error while reading seasons weeks and games')
logger.debug('Trace Message:\n{}'.format(format_exc()))
elif controlId == 130:
xbmc.executebuiltin('ActivateWindow(busydialognocancel)')
self.main_selection = 'NFL Network'
self.window.setProperty('NW_clicked', 'true')
self.window.setProperty('GP_clicked', 'false')
self.gp.parse_shows()
listitem = xbmcgui.ListItem('NFL Network - Live', 'NFL Network - Live')
self.live_items.append(listitem)
if self.gp.redzone_on_air():
listitem = xbmcgui.ListItem('NFL RedZone - Live', 'NFL RedZone - Live')
self.live_items.append(listitem)
self.live_list.addItems(self.live_items)
self.display_nfln_seasons()
xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
return
if self.main_selection == 'GamePass':
if controlId == 210: # season is clicked
self.init('season')
self.selected_season = self.season_list.getSelectedItem().getLabel()
try:
self.display_seasons_weeks()
except Exception as e:
logger.debug('Error while reading seasons weeks and games')
logger.debug('Trace Message:\n{}'.format(format_exc()))
elif controlId == 220: # week is clicked
self.init('week')
self.selected_week = self.weeks_list.getSelectedItem().getProperty('week')
self.selected_season_type = self.weeks_list.getSelectedItem().getProperty('season_type')
self.display_weeks_games()
elif controlId == 230: # game is clicked
selected_game = self.games_list.getSelectedItem()
if selected_game.getProperty('isPlayable') == 'true':
self.init('game')
game_id = selected_game.getProperty('game_id')
live = False
if selected_game.getProperty('live_video_id'):
video_id = selected_game.getProperty('live_video_id')
live = True
else:
game_versions = self.gp.get_game_versions(game_id, self.selected_season)
video_id = select_version(game_versions)
if video_id:
streams = self.gp.get_game_streams(video_id, live)
stream_url = self.select_stream_url(streams)
self.play_url(stream_url)
elif self.main_selection == 'NFL Network':
if controlId == 210: # season is clicked
self.init('season')
self.selected_season = self.season_list.getSelectedItem().getLabel()
self.display_nfl_network_archive()
elif controlId == 220: # show is clicked
self.init('show')
show_name = self.weeks_list.getSelectedItem().getLabel()
self.display_shows_episodes(show_name, self.selected_season)
elif controlId == 230: # episode is clicked
self.init('episode')
video_id = self.games_list.getSelectedItem().getProperty('id')
streams = self.gp.get_game_streams(video_id)
stream_url = self.select_stream_url(streams)
self.play_url(stream_url)
elif controlId == 240: # Live content (though not games)
show_name = self.live_list.getSelectedItem().getLabel()
if show_name == 'NFL RedZone - Live':
streams = self.gp.get_redzone_streams()
stream_url = self.select_stream_url(streams)
self.play_url(stream_url)
elif show_name == 'NFL Network - Live':
streams = self.gp.get_nfl_network_streams()
stream_url = self.select_stream_url(streams)
self.play_url(stream_url)
except Exception as e: # catch anything that might fail
logger.debug('Trace Message:\n{}'.format(format_exc()))
if self.main_selection == 'NFL Network' and controlId == 230: # episode
# inform that not all shows will work
dialog.ok(language(30043), language(30044))
else:
# generic oops
dialog.ok(language(30021), language(30024))
if __name__ == '__main__':
logger.debug('script starting')
# Launch window
# Login and initialization in onInit method
gui = GamepassGUI('script-gamepass.xml', ADDON_PATH)
gui.doModal()
del gui
logger.debug('script finished')