コード例 #1
0
    def get_episode_url(start_timestamp, duration, force_login=False):
        if not vars.cookies or force_login:
            common.login()
        if not vars.cookies:
            return None

        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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
        }
        body = {
            'type': 'channel',
            'id': 1,
            'drmtoken': True,
            'deviceid': xbmc.getInfoLabel('Network.MacAddress'),
            'st': start_timestamp,
            'dur': duration,
            'pcid': vars.player_id,
            '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 err:
            utils.logHttpException(err, url)
            utils.littleErrorPopup(xbmcaddon.Addon().getLocalizedString(50020))
            return None

        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)

        return {'url': url, 'drm': drm}
コード例 #2
0
ファイル: tv.py プロジェクト: stevmert/nba.leaguepass.repo
 def get_serie_episode():
     video_id = vars.params.get("url")
     if not common.authenticate():
         return None
     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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
     }
     body = {
         'type': 'video',
         'id': video_id,
         'drmtoken': True,
         'token': vars.access_token,
         'deviceid': 'web-%s' % vars.player_id,
         'pcid': vars.player_id,
         'format': 'json',
     }
     body = urlencode(body).encode()
     utils.log('the body of publishpoint request is: %s' % body, xbmc.LOGDEBUG)
     try:
         request = urllib2.Request(url, body, headers)
         response = urllib2.urlopen(request, timeout=30)
         content = response.read()
     except urllib2.HTTPError as err:
         utils.logHttpException(err, url)
         utils.littleErrorPopup(xbmcaddon.Addon().getLocalizedString(50020))
         return None
     content_json = json.loads(content)
     url = content_json['path']
     drm = content_json['drmToken']
     utils.log('response URL from publishpoint: %s' % url, xbmc.LOGDEBUG)
     utils.log(drm, xbmc.LOGDEBUG)
     
     return {'url': url, 'drm': drm}
コード例 #3
0
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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
    }
    body = {
        'type': 'game',
        'extid': str(video_id),
        'drmtoken': True,
        'deviceid': xbmc.getInfoLabel('Network.MacAddress'),
        'gt': gt,
        'gs': vars.params.get('game_state', 3),
        'pcid': vars.player_id,
        'format': 'xml',
    }

    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")

    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 err:
        utils.logHttpException(err, 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)

            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.
        selected_video_url = url

    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}
コード例 #4
0
def addGamesLinks(date = '', video_type = "archive"):
    try:
        now_datetime_est = utils.nowEST()
        schedule = 'https://nlnbamdnyc-a.akamaihd.net/fs/nba/feeds_s2019/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://nbadsdmt.akamaized.net/media/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
コード例 #5
0
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}
コード例 #6
0
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
コード例 #7
0
def addGamesLinks(date='', video_type="archive", playlist=None, in_a_hurry=False):
    try:
        now_datetime_est = utils.nowEST()
        schedule = 'https://nlnbamdnyc-a.akamaihd.net/fs/nba/feeds_s2019/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:
                processed_keys = set()

                v = process_key(game, 'v', processed_keys)
                h = process_key(game, 'h', processed_keys)
                vr = process_key(game, 'vr', processed_keys)
                hr = process_key(game, 'hr', processed_keys)
                vs = process_key(game, 'vs', processed_keys)
                hs = process_key(game, 'hs', processed_keys)

                if v is None or h is None:  # TODO
                    utils.log(json.dumps(game), xbmc.LOGDEBUG)
                    continue

                game_id = process_key(game, 'id', processed_keys)
                game_start_date_est = process_key(game, 'd', processed_keys)

                name = process_key(game, 'name', processed_keys)
                image = process_key(game, 'image', processed_keys)
                seo_name = process_key(game, 'seoName', processed_keys)

                video = process_key(game, 'video', processed_keys)
                has_video = video is not None
                has_condensed_video = has_video and bool(video.get('c'))
                has_away_feed = has_video and bool(video.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 is not None:
                    # 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']]

                    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

                    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)")

                    name += " %s%s vs %s%s" % (visitor_name,
                                               " (%s)" % vr if vars.show_records_and_scores else '',
                                               host_name,
                                               " (%s)" % hr if vars.show_records_and_scores else '')

                    if playoff_game_number != 0:
                        name += ' (game %d)' % (playoff_game_number)
                    if vars.show_records_and_scores and not future_video:
                        name += ' %s:%s' % (vs, hs)

                        if playoff_status:
                            name += " (series: %s)" % playoff_status

                    thumbnail_url = utils.generateCombinedThumbnail(v, h)

                    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:
                        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",
                            'foldername': name,
                            'iconimage': thumbnail_url,
                        }

                        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
                        if playlist is None:
                            common.addListItem(name, url="", mode="gamechoosevideo", iconimage=thumbnail_url, isfolder=True, customparams=params)
                        else:
                            chooseGameVideoMenu(playlist, params, in_a_hurry)

                remaining_keys = set(game.keys()).difference(processed_keys)
                utils.log('Remaining keys: {}'.format(remaining_keys), xbmc.LOGDEBUG)

        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
コード例 #8
0
def get_game(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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
    }
    body = {
        'type': 'game',
        'extid': str(video_id),
        'drmtoken': True,
        'token': vars.access_token,
        'deviceid': xbmc.getInfoLabel('Network.MacAddress'),  # TODO
        'gt': gt,
        'gs': vars.params.get('game_state', 3),
        'pcid': vars.player_id,
        'format': 'xml',
    }

    if video_type == "live":
        line1 = "Start from Beginning"
        line2 = "Go LIVE"
        ret = xbmcgui.Dialog().select("Game Options", [line1, line2])
        if ret == -1:
            return None
        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")

    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 err:
        utils.logHttpException(err, url)
        utils.littleErrorPopup(xbmcaddon.Addon().getLocalizedString(50020))
        return None

    xml = parseString(str(content))
    url = xml.getElementsByTagName("path")[0].childNodes[0].nodeValue
    utils.log("URL: %s" % url, xbmc.LOGDEBUG)
    drm = xml.getElementsByTagName("drmToken")[0].childNodes[0].nodeValue
    utils.log("DRM: %s" % drm, xbmc.LOGDEBUG)

    return {'url': url, 'drm': drm}