Exemplo n.º 1
0
def get_replay_channels(all=False):
    channels = []

    query = "SELECT * FROM `channels`"
    data = query_epg(query=query,
                     return_result=True,
                     return_insert=False,
                     commit=False)

    prefs = load_prefs(profile_id=1)

    if data:
        for row in data:
            if '18+' in row['name']:
                continue

            id = unicode(row['id'])

            if all or not prefs or not check_key(
                    prefs, id) or prefs[id]['replay'] == 1:
                image_path = ADDON_PROFILE + "images" + os.sep + unicode(
                    row['id']) + ".png"

                if os.path.isfile(image_path):
                    image = image_path
                else:
                    image = row['icon']

                channels.append({
                    'label':
                    row['name'],
                    'channel':
                    row['id'],
                    'chno':
                    row['channelno'],
                    'description':
                    row['description'],
                    'image':
                    image,
                    'path':
                    plugin.url_for(func_or_url=replaytv_by_day,
                                   image=row['icon'],
                                   description=row['description'],
                                   label=row['name'],
                                   station=row['id']),
                    'playable':
                    False,
                    'context': [],
                })

        channels[:] = sorted(channels, key=_sort_live)

    return channels
Exemplo n.º 2
0
def process_replaytv_list_content(label, idtitle, start=0):
    profile_settings = load_profile(profile_id=1)

    start = int(start)

    now = datetime.datetime.now(pytz.timezone("Europe/Amsterdam"))
    sevendays = datetime.datetime.now(pytz.timezone("Europe/Amsterdam")) - datetime.timedelta(days=7)
    nowstamp = int((now - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())
    sevendaysstamp = int((sevendays - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())

    query = "SELECT * FROM `channels`"
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    channels_ar2 = {}

    if data:
        for row in data:
            channels_ar2[unicode(row['id'])] = row['name']

    prefs = load_prefs(profile_id=1)
    channels_ar = []

    if prefs:
        for row in prefs:
            currow = prefs[row]

            if '18+' in channels_ar2[unicode(currow['id'])]:
                continue

            if currow['replay'] == 1:
                channels_ar.append(row)

    channels = "', '".join(map(str, channels_ar))

    query = "SELECT * FROM `epg` WHERE idtitle='{idtitle}' AND start < {nowstamp} AND end > {sevendaysstamp} AND channel IN ('{channels}') LIMIT 51 OFFSET {start}".format(idtitle=idtitle, nowstamp=nowstamp, sevendaysstamp=sevendaysstamp, channels=channels, start=start)
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    items = []
    item_count = 0

    if not data:
        return {'items': items, 'count': item_count, 'total': 0}

    for row in data:
        if item_count == 51:
            break

        item_count += 1

        startT = datetime.datetime.fromtimestamp(row['start'])
        startT = convert_datetime_timezone(startT, "Europe/Amsterdam", "Europe/Amsterdam")
        endT = datetime.datetime.fromtimestamp(row['end'])
        endT = convert_datetime_timezone(endT, "Europe/Amsterdam", "Europe/Amsterdam")

        if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
            itemlabel = '{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:
            itemlabel = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

        itemlabel += row['title'] + " (" + channels_ar2[unicode(row['channel'])] + ")"

        description = row['description']
        duration = int((endT - startT).total_seconds())
        program_image = row['icon']
        program_image_large = row['icon']

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

    returnar = {'items': items, 'count': item_count, 'total': len(data)}

    return returnar
Exemplo n.º 3
0
def process_replaytv_content(station, day=0, start=0):
    profile_settings = load_profile(profile_id=1)

    day = int(day)
    start = int(start)
    curdate = datetime.date.today() - datetime.timedelta(days=day)

    startDate = convert_datetime_timezone(datetime.datetime(curdate.year, curdate.month, curdate.day, 0, 0, 0), "Europe/Amsterdam", "UTC")
    endDate = convert_datetime_timezone(datetime.datetime(curdate.year, curdate.month, curdate.day, 23, 59, 59), "Europe/Amsterdam", "UTC")
    startTimeStamp = int((startDate - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())
    endTimeStamp = int((endDate - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())

    query = "SELECT * FROM `epg` WHERE channel='{channel}' AND start >= {startTime} AND start <= {endTime} LIMIT 51 OFFSET {start}".format(channel=station, startTime=startTimeStamp, endTime=endTimeStamp, start=start)
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    items = []
    item_count = 0

    if not data:
        return {'items': items, 'count': item_count, 'total': 0}

    for row in data:
        if item_count == 51:
            break

        item_count += 1

        startT = datetime.datetime.fromtimestamp(row['start'])
        startT = convert_datetime_timezone(startT, "Europe/Amsterdam", "Europe/Amsterdam")
        endT = datetime.datetime.fromtimestamp(row['end'])
        endT = convert_datetime_timezone(endT, "Europe/Amsterdam", "Europe/Amsterdam")

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

        label = startT.strftime("%H:%M") + " - " + row['title']

        description = row['description']

        duration = int((endT - startT).total_seconds())

        program_image = row['icon']
        program_image_large = row['icon']

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

    returnar = {'items': items, 'count': item_count, 'total': len(data)}

    return returnar
Exemplo n.º 4
0
def process_replaytv_search(search):
    profile_settings = load_profile(profile_id=1)

    now = datetime.datetime.now(pytz.timezone("Europe/Amsterdam"))
    sevendays = datetime.datetime.now(pytz.timezone("Europe/Amsterdam")) - datetime.timedelta(days=7)
    nowstamp = int((now - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())
    sevendaysstamp = int((sevendays - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())

    query = "SELECT * FROM `channels`"
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    channels_ar2 = {}

    if data:
        for row in data:
            channels_ar2[unicode(row['id'])] = row['name']

    prefs = load_prefs(profile_id=1)
    channels_ar = []

    if prefs:
        for row in prefs:
            currow = prefs[row]

            if '18+' in channels_ar2[unicode(currow['id'])]:
                continue

            if currow['replay'] == 1:
                channels_ar.append(row)

    channels = "', '".join(map(str, channels_ar))

    query = "SELECT idtitle, title, icon FROM `epg` WHERE start < {nowstamp} AND end > {sevendaysstamp} AND channel IN ('{channels}') GROUP BY idtitle".format(nowstamp=nowstamp, sevendaysstamp=sevendaysstamp, channels=channels)
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    items = []

    if not data:
        return {'items': items}

    for row in data:
        fuzz_set = fuzz.token_set_ratio(row['title'], search)
        fuzz_partial = fuzz.partial_ratio(row['title'], search)
        fuzz_sort = fuzz.token_sort_ratio(row['title'], search)

        if (fuzz_set + fuzz_partial + fuzz_sort) > 160:
            label = row['title'] + ' (ReplayTV)'
            idtitle = row['idtitle']

            items.append(plugin.Item(
                label = label,
                art = {
                    'thumb': row['icon'],
                    'fanart': row['icon']
                },
                properties = {"fuzz_set": fuzz_set, "fuzz_sort": fuzz_sort, "fuzz_partial": fuzz_partial, "fuzz_total": fuzz_set + fuzz_partial + fuzz_sort},
                path = plugin.url_for(func_or_url=replaytv_item, label=label, idtitle=idtitle, start=0),
            ))

    returnar = {'items': items}

    return returnar
Exemplo n.º 5
0
def process_replaytv_list(character, start=0):
    profile_settings = load_profile(profile_id=1)

    now = datetime.datetime.now(pytz.timezone("Europe/Amsterdam"))
    sevendays = datetime.datetime.now(pytz.timezone("Europe/Amsterdam")) - datetime.timedelta(days=7)
    nowstamp = int((now - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())
    sevendaysstamp = int((sevendays - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())

    query = "SELECT * FROM `channels`"
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    channels_ar2 = {}

    if data:
        for row in data:
            channels_ar2[unicode(row['id'])] = row['name']

    prefs = load_prefs(profile_id=1)
    channels_ar = []

    if prefs:
        for row in prefs:
            currow = prefs[row]

            if '18+' in channels_ar2[unicode(currow['id'])]:
                continue

            if currow['replay'] == 1:
                channels_ar.append(row)

    channels = "', '".join(map(str, channels_ar))

    query = "SELECT idtitle, title, icon FROM `epg` WHERE first='{first}' AND start < {nowstamp} AND end > {sevendaysstamp} AND channel IN ('{channels}') GROUP BY idtitle LIMIT 51 OFFSET {start}".format(first=character, nowstamp=nowstamp, sevendaysstamp=sevendaysstamp, channels=channels, start=start)
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    start = int(start)
    items = []
    item_count = 0

    if not data:
        return {'items': items, 'count': item_count, 'total': 0}

    for row in data:
        if item_count == 51:
            break

        item_count += 1

        label = row['title']
        idtitle = row['idtitle']

        items.append(plugin.Item(
            label = label,
            art = {
                'thumb': row['icon'],
                'fanart': row['icon']
            },
            path = plugin.url_for(func_or_url=replaytv_item, label=label, idtitle=idtitle, start=0),
        ))

    returnar = {'items': items, 'count': item_count, 'total': len(data)}

    return returnar
Exemplo n.º 6
0
def get_live_channels(addon=False, all=False):
    global backend
    channels = []
    pvrchannels = []

    query = "SELECT * FROM `channels`"
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    prefs = load_prefs(profile_id=1)

    if data:
        if addon:
            query_addons = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id": 1, "method": "Addons.GetAddons", "params": {"type": "xbmc.pvrclient"}}'))

            if check_key(query_addons, 'result') and check_key(query_addons['result'], 'addons'):
                addons = query_addons['result']['addons']
                backend = addons[0]['addonid']

                query_channel = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "PVR.GetChannels", "params": {"channelgroupid": "alltv", "properties" :["uniqueid"]},"id": 1}'))

                if check_key(query_channel, 'result') and check_key(query_channel['result'], 'channels'):
                    pvrchannels = query_channel['result']['channels']

        for row in data:
            path = plugin.url_for(func_or_url=play_video, type='channel', channel=row['id'], id=None, _is_live=True)
            playable = True

            for channel in pvrchannels:
                if channel['label'] == row['name']:
                    channel_uid = channel['uniqueid']
                    path = plugin.url_for(func_or_url=switchChannel, channel_uid=channel_uid)
                    playable = False
                    break

            if '18+' in row['name']:
                continue

            id = unicode(row['id'])

            if all or not prefs or not check_key(prefs, id) or prefs[id]['live'] == 1:
                image_path = ADDON_PROFILE + "images" + os.sep + unicode(row['id']) + ".png"

                if os.path.isfile(image_path):
                    image = image_path
                else:
                    image = row['icon']

                channels.append({
                    'label': row['name'],
                    'channel': row['id'],
                    'chno': row['channelno'],
                    'description': row['description'],
                    'image': image,
                    'path':  path,
                    'playable': playable,
                    'context': [
                        (_.START_BEGINNING, 'RunPlugin({context_url})'.format(context_url=plugin.url_for(func_or_url=play_video, type='channel', channel=row['id'], id=None, from_beginning=1)), ),
                    ],
                })

        channels[:] = sorted(channels, key=_sort_live)

    return channels
Exemplo n.º 7
0
def play_video(type=None, channel=None, id=None, from_beginning=0, **kwargs):
    from_beginning = int(from_beginning)

    profile_settings = load_profile(profile_id=1)

    properties = {}

    if not type and not len(unicode(type)) > 0:
        return False

    if type == 'program':
        properties['seekTime'] = 1

    playdata = api.play_url(type=type, channel=channel, id=id, from_beginning=from_beginning)

    if not playdata or not check_key(playdata, 'path'):
        return False

    CDMHEADERS = {
        'User-Agent': profile_settings['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'):
        item_inputstream = inputstream.Widevine(
            license_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'
    else:
        item_inputstream = inputstream.MPD()

    itemlabel = ''
    label2 = ''
    description = ''
    program_image = ''
    program_image_large = ''
    duration = 0
    cast = []
    director = []
    writer = []
    credits = []

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

        duration = int((endT - startT).total_seconds())

        if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
            itemlabel = '{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:
            itemlabel = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

        itemlabel += " - "

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

    if type == 'channel':
        if from_beginning == 1:
            properties['seekTime'] = 1
        elif settings.getBool(key='ask_start_from_beginning'):
            if gui.yes_no(message=_.START_FROM_BEGINNING, heading=label2):
                properties['seekTime'] = 1

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

    if check_key(playdata['info'], 'picture'):
        program_image = playdata['info']['picture']['posters'][0]
        program_image_large = playdata['info']['picture']['posters'][0]

    query = "SELECT name 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:
            label2 += " - "  + row['name']

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

    listitem = plugin.Item(
        label = itemlabel,
        label2 = label2,
        art = {
            'thumb': program_image,
            'fanart': program_image_large
        },
        info = {
            'credits': credits,
            'cast': cast,
            'writer': writer,
            'director': director,
            'plot': description,
            'duration': duration,
            'mediatype': 'video',
        },
        properties = properties,
        path = playdata['path'],
        headers = CDMHEADERS,
        inputstream = item_inputstream,
    )

    return listitem
Exemplo n.º 8
0
def process_vod_content(data, start=0, search=None, type=None):
    profile_settings = load_profile(profile_id=1)

    subscription = load_file(file='vod_subscription.json', isJSON=True)

    start = int(start)

    items = []
    count = start
    item_count = 0

    if subscription and sys.version_info >= (3, 0):
        subscription = list(subscription)

    query = "SELECT * FROM `{table}` ORDER BY title ASC LIMIT 999999 OFFSET {start}".format(table=data, start=start)
    data = query_epg(query=query, return_result=True, return_insert=False, commit=False)

    if not data:
        return {'items': items, 'count': item_count, 'count2': count, 'total': 0}

    for row in data:
        if item_count == 50:
            break

        count += 1

        id = row['id']
        label = row['title']

        if subscription and not int(id) in subscription:
            continue

        if search:
            fuzz_set = fuzz.token_set_ratio(label,search)
            fuzz_partial = fuzz.partial_ratio(label,search)
            fuzz_sort = fuzz.token_sort_ratio(label,search)

            if (fuzz_set + fuzz_partial + fuzz_sort) > 160:
                properties = {"fuzz_set": fuzz.token_set_ratio(label,search), "fuzz_sort": fuzz.token_sort_ratio(label,search), "fuzz_partial": fuzz.partial_ratio(label,search), "fuzz_total": fuzz.token_set_ratio(label,search) + fuzz.partial_ratio(label,search) + fuzz.token_sort_ratio(label,search)}
                label = label + " (" + type + ")"
            else:
                continue

        item_count += 1

        properties = []
        description = row['description']
        duration = 0

        if row['duration'] and len(unicode(row['duration'])) > 0:
            duration = int(row['duration'])

        program_image = row['icon']
        program_image_large = row['icon']

        if row['type'] == "show":
            path = plugin.url_for(func_or_url=vod_series, label=label, description=description, image=program_image_large, id=id)
            info = {'plot': description}
            playable = False
        else:
            path = plugin.url_for(func_or_url=play_video, type='vod', channel=None, id=id)
            info = {'plot': description, 'duration': duration, 'mediatype': 'video'}
            playable = True

        items.append(plugin.Item(
            label = label,
            properties = properties,
            info = info,
            art = {
                'thumb': program_image,
                'fanart': program_image_large
            },
            path = path,
            playable = playable,
        ))

    if item_count == 50:
        total = int(len(data) + count)
    else:
        total = count

    returnar = {'items': items, 'count': item_count, 'count2': count, 'total': total}

    return returnar
Exemplo n.º 9
0
    def test_channels(self, 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'):
                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 = self.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 self._abortRequested and not xbmc.Monitor(
                    ).abortRequested() and counter < 5:
                        if self._abortRequested or xbmc.Monitor().waitForAbort(
                                1):
                            self._abortRequested = True
                            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 self._abortRequested or 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 = self.download(url=program_url,
                                             type='get',
                                             headers=None,
                                             data=None,
                                             json_data=False,
                                             return_json=True)
                    data = download['data']
                    resp = download['resp']

                    if resp and resp.status_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 = self.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 self._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 self._abortRequested and not xbmc.Monitor(
                    ).abortRequested() and counter < 15:
                        if self._abortRequested or xbmc.Monitor().waitForAbort(
                                1):
                            self._abortRequested = True
                            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 self._abortRequested or 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
Exemplo n.º 10
0
    def play_url(self,
                 type,
                 channel=None,
                 id=None,
                 test=False,
                 from_beginning=0):
        from_beginning = int(from_beginning)

        if not self.get_session():
            return None

        profile_settings = load_profile(profile_id=1)
        playdata = {'path': '', 'license': '', 'info': ''}

        headers = CONST_BASE_HEADERS
        headers.update({'Content-Type': 'application/json'})
        headers.update({'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 self._abortRequested and 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 self._abortRequested or xbmc.Monitor().waitForAbort(1):
                    self._abortRequested = True
                    break

            if self._abortRequested or xbmc.Monitor().abortRequested():
                return playdata

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

        if not type == 'vod':
            mediaID = int(channel) + 1

            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 not test:
                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 = self.download(url=channel_url,
                                         type='post',
                                         headers=headers,
                                         data=session_post_data,
                                         json_data=True,
                                         return_json=True)
                data = download['data']
                resp = download['resp']

                if not resp or not resp.status_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 = self.download(url=program_url,
                                         type='post',
                                         headers=headers,
                                         data=session_post_data,
                                         json_data=True,
                                         return_json=True)
                data = download['data']
                resp = download['resp']

                if not resp or not resp.status_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'):
                    return playdata

                info = data['playbillDetail']

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

        elif type == 'program' and id:
            if not test:
                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 = self.download(url=program_url,
                                         type='post',
                                         headers=headers,
                                         data=session_post_data,
                                         json_data=True,
                                         return_json=True)
                data = download['data']
                resp = download['resp']

                if not resp or not resp.status_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'):
                    return playdata

                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 = self.download(url=program_url,
                                     type='post',
                                     headers=headers,
                                     data=session_post_data,
                                     json_data=True,
                                     return_json=True)
            data = download['data']
            resp = download['resp']

            if not resp or not resp.status_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 check_key(info, 'series') and check_key(info['series'][0],
                                                       'VODID'):
                session_post_data["seriesID"] = info['series'][0]['VODID']
                session_post_data["mediaID"] = channel
            else:
                if not check_key(info, 'mediaFiles') or not check_key(
                        info['mediaFiles'][0], 'ID'):
                    return playdata

                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 self._abortRequested or xbmc.Monitor().abortRequested():
            return playdata

        download = self.download(url=play_url_path,
                                 type='post',
                                 headers=headers,
                                 data=session_post_data,
                                 json_data=True,
                                 return_json=True)
        data = download['data']
        resp = download['resp']

        if not resp or not resp.status_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'] = self.getCookies(
                profile_settings['cookies'], '')
            license = data['authorizeResult']

        if not test:
            real_url = "{hostscheme}://{netloc}".format(
                hostscheme=urlparse(path).scheme, netloc=urlparse(path).netloc)
            proxy_url = "http://127.0.0.1:{proxy_port}".format(
                proxy_port=profile_settings['proxyserver_port'])

            path = path.replace(real_url, proxy_url)

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

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

        return playdata
Exemplo n.º 11
0
    def test_channels(self, 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 self.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 = self.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 self._abortRequested and not xbmc.Monitor(
                    ).abortRequested() and counter < 5:
                        if self._abortRequested or xbmc.Monitor().waitForAbort(
                                1):
                            self._abortRequested = True
                            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 self._abortRequested or 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 = CONST_BASE_HEADERS
                    headers.update({'Content-Type': 'application/json'})
                    headers.update(
                        {'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 = self.download(url=channel_url,
                                             type='post',
                                             headers=headers,
                                             data=session_post_data,
                                             json_data=True,
                                             return_json=True)
                    data = download['data']
                    resp = download['resp']

                    if resp and resp.status_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 = self.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 self._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 self._abortRequested and not xbmc.Monitor(
                    ).abortRequested() and counter < 15:
                        if self._abortRequested or xbmc.Monitor().waitForAbort(
                                1):
                            self._abortRequested = True
                            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 self._abortRequested or 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
Exemplo n.º 12
0
def play_video(type=None,
               channel=None,
               id=None,
               title=None,
               from_beginning=0,
               **kwargs):
    from_beginning = int(from_beginning)

    profile_settings = load_profile(profile_id=1)

    properties = {}

    if not type and not len(unicode(type)) > 0:
        return False

    if type == 'program':
        properties['seekTime'] = 1

    playdata = api.play_url(type=type,
                            channel=channel,
                            id=id,
                            from_beginning=from_beginning)

    if not playdata or not check_key(playdata, 'path'):
        return False

    CDMHEADERS = CONST_BASE_HEADERS
    CDMHEADERS['User-Agent'] = profile_settings['user_agent']

    if check_key(playdata, 'license'):
        item_inputstream = inputstream.Widevine(
            license_key=playdata['license'], )
    else:
        item_inputstream = inputstream.MPD()

    itemlabel = ''
    label2 = ''
    description = ''
    program_image = ''
    program_image_large = ''
    duration = 0
    cast = []
    director = []
    writer = []
    genres = []

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

                duration = int((endT - startT).total_seconds())

                if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                    itemlabel = '{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:
                    itemlabel = startT.strftime(
                        "%A %d %B %Y %H:%M ").capitalize()

                itemlabel += " - "

        if title:
            itemlabel += title + ' - '

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

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

        if check_key(playdata['info'], 'images') and check_key(
                playdata['info']['images'][0], 'url'):
            program_image = playdata['info']['images'][0]['url']
            program_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":
                        cast.append(castmember['person'])
                    elif castmember['role'] == "Director":
                        director.append(castmember['person'])
                    elif castmember['role'] == "Writer":
                        writer.append(castmember['person'])

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

            if check_key(playdata['info']['params'], 'duration'):
                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'):
                label2 = playdata['info']['params']['episodeTitle']

                if len(epcode) > 0:
                    label2 += " (" + epcode + ")"
            elif check_key(playdata['info'], 'title'):
                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:
                        label2 += " - " + row['name']

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

    listitem = plugin.Item(
        label=itemlabel,
        label2=label2,
        art={
            'thumb': program_image,
            'fanart': program_image_large
        },
        info={
            'cast': cast,
            'writer': writer,
            'director': director,
            'genre': genres,
            'plot': description,
            'duration': duration,
            'mediatype': 'video',
        },
        properties=properties,
        path=playdata['path'],
        headers=CDMHEADERS,
        inputstream=item_inputstream,
    )

    return listitem
Exemplo n.º 13
0
    def test_channels(self, 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'):
                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 = self.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 self._abortRequested and not xbmc.Monitor(
                    ).abortRequested() and counter < 5:
                        if self._abortRequested or xbmc.Monitor().waitForAbort(
                                1):
                            self._abortRequested = True
                            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 self._abortRequested or xbmc.Monitor().abortRequested():
                        return 5

                    headers = CONST_BASE_HEADERS
                    headers.update({
                        '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 = self.download(url=program_url,
                                             type='get',
                                             headers=headers,
                                             data=None,
                                             json_data=False,
                                             return_json=True)
                    data = download['data']
                    resp = download['resp']

                    if resp and resp.status_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 = self.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 self._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 self._abortRequested and not xbmc.Monitor(
                    ).abortRequested() and counter < 15:
                        if self._abortRequested or xbmc.Monitor().waitForAbort(
                                1):
                            self._abortRequested = True
                            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 self._abortRequested or 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