-
Notifications
You must be signed in to change notification settings - Fork 43
/
games.py
450 lines (381 loc) · 18.9 KB
/
games.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
import json, datetime, time, calendar, re, sys, traceback, urllib,urllib2
from datetime import timedelta
import xbmc,xbmcplugin,xbmcgui,xbmcaddon
from xml.dom.minidom import parseString
import utils,common
from request import Request
import vars
import inputstreamhelper
def getGameUrl(video_id, video_type, video_ishomefeed, start_time, duration):
utils.log("cookies: %s %s" % (video_type, vars.cookies), xbmc.LOGDEBUG)
# video_type could be archive, live, condensed or oldseason
if video_type not in ["live", "archive", "condensed"]:
video_type = "archive"
gt = 1
if not video_ishomefeed:
gt = 4
if video_type == "condensed":
gt = 8
url = vars.config['publish_endpoint']
headers = {
'Cookie': vars.cookies,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10553',
}
body = {
'extid': str(video_id),
'format': "xml",
'gt': gt,
'gs': vars.params.get("game_state", "3"),
'type': 'game',
'plid': vars.player_id,
'drmtoken': 'true',
'deviceid': xbmc.getInfoLabel('Network.MacAddress')
}
if video_type == "live":
line1 = "Start from Beginning"
line2 = "Go LIVE"
ret = xbmcgui.Dialog().select("Game Options", [line1, line2])
if ret == -1:
return
elif ret == 0:
if start_time:
body['st'] = str(start_time)
if duration:
body['dur'] = str(duration)
else:
utils.log("No end time, can't start from beginning", xbmc.LOGERROR)
else:
utils.log("No start time can't start from beginning", xbmc.LOGERROR)
else:
if start_time:
body['st'] = str(start_time)
utils.log("start_time: %s" % start_time, xbmc.LOGDEBUG)
if duration:
body['dur'] = str(duration)
utils.log("Duration: %s"% str(duration), xbmc.LOGDEBUG)
else:
utils.log("No end time for game", xbmc.LOGDEBUG)
else:
utils.log("No start time, can't start from beginning", xbmc.LOGERROR)
if vars.params.get("camera_number"):
body['cam'] = vars.params.get("camera_number")
if video_type != "live":
body['format'] = 'xml'
body = urllib.urlencode(body)
utils.log("the body of publishpoint request is: %s" % body, xbmc.LOGDEBUG)
try:
request = urllib2.Request(url, body, headers)
response = urllib2.urlopen(request)
content = response.read()
except urllib2.HTTPError as e:
utils.logHttpException(e, url)
utils.littleErrorPopup( xbmcaddon.Addon().getLocalizedString(50020) )
return ''
xml = parseString(str(content))
url = xml.getElementsByTagName("path")[0].childNodes[0].nodeValue
utils.log("response URL from publishpoint: %s" % url, xbmc.LOGDEBUG)
drm = xml.getElementsByTagName("drmToken")[0].childNodes[0].nodeValue
utils.log(drm, xbmc.LOGDEBUG)
selected_video_url = ''
if video_type == "live":
if '.mpd' in url:
selected_video_url = url
else:
# transform the url
match = re.search('(https?)://([^:]+)/([^?]+?)\?(.+)$', url)
protocol = match.group(1)
domain = match.group(2)
arguments = match.group(3)
querystring = match.group(4)
livecookies = "nlqptid=%s" % (querystring)
livecookiesencoded = urllib.quote(livecookies)
utils.log("live cookie: %s %s" % (querystring, livecookies), xbmc.LOGDEBUG)
url = "%s://%s/%s?%s" % (protocol, domain, arguments, querystring)
url = common.getGameUrlWithBitrate(url, video_type)
selected_video_url = "%s&Cookie=%s" % (url, livecookiesencoded)
else:
# Archive and condensed flow: We now work with HLS.
# The cookies are already in the URL and the server will supply them to ffmpeg later.
if '.mpd' in url:
selected_video_url = url
else:
selected_video_url = common.getGameUrlWithBitrate(url, video_type)
if selected_video_url:
utils.log("the url of video %s is %s" % (video_id, selected_video_url), xbmc.LOGDEBUG)
return {'url':selected_video_url, 'drm':drm}
def getHighlightGameUrl(video_id):
url = 'https://watch.nba.com/service/publishpoint'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': "AppleCoreMedia/1.0.0.8C148a (iPad; U; CPU OS 6_2_1 like Mac OS X; en_us)",
}
body = urllib.urlencode({
'extid': str(video_id),
'plid': vars.player_id,
'gt': "64",
'type': 'game',
'bitrate': "1600"
})
utils.log("the body of publishpoint request is: %s" % body, xbmc.LOGDEBUG)
try:
request = urllib2.Request(url, body, headers)
response = urllib2.urlopen(request)
content = response.read()
except urllib2.HTTPError as ex:
utils.log("Highlight url not found. Error: %s - body: %s" % (str(ex), ex.read()), xbmc.LOGERROR)
return ''
xml = parseString(str(content))
url = xml.getElementsByTagName("path")[0].childNodes[0].nodeValue
# Remove everything after ? otherwise XBMC fails to read the rtpm stream
#url, _,_ = url.partition("?")
utils.log("highlight video url: %s" % url, xbmc.LOGDEBUG)
return url
def addGamesLinks(date = '', video_type = "archive"):
try:
now_datetime_est = utils.nowEST()
#example: http://smb.cdnak.neulion.com/fs/nba/feeds_s2012/schedule/2013/10_7.js?t=1381054350000
schedule = 'http://smb.cdnak.neulion.com/fs/nba/feeds_s2012/schedule/%04d/%d_%d.js?t=%d' % \
(date.year, date.month, date.day, time.time())
utils.log('Requesting %s' % schedule, xbmc.LOGDEBUG)
schedule_request = urllib2.Request(schedule, None)
schedule_response = str(urllib2.urlopen(schedule_request).read())
schedule_json = json.loads(schedule_response[schedule_response.find("{"):])
unknown_teams = {}
for index, daily_games in enumerate(schedule_json['games']):
utils.log("daily games for day %d are %s" % (index, daily_games), xbmc.LOGDEBUG)
for game in daily_games:
h = game.get('h', '')
v = game.get('v', '')
game_id = game.get('id', '')
game_start_date_est = game.get('d', '')
vs = game.get('vs', '')
hs = game.get('hs', '')
name = game.get('name', '')
image = game.get('image', '')
seo_name = game.get("seoName", "")
has_condensed_video = game.get("video", {}).get("c", False)
has_away_feed = False
video_details = game.get('video', {})
has_away_feed = bool(video_details.get("af", {}))
# Try to convert start date to datetime
try:
game_start_datetime_est = datetime.datetime.strptime(game_start_date_est, "%Y-%m-%dT%H:%M:%S.%f" )
except:
game_start_datetime_est = datetime.datetime.fromtimestamp(time.mktime(time.strptime(game_start_date_est, "%Y-%m-%dT%H:%M:%S.%f")))
#Set game start date in the past if python can't parse the date
#so it doesn't get flagged as live or future game and you can still play it
#if a video is available
if type(game_start_datetime_est) is not datetime.datetime:
game_start_datetime_est = now_datetime_est + timedelta(-30)
#guess end date by adding 4 hours to start date
game_end_datetime_est = game_start_datetime_est + timedelta(hours=4)
# Get playoff game number, if available
playoff_game_number = 0
playoff_status = ""
if 'playoff' in game:
playoff_home_wins = int(game['playoff']['hr'].split("-")[0])
playoff_visitor_wins = int(game['playoff']['vr'].split("-")[0])
playoff_status = "%d-%d" % (playoff_visitor_wins, playoff_home_wins)
playoff_game_number = playoff_home_wins + playoff_visitor_wins
if game_id != '':
# Get pretty names for the team names
[visitor_name, host_name] = [vars.config['teams'].get(t.lower(), t) for t in [v, h]]
[unknown_teams.setdefault(t, []).append(game_start_datetime_est.strftime("%Y-%m-%d"))
for t in [v, h] if t.lower() not in vars.config['teams']]
has_video = "video" in game
future_video = game_start_datetime_est > now_datetime_est and \
game_start_datetime_est.date() == now_datetime_est.date()
live_video = game_start_datetime_est < now_datetime_est < game_end_datetime_est
# Create the title
if host_name and visitor_name:
name = game_start_datetime_est.strftime("%Y-%m-%d")
if video_type == "live":
name = utils.toLocalTimezone(game_start_datetime_est).strftime("%Y-%m-%d (at %I:%M %p)")
# Add the teams' names and the scores if needed
name += ' %s vs %s' % (visitor_name, host_name)
if playoff_game_number != 0:
name += ' (game %d)' % (playoff_game_number)
if vars.show_scores and not future_video:
name += ' %s:%s' % (str(vs), str(hs))
if playoff_status:
name += " (series: %s)" % playoff_status
thumbnail_url = utils.generateCombinedThumbnail(v, h)
elif image:
thumbnail_url = "https://neulionmdnyc-a.akamaihd.net/u/nba/nba/thumbs/%s" % image
if video_type == "live":
if future_video:
name = "UPCOMING: " + name
elif live_video:
name = "LIVE: " + name
add_link = True
if video_type == "live" and not (live_video or future_video):
add_link = False
elif video_type != "live" and (live_video or future_video):
add_link = False
elif not future_video and not has_video:
add_link = False
if add_link == True:
params = {
'video_id': game_id,
'video_type': video_type,
'seo_name': seo_name,
'visitor_team': visitor_name,
'home_team': host_name,
'has_away_feed': 1 if has_away_feed else 0,
'has_condensed_game': 1 if has_condensed_video else 0,
}
if 'st' in game:
start_time = calendar.timegm(time.strptime(game['st'], '%Y-%m-%dT%H:%M:%S.%f')) * 1000
params['start_time'] = start_time
if 'et' in game:
end_time = calendar.timegm(time.strptime(game['et'], '%Y-%m-%dT%H:%M:%S.%f')) * 1000
params['end_time'] = end_time
params['duration'] = end_time - start_time
else:
# create my own et for game (now)
end_time = str(datetime.datetime.now()).replace(' ', 'T')
end_time = calendar.timegm(time.strptime(end_time, '%Y-%m-%dT%H:%M:%S.%f')) * 1000
params['end_time'] = end_time
params['duration'] = end_time - start_time
# Add a directory item that contains home/away/condensed items
common.addListItem(name, url="", mode="gamechoosevideo",
iconimage=thumbnail_url, isfolder=True, customparams=params)
if unknown_teams:
utils.log("Unknown teams: %s" % str(unknown_teams), xbmc.LOGWARNING)
except Exception, e:
utils.littleErrorPopup("Error: %s" % str(e))
utils.log(traceback.format_exc(), xbmc.LOGDEBUG)
pass
def playGame():
# Authenticate
if vars.cookies == '':
vars.cookies = common.login()
if not vars.cookies:
return
currentvideo_id = vars.params.get("video_id")
currentvideo_type = vars.params.get("video_type")
start_time = vars.params.get("start_time")
duration = vars.params.get("duration")
currentvideo_ishomefeed = vars.params.get("video_ishomefeed", "1")
currentvideo_ishomefeed = currentvideo_ishomefeed == "1"
# Get the video url.
# Authentication is needed over this point!
currentvideo = getGameUrl(currentvideo_id, currentvideo_type, currentvideo_ishomefeed, start_time, duration)
if 'url' in currentvideo:
item = xbmcgui.ListItem(path=currentvideo['url'])
if '.mpd' in currentvideo['url']:
is_helper = inputstreamhelper.Helper('mpd', drm='com.widevine.alpha')
if is_helper.check_inputstream():
item.setProperty('inputstreamaddon', 'inputstream.adaptive')
item.setProperty('inputstream.adaptive.manifest_type', 'mpd')
item.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha')
item.setProperty('inputstream.adaptive.manifest_update_parameter', 'full')
item.setContentLookup(False)
#TODO: get license url from config
licUrl = 'https://prod-lic2widevine.sd-ngp.net/proxy|authorization=bearer ' + currentvideo['drm'] + '|R{SSM}|';
item.setProperty('inputstream.adaptive.license_key', licUrl)
xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
def chooseGameVideoMenu():
video_id = vars.params.get("video_id")
video_type = vars.params.get("video_type")
seo_name = vars.params.get("seo_name")
has_away_feed = vars.params.get("has_away_feed", "0") == "1"
has_condensed_game = vars.params.get("has_condensed_game", "0") == "1"
start_time = vars.params.get("start_time")
duration = vars.params.get("duration")
game_data_json = Request.getJson(vars.config['game_data_endpoint'] % seo_name)
game_state = game_data_json['gameState']
game_home_team = vars.params.get("home_team")
game_visitor_team = vars.params.get("visitor_team")
game_cameras = []
if 'multiCameras' in game_data_json:
game_cameras = game_data_json['multiCameras'].split(",")
nba_config = Request.getJson(vars.config['config_endpoint'])
nba_cameras = {}
for camera in nba_config['content']['cameras']:
nba_cameras[ camera['number'] ] = camera['name']
if has_away_feed:
# Create the "Home" and "Away" list items
for ishomefeed in [True, False]:
listitemname = "Full game, " + ("away feed" if not ishomefeed else "home feed")
# Show actual team names instead of 'home feed' and 'away feed'
if game_home_team and game_visitor_team:
if ishomefeed:
listitemname += " (" + game_home_team + ")"
else:
listitemname += " (" + game_visitor_team + ")"
params = {
'video_id': video_id,
'video_type': video_type,
'video_ishomefeed': 1 if ishomefeed else 0,
'game_state': game_state,
'start_time': start_time,
'duration': duration,
}
common.addListItem(listitemname, url="", mode="playgame", iconimage="", customparams=params)
else:
#Add a "Home" list item
params = {
'video_id': video_id,
'video_type': video_type,
'game_state': game_state,
'start_time': start_time,
'duration': duration,
}
common.addListItem("Full game", url="", mode="playgame", iconimage="", customparams=params)
if vars.show_cameras:
#Add all the cameras available
for camera_number in game_cameras:
#Skip camera number 0 (broadcast?) - the full game links are the same
camera_number = int(camera_number)
if camera_number == 0:
continue
params = {
'video_id': video_id,
'video_type': video_type,
'game_state': game_state,
'camera_number': camera_number,
'start_time': start_time,
'duration': duration,
}
name = "Camera %d: %s" % (camera_number, nba_cameras[camera_number])
common.addListItem(name
, url="", mode="playgame", iconimage="", customparams=params)
#Live games have no condensed or highlight link
if video_type != "live":
# Create the "Condensed" list item
if has_condensed_game:
params = {
'video_id': video_id,
'video_type': 'condensed',
'game_state': game_state
}
common.addListItem("Condensed game", url="", mode="playgame", iconimage="", customparams=params)
# Get the highlights video if available
highlights_url = getHighlightGameUrl(video_id)
if highlights_url:
common.addVideoListItem("Highlights", highlights_url, iconimage="")
xbmcplugin.endOfDirectory(handle = int(sys.argv[1]) )
def chooseGameMenu(mode, video_type, date2Use = None):
try:
if mode == "selectdate":
date = common.getDate()
elif mode == "oldseason":
date = date2Use
else:
date = utils.nowEST()
utils.log("current date (america timezone) is %s" % str(date), xbmc.LOGDEBUG)
# starts on mondays
day = date.isoweekday()
date = date - timedelta(day-1)
if mode == "lastweek":
date = date - timedelta(7)
addGamesLinks(date, video_type)
# Can't sort the games list correctly because XBMC treats file items and directory
# items differently and puts directory first, then file items (home/away feeds
# require a directory item while only-home-feed games is a file item)
#xbmcplugin.addSortMethod( handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_DATE )
except:
xbmcplugin.endOfDirectory(handle = int(sys.argv[1]),succeeded=False)
return None