Beispiel #1
0
def api_vod_seasons(id):
    seasons = []

    for entry in CONST_VOD_CAPABILITY:
        sql_query = "SELECT * FROM `{table}` WHERE id='{id}'".format(
            table=entry['file'], id=id)
        sql_data = query_epg(query=sql_query,
                             return_result=True,
                             return_insert=False,
                             commit=False)

        if len(sql_data) > 0:
            for row in sql_data:
                sql_seasons = json.loads(row['seasons'])

                for season in sql_seasons:
                    seasons.append({
                        'id': season['id'],
                        'seriesNumber': season['seriesNumber'],
                        'description': row['description'],
                        'image': row['icon']
                    })

            break

    return {'type': 'seasons', 'seasons': seasons, 'watchlist': id}
Beispiel #2
0
def plugin_process_info(playdata):
    info = {
        'label1': '',
        'label2': '',
        'description': '',
        'image': '',
        'image_large': '',
        'duration': 0,
        'credits': [],
        'cast': [],
        'director': [],
        'writer': [],
        'genres': [],
        'year': '',
    }

    if playdata['info']:
        if check_key(playdata['info'], 'params'):
            if check_key(playdata['info']['params'], 'start') and check_key(
                    playdata['info']['params'], 'end'):
                startT = datetime.datetime.fromtimestamp(
                    time.mktime(
                        time.strptime(playdata['info']['params']['start'],
                                      "%Y-%m-%dT%H:%M:%SZ")))
                endT = datetime.datetime.fromtimestamp(
                    time.mktime(
                        time.strptime(playdata['info']['params']['end'],
                                      "%Y-%m-%dT%H:%M:%SZ")))

                info['duration'] = int((endT - startT).total_seconds())

                if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                    info[
                        'label1'] = '{weekday} {day} {month} {yearhourminute} '.format(
                            weekday=date_to_nl_dag(startT),
                            day=startT.strftime("%d"),
                            month=date_to_nl_maand(startT),
                            yearhourminute=startT.strftime("%Y %H:%M"))
                else:
                    info['label1'] = startT.strftime(
                        "%A %d %B %Y %H:%M ").capitalize()

                info['label1'] += " - "

        if playdata['title']:
            info['label1'] += playdata['title'] + ' - '

        if check_key(playdata['info'], 'title'):
            info['label1'] += playdata['info']['title']

        if check_key(playdata['info'], 'descriptiondescription'):
            info['description'] = playdata['info']['description']

        if check_key(playdata['info'], 'images') and check_key(
                playdata['info']['images'][0], 'url'):
            info['image'] = playdata['info']['images'][0]['url']
            info['image_large'] = playdata['info']['images'][0]['url']

        if check_key(playdata['info'], 'params'):
            if check_key(playdata['info']['params'], 'credits'):
                for castmember in playdata['info']['params']['credits']:
                    if castmember['role'] == "Actor":
                        info['cast'].append(castmember['person'])
                    elif castmember['role'] == "Director":
                        info['director'].append(castmember['person'])
                    elif castmember['role'] == "Writer":
                        info['writer'].append(castmember['person'])

            if check_key(playdata['info']['params'], 'genres'):
                for genre in playdata['info']['params']['genres']:
                    info['genres'].append(genre['title'])

            if check_key(playdata['info']['params'], 'duration'):
                info['duration'] = playdata['info']['params']['duration']

            epcode = ''

            if check_key(playdata['info']['params'], 'seriesSeason'):
                epcode += 'S' + unicode(
                    playdata['info']['params']['seriesSeason'])

            if check_key(playdata['info']['params'], 'seriesEpisode'):
                epcode += 'E' + unicode(
                    playdata['info']['params']['seriesEpisode'])

            if check_key(playdata['info']['params'], 'episodeTitle'):
                info['label2'] = playdata['info']['params']['episodeTitle']

                if len(epcode) > 0:
                    info['label2'] += " (" + epcode + ")"
            elif check_key(playdata['info'], 'title'):
                info['label2'] = playdata['info']['title']

            if check_key(playdata['info']['params'], 'channelId'):
                query = "SELECT name FROM `channels` WHERE id='{channel}'".format(
                    channel=playdata['info']['params']['channelId'])
                data = query_epg(query=query,
                                 return_result=True,
                                 return_insert=False,
                                 commit=False)

                if data:
                    for row in data:
                        info['label2'] += " - " + row['name']

    return info
Beispiel #3
0
def plugin_process_info(playdata):
    info = {
        'label1': '',
        'label2': '',
        'description': '',
        'image': '',
        'image_large': '',
        'duration': 0,
        'credits': [],
        'cast': [],
        'director': [],
        'writer': [],
        'genres': [],
        'year': '',
    }

    if playdata['info'] and check_key(playdata['info'], 'resultObj'):
        for row in playdata['info']['resultObj']['containers']:
            if check_key(row, 'metadata'):
                if check_key(row['metadata'], 'airingStartTime') and check_key(
                        row['metadata'], 'airingEndTime'):
                    startT = datetime.datetime.fromtimestamp(
                        int(int(row['metadata']['airingStartTime']) / 1000))
                    startT = convert_datetime_timezone(startT, "UTC", "UTC")
                    endT = datetime.datetime.fromtimestamp(
                        int(int(row['metadata']['airingEndTime']) / 1000))
                    endT = convert_datetime_timezone(endT, "UTC", "UTC")

                    info['duration'] = int((endT - startT).total_seconds())

                    if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                        info[
                            'label1'] = '{weekday} {day} {month} {yearhourminute} '.format(
                                weekday=date_to_nl_dag(startT),
                                day=startT.strftime("%d"),
                                month=date_to_nl_maand(startT),
                                yearhourminute=startT.strftime("%Y %H:%M"))
                    else:
                        info['label1'] = startT.strftime(
                            "%A %d %B %Y %H:%M ").capitalize()

                    info['label1'] += " - "

                if playdata['title']:
                    info['label1'] += playdata['title'] + ' - '

                if check_key(row['metadata'], 'title'):
                    info['label1'] += row['metadata']['title']

                if check_key(row['metadata'], 'longDescription'):
                    info['description'] = row['metadata']['longDescription']

                if playdata['type'] == 'VOD':
                    imgtype = 'vod'
                else:
                    imgtype = 'epg'

                if check_key(row['metadata'], 'pictureUrl'):
                    info[
                        'image'] = "{image_url}/{imgtype}/{image}/1920x1080.jpg?blurred=false".format(
                            image_url=CONST_IMAGE_URL,
                            imgtype=imgtype,
                            image=row['metadata']['pictureUrl'])
                    info[
                        'image_large'] = "{image_url}/{imgtype}/{image}/1920x1080.jpg?blurred=false".format(
                            image_url=CONST_IMAGE_URL,
                            imgtype=imgtype,
                            image=row['metadata']['pictureUrl'])

                if check_key(row['metadata'], 'actors'):
                    for castmember in row['metadata']['actors']:
                        info['cast'].append(castmember)

                if check_key(row['metadata'], 'directors'):
                    for directormember in row['metadata']['directors']:
                        info['director'].append(directormember)

                if check_key(row['metadata'], 'authors'):
                    for writermember in row['metadata']['authors']:
                        info['writer'].append(writermember)

                if check_key(row['metadata'], 'genres'):
                    for genre in row['metadata']['genres']:
                        info['genres'].append(genre)

                if check_key(row['metadata'], 'duration'):
                    info['duration'] = row['metadata']['duration']

                epcode = ''

                if check_key(row['metadata'], 'season'):
                    epcode += 'S' + unicode(row['metadata']['season'])

                if check_key(row['metadata'], 'episodeNumber'):
                    epcode += 'E' + unicode(row['metadata']['episodeNumber'])

                if check_key(row['metadata'], 'episodeTitle'):
                    info['label2'] = row['metadata']['episodeTitle']

                    if len(epcode) > 0:
                        info['label2'] += " (" + epcode + ")"
                elif check_key(row['metadata'], 'title'):
                    info['label2'] = row['metadata']['title']

                if check_key(row, 'channel'):
                    if check_key(row['channel'], 'channelName'):
                        info['label2'] += " - " + row['channel']['channelName']
    else:
        nowstamp = int(time.time())

        query = "SELECT a.*, b.name FROM `epg` as a JOIN `channels` as b ON a.channel=b.id WHERE a.channel='{channel}' AND a.start < {nowstamp} AND a.end > {nowstamp}".format(
            channel=playdata['channel'], nowstamp=nowstamp)
        data = query_epg(query=query,
                         return_result=True,
                         return_insert=False,
                         commit=False)

        for row in data:
            startT = datetime.datetime.fromtimestamp(int(row['start']))
            startT = convert_datetime_timezone(startT, "UTC", "UTC")
            endT = datetime.datetime.fromtimestamp(int(row['end']))
            endT = convert_datetime_timezone(endT, "UTC", "UTC")

            info['duration'] = int((endT - startT).total_seconds())

            if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                info[
                    'label1'] = '{weekday} {day} {month} {yearhourminute} '.format(
                        weekday=date_to_nl_dag(startT),
                        day=startT.strftime("%d"),
                        month=date_to_nl_maand(startT),
                        yearhourminute=startT.strftime("%Y %H:%M"))
            else:
                info['label1'] = startT.strftime(
                    "%A %d %B %Y %H:%M ").capitalize()

            info['label1'] += " - "

            if playdata['title']:
                info['label1'] += playdata['title'] + ' - '

            info['label1'] += row['title']

            info['description'] = row['description']

            info['image'] = row['icon']
            info['image_large'] = row['icon']

            info['label2'] = row['title']
            info['label2'] += " - " + row['name']

    return info
Beispiel #4
0
def api_test_channels(tested=False, channel=None):
    profile_settings = load_profile(profile_id=1)

    if channel:
        channel = unicode(channel)

    try:
        if not profile_settings['last_login_success'] == 1 or not settings.getBool(key='run_tests') or not api_get_session():
            return 5

        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=1,profile_id=1)
        query_settings(query=query, return_result=False, return_insert=False, commit=True)

        query = "SELECT * FROM `channels`"
        channels = query_epg(query=query, return_result=True, return_insert=False, commit=False)
        results = load_tests(profile_id=1)

        count = 0
        first = True
        last_tested_found = False
        test_run = False
        user_agent = profile_settings['user_agent']

        if not results:
            results = {}

        for row in channels:
            if count == 5 or (count == 1 and tested):
                if test_run:
                    update_prefs()

                query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                query_settings(query=query, return_result=False, return_insert=False, commit=True)
                return count

            id = unicode(row['id'])

            if len(id) > 0:
                if channel:
                    if not id == channel:
                        continue
                elif tested:
                    if unicode(profile_settings['last_tested']) == id:
                        last_tested_found = True
                        continue
                    elif last_tested_found:
                        pass
                    else:
                        continue

                if check_key(results, id) and not tested and not first:
                    continue

                livebandwidth = 0
                replaybandwidth = 0
                live = 0
                replay = 0
                epg = 0
                guide = 0

                profile_settings = load_profile(profile_id=1)

                if profile_settings['last_playing'] > int(time.time() - 300):
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)
                    return 5

                playdata = api_play_url(type='channel', channel=id, id=None, test=True)

                if first and not profile_settings['last_login_success']:
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)
                    return 5

                if len(playdata['path']) > 0:
                    CDMHEADERS = {
                        'User-Agent': user_agent,
                        'X_CSRFToken': profile_settings['csrf_token'],
                        'Cookie': playdata['license']['cookie'],
                    }

                    if check_key(playdata, 'license') and check_key(playdata['license'], 'triggers') and check_key(playdata['license']['triggers'][0], 'licenseURL'):
                        if check_key(playdata['license']['triggers'][0], 'customData'):
                            CDMHEADERS['AcquireLicense.CustomData'] = playdata['license']['triggers'][0]['customData']
                            CDMHEADERS['CADeviceType'] = 'Widevine OTT client'

                    session = Session(headers=CDMHEADERS)
                    resp = session.get(playdata['path'])

                    if resp.status_code == 200:
                        livebandwidth = find_highest_bandwidth(xml=resp.text)
                        live = 1

                if check_key(results, id) and first and not tested:
                    first = False

                    if live == 1:
                        continue
                    else:
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                first = False
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 5:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() - 300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                militime = int(int(time.time() - 86400) * 1000)

                session_post_data = {
                    'needChannel': '0',
                    'queryChannel': {
                        'channelIDs': [
                            id,
                        ],
                        'isReturnAllMedia': '1',
                    },
                    'queryPlaybill': {
                        'count': '1',
                        'endTime': militime,
                        'isFillProgram': '1',
                        'offset': '0',
                        'startTime': militime,
                        'type': '0',
                    }
                }

                headers = {'Content-Type': 'application/json', 'X_CSRFToken': profile_settings['csrf_token']}

                channel_url = '{base_url}/VSP/V3/QueryPlaybillListStcProps?SID=queryPlaybillListStcProps3&DEVICE=PC&DID={deviceID}&from=throughMSAAccess'.format(base_url=CONST_BASE_URL, deviceID=profile_settings['devicekey'])

                download = api_download(url=channel_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True)
                data = download['data']
                code = download['code']

                if code and code == 200 and data and check_key(data, 'channelPlaybills') and check_key(data['channelPlaybills'][0], 'playbillLites') and check_key(data['channelPlaybills'][0]['playbillLites'][0], 'ID'):
                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() - 300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                    playdata = api_play_url(type='program', channel=id, id=data['channelPlaybills'][0]['playbillLites'][0]['ID'], test=True)

                    if len(playdata['path']) > 0:
                        CDMHEADERS = {
                            'User-Agent': user_agent,
                            'X_CSRFToken': profile_settings['csrf_token'],
                            'Cookie': playdata['license']['cookie'],
                        }

                        if check_key(playdata, 'license') and check_key(playdata['license'], 'triggers') and check_key(playdata['license']['triggers'][0], 'licenseURL'):
                            if check_key(playdata['license']['triggers'][0], 'customData'):
                                CDMHEADERS['AcquireLicense.CustomData'] = playdata['license']['triggers'][0]['customData']
                                CDMHEADERS['CADeviceType'] = 'Widevine OTT client'

                        session = Session(headers=CDMHEADERS)
                        resp = session.get(playdata['path'])

                        if resp.status_code == 200:
                            replaybandwidth = find_highest_bandwidth(xml=resp.text)
                            replay = 1

                query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format(channel=id)
                data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

                if len(data) > 0:
                    guide = 1

                    if live == 1:
                        epg = 1

                if not xbmc.Monitor().abortRequested():
                    query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format(last_tested=id,profile_id=1)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)

                    query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format(profile_id=1, id=id, live=live, livebandwidth=livebandwidth, replay=replay, replaybandwidth=replaybandwidth, epg=epg, guide=guide)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)

                test_run = True
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 15:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() - 300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                count += 1
    except:
        if test_run:
            update_prefs()

        count = 5

    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
    query_settings(query=query, return_result=False, return_insert=False, commit=True)

    return count
Beispiel #5
0
def api_play_url(type, channel=None, id=None, video_data=None, test=False, from_beginning=0, pvr=0):
    playdata = {'path': '', 'license': '', 'info': '', 'alt_path': '', 'alt_license': ''}

    if not api_get_session():
        return playdata

    alt_path = ''
    alt_license = ''

    from_beginning = int(from_beginning)
    pvr = int(pvr)
    profile_settings = load_profile(profile_id=1)

    headers = {'Content-Type': 'application/json', 'X_CSRFToken': profile_settings['csrf_token']}

    mediaID = None
    info = {}

    if not type or not len(unicode(type)) > 0:
        return playdata

    if not test:
        counter = 0

        while not xbmc.Monitor().abortRequested() and counter < 5:
            profile_settings = load_profile(profile_id=1)

            if profile_settings['test_running'] == 0:
                break

            counter += 1

            query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format(last_playing=int(time.time()),profile_id=1)
            query_settings(query=query, return_result=False, return_insert=False, commit=True)

            if xbmc.Monitor().waitForAbort(1):
                break

        if xbmc.Monitor().abortRequested():
            return playdata

    militime = int(time.time() * 1000)

    if not type == 'vod':
        if video_data:
            try:
                video_data = json.loads(video_data)
                mediaID = int(video_data['media_id']) + 1
            except:
                pass

        query = "SELECT assetid FROM `channels` WHERE id='{channel}'".format(channel=channel)
        data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

        if data:
            for row in data:
                mediaID = row['assetid']

    if type == 'channel' and channel:
        if test:
            pass
        elif not pvr == 1 or settings.getBool(key='ask_start_from_beginning') or from_beginning == 1:
            session_post_data = {
                'needChannel': '0',
                'queryChannel': {
                    'channelIDs': [
                        channel,
                    ],
                    'isReturnAllMedia': '1',
                },
                'queryPlaybill': {
                    'count': '1',
                    'endTime': militime,
                    'isFillProgram': '1',
                    'offset': '0',
                    'startTime': militime,
                    'type': '0',
                }
            }

            channel_url = '{base_url}/VSP/V3/QueryPlaybillListStcProps?SID=queryPlaybillListStcProps3&DEVICE=PC&DID={deviceID}&from=throughMSAAccess'.format(base_url=CONST_BASE_URL, deviceID=profile_settings['devicekey'])

            download = api_download(url=channel_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True)
            data = download['data']
            code = download['code']

            if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'channelPlaybills') or not check_key(data['channelPlaybills'][0], 'playbillLites') or not check_key(data['channelPlaybills'][0]['playbillLites'][0], 'ID'):
                return playdata

            id = data['channelPlaybills'][0]['playbillLites'][0]['ID']

            session_post_data = {
                'playbillID': id,
                'channelNamespace': '310303',
                'isReturnAllMedia': '1',
            }

            program_url = '{base_url}/VSP/V3/QueryPlaybill?from=throughMSAAccess'.format(base_url=CONST_BASE_URL)

            download = api_download(url=program_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True)
            data = download['data']
            code = download['code']

            if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playbillDetail'):
                info = {}
            else:
                info = data['playbillDetail']

            if settings.getBool(key='ask_start_from_beginning') or from_beginning == 1:
                session_post_data = {
                    "businessType": "PLTV",
                    "channelID": channel,
                    "checkLock": {
                        "checkType": "0",
                    },
                    "isHTTPS": "1",
                    "isReturnProduct": "1",
                    "mediaID": mediaID,
                    'playbillID': id,
                }

                play_url_path = '{base_url}/VSP/V3/PlayChannel?from=throughMSAAccess'.format(base_url=CONST_BASE_URL)

                download = api_download(url=play_url_path, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True)
                data = download['data']
                code = download['code']

                if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playURL'):
                    pass
                else:
                    alt_path = data['playURL']

                    if check_key(data, 'authorizeResult'):
                        profile_settings = load_profile(profile_id=1)

                        data['authorizeResult']['cookie'] = api_getCookies(profile_settings['cookies'], '')
                        alt_license = data['authorizeResult']

        session_post_data = {
            "businessType": "BTV",
            "channelID": channel,
            "checkLock": {
                "checkType": "0",
            },
            "isHTTPS": "1",
            "isReturnProduct": "1",
            "mediaID": mediaID,
        }

    elif type == 'program' and id:
        if not test and not pvr == 1:
            session_post_data = {
                'playbillID': id,
                'channelNamespace': '310303',
                'isReturnAllMedia': '1',
            }

            program_url = '{base_url}/VSP/V3/QueryPlaybill?from=throughMSAAccess'.format(base_url=CONST_BASE_URL)

            download = api_download(url=program_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True)
            data = download['data']
            code = download['code']

            if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playbillDetail'):
                info = {}
            else:
                info = data['playbillDetail']

        session_post_data = {
            "businessType": "CUTV",
            "channelID": channel,
            "checkLock": {
                "checkType": "0",
            },
            "isHTTPS": "1",
            "isReturnProduct": "1",
            "mediaID": mediaID,
            "playbillID": id,
        }
    elif type == 'vod' and id:
        session_post_data = {
            'VODID': id
        }

        program_url = '{base_url}/VSP/V3/QueryVOD?from=throughMSAAccess'.format(base_url=CONST_BASE_URL)

        download = api_download(url=program_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True)
        data = download['data']
        code = download['code']

        if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'VODDetail') or not check_key(data['VODDetail'], 'VODType'):
            return playdata

        info = data['VODDetail']

        session_post_data = {
            "VODID": id,
            "checkLock": {
                "checkType": "0",
            },
            "isHTTPS": "1",
            "isReturnProduct": "1",
            "mediaID": '',
        }

        if not check_key(info, 'mediaFiles') or not check_key(info['mediaFiles'][0], 'ID'):
            return playdata

        if check_key(info, 'series') and check_key(info['series'][0], 'VODID'):
            session_post_data["seriesID"] = info['series'][0]['VODID']

        session_post_data["mediaID"] = info['mediaFiles'][0]['ID']

    if not len(unicode(session_post_data["mediaID"])) > 0:
        return playdata

    if type == 'vod':
        play_url_path = '{base_url}/VSP/V3/PlayVOD?from=throughMSAAccess'.format(base_url=CONST_BASE_URL)
    else:
        play_url_path = '{base_url}/VSP/V3/PlayChannel?from=throughMSAAccess'.format(base_url=CONST_BASE_URL)

    if xbmc.Monitor().abortRequested():
        return playdata

    download = api_download(url=play_url_path, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True)
    data = download['data']
    code = download['code']

    if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playURL'):
        return playdata

    path = data['playURL']

    if check_key(data, 'authorizeResult'):
        profile_settings = load_profile(profile_id=1)

        data['authorizeResult']['cookie'] = api_getCookies(profile_settings['cookies'], '')
        license = data['authorizeResult']

    playdata = {'path': path, 'license': license, 'info': info, 'alt_path': alt_path, 'alt_license': alt_license}

    return playdata
Beispiel #6
0
def api_test_channels(tested=False, channel=None):
    profile_settings = load_profile(profile_id=1)

    if channel:
        channel = unicode(channel)

    try:
        if not profile_settings['last_login_success'] == 1 or not settings.getBool(key='run_tests') or not api_get_session():
            return 5

        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=1,profile_id=1)
        query_settings(query=query, return_result=False, return_insert=False, commit=True)

        query = "SELECT * FROM `channels`"
        channels = query_epg(query=query, return_result=True, return_insert=False, commit=False)
        results = load_tests(profile_id=1)

        count = 0
        first = True
        last_tested_found = False
        test_run = False
        user_agent = profile_settings['user_agent']

        if not results:
            results = {}

        for row in channels:
            if count == 5 or (count == 1 and tested):
                if test_run:
                    update_prefs()

                query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                query_settings(query=query, return_result=False, return_insert=False, commit=True)
                return count

            id = unicode(row['id'])

            if len(id) > 0:
                if channel:
                    if not id == channel:
                        continue
                elif tested:
                    if unicode(profile_settings['last_tested']) == id:
                        last_tested_found = True
                        continue
                    elif last_tested_found:
                        pass
                    else:
                        continue

                if check_key(results, id) and not tested and not first:
                    continue

                livebandwidth = 0
                replaybandwidth = 0
                live = 0
                replay = 0
                epg = 0
                guide = 0

                profile_settings = load_profile(profile_id=1)

                if profile_settings['last_playing'] > int(time.time() - 300):
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)
                    return 5

                playdata = api_play_url(type='channel', channel=id, id=None, test=True)

                if first and not profile_settings['last_login_success']:
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)
                    return 5

                if len(playdata['path']) > 0:
                    CDMHEADERS = {}

                    if check_key(playdata, 'license') and check_key(playdata['license'], 'drmConfig') and check_key(playdata['license']['drmConfig'], 'widevine'):
                        if 'nlznl.solocoo.tv' in playdata['license']['drmConfig']['widevine']['drmServerUrl']:
                            if xbmc.Monitor().waitForAbort(1):
                                return 5

                        if check_key(playdata['license']['drmConfig']['widevine'], 'customHeaders'):
                            for row in playdata['license']['drmConfig']['widevine']['customHeaders']:
                                CDMHEADERS[row] = playdata['license']['drmConfig']['widevine']['customHeaders'][row]

                    session = Session(headers=CDMHEADERS)
                    resp = session.get(playdata['path'])

                    if resp.status_code == 200:
                        livebandwidth = find_highest_bandwidth(xml=resp.text)
                        live = 1

                if check_key(results, id) and first and not tested:
                    first = False

                    if live == 1:
                        continue
                    else:
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                first = False
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 5:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() - 300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                yesterday = datetime.datetime.now() - datetime.timedelta(1)
                fromtime = datetime.datetime.strftime(yesterday, "%Y-%m-%dT%H%M%S")
                channel_url = '{base_url}/v6/epg/locations/{friendly}/live/1?fromDate={date}'.format(base_url=CONST_API_URL, friendly=channeldata['channel_friendly'], date=fromtime)

                download = api_download(url=channel_url, type='get', headers=None, data=None, json_data=False, return_json=True)
                data = download['data']
                code = download['code']

                if code and code == 200 and data:
                    for row in data:
                        if check_key(row, 'Channel') and check_key(row, 'Locations'):
                            for row2 in row['Locations']:
                                program_id = row2['LocationId']

                if program_id:
                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() - 300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                    playdata = api_play_url(type='program', channel=id, id=program_id, test=True)

                    if len(playdata['path']) > 0:
                        CDMHEADERS = {}

                        if check_key(playdata, 'license') and check_key(playdata['license'], 'drmConfig') and check_key(playdata['license']['drmConfig'], 'widevine'):
                            if 'nlznl.solocoo.tv' in playdata['license']['drmConfig']['widevine']['drmServerUrl']:
                                if xbmc.Monitor().waitForAbort(1):
                                    return 5

                            if check_key(playdata['license']['drmConfig']['widevine'], 'customHeaders'):
                                for row in playdata['license']['drmConfig']['widevine']['customHeaders']:
                                    CDMHEADERS[row] = playdata['license']['drmConfig']['widevine']['customHeaders'][row]

                        session = Session(headers=CDMHEADERS)
                        resp = session.get(playdata['path'])

                        if resp.status_code == 200:
                            replaybandwidth = find_highest_bandwidth(xml=resp.text)
                            replay = 1

                query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format(channel=id)
                data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

                if len(data) > 0:
                    guide = 1

                    if live == 1:
                        epg = 1

                if not xbmc.Monitor().abortRequested():
                    query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format(last_tested=id,profile_id=1)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)

                    query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format(profile_id=1, id=id, live=live, livebandwidth=livebandwidth, replay=replay, replaybandwidth=replaybandwidth, epg=epg, guide=guide)
                    query_settings(query=query, return_result=False, return_insert=False, commit=True)

                test_run = True
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 15:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() - 300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
                        query_settings(query=query, return_result=False, return_insert=False, commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                count += 1
    except:
        if test_run:
            update_prefs()

        count = 5

    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1)
    query_settings(query=query, return_result=False, return_insert=False, commit=True)

    return count
Beispiel #7
0
def api_play_url(type, channel=None, id=None, video_data=None, test=False, from_beginning=0, pvr=0):
    playdata = {'path': '', 'license': '', 'info': '', 'alt_path': '', 'alt_license': ''}

    if not api_get_session():
        return None

    alt_path = ''
    alt_license = ''
    found_alt = False

    from_beginning = int(from_beginning)
    pvr = int(pvr)
    profile_settings = load_profile(profile_id=1)

    friendly = ''

    query = "SELECT assetid FROM `channels` WHERE id='{channel}'".format(channel=channel)
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    if data:
        for row in data:
            friendly = row['assetid']

    if not test:
        counter = 0

        while not xbmc.Monitor().abortRequested() and counter < 5:
            profile_settings = load_profile(profile_id=1)

            if profile_settings['test_running'] == 0:
                break

            counter += 1

            query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format(last_playing=int(time.time()),profile_id=1)
            query_settings(query=query, return_result=False, return_insert=False, commit=True)

            if xbmc.Monitor().waitForAbort(1):
                break

        if xbmc.Monitor().abortRequested():
            return playdata

    if test:
        pass
    elif not type == 'vod' and (pvr == 0 or settings.getBool(key='ask_start_from_beginning') or from_beginning == 1):
        if type == 'channel' and friendly:
            channel_url = '{base_url}/v6/epg/locations/{friendly}/live/1?fromDate={date}'.format(base_url=CONST_API_URL, friendly=friendly, date=datetime.datetime.now().strftime("%Y-%m-%dT%H%M%S"))

            download = api_download(url=channel_url, type='get', headers=None, data=None, json_data=False, return_json=True)
            data = download['data']
            code = download['code']

            if not code or not code == 200 or not data:
                return playdata

            for row in data:
                if not check_key(row, 'Channel') or not check_key(row, 'Locations'):
                    return playdata

                for row2 in row['Locations']:
                    id = row2['LocationId']

        if not id:
            return playdata

        token_url_base = '{base_url}/v6/epg/location/{location}'.format(base_url=CONST_API_URL, location=id)

        token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}'
        url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter)

        download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True)
        data = download['data']
        code = download['code']

        if not code or not code == 200 or not data:
            return playdata

        info = data

        timeshift = ''

        if check_key(info, 'VodContentId') and len(unicode(info['VodContentId'])) > 0:
            token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/VOD/{id}'.format(base_url=CONST_API_URL, id=info['VodContentId'])
            timeshift = info['VodContentId']

            token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&playerName=NLZIET%20Meister%20Player%20Web&profile=default&maxResolution=&timeshift=' + unicode(timeshift) + '&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}'
            url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter)

            download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True)
            data = download['data']
            code = download['code']

            if not code or not code == 200 or not data or not check_key(data, 'uri'):
                pass
            else:
                alt_license = data
                alt_path = data['uri']
                found_alt = True

        elif type == 'channel' and channel and friendly:
            token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/Restart/{id}'.format(base_url=CONST_API_URL, id=id)
            timeshift = 'false'

            token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&playerName=NLZIET%20Meister%20Player%20Web&profile=default&maxResolution=&timeshift=' + unicode(timeshift) + '&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}'
            url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter)

            download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True)
            data = download['data']
            code = download['code']

            if not code or not code == 200 or not data or not check_key(data, 'uri'):
                pass
            else:
                alt_license = data
                alt_path = data['uri']
                found_alt = True

    if type == 'vod':
        token_url_base = '{base_url}/v6/playnow/ondemand/0/{location}'.format(base_url=CONST_API_URL, location=id)

        token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}'
        url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter)

        download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True)
        data = download['data']
        code = download['code']

        if not code or not code == 200 or not data or not check_key(data, 'VideoInformation'):
            return playdata

        info = data['VideoInformation']
        token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/VOD/{id}'.format(base_url=CONST_API_URL, id=info['Id'])
        timeshift = info['Id']
    elif type == 'channel' and channel and friendly:
        token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/Live/{friendly}'.format(base_url=CONST_API_URL, friendly=friendly)
        timeshift = 'false'
    else:
        if len(unicode(alt_path)) == 0:
            token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/Replay/{id}'.format(base_url=CONST_API_URL, id=id)
            timeshift = id
        else:
            license = alt_license = data
            path = alt_path
            alt_license = ''
            alt_path = ''

    if not type == 'program' or found_alt == False:
        token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&playerName=NLZIET%20Meister%20Player%20Web&profile=default&maxResolution=&timeshift=' + unicode(timeshift) + '&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}'
        url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter)

        download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True)
        data = download['data']
        code = download['code']

        if not code or not code == 200 or not data or not check_key(data, 'uri'):
            return playdata

        license = data
        path = data['uri']

    if not len(unicode(license)) > 0:
        return playdata

    playdata = {'path': path, 'license': license, 'info': info, 'alt_path': alt_path, 'alt_license': alt_license}

    return playdata
Beispiel #8
0
def plugin_process_watchlist_listing(data, id=None):
    items = []

    if check_key(data, 'listings'):
        for row in data['listings']:
            context = []

            if not check_key(row, 'program'):
                continue

            currow = row['program']

            if not check_key(currow, 'title') or not check_key(row, 'id'):
                continue

            duration = 0

            if check_key(row, 'endTime') and check_key(row, 'startTime'):
                startsplit = int(row['startTime']) // 1000
                endsplit = int(row['endTime']) // 1000
                duration = endsplit - startsplit

                startT = datetime.datetime.fromtimestamp(startsplit)
                startT = convert_datetime_timezone(startT, "UTC", "UTC")
                endT = datetime.datetime.fromtimestamp(endsplit)
                endT = convert_datetime_timezone(endT, "UTC", "UTC")

                if endT < (datetime.datetime.now(pytz.timezone("UTC")) - datetime.timedelta(days=7)):
                    continue

                if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                    label = '{weekday} {day} {month} {yearhourminute} '.format(weekday=date_to_nl_dag(startT), day=startT.strftime("%d"), month=date_to_nl_maand(startT), yearhourminute=startT.strftime("%Y %H:%M"))
                else:
                    label = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

                label += currow['title']
            else:
                label = currow['title']

            query = "SELECT name FROM `channels` WHERE id='{channel}'".format(channel=currow['stationId'])
            data2 = query_epg(query=query, return_result=True, return_insert=False, commit=False)

            if data2:
                for row2 in data2:
                    label += ' ({station})'.format(station=row2['name'])

            if id:
                context.append((_.ADD_TO_WATCHLIST, 'RunPlugin({context_url})'.format(context_url=plugin.url_for(func_or_url=add_to_watchlist, id=id, type="group")), ))

            channel = ''
            description = ''
            program_image = ''
            program_image_large = ''

            if check_key(currow, 'description'):
                description = currow['description']

            if check_key(currow, 'duration'):
                duration = int(currow['duration'])

            if check_key(currow, 'images'):
                program_image = get_image("boxart", currow['images'])
                program_image_large = get_image("HighResLandscape", currow['images'])

                if program_image_large == '':
                    program_image_large = program_image
                else:
                    program_image_large += '?w=1920&mode=box'

            items.append(plugin.Item(
                label = label,
                info = {
                    'plot': description,
                    'duration': duration,
                    'mediatype': 'video',
                    'sorttitle': label.upper(),
                },
                art = {
                    'thumb': program_image,
                    'fanart': program_image_large
                },
                path = plugin.url_for(func_or_url=play_video, type="program", channel=channel, id=row['id']),
                playable = True,
                context = context
            ))

    return items
Beispiel #9
0
def plugin_process_info(playdata):
    info = {
        'label1': '',
        'label2': '',
        'description': '',
        'image': '',
        'image_large': '',
        'duration': 0,
        'credits': [],
        'cast': [],
        'director': [],
        'writer': [],
        'genres': [],
        'year': '',
    }

    if check_key(playdata, 'info'):
        if check_key(playdata['info'], 'latestBroadcastEndTime') and check_key(playdata['info'], 'latestBroadcastStartTime'):
            startsplit = int(playdata['info']['latestBroadcastStartTime']) // 1000
            endsplit = int(playdata['info']['latestBroadcastEndTime']) // 1000
            duration = endsplit - startsplit

            startT = datetime.datetime.fromtimestamp(startsplit)
            startT = convert_datetime_timezone(startT, "UTC", "UTC")
            endT = datetime.datetime.fromtimestamp(endsplit)
            endT = convert_datetime_timezone(endT, "UTC", "UTC")

            if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                info['label1'] = '{weekday} {day} {month} {yearhourminute} '.format(weekday=date_to_nl_dag(startT), day=startT.strftime("%d"), month=date_to_nl_maand(startT), yearhourminute=startT.strftime("%Y %H:%M"))
            else:
                info['label1'] = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

        if playdata['title']:
            info['label1'] += playdata['title'] + ' - ' + playdata['info']['title']
        else:
            info['label1'] += playdata['info']['title']

        if check_key(playdata['info'], 'duration'):
            info['duration'] = int(playdata['info']['duration'])
        elif check_key(playdata['info'], 'latestBroadcastStartTime') and check_key(playdata['info'], 'latestBroadcastEndTime'):
            info['duration'] = int(int(playdata['info']['latestBroadcastEndTime']) - int(playdata['info']['latestBroadcastStartTime'])) // 1000

        if check_key(playdata['info'], 'description'):
            info['description'] = playdata['info']['description']

        if check_key(playdata['info'], 'duration'):
            info['duration'] = int(playdata['info']['duration'])

        if check_key(playdata['info'], 'year'):
            info['year'] = int(playdata['info']['year'])

        if check_key(playdata['info'], 'images'):
            info['image'] = get_image("boxart", playdata['info']['images'])
            info['image_large'] = get_image("HighResLandscape", playdata['info']['images'])

            if info['image_large'] == '':
                info['image_large'] = info['image']
            else:
                info['image_large'] += '?w=1920&mode=box'

        if check_key(playdata['info'], 'categories'):
            for categoryrow in playdata['info']['categories']:
                info['genres'].append(categoryrow['title'])

        if check_key(playdata['info'], 'cast'):
            for castrow in playdata['info']['cast']:
                info['cast'].append(castrow)

        if check_key(playdata['info'], 'directors'):
            for directorrow in playdata['info']['directors']:
                info['director'].append(directorrow)

        epcode = ''

        if check_key(playdata['info'], 'seriesNumber'):
            epcode += 'S' + unicode(playdata['info']['seriesNumber'])

        if check_key(playdata['info'], 'seriesEpisodeNumber'):
            epcode += 'E' + unicode(playdata['info']['seriesEpisodeNumber'])

        if check_key(playdata['info'], 'secondaryTitle'):
            info['label2'] = playdata['info']['secondaryTitle']

            if len(epcode) > 0:
                info['label2'] += " (" + epcode + ")"
        else:
            info['label2'] = playdata['info']['title']

        query = "SELECT name FROM `channels` WHERE id='{channel}'".format(channel=playdata['channel'])
        data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

        if data:
            for row in data:
                info['label2'] += " - "  + row['name']

    return info
Beispiel #10
0
def plugin_process_info(playdata):
    info = {
        'label1': '',
        'label2': '',
        'description': '',
        'image': '',
        'image_large': '',
        'duration': 0,
        'credits': [],
        'cast': [],
        'director': [],
        'writer': [],
        'genres': [],
        'year': '',
    }

    if check_key(playdata['info'], 'startTime') and check_key(
            playdata['info'], 'endTime'):
        startT = datetime.datetime.fromtimestamp(
            (int(playdata['info']['startTime']) / 1000))
        startT = convert_datetime_timezone(startT, "UTC", "UTC")
        endT = datetime.datetime.fromtimestamp(
            (int(playdata['info']['endTime']) / 1000))
        endT = convert_datetime_timezone(endT, "UTC", "UTC")

        info['duration'] = int((endT - startT).total_seconds())

        if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
            info[
                'label1'] = '{weekday} {day} {month} {yearhourminute} '.format(
                    weekday=date_to_nl_dag(startT),
                    day=startT.strftime("%d"),
                    month=date_to_nl_maand(startT),
                    yearhourminute=startT.strftime("%Y %H:%M"))
        else:
            info['label1'] = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

        info['label1'] += " - "

    if check_key(playdata['info'], 'name'):
        info['label1'] += playdata['info']['name']
        info['label2'] = playdata['info']['name']

    if check_key(playdata['info'], 'introduce'):
        info['description'] = playdata['info']['introduce']

    if check_key(playdata['info'], 'picture'):
        info['image'] = playdata['info']['picture']['posters'][0]
        info['image_large'] = playdata['info']['picture']['posters'][0]

    query = "SELECT name FROM `channels` WHERE id='{channel}'".format(
        channel=playdata['channel'])
    data = query_epg(query=query,
                     return_result=True,
                     return_insert=False,
                     commit=False)

    if data:
        for row in data:
            info['label2'] += " - " + row['name']

    return info
Beispiel #11
0
def api_test_channels(tested=False, channel=None):
    profile_settings = load_profile(profile_id=1)

    if channel:
        channel = unicode(channel)

    try:
        if not profile_settings[
                'last_login_success'] == 1 or not settings.getBool(
                    key='run_tests') or not api_get_session():
            return 5

        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
            test_running=1, profile_id=1)
        query_settings(query=query,
                       return_result=False,
                       return_insert=False,
                       commit=True)

        query = "SELECT * FROM `channels`"
        channels = query_epg(query=query,
                             return_result=True,
                             return_insert=False,
                             commit=False)
        results = load_tests(profile_id=1)

        count = 0
        first = True
        last_tested_found = False
        test_run = False
        user_agent = profile_settings['user_agent']

        if not results:
            results = {}

        for row in channels:
            if count == 5 or (count == 1 and tested):
                if test_run:
                    update_prefs()

                query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                    test_running=0, profile_id=1)
                query_settings(query=query,
                               return_result=False,
                               return_insert=False,
                               commit=True)
                return count

            id = unicode(row['id'])

            if len(id) > 0:
                if channel:
                    if not id == channel:
                        continue
                elif tested:
                    if unicode(profile_settings['last_tested']) == id:
                        last_tested_found = True
                        continue
                    elif last_tested_found:
                        pass
                    else:
                        continue

                if check_key(results, id) and not tested and not first:
                    continue

                livebandwidth = 0
                replaybandwidth = 0
                live = 0
                replay = 0
                epg = 0
                guide = 0

                profile_settings = load_profile(profile_id=1)

                if profile_settings['last_playing'] > int(time.time() - 300):
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                        test_running=0, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)
                    return 5

                playdata = api_play_url(type='channel',
                                        channel=id,
                                        id=id,
                                        test=True)

                if first and not profile_settings['last_login_success']:
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                        test_running=0, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)
                    return 5

                if len(playdata['path']) > 0:
                    CDMHEADERS = CONST_BASE_HEADERS
                    CDMHEADERS['User-Agent'] = user_agent
                    session = Session(headers=CDMHEADERS)
                    resp = session.get(playdata['path'])

                    if resp.status_code == 200:
                        livebandwidth = find_highest_bandwidth(xml=resp.text)
                        live = 1

                if check_key(results, id) and first and not tested:
                    first = False

                    if live == 1:
                        continue
                    else:
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                first = False
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 5:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                headers = {
                    'Authorization':
                    'Bearer ' + profile_settings['session_token']
                }
                yesterday = datetime.datetime.now() - datetime.timedelta(1)
                fromtime = datetime.datetime.strftime(
                    yesterday, '%Y-%m-%dT%H:%M:%S.000Z')
                tilltime = datetime.datetime.strftime(
                    yesterday, '%Y-%m-%dT%H:%M:59.999Z')

                program_url = "{api_url}/schedule?channels={id}&from={fromtime}&until={tilltime}".format(
                    api_url=CONST_DEFAULT_API,
                    id=id,
                    fromtime=fromtime,
                    tilltime=tilltime)

                download = api_download(url=program_url,
                                        type='get',
                                        headers=headers,
                                        data=None,
                                        json_data=False,
                                        return_json=True)
                data = download['data']
                code = download['code']

                if code and code == 200 and data and check_key(
                        data, 'epg') and check_key(data['epg'][0], 'id'):
                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                    playdata = api_play_url(type='program',
                                            channel=id,
                                            id=data['epg'][0]['id'],
                                            test=True)

                    if len(playdata['path']) > 0:
                        CDMHEADERS = CONST_BASE_HEADERS
                        CDMHEADERS['User-Agent'] = user_agent
                        session = Session(headers=CDMHEADERS)
                        resp = session.get(playdata['path'])

                        if resp.status_code == 200:
                            replaybandwidth = find_highest_bandwidth(
                                xml=resp.text)
                            replay = 1

                query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format(
                    channel=id)
                data = query_epg(query=query,
                                 return_result=True,
                                 return_insert=False,
                                 commit=False)

                if len(data) > 0:
                    guide = 1

                    if live == 1:
                        epg = 1

                if not xbmc.Monitor().abortRequested():
                    query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format(
                        last_tested=id, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)

                    query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format(
                        profile_id=1,
                        id=id,
                        live=live,
                        livebandwidth=livebandwidth,
                        replay=replay,
                        replaybandwidth=replaybandwidth,
                        epg=epg,
                        guide=guide)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)

                test_run = True
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 15:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                count += 1
    except:
        if test_run:
            update_prefs()

        count = 5

    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
        test_running=0, profile_id=1)
    query_settings(query=query,
                   return_result=False,
                   return_insert=False,
                   commit=True)

    return count
Beispiel #12
0
def api_test_channels(tested=False, channel=None):
    profile_settings = load_profile(profile_id=1)

    if channel:
        channel = unicode(channel)

    try:
        if not profile_settings[
                'last_login_success'] == 1 or not settings.getBool(
                    key='run_tests') or not api_get_session():
            return 5

        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
            test_running=1, profile_id=1)
        query_settings(query=query,
                       return_result=False,
                       return_insert=False,
                       commit=True)

        query = "SELECT * FROM `channels`"
        channels = query_epg(query=query,
                             return_result=True,
                             return_insert=False,
                             commit=False)
        results = load_tests(profile_id=1)

        count = 0
        first = True
        last_tested_found = False
        test_run = False
        user_agent = profile_settings['user_agent']
        listing_url = profile_settings['listings_url']

        if not results:
            results = {}

        for row in channels:
            if count == 5 or (count == 1 and tested):
                if test_run:
                    update_prefs()

                query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                    test_running=0, profile_id=1)
                query_settings(query=query,
                               return_result=False,
                               return_insert=False,
                               commit=True)
                return count

            id = unicode(row['id'])

            if len(id) > 0:
                if channel:
                    if not id == channel:
                        continue
                elif tested:
                    if unicode(profile_settings['last_tested']) == id:
                        last_tested_found = True
                        continue
                    elif last_tested_found:
                        pass
                    else:
                        continue

                if check_key(results, id) and not tested and not first:
                    continue

                livebandwidth = 0
                replaybandwidth = 0
                live = 0
                replay = 0
                epg = 0
                guide = 0

                profile_settings = load_profile(profile_id=1)

                if profile_settings['last_playing'] > int(time.time() - 300):
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                        test_running=0, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)
                    return 5

                playdata = api_play_url(type='channel',
                                        id=row['id'],
                                        test=True)

                if first and not profile_settings['last_login_success']:
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                        test_running=0, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)
                    return 5

                if len(playdata['path']) > 0:
                    CDMHEADERS = {
                        'User-Agent': user_agent,
                        'X-Client-Id':
                        profile_settings['client_id'] + '||' + user_agent,
                        'X-OESP-Token': profile_settings['access_token'],
                        'X-OESP-Username': profile_settings['username'],
                        'X-OESP-License-Token': profile_settings['drm_token'],
                        'X-OESP-DRM-SchemeIdUri':
                        'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',
                        'X-OESP-Content-Locator': playdata['locator'],
                    }

                    session = Session(headers=CDMHEADERS)
                    resp = session.get(playdata['path'])

                    if resp.status_code == 200:
                        livebandwidth = find_highest_bandwidth(xml=resp.text)
                        live = 1

                if check_key(results, id) and first and not tested:
                    first = False

                    if live == 1:
                        continue
                    else:
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                first = False
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 5:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                listing_url = '{listings_url}?byEndTime={time}~&byStationId={channel}&range=1-1&sort=startTime'.format(
                    listings_url=listing_url,
                    time=int(int(time.time() - 86400) * 1000),
                    channel=id)
                download = api_download(url=listing_url,
                                        type='get',
                                        headers=api_get_headers(),
                                        data=None,
                                        json_data=False,
                                        return_json=True)
                data = download['data']
                code = download['code']

                program_id = None

                if code and code == 200 and data and check_key(
                        data, 'listings'):
                    for row in data['listings']:
                        program_id = row['id']

                if program_id:
                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                    playdata = api_play_url(type='program',
                                            id=program_id,
                                            test=True)

                    if len(playdata['path']) > 0:
                        CDMHEADERS = {
                            'User-Agent': user_agent,
                            'X-Client-Id':
                            profile_settings['client_id'] + '||' + user_agent,
                            'X-OESP-Token': profile_settings['access_token'],
                            'X-OESP-Username': profile_settings['username'],
                            'X-OESP-License-Token':
                            profile_settings['drm_token'],
                            'X-OESP-DRM-SchemeIdUri':
                            'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',
                            'X-OESP-Content-Locator': playdata['locator'],
                        }

                        session = Session(headers=CDMHEADERS)
                        resp = session.get(playdata['path'])

                        if resp.status_code == 200:
                            replaybandwidth = find_highest_bandwidth(
                                xml=resp.text)
                            replay = 1

                query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format(
                    channel=id)
                data = query_epg(query=query,
                                 return_result=True,
                                 return_insert=False,
                                 commit=False)

                if len(data) > 0:
                    guide = 1

                    if live == 1:
                        epg = 1

                if not xbmc.Monitor().abortRequested():
                    query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format(
                        last_tested=id, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)

                    query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format(
                        profile_id=1,
                        id=id,
                        live=live,
                        livebandwidth=livebandwidth,
                        replay=replay,
                        replaybandwidth=replaybandwidth,
                        epg=epg,
                        guide=guide)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)

                test_run = True
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 15:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                count += 1
    except:
        if test_run:
            update_prefs()

        count = 5

    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
        test_running=0, profile_id=1)
    query_settings(query=query,
                   return_result=False,
                   return_insert=False,
                   commit=True)

    return count
Beispiel #13
0
def api_search(query):
    if not api_get_session():
        return None

    profile_settings = load_profile(profile_id=1)

    if profile_settings['base_v3'] == 1:
        return False

    end = int(time.time() * 1000)
    start = end - (7 * 24 * 60 * 60 * 1000)
    enable_cache = settings.getBool(key='enable_cache')

    vodstr = ''

    file = "cache" + os.sep + "search_" + clean_filename(query) + ".json"

    search_url = '{search_url}?byBroadcastStartTimeRange={start}~{end}&numItems=25&byEntitled=true&personalised=true&q={query}'.format(
        search_url=profile_settings['search_url'],
        start=start,
        end=end,
        query=quote(query))

    if enable_cache and not is_file_older_than_x_minutes(
            file=ADDON_PROFILE + file, minutes=10):
        data = load_file(file=file, isJSON=True)
    else:
        download = api_download(url=search_url,
                                type='get',
                                headers=api_get_headers(),
                                data=None,
                                json_data=False,
                                return_json=True)
        data = download['data']
        code = download['code']

        if code and code == 200 and data and (
                check_key(data, 'tvPrograms')
                or check_key(data, 'moviesAndSeries')) and enable_cache:
            write_file(file=file, data=data, isJSON=True)

    if not data or (not check_key(data, 'tvPrograms')
                    and not check_key(data, 'moviesAndSeries')):
        return False

    items = []
    items_vod = []
    items_program = []
    vod_links = {}

    if not settings.getBool('showMoviesSeries'):
        try:
            data.pop('moviesAndSeries', None)
        except:
            pass
    else:
        for entry in CONST_VOD_CAPABILITY:
            sql_query = "SELECT * FROM `{table}`".format(table=entry['file'])
            sql_data = query_epg(query=sql_query,
                                 return_result=True,
                                 return_insert=False,
                                 commit=False)

            for row in sql_data:
                vod_links[row['id']] = {}
                vod_links[row['id']]['seasons'] = row['seasons']
                vod_links[row['id']]['duration'] = row['duration']
                vod_links[row['id']]['desc'] = row['description']
                vod_links[row['id']]['type'] = row['type']

    for currow in list(data):
        if currow == "moviesAndSeries":
            type = 'vod'
        else:
            type = 'program'

        for row in data[currow]['entries']:
            if not check_key(row, 'id') or not check_key(row, 'title'):
                continue

            item = {}

            id = row['id']
            label = row['title']
            description = ''
            duration = 0
            program_image = ''
            program_image_large = ''
            start = ''

            if check_key(row, 'images'):
                program_image = get_image("boxart", row['images'])
                program_image_large = get_image("HighResLandscape",
                                                row['images'])

                if program_image_large == '':
                    program_image_large = program_image
                else:
                    program_image_large += '?w=1920&mode=box'

            if type == 'vod':
                if check_key(vod_links, row['id']):
                    description = vod_links[row['id']]['desc']
                    item_type = vod_links[row['id']]['type']
                else:
                    item_type = 'Vod'

                label += " (Movies and Series)"
            else:
                item_type = 'Epg'
                label += " (ReplayTV)"

            if check_key(row, 'groupType') and row['groupType'] == 'show':
                if check_key(row, 'episodeMatch') and check_key(
                        row['episodeMatch'],
                        'seriesEpisodeNumber') and check_key(
                            row['episodeMatch'], 'secondaryTitle'):
                    if len(description) == 0:
                        description += label

                    season = ''

                    if check_key(row, 'seriesNumber'):
                        season = "S" + row['seriesNumber']

                    description += " Episode Match: {season}E{episode} - {secondary}".format(
                        season=season,
                        episode=row['episodeMatch']['seriesEpisodeNumber'],
                        secondary=row['episodeMatch']['secondaryTitle'])
            else:
                if check_key(row, 'duration'):
                    duration = int(row['duration'])
                elif check_key(row, 'episodeMatch') and check_key(
                        row['episodeMatch'], 'startTime') and check_key(
                            row['episodeMatch'], 'endTime'):
                    duration = int(
                        int(row['episodeMatch']['endTime']) -
                        int(row['episodeMatch']['startTime'])) // 1000
                    id = row['episodeMatch']['id']
                elif check_key(vod_links, row['id']) and check_key(
                        vod_links[row['id']], 'duration'):
                    duration = vod_links[row['id']]['duration']

            item['id'] = id
            item['title'] = label
            item['description'] = description
            item['duration'] = duration
            item['type'] = item_type
            item['icon'] = program_image_large
            item['start'] = start

            if type == "vod":
                items_vod.append(item)
            else:
                items_program.append(item)

    num = min(len(items_program), len(items_vod))
    items = [None] * (num * 2)
    items[::2] = items_program[:num]
    items[1::2] = items_vod[:num]
    items.extend(items_program[num:])
    items.extend(items_vod[num:])

    return items
Beispiel #14
0
def api_play_url(type,
                 channel=None,
                 id=None,
                 video_data=None,
                 test=False,
                 from_beginning=0,
                 pvr=0):
    playdata = {
        'path': '',
        'license': '',
        'token': '',
        'locator': '',
        'type': '',
        'alt_path': '',
        'alt_license': '',
        'alt_locator': ''
    }

    if not api_get_session():
        return playdata

    from_beginning = int(from_beginning)
    pvr = int(pvr)
    profile_settings = load_profile(profile_id=1)

    if type == "channel":
        id = channel

    alt_path = ''
    alt_license = ''
    alt_locator = ''
    info = {}
    base_listing_url = profile_settings['listings_url']
    urldata = None
    urldata2 = None
    path = None
    locator = None

    if not type or not len(unicode(type)) > 0 or not id or not len(
            unicode(id)) > 0:
        return playdata

    if not test:
        counter = 0

        while not xbmc.Monitor().abortRequested() and counter < 5:
            profile_settings = load_profile(profile_id=1)

            if profile_settings['test_running'] == 0:
                break

            counter += 1

            query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format(
                last_playing=int(time.time()), profile_id=1)
            query_settings(query=query,
                           return_result=False,
                           return_insert=False,
                           commit=True)

            if xbmc.Monitor().waitForAbort(1):
                break

        if xbmc.Monitor().abortRequested():
            return playdata

    if type == 'channel':
        query = "SELECT assetid FROM `channels` WHERE id='{channel}'".format(
            channel=id)
        data = query_epg(query=query,
                         return_result=True,
                         return_insert=False,
                         commit=False)

        if data:
            for row in data:
                split = row['assetid'].rsplit('&%%&', 1)

                if len(split) == 2:
                    urldata = {'play_url': split[0], 'locator': split[1]}
                else:
                    return playdata

        listing_url = '{listings_url}?byEndTime={time}~&byStationId={channel}&range=1-1&sort=startTime'.format(
            listings_url=base_listing_url,
            time=int(time.time() * 1000),
            channel=id)
        download = api_download(url=listing_url,
                                type='get',
                                headers=api_get_headers(),
                                data=None,
                                json_data=False,
                                return_json=True)
        data = download['data']
        code = download['code']

        if code and code == 200 and data and check_key(data, 'listings'):
            for row in data['listings']:
                if check_key(row, 'program'):
                    info = row['program']
    elif type == 'program':
        listings_url = "{listings_url}/{id}".format(
            listings_url=base_listing_url, id=id)
        download = api_download(url=listings_url,
                                type='get',
                                headers=api_get_headers(),
                                data=None,
                                json_data=False,
                                return_json=True)
        data = download['data']
        code = download['code']

        if not code or not code == 200 or not data or not check_key(
                data, 'program'):
            return playdata

        info = data['program']
    elif type == 'vod':
        mediaitems_url = '{mediaitems_url}/{id}'.format(
            mediaitems_url=profile_settings['mediaitems_url'], id=id)
        download = api_download(url=mediaitems_url,
                                type='get',
                                headers=api_get_headers(),
                                data=None,
                                json_data=False,
                                return_json=True)
        data = download['data']
        code = download['code']

        if not code or not code == 200 or not data:
            return playdata

        info = data

    if check_key(info, 'videoStreams'):
        urldata2 = get_play_url(content=info['videoStreams'])

    if not type == 'channel' and (
            not urldata2 or not check_key(urldata2, 'play_url')
            or not check_key(urldata2, 'locator')
            or urldata2['play_url'] == 'http://Playout/using/Session/Service'
    ) and profile_settings['base_v3'] == 1:
        urldata2 = {}

        if type == 'program':
            playout_str = 'replay'
        elif type == 'vod':
            playout_str = 'vod'
        else:
            return playdata

        playout_url = '{base_url}/playout/{playout_str}/{id}?abrType=BR-AVC-DASH'.format(
            base_url=profile_settings['base_url'],
            playout_str=playout_str,
            id=id)
        download = api_download(url=playout_url,
                                type='get',
                                headers=api_get_headers(),
                                data=None,
                                json_data=False,
                                return_json=True)
        data = download['data']
        code = download['code']

        if not code or not code == 200 or not data or not check_key(
                data, 'url') or not check_key(data, 'contentLocator'):
            return playdata

        urldata2['play_url'] = data['url']
        urldata2['locator'] = data['contentLocator']

    if urldata and urldata2 and check_key(urldata, 'play_url') and check_key(
            urldata, 'locator') and check_key(
                urldata2, 'play_url') and check_key(urldata2, 'locator'):
        path = urldata['play_url']
        locator = urldata['locator']

        alt_path = urldata2['play_url']
        alt_locator = urldata2['locator']
    else:
        if urldata and check_key(urldata, 'play_url') and check_key(
                urldata, 'locator'):
            path = urldata['play_url']
            locator = urldata['locator']
        elif urldata2 and check_key(urldata2, 'play_url') and check_key(
                urldata2, 'locator'):
            path = urldata2['play_url']
            locator = urldata2['locator']

    if not locator or not len(unicode(locator)) > 0:
        return playdata

    license = profile_settings['widevine_url']
    alt_license = profile_settings['widevine_url']

    if xbmc.Monitor().abortRequested():
        return playdata

    token = api_get_play_token(locator=locator, path=path, force=1)

    if not token or not len(unicode(token)) > 0:
        if not test:
            gui.ok(message=_.NO_STREAM_AUTH, heading=_.PLAY_ERROR)

        return playdata

    if not test:
        token = 'WIDEVINETOKEN'

    token_regex = re.search(r"(?<=;vxttoken=)(.*?)(?=/)", path)

    if token_regex and token_regex.group(1) and len(token_regex.group(1)) > 0:
        path = path.replace(token_regex.group(1), token)
    else:
        if 'sdash/' in path:
            spliturl = path.split('sdash/', 1)

            if len(spliturl) == 2:
                if profile_settings['base_v3'] == 1:
                    path = '{urlpart1}sdash;vxttoken={token}/{urlpart2}'.format(
                        urlpart1=spliturl[0],
                        token=token,
                        urlpart2=spliturl[1])
                else:
                    path = '{urlpart1}sdash;vxttoken={token}/{urlpart2}?device=Orion-Replay-DASH'.format(
                        urlpart1=spliturl[0],
                        token=token,
                        urlpart2=spliturl[1])
        else:
            spliturl = path.rsplit('/', 1)

            if len(spliturl) == 2:
                path = '{urlpart1};vxttoken={token}/{urlpart2}'.format(
                    urlpart1=spliturl[0], token=token, urlpart2=spliturl[1])

    playdata = {
        'path': path,
        'license': license,
        'token': token,
        'locator': locator,
        'info': info,
        'type': type,
        'alt_path': alt_path,
        'alt_license': alt_license,
        'alt_locator': alt_license
    }

    return playdata
Beispiel #15
0
def api_test_channels(tested=False, channel=None):
    profile_settings = load_profile(profile_id=1)

    if channel:
        channel = unicode(channel)

    try:
        if not profile_settings[
                'last_login_success'] == 1 or not settings.getBool(
                    key='run_tests') or not api_get_session():
            return 5

        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
            test_running=1, profile_id=1)
        query_settings(query=query,
                       return_result=False,
                       return_insert=False,
                       commit=True)

        query = "SELECT * FROM `channels`"
        channels = query_epg(query=query,
                             return_result=True,
                             return_insert=False,
                             commit=False)
        results = load_tests(profile_id=1)

        count = 0
        first = True
        last_tested_found = False
        test_run = False
        user_agent = profile_settings['user_agent']

        if not results:
            results = {}

        for row in channels:
            if count == 5 or (count == 1 and tested):
                if test_run:
                    update_prefs()

                query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                    test_running=0, profile_id=1)
                query_settings(query=query,
                               return_result=False,
                               return_insert=False,
                               commit=True)
                return count

            id = unicode(row['id'])

            if len(id) > 0:
                if channel:
                    if not id == channel:
                        continue
                elif tested:
                    if unicode(profile_settings['last_tested']) == id:
                        last_tested_found = True
                        continue
                    elif last_tested_found:
                        pass
                    else:
                        continue

                if check_key(results, id) and not tested and not first:
                    continue

                livebandwidth = 0
                replaybandwidth = 0
                live = 0
                replay = 0
                epg = 0
                guide = 0

                profile_settings = load_profile(profile_id=1)

                if profile_settings['last_playing'] > int(time.time() - 300):
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                        test_running=0, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)
                    return 5

                playdata = api_play_url(type='channel',
                                        channel=id,
                                        id=row['assetid'],
                                        test=True)

                if first and not profile_settings['last_login_success']:
                    if test_run:
                        update_prefs()

                    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                        test_running=0, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)
                    return 5

                if len(playdata['path']) > 0:
                    CDMHEADERS = CONST_BASE_HEADERS
                    CDMHEADERS['User-Agent'] = user_agent
                    playdata['path'] = playdata['path'].split("&", 1)[0]
                    session = Session(headers=CDMHEADERS)
                    resp = session.get(playdata['path'])

                    if resp.status_code == 200:
                        livebandwidth = find_highest_bandwidth(xml=resp.text)
                        live = 1

                if check_key(results, id) and first and not tested:
                    first = False

                    if live == 1:
                        continue
                    else:
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                first = False
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 5:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                program_url = '{api_url}/TRAY/AVA/TRENDING/YESTERDAY?maxResults=1&filter_channelIds={channel}'.format(
                    api_url=profile_settings['api_url'],
                    channel=channeldata['channel_id'])
                download = api_download(url=program_url,
                                        type='get',
                                        headers=None,
                                        data=None,
                                        json_data=False,
                                        return_json=True)
                data = download['data']
                code = download['code']

                if code and code == 200 and data and check_key(
                        data, 'resultCode'
                ) and data['resultCode'] == 'OK' and check_key(
                        data, 'resultObj') and check_key(
                            data['resultObj'], 'containers') and check_key(
                                data['resultObj']['containers'][0], 'id'):
                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                    playdata = api_play_url(
                        type='program',
                        channel=id,
                        id=data['resultObj']['containers'][0]['id'],
                        test=True)

                    if len(playdata['path']) > 0:
                        CDMHEADERS = CONST_BASE_HEADERS
                        CDMHEADERS['User-Agent'] = user_agent
                        playdata['path'] = playdata['path'].split(
                            "&min_bitrate", 1)[0]
                        session = Session(headers=CDMHEADERS)
                        resp = session.get(playdata['path'])

                        if resp.status_code == 200:
                            replaybandwidth = find_highest_bandwidth(
                                xml=resp.text)
                            replay = 1

                query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format(
                    channel=id)
                data = query_epg(query=query,
                                 return_result=True,
                                 return_insert=False,
                                 commit=False)

                if len(data) > 0:
                    guide = 1

                    if live == 1:
                        epg = 1

                if not xbmc.Monitor().abortRequested():
                    query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format(
                        last_tested=id, profile_id=1)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)

                    query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format(
                        profile_id=1,
                        id=id,
                        live=live,
                        livebandwidth=livebandwidth,
                        replay=replay,
                        replaybandwidth=replaybandwidth,
                        epg=epg,
                        guide=guide)
                    query_settings(query=query,
                                   return_result=False,
                                   return_insert=False,
                                   commit=True)

                test_run = True
                counter = 0

                while not xbmc.Monitor().abortRequested() and counter < 15:
                    if xbmc.Monitor().waitForAbort(1):
                        break

                    counter += 1

                    profile_settings = load_profile(profile_id=1)

                    if profile_settings['last_playing'] > int(time.time() -
                                                              300):
                        if test_run:
                            update_prefs()

                        query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
                            test_running=0, profile_id=1)
                        query_settings(query=query,
                                       return_result=False,
                                       return_insert=False,
                                       commit=True)
                        return 5

                if xbmc.Monitor().abortRequested():
                    return 5

                count += 1
    except:
        if test_run:
            update_prefs()

        count = 5

    query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(
        test_running=0, profile_id=1)
    query_settings(query=query,
                   return_result=False,
                   return_insert=False,
                   commit=True)

    return count