Esempio n. 1
0
def index():
    refresh = arg_as_bool('refresh')
    clear_cache = arg_as_bool('clear-cache')
    if clear_cache:
        include_premium = adobe_activate_api.is_authenticated()
        channel_list = events.get_channel_list(include_premium)
        util.clear_cache(events.get_live_events_url(channel_list))

    current_time = time.strftime("%I:%M %p", time.localtime(time.time()))
    addDirectoryItem(plugin.handle, plugin.url_for(index, refresh=True),
                     ListItem(get_string(30850) % current_time), True)
    include_premium = adobe_activate_api.is_authenticated()
    channel_list = events.get_channel_list(include_premium)
    espn_url = events.get_live_events_url(channel_list)
    legacy.index_legacy_live_events(espn_url)
    if get_setting_as_bool('ShowAndroidTVMenu'):
        url = base64.b64decode(
            'aHR0cHM6Ly93YXRjaC5wcm9kdWN0LmFwaS5lc3BuLmNvbS9hcGkvcHJvZHVjdC92MS9hbmRyb2lkL3R2L2hvbWU='
        )
        addDirectoryItem(plugin.handle, plugin.url_for(page_api_url, url=url),
                         ListItem(get_string(30780)), True)
    if get_setting_as_bool('ShowAppleTVMenu'):
        addDirectoryItem(plugin.handle,
                         plugin.url_for(appletv.appletv_root_menu),
                         ListItem(get_string(30730)), True)
    if get_setting_as_bool('ShowLegacyMenu'):
        addDirectoryItem(plugin.handle, plugin.url_for(legacy_root_menu),
                         ListItem(get_string(30740)), True)
    if get_setting_as_bool('ShowRokuMenu'):
        addDirectoryItem(plugin.handle, plugin.url_for(roku.roku_root_menu),
                         ListItem(get_string(30760)), True)
    if get_setting_as_bool('ShowTVOSMenu'):
        addDirectoryItem(plugin.handle, plugin.url_for(tvos.tvos_root_menu),
                         ListItem(get_string(30750)), True)
    endOfDirectory(plugin.handle, updateListing=refresh, cacheToDisc=False)
Esempio n. 2
0
def ROOT_ITEM(refresh):
    include_premium = adobe_activate_api.is_authenticated()
    channel_list = events.get_channel_list(include_premium)
    legacy_inst = legacy.Legacy()
    espn_url = list()
    espn_url.append(events.get_live_events_url(channel_list))
    legacy_inst.index_legacy_live_events(dict(ESPN_URL=espn_url))
    addDir(translation(30730),
           dict(MODE='/appletv/'),
           defaultlive)
    addDir(translation(30740),
           dict(MODE='/legacy/'),
           defaultlive)
    addDir(translation(30750),
           dict(MODE='/tvos/'),
           defaultlive)
    addDir(translation(30760),
           dict(MODE='/roku/'),
           defaultlive)
    addDir(translation(30780),
           dict(MODE='/androidtv/'),
           defaultlive)
    if not adobe_activate_api.is_authenticated():
        addDir('[COLOR=FFFF0000]' + translation(30300) + '[/COLOR]',
               dict(MODE=AUTHENTICATE_MODE),
               defaultreplay)
    if adobe_activate_api.is_authenticated():
        addDir('[COLOR=FF00FF00]' + translation(30380) + '[/COLOR]',
           dict(MODE=AUTHENTICATION_DETAILS_MODE),
           defaultfanart)
    xbmcplugin.endOfDirectory(pluginhandle, updateListing=refresh)
Esempio n. 3
0
def ROOT_ITEM(refresh):
    if not adobe_activate_api.is_authenticated():
        addDir('[COLOR=FFFF0000]' + translation(30300) + '[/COLOR]',
               dict(MODE=AUTHENTICATE_MODE), defaultreplay)
    current_time = time.strftime("%I:%M %p", time.localtime(time.time()))
    addDir(
        translation(30850) % current_time, dict(MODE=REFRESH_LIVE_MODE),
        defaultlive)
    include_premium = adobe_activate_api.is_authenticated()
    channel_list = events.get_channel_list(include_premium)
    legacy_inst = legacy.Legacy()
    espn_url = list()
    espn_url.append(events.get_live_events_url(channel_list))
    legacy_inst.index_legacy_live_events(dict(ESPN_URL=espn_url))
    if selfAddon.getSetting('ShowAndroidTVMenu') == 'true':
        addDir(translation(30780), dict(MODE='/androidtv/'), defaultlive)
    if selfAddon.getSetting('ShowAppleTVMenu') == 'true':
        addDir(translation(30730), dict(MODE='/appletv/'), defaultlive)
    if selfAddon.getSetting('ShowLegacyMenu') == 'true':
        addDir(translation(30740), dict(MODE='/legacy/'), defaultlive)
    if selfAddon.getSetting('ShowRokuMenu') == 'true':
        addDir(translation(30760), dict(MODE='/roku/'), defaultlive)
    if selfAddon.getSetting('ShowTVOSMenu') == 'true':
        addDir(translation(30750), dict(MODE='/tvos/'), defaultlive)
    if adobe_activate_api.is_authenticated():
        addDir('[COLOR=FF00FF00]' + translation(30380) + '[/COLOR]',
               dict(MODE=AUTHENTICATION_DETAILS_MODE), defaultfanart)
    xbmcplugin.endOfDirectory(pluginhandle,
                              updateListing=refresh,
                              cacheToDisc=False)
Esempio n. 4
0
def get_item_listing_text(event_name,
                          starttime,
                          duration,
                          status,
                          network,
                          blackout,
                          auth_types,
                          requires_package=False,
                          sport=None,
                          sport2=None):
    if sport != sport2 and len(sport2) > 0:
        sport += ' (' + sport2 + ')'
    length = duration
    if len(network) > 0:
        ename = '[B]%s[/B]' % event_name
    else:
        ename = event_name

    if starttime is not None:
        now = time.time()
        etime = time.strftime("%I:%M %p", starttime)
        if status == 'replay':
            etime_local = starttime
            if etime_local.tm_hour == 0 and etime_local.tm_min == 0:
                etime = time.strftime("%m/%d/%Y", starttime)
            else:
                etime = time.strftime("%m/%d %I:%M %p", starttime)
            ename = etime + ' - ' + ename
        elif status == 'live':
            starttime_time = time.mktime(starttime)
            length -= (time.time() - starttime_time)
            ename = ename + ' - ' + etime
        else:
            now_time = time.localtime(now)
            if now_time.tm_year == starttime.tm_year and \
                    now_time.tm_mon == starttime.tm_mon and \
                    now_time.tm_mday == starttime.tm_mday:
                etime = time.strftime("%I:%M %p", starttime)
            else:
                etime = time.strftime("%m/%d %I:%M %p", starttime)
            ename = etime + ' - ' + ename

    blackout_text = ''
    if blackout:
        blackout_text = get_string(30580)
    if len(blackout_text) > 0:
        ename = blackout_text + ' ' + ename
    if len(network) > 0:
        if get_setting_as_bool('NoColors'):
            ename = network + ' ' + ename
        else:
            # ename = '[B]%s[/B] %s' % (network, ename)
            ename = '%s %s' % (network, ename)

    requires_auth = check_auth_types(auth_types)
    if requires_auth and not adobe_activate_api.is_authenticated():
        ename = get_string(40300) + ' - ' + ename
    if requires_package:
        ename = get_string(40310) + ' - ' + ename
    return ename, length
Esempio n. 5
0
def ROOT_ITEM(refresh):
    if not adobe_activate_api.is_authenticated():
        addDir('[COLOR=FFFF0000]' + translation(30300) + '[/COLOR]',
               dict(MODE=AUTHENTICATE_MODE),
               defaultreplay)
    current_time = time.strftime("%I:%M %p", time.localtime(time.time()))
    addDir(translation(30850) % current_time,
           dict(MODE=REFRESH_LIVE_MODE),
           defaultlive)
    include_premium = adobe_activate_api.is_authenticated()
    channel_list = events.get_channel_list(include_premium)
    legacy_inst = legacy.Legacy()
    espn_url = list()
    espn_url.append(events.get_live_events_url(channel_list))
    legacy_inst.index_legacy_live_events(dict(ESPN_URL=espn_url))
    if selfAddon.getSetting('ShowAndroidTVMenu') == 'true':
        addDir(translation(30780),
               dict(MODE='/androidtv/'),
               defaultlive)
    if selfAddon.getSetting('ShowAppleTVMenu') == 'true':
        addDir(translation(30730),
               dict(MODE='/appletv/'),
               defaultlive)
    if selfAddon.getSetting('ShowLegacyMenu') == 'true':
        addDir(translation(30740),
               dict(MODE='/legacy/'),
               defaultlive)
    if selfAddon.getSetting('ShowRokuMenu') == 'true':
        addDir(translation(30760),
               dict(MODE='/roku/'),
               defaultlive)
    if selfAddon.getSetting('ShowTVOSMenu') == 'true':
        addDir(translation(30750),
               dict(MODE='/tvos/'),
               defaultlive)
    if adobe_activate_api.is_authenticated():
        addDir('[COLOR=FF00FF00]' + translation(30380) + '[/COLOR]',
           dict(MODE=AUTHENTICATION_DETAILS_MODE),
           defaultfanart)
    xbmcplugin.endOfDirectory(pluginhandle, updateListing=refresh, cacheToDisc=False)
Esempio n. 6
0
def roku_root_menu():
    # Roku config
    url = 'http://assets.espn.go.com/prod/assets/watchespn/roku/config.json'
    json_data = util.get_url_as_json_cache(get_url(url))
    for group in json_data['config']['featured']['groups']:
        if group['visibility'] == 'not authenticated':
            # This represents the duplicate Browse by Sport
            continue
        extra = ''
        if group['visibility'] == 'authenticated':
            if not adobe_activate_api.is_authenticated():
                extra = '*'
        if len(group['contents']) > 1:
            extra += group['name'] + ' - '
        for content in group['contents']:
            addDirectoryItem(
                plugin.handle,
                plugin.url_for(roku_url_mode, url=content['href']),
                ListItem(extra + content['name']), True)
    endOfDirectory(plugin.handle)
def login_tv_provider():
    logging.debug('Authenticate Device')
    if adobe_activate_api.is_authenticated():
        logging.debug('Device already authenticated, skipping authentication')
        dialog = xbmcgui.Dialog()
        dialog.ok(get_string(30037), get_string(30301))
        set_setting('LoggedInToTvProvider', True)
        return True
    else:
        regcode = adobe_activate_api.get_regcode()
        dialog = xbmcgui.Dialog()
        ok = dialog.yesno(get_string(30310), get_string(30320),
                          get_string(30330) % regcode, get_string(30340),
                          get_string(30360), get_string(30350))
        if ok:
            try:
                adobe_activate_api.authenticate(regcode)
                dialog.ok(get_string(30310), get_string(30370))
                set_setting('LoggedInToTvProvider', True)
                return True
            except HTTPError as e:
                dialog.ok(get_string(30037), get_string(30420) % e)
                set_setting('LoggedInToTvProvider', False)
                return False
Esempio n. 8
0
def PLAY_TV(args):

    resource = args.get(ADOBE_RSS, None)
    network_name = args.get(NETWORK_NAME)[0]
    if resource is None:
        event_name = args.get(EVENT_NAME)[0]
        event_guid = args.get(EVENT_GUID)[0]
        event_parental_rating = args.get(EVENT_PARENTAL_RATING)[0]
        resource = adobe_activate_api.get_resource(network_name, event_name, event_guid, event_parental_rating)
    else:
        resource = resource[0]

    requires_auth = does_requires_auth(network_name)

    if requires_auth:
        if not adobe_activate_api.is_authenticated():
            dialog = xbmcgui.Dialog()
            dialog.ok(translation(30037), translation(30410))
            return
        media_token = adobe_activate_api.get_short_media_token(resource)
        token_type = 'ADOBEPASS'
    else:
        media_token = adobe_activate_api.get_device_id()
        token_type = 'DEVICE'


    # see aHR0cDovL2FwaS1hcHAuZXNwbi5jb20vdjEvd2F0Y2gvY2xpZW50cy93YXRjaGVzcG4tdHZvcw== for details
    # see aHR0cDovL2VzcG4uZ28uY29tL3dhdGNoZXNwbi9hcHBsZXR2L2ZlYXR1cmVk for details
    start_session_url = args.get(SESSION_URL)[0]
    params = urllib.urlencode({'partner':'watchespn',
                               'playbackScenario':'HTTP_CLOUD_HIGH',
                               'platform':'chromecast_uplynk',
                               'token':media_token,
                               'tokenType':token_type,
                               'resource':base64.b64encode(resource),
                               'v': '2.0.0'
                               })
    start_session_url += '&' + params

    xbmc.log('ESPN3: start_session_url: ' + start_session_url, LOG_LEVEL)

    session_json = util.get_url_as_json(start_session_url)
    if check_error(session_json):
        return

    playback_url = session_json['session']['playbackUrls']['default']
    xbmc.log(TAG + 'Playback url %s' % playback_url, LOG_LEVEL)
    stream_quality = str(selfAddon.getSetting('StreamQuality'))
    bitrate_limit = int(selfAddon.getSetting('BitrateLimit'))
    xbmc.log(TAG + 'Stream Quality %s' % stream_quality, LOG_LEVEL)
    try:
        m3u8_obj = m3u8.load(playback_url)
    except:
        playback_url += '|Connection=keep-alive&User-Agent=' + urllib.quote(UA_PC) + '&Cookie=_mediaAuth=' +\
                        urllib.quote(session_json['session']['token'])
        item = xbmcgui.ListItem(path=playback_url)
        return xbmcplugin.setResolvedUrl(pluginhandle, True, item)

    success = True
    if m3u8_obj.is_variant:
        stream_options = list()
        bandwidth_key = 'bandwidth'
        m3u8_obj.playlists.sort(key=lambda playlist: playlist.stream_info.bandwidth, reverse=True)
        m3u8_obj.data['playlists'].sort(key=lambda playlist: int(playlist['stream_info'][bandwidth_key]), reverse=True)
        stream_quality_index = str(selfAddon.getSetting('StreamQualityIndex'))
        stream_index = None
        should_ask = False
        try:
            stream_index = int(stream_quality_index)
            if stream_index < 0 or stream_index >= len(m3u8_obj.playlists):
                should_ask = True
        except:
            should_ask = True
        if '0' == stream_quality: # Best
            stream_index = 0
            should_ask = False
            for playlist in m3u8_obj.data['playlists']:
                stream_info = playlist['stream_info']
                bandwidth = int(stream_info[bandwidth_key]) / 1024
                if bandwidth <= bitrate_limit:
                    break
                stream_index = stream_index + 1
        elif '2' == stream_quality: #Ask everytime
            should_ask = True
        if should_ask:
            for playlist in m3u8_obj.data['playlists']:
                stream_info = playlist['stream_info']
                resolution = stream_info['resolution']
                frame_rate = stream_info['frame_rate']
                bandwidth = int(stream_info[bandwidth_key]) / 1024
                if 'average_bandwidth' in stream_info:
                    xbmc.log(TAG + 'bandwidth: %s average bandwidth: %s' %
                             (stream_info['bandwidth'], stream_info['average_bandwidth']), LOG_LEVEL)
                stream_options.append(translation(30450) % (resolution,
                                                      frame_rate,
                                                      bandwidth))
            dialog = xbmcgui.Dialog()
            stream_index = dialog.select(translation(30440), stream_options)
            if stream_index < 0:
                success = False
            else:
                selfAddon.setSetting(id='StreamQualityIndex', value=str(stream_index))

        xbmc.log(TAG + 'Chose stream %d' % stream_index, LOG_LEVEL)
        item = xbmcgui.ListItem(path=m3u8_obj.playlists[stream_index].uri)
        return xbmcplugin.setResolvedUrl(pluginhandle, success, item)
    else:
        item = xbmcgui.ListItem(path=playback_url)
        return xbmcplugin.setResolvedUrl(pluginhandle, success, item)
Esempio n. 9
0
def legacy_root_menu():
    include_premium = adobe_activate_api.is_authenticated()
    channel_list = events.get_channel_list(include_premium)
    curdate = datetime.utcnow()
    upcoming = get_setting_as_int('upcoming') + 1
    days = (curdate + timedelta(days=upcoming)).strftime("%Y%m%d")
    # Live
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(live_events_mode,
                       espn_url=events.get_live_events_url(channel_list)),
        make_list_item(get_string(30029)), True)
    # Upcoming
    espn_url = events.get_upcoming_events_url(channel_list) + '&endDate=' + days \
        + '&startDate=' + curdate.strftime("%Y%m%d")
    addDirectoryItem(plugin.handle,
                     plugin.url_for(list_sports, espn_url=espn_url),
                     make_list_item(get_string(30030)), True)
    enddate = '&endDate=' + (curdate + timedelta(days=1)).strftime("%Y%m%d")
    replays1 = [5, 10, 15, 20, 25]
    replays1 = replays1[get_setting_as_int('replays1')]
    start1 = (curdate - timedelta(days=replays1)).strftime("%Y%m%d")
    replays2 = [10, 20, 30, 40, 50]
    replays2 = replays2[get_setting_as_int('replays2')]
    start2 = (curdate - timedelta(days=replays2)).strftime("%Y%m%d")
    replays3 = [30, 60, 90, 120]
    replays3 = replays3[get_setting_as_int('replays3')]
    start3 = (curdate - timedelta(days=replays3)).strftime("%Y%m%d")
    replays4 = [60, 90, 120, 240]
    replays4 = replays4[get_setting_as_int('replays4')]
    start4 = (curdate - timedelta(days=replays4)).strftime("%Y%m%d")
    start_all = (curdate - timedelta(days=365)).strftime("%Y%m%d")
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start1),
        make_list_item(get_string(30031) % replays1), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start2),
        make_list_item(get_string(30031) % replays2), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start3),
        make_list_item(get_string(30031) % replays3), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       '&endDate=' + start3 + '&startDate=' + start4),
        make_list_item(get_string(30033) % (replays3, replays4)), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start_all),
        make_list_item(get_string(30032)), True)
    xbmcplugin.endOfDirectory(plugin.handle)
Esempio n. 10
0
def index_item(args):
    if args['type'] == 'over':
        return
    sport = args['sport']
    ename = args['eventName']
    sport2 = args['subcategory'] if 'subcategory' in args else sport
    if sport != sport2 and len(sport2) > 0:
        sport += ' (' + sport2 + ')'
    starttime = args['starttime'] if 'starttime' in args else None
    length = int(args['duration'])

    etime = time.time()
    if starttime is not None:
        now = time.time()
        etime = time.strftime("%I:%M %p", starttime)
        if 'replay' in args['type']:
            etime_local = starttime
            if etime_local.tm_hour == 0 and etime_local.tm_min == 0:
                etime = time.strftime("%m/%d/%Y", starttime)
            else:
                etime = time.strftime("%m/%d %I:%M %p", starttime)
            ename = etime + ' - ' + ename
        elif args['type'] == 'live':
            starttime_time = time.mktime(starttime)
            length -= (time.time() - starttime_time)
            ename += ' - ' + etime
        else:
            now_time = time.localtime(now)
            if now_time.tm_year == starttime.tm_year and \
                    now_time.tm_mon == starttime.tm_mon and \
                    now_time.tm_mday == starttime.tm_mday:
                etime = time.strftime("%I:%M %p", starttime)
            else:
                etime = time.strftime("%m/%d %I:%M %p", starttime)
            ename = etime + ' - ' + ename
        aired = time.strftime("%Y-%m-%d", starttime)
    else:
        aired = 0

    network_id = args['networkId'] if 'networkId' in args else ''
    if 'networkName' in args:
        network = args['networkName']
    else:
        network = network_id
    logging.debug('network_id ' + network_id)
    if network_id in NETWORK_ID_TO_NETWORK_NAME:
        network = get_string(NETWORK_ID_TO_NETWORK_NAME[network_id])
    blackout = args['blackout'] if 'blackout' in args else False
    blackout_text = ''
    if blackout:
        blackout_text = get_string(30580)
    if len(blackout_text) > 0:
        ename = blackout_text + ' ' + ename
    if len(network) > 0:
        if get_setting_as_bool('NoColors'):
            ename = network + ' ' + ename
        else:
            ename = '[B]%s[/B] ' % (network) + ename

    description = args['description']
    auth_types = get_auth_types_from_network(network_id)
    requires_auth = check_auth_types(auth_types)
    if requires_auth and not adobe_activate_api.is_authenticated():
        ename = '*' + ename

    logging.debug('Duration %s' % length)

    mpaa = args['parentalRating'] if 'parentRating' in args else 'U'
    info_labels = {
        'title': ename,
        'genre': sport,
        'duration': length,
        'studio': network,
        'mpaa': mpaa,
        'plot': description,
        'aired': aired,
        'premiered': aired
    }

    fanart = args['imageHref']

    if args['type'] == 'upcoming':
        addDirectoryItem(
            plugin.handle,
            plugin.url_for(upcoming_event,
                           event_id=args['eventId'],
                           starttime=etime,
                           event_name=quote_plus(ename.encode('utf-8'))),
            make_list_item(ename, icon=fanart, info_labels=info_labels))
    else:
        adobe_rss = args['adobeRSS'] if 'adobeRSS' in args else None
        guid = args['guid'] if 'guid' in args else None
        if adobe_rss is None and guid is None:
            addDirectoryItem(
                plugin.handle,
                plugin.url_for(play_item,
                               url=args['sessionUrl'],
                               event_id=args['eventId']),
                make_list_item(ename, icon=fanart, info_labels=info_labels))
        else:
            if 'adobeRSS' in args:
                adobe_rss = args['adobeRSS']
            else:
                adobe_rss = adobe_activate_api.get_resource(
                    args['channelResourceId'], args['eventName'], args['guid'],
                    mpaa)

            if include_item(network_id):
                logging.debug('Adding %s with handle %d and id %s' %
                              (ename, plugin.handle, args['eventId']))
                logging.debug(adobe_rss)
                addDirectoryItem(
                    plugin.handle,
                    plugin.url_for(play_tv,
                                   event_id=args['eventId'],
                                   session_url=args['sessionUrl'],
                                   network_name=args['networkId'],
                                   resource=quote_plus(
                                       adobe_rss.encode('utf-8'))),
                    make_list_item(ename, icon=fanart,
                                   info_labels=info_labels))
            else:
                logging.debug('Skipping %s' % args['networkId'])
Esempio n. 11
0
def PLAY_TV(args):

    resource = args.get(ADOBE_RSS, None)
    network_name = args.get(NETWORK_NAME)[0]
    if resource is None:
        event_name = args.get(EVENT_NAME)[0]
        event_guid = args.get(EVENT_GUID)[0]
        event_parental_rating = args.get(EVENT_PARENTAL_RATING)[0]
        channel_resource_id = args.get(CHANNEL_RESOURCE_ID)[0]
        resource = adobe_activate_api.get_resource(channel_resource_id,
                                                   event_name, event_guid,
                                                   event_parental_rating)
    else:
        resource = resource[0]

    requires_auth = does_requires_auth(network_name)
    if not requires_auth:
        xbmc.log(TAG + ' Forcing auth', xbmc.LOGDEBUG)
        requires_auth = adobe_activate_api.is_authenticated()

    if requires_auth:
        if not adobe_activate_api.is_authenticated():
            dialog = xbmcgui.Dialog()
            dialog.ok(translation(30037), translation(30410))
            return
        try:
            # testing code raise urllib2.HTTPError(url='test', code=403, msg='no', hdrs=dict(), fp=None)
            xbmc.log(TAG + ' getting media token for resource %s' % resource,
                     xbmc.LOGDEBUG)
            media_token = adobe_activate_api.get_short_media_token(resource)
        except urllib2.HTTPError as http_exception:
            xbmc.log(TAG + ' error getting media token %s' % http_exception,
                     xbmc.LOGDEBUG)
            if http_exception.code == 410 or http_exception.code == 404 or http_exception.code == 401:
                dialog = xbmcgui.Dialog()
                dialog.ok(translation(30037), translation(30840))
                adobe_activate_api.deauthorize()
                xbmcplugin.endOfDirectory(pluginhandle,
                                          succeeded=False,
                                          updateListing=True)
                return
            elif http_exception.code == 403:
                # Check for blackout
                dialog = xbmcgui.Dialog()
                ok = dialog.yesno(translation(30037), translation(30900))
                if ok:
                    setting = get_setting_from_channel(network_name)
                    if setting is not None:
                        selfAddon.setSetting(setting, 'false')
                return
            else:
                raise http_exception
        except adobe_activate_api.AuthorizationException as exception:
            xbmc.log(TAG + ' Error authorizating media token %s' % exception,
                     xbmc.LOGDEBUG)
            dialog = xbmcgui.Dialog()
            dialog.ok(translation(30037), translation(30840))
            adobe_activate_api.deauthorize()
            xbmcplugin.endOfDirectory(pluginhandle,
                                      succeeded=False,
                                      updateListing=True)
            return

        token_type = 'ADOBEPASS'
    else:
        media_token = adobe_activate_api.get_device_id()
        token_type = 'DEVICE'

    # see aHR0cDovL2FwaS1hcHAuZXNwbi5jb20vdjEvd2F0Y2gvY2xpZW50cy93YXRjaGVzcG4tdHZvcw== for details
    # see aHR0cDovL2VzcG4uZ28uY29tL3dhdGNoZXNwbi9hcHBsZXR2L2ZlYXR1cmVk for details
    start_session_url = args.get(SESSION_URL)[0]
    params = urllib.urlencode({
        'partner': 'watchespn',
        'playbackScenario': 'HTTP_CLOUD_HIGH',
        'platform': 'chromecast_uplynk',
        'token': media_token,
        'tokenType': token_type,
        'resource': base64.b64encode(resource),
        'v': '2.0.0'
    })
    start_session_url += '&' + params

    xbmc.log('ESPN3: start_session_url: ' + start_session_url, xbmc.LOGDEBUG)

    try:
        session_json = util.get_url_as_json(start_session_url)
    except urllib2.HTTPError as exception:
        if exception.code == 403:
            session_json = json.load(exception)
            xbmc.log(TAG + 'checking for errors in %s' % session_json)
        else:
            raise exception

    if check_error(session_json):
        return

    playback_url = session_json['session']['playbackUrls']['default']
    xbmc.log(TAG + 'Playback url %s' % playback_url, xbmc.LOGDEBUG)
    stream_quality = str(selfAddon.getSetting('StreamQuality'))
    bitrate_limit = int(selfAddon.getSetting('BitrateLimit'))
    xbmc.log(TAG + 'Stream Quality %s' % stream_quality, xbmc.LOGDEBUG)
    try:
        m3u8_obj = m3u8.load(playback_url)
    except:
        playback_url += '|Connection=keep-alive&User-Agent=' + urllib.quote(UA_PC) + '&Cookie=_mediaAuth=' +\
                        urllib.quote(session_json['session']['token'])
        item = xbmcgui.ListItem(path=playback_url)
        return xbmcplugin.setResolvedUrl(pluginhandle, True, item)

    success = True
    if m3u8_obj.is_variant:
        stream_options = list()
        bandwidth_key = 'bandwidth'
        m3u8_obj.playlists.sort(
            key=lambda playlist: playlist.stream_info.bandwidth, reverse=True)
        m3u8_obj.data['playlists'].sort(
            key=lambda playlist: int(playlist['stream_info'][bandwidth_key]),
            reverse=True)
        stream_quality_index = str(selfAddon.getSetting('StreamQualityIndex'))
        stream_index = None
        should_ask = False
        try:
            stream_index = int(stream_quality_index)
            if stream_index < 0 or stream_index >= len(m3u8_obj.playlists):
                should_ask = True
        except:
            should_ask = True
        if '0' == stream_quality:  # Best
            stream_index = 0
            should_ask = False
            for playlist in m3u8_obj.data['playlists']:
                stream_info = playlist['stream_info']
                bandwidth = int(stream_info[bandwidth_key]) / 1024
                if bandwidth <= bitrate_limit:
                    break
                stream_index += 1
        elif '2' == stream_quality:  #Ask everytime
            should_ask = True
        if should_ask:
            for playlist in m3u8_obj.data['playlists']:
                stream_info = playlist['stream_info']
                resolution = stream_info['resolution']
                frame_rate = stream_info['frame_rate']
                bandwidth = int(stream_info[bandwidth_key]) / 1024
                if 'average_bandwidth' in stream_info:
                    xbmc.log(
                        TAG + 'bandwidth: %s average bandwidth: %s' %
                        (stream_info['bandwidth'],
                         stream_info['average_bandwidth']), xbmc.LOGDEBUG)
                stream_options.append(
                    translation(30450) % (resolution, frame_rate, bandwidth))
            dialog = xbmcgui.Dialog()
            stream_index = dialog.select(translation(30440), stream_options)
            if stream_index < 0:
                success = False
            else:
                selfAddon.setSetting(id='StreamQualityIndex',
                                     value=str(stream_index))

        xbmc.log(TAG + 'Chose stream %d' % stream_index, xbmc.LOGDEBUG)
        item = xbmcgui.ListItem(path=m3u8_obj.playlists[stream_index].uri)
        xbmcplugin.setResolvedUrl(pluginhandle, success, item)
    else:
        item = xbmcgui.ListItem(path=playback_url)
        xbmcplugin.setResolvedUrl(pluginhandle, success, item)
Esempio n. 12
0
        xbmcplugin.setResolvedUrl(pluginhandle, success, item)
    else:
        item = xbmcgui.ListItem(path=playback_url)
        xbmcplugin.setResolvedUrl(pluginhandle, success, item)


base_url = sys.argv[0]
xbmc.log(TAG + 'QS: %s' % sys.argv[2], xbmc.LOGDEBUG)
args = urlparse.parse_qs(sys.argv[2][1:])
xbmc.log('ESPN3: args %s' % args, xbmc.LOGDEBUG)
mode = args.get(MODE, None)

refresh = False
if mode is not None and mode[0] == AUTHENTICATE_MODE:
    xbmc.log('Authenticate Device', xbmc.LOGDEBUG)
    if adobe_activate_api.is_authenticated():
        xbmc.log('Device already authenticated, skipping authentication',
                 xbmc.LOGDEBUG)
    else:
        regcode = adobe_activate_api.get_regcode()
        dialog = xbmcgui.Dialog()
        ok = dialog.yesno(translation(30310), translation(30320),
                          translation(30330) % regcode, translation(30340),
                          translation(30360), translation(30350))
        if ok:
            try:
                adobe_activate_api.authenticate(regcode)
                dialog.ok(translation(30310), translation(30370))
            except urllib2.HTTPError as e:
                dialog.ok(translation(30037), translation(30420) % e)
    mode = None
Esempio n. 13
0
def check_auth_status(auth_types, packages, resource, network_name):
    logging.debug('Checking auth of %s and %s' % (auth_types, packages))

    if requires_adobe_auth(auth_types):
        # Adobe auth
        if not adobe_activate_api.is_authenticated():
            dialog = xbmcgui.Dialog()
            ret = dialog.yesno(get_string(30038),
                               get_string(30050),
                               yeslabel=get_string(30051),
                               nolabel=get_string(30360))
            if ret:
                authed = auth_routes.login_tv_provider()
                if not authed:
                    return None
            else:
                return None
        try:
            # testing code raise HTTPError(url='test', code=403, msg='no', hdrs=dict(), fp=None)
            logging.debug('getting media token for resource %s' % resource)
            return adobe_activate_api.get_short_media_token(resource)
        except HTTPError as http_exception:
            logging.debug('error getting media token %s' % http_exception)
            if http_exception.code == 410 or http_exception.code == 404 or http_exception.code == 401:
                dialog = xbmcgui.Dialog()
                dialog.ok(get_string(30037), get_string(30840))
                adobe_activate_api.deauthorize()
                return None
            elif http_exception.code == 403:
                # Check for blackout
                dialog = xbmcgui.Dialog()
                ok = dialog.yesno(get_string(30037),
                                  get_string(30900) % http_exception)
                if ok:
                    setting = get_setting_from_channel(network_name)
                    if setting is not None:
                        set_setting(setting, False)
                return None
            else:
                return None
        except adobe_activate_api.AuthorizationException as exception:
            logging.debug('Error authorizating media token %s' % exception)
            if 'message' in exception.resp and 'details' in exception.resp:
                message = exception.resp['message']
                details = exception.resp['details']
                if 'noAuthz' == message:
                    # Channel likely not supported
                    dialog = xbmcgui.Dialog()
                    ok = dialog.yesno(get_string(30037),
                                      get_string(30900) % details)
                    if ok:
                        setting = get_setting_from_channel(network_name)
                        if setting is not None:
                            set_setting(setting, False)
                    return None
            dialog = xbmcgui.Dialog()
            dialog.ok(get_string(30037), get_string(30840))
            adobe_activate_api.deauthorize()
            return None
    elif 'direct' in auth_types:
        # bam authentication
        if not espnplus.can_we_access_without_prompt():
            logging.debug('Invalid token')
            dialog = xbmcgui.Dialog()
            ret = dialog.yesno(get_string(30038),
                               get_string(30060),
                               yeslabel=get_string(30061),
                               nolabel=get_string(30360))
            if ret:
                authed = auth_routes.login_espn_plus()
                if not authed:
                    return None
            else:
                return None
        espnplus.ensure_valid_access_token()

        # Check packages
        entitlements = espnplus.get_entitlements()
        has_entitlement = is_entitled(packages, entitlements)

        if not has_entitlement:
            missing_packages = get_missing_packages(packages, entitlements)
            dialog = xbmcgui.Dialog()
            dialog.ok(get_string(40000),
                      get_string(40270) % ', '.join(missing_packages))

        return espnplus.get_bam_account_access_token()

    elif 'isp' in auth_types:
        return adobe_activate_api.get_device_id()
    logging.error('Unable to handle auth types')
    return None
Esempio n. 14
0
        item = xbmcgui.ListItem(path=m3u8_obj.playlists[stream_index].uri)
        xbmcplugin.setResolvedUrl(pluginhandle, success, item)
    else:
        item = xbmcgui.ListItem(path=playback_url)
        xbmcplugin.setResolvedUrl(pluginhandle, success, item)

base_url = sys.argv[0]
xbmc.log(TAG + 'QS: %s' % sys.argv[2], xbmc.LOGDEBUG)
args = urlparse.parse_qs(sys.argv[2][1:])
xbmc.log('ESPN3: args %s' % args, xbmc.LOGDEBUG)
mode = args.get(MODE, None)

refresh = False
if mode is not None and mode[0] == AUTHENTICATE_MODE:
    xbmc.log('Authenticate Device', xbmc.LOGDEBUG)
    if adobe_activate_api.is_authenticated():
        xbmc.log('Device already authenticated, skipping authentication', xbmc.LOGDEBUG)
    else:
        regcode = adobe_activate_api.get_regcode()
        dialog = xbmcgui.Dialog()
        ok = dialog.yesno(translation(30310),
                       translation(30320),
                       translation(30330) % regcode,
                       translation(30340),
                       translation(30360),
                       translation(30350))
        if ok:
            try:
                adobe_activate_api.authenticate()
                dialog.ok(translation(30310), translation(30370))
            except urllib2.HTTPError as e: