예제 #1
0
def replaytv_list(character, label='', start=0, **kwargs):
    start = int(start)
    folder = plugin.Folder(title=label)

    data = load_file(file='list_replay.json', isJSON=True)

    if not data:
        gui.ok(message=_.NO_REPLAY_TV_INFO, heading=_.NO_REPLAY_TV_INFO)
        return folder

    if not check_key(data, character):
        return folder

    processed = process_replaytv_list(data=data[character], start=start)

    if check_key(processed, 'items'):
        folder.add_items(processed['items'])

    if check_key(processed,
                 'count') and len(data[character]) > processed['count']:
        folder.add_item(
            label=_(_.NEXT_PAGE, _bold=True),
            path=plugin.url_for(func_or_url=replaytv_list,
                                character=character,
                                label=label,
                                start=processed['count']),
        )

    return folder
예제 #2
0
def replaytv_item(ids=None, label=None, start=0, **kwargs):
    start = int(start)
    first = label[0]

    folder = plugin.Folder(title=label)

    if first.isalpha():
        data = load_file(file=first + "_replay.json", isJSON=True)
    else:
        data = load_file(file='other_replay.json', isJSON=True)

    if not data:
        return folder

    processed = process_replaytv_list_content(data=data, ids=ids, start=start)

    if check_key(processed, 'items'):
        folder.add_items(processed['items'])

    if check_key(processed, 'totalrows') and check_key(
            processed,
            'count') and processed['totalrows'] > processed['count']:
        folder.add_item(
            label=_(_.NEXT_PAGE, _bold=True),
            path=plugin.url_for(func_or_url=replaytv_item,
                                ids=ids,
                                label=label,
                                start=processed['count']),
        )

    return folder
예제 #3
0
    def vod_subscription(self):
        if not self.get_session():
            return None

        profile_settings = load_profile(profile_id=1)
        subscription = []

        series_url = '{api_url}/TRAY/SEARCH/VOD?from=1&to=9999&filter_contentType=GROUP_OF_BUNDLES,VOD&filter_contentSubtype=SERIES,VOD&filter_contentTypeExtended=VOD&filter_excludedGenres=erotiek&filter_technicalPackages=10078,10081,10258,10255&dfilter_packages=matchSubscription&orderBy=activationDate&sortOrder=desc'.format(
            api_url=profile_settings['api_url'])
        download = self.download(url=series_url,
                                 type='get',
                                 headers=None,
                                 data=None,
                                 json_data=False,
                                 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, 'resultCode'
        ) or not data['resultCode'] == 'OK' or not check_key(
                data, 'resultObj') or not check_key(data['resultObj'],
                                                    'containers'):
            return False

        for row in data['resultObj']['containers']:
            subscription.append(row['metadata']['contentId'])

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

        return True
예제 #4
0
def process_replaytv_list(data, start=0):
    start = int(start)
    items = []
    count = 0
    item_count = 0
    time_now = int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds())

    for row in sorted(data):
        currow = data[row]

        if item_count == 51:
            break

        if count < start:
            count += 1
            continue

        count += 1

        if not check_key(currow, 'orig') or not check_key(currow, 'ids'):
            continue

        if check_key(currow, 'a') and check_key(currow, 'e') and (time_now < int(currow['a']) or time_now > int(currow['e'])):
            continue

        label = currow['orig']

        items.append(plugin.Item(
            label = label,
            path = plugin.url_for(func_or_url=replaytv_item, ids=json.dumps(currow['ids']), label=label, start=0),
        ))

        item_count += 1

    return {'items': items, 'count': count}
예제 #5
0
    def check_data(self, resp, json=True):
        if self._debug_mode:
            log.debug('Executing: api.check_data')
            log.debug('Vars: resp={resp}, json={json}'.format(
                resp='Unaltered response, see above', json=json))

        if json:
            data = resp.json()

            if data and check_key(data,
                                  'resultCode') and data['resultCode'] == 'KO':
                if self._debug_mode:
                    log.debug('Execution Done: api.check_data')

                return False

            if not data or not check_key(data, 'resultCode') or not data[
                    'resultCode'] == 'OK' or not check_key(data, 'resultObj'):
                if self._debug_mode:
                    log.debug('Execution Done: api.check_data')

                return False

        if self._debug_mode:
            log.debug('Execution Done: api.check_data')

        return True
예제 #6
0
def replaytv_content(label, day, station='', start=0, **kwargs):
    day = int(day)
    start = int(start)
    folder = plugin.Folder(title=label)

    data = load_file(file=station + "_replay.json", isJSON=True)

    if not data:
        gui.ok(_.DISABLE_ONLY_STANDARD, _.NO_REPLAY_TV_INFO)
        return folder

    totalrows = len(data)
    processed = process_replaytv_content(data=data, day=day, start=start)

    if check_key(processed, 'items'):
        folder.add_items(processed['items'])

    if check_key(processed, 'count') and totalrows > processed['count']:
        folder.add_item(
            label=_(_.NEXT_PAGE, _bold=True),
            path=plugin.url_for(func_or_url=replaytv_content,
                                label=label,
                                day=day,
                                station=station,
                                start=processed['count']),
        )

    return folder
예제 #7
0
def change_channel(type, id, change, **kwargs):
    change = int(change)

    if not id or len(unicode(id)) == 0 or not type or len(unicode(type)) == 0:
        return False

    prefs = load_prefs(profile_id=1)
    id = unicode(id)
    type = unicode(type)

    mod_pref = {
        'live': 1,
        'live_auto': 1,
        'replay': 1,
        'replay_auto': 1,
        'epg': 1,
        'epg_auto': 1,
    }

    if change == 0:
        mod_pref[unicode(type) + '_auto'] = 0

        if not check_key(prefs, id):
            mod_pref[type] = 0
        else:
            if prefs[id][type] == 1:
                mod_pref[type] = 0
            else:
                mod_pref[type] = 1
    else:
        mod_pref[unicode(type) + '_auto'] = 1

        results = load_tests(profile_id=1)

        if not results or not check_key(results,
                                        id) or not results[id][type] == 1:
            mod_pref[type] = 1
        else:
            mod_pref[type] = 0

    query = "REPLACE INTO `prefs_{profile_id}` VALUES ('{id}', '{live}', '{live_auto}', '{replay}', '{replay_auto}', '{epg}', '{epg_auto}')".format(
        profile_id=1,
        id=id,
        live=mod_pref['live'],
        live_auto=mod_pref['live_auto'],
        replay=mod_pref['replay'],
        replay_auto=mod_pref['replay_auto'],
        epg=mod_pref['epg'],
        epg_auto=mod_pref['epg_auto'])
    query_settings(query=query,
                   return_result=False,
                   return_insert=False,
                   commit=True)

    if type == 'epg':
        create_playlist()

    xbmc.executeJSONRPC(
        '{{"jsonrpc":"2.0","id":1,"method":"GUI.ActivateWindow","params":{{"window":"videos","parameters":["plugin://'
        + unicode(ADDON_ID) + '/?_=channel_picker&type=' + type + '"]}}}}')
예제 #8
0
def get_play_url(content):
    if settings.getBool(key='_base_v3') and check_key(content, 'url') and check_key(content, 'contentLocator'):
        return {'play_url': content['url'], 'locator': content['contentLocator']}
    else:
        for stream in content:
            if  'streamingUrl' in stream and 'contentLocator' in stream and 'assetTypes' in stream and 'Orion-DASH' in stream['assetTypes']:
                return {'play_url': stream['streamingUrl'], 'locator': stream['contentLocator']}

    return {'play_url': '', 'locator': ''}
예제 #9
0
    def vod_seasons(self, id):
        if self._debug_mode:
            log.debug('Executing: api.vod_seasons')
            log.debug('Vars: id={id}'.format(id=id))

        seasons = []

        program_url = '{api_url}/CONTENT/DETAIL/GROUP_OF_BUNDLES/{id}'.format(
            api_url=self._api_url, id=id)

        file = "cache" + os.sep + "vod_seasons_" + unicode(id) + ".json"

        if self._enable_cache and not is_file_older_than_x_minutes(
                file=ADDON_PROFILE + file, minutes=10):
            data = load_file(file=file, isJSON=True)
        else:
            data = self.download(url=program_url,
                                 type='get',
                                 code=[200],
                                 data=None,
                                 json_data=False,
                                 data_return=True,
                                 return_json=True,
                                 retry=True,
                                 check_data=True)

            if data and check_key(data['resultObj'],
                                  'containers') and self._enable_cache:
                write_file(file=file, data=data, isJSON=True)

        if not data or not check_key(data['resultObj'], 'containers'):
            if self._debug_mode:
                log.debug('Failure to retrieve expected data')
                log.debug('Execution Done: api.vod_seasons')

            return None

        for row in data['resultObj']['containers']:
            for currow in row['containers']:
                if check_key(currow, 'metadata') and check_key(
                        currow['metadata'], 'season'
                ) and currow['metadata']['contentSubtype'] == 'SEASON':
                    seasons.append({
                        'id':
                        currow['metadata']['contentId'],
                        'seriesNumber':
                        currow['metadata']['season'],
                        'desc':
                        currow['metadata']['shortDescription'],
                        'image':
                        currow['metadata']['pictureUrl']
                    })

        if self._debug_mode:
            log.debug('Execution Done: api.vod_seasons')

        return seasons
예제 #10
0
def process_replaytv_search(data, start=0, search=None):
    start = int(start)
    items = []
    count = 0
    item_count = 0
    time_now = int((datetime.datetime.utcnow() -
                    datetime.datetime(1970, 1, 1)).total_seconds())

    for row in data:
        letter_row = data[row]

        for row2 in letter_row:
            currow = data[row][row2]

            if item_count == 51:
                break

            if count < start:
                count += 1
                continue

            count += 1

            if not check_key(currow, 'orig') or not check_key(currow, 'ids'):
                continue

            if check_key(currow, 'a') and check_key(
                    currow, 'e') and (time_now < int(currow['a'])
                                      or time_now > int(currow['e'])):
                continue

            label = currow['orig'] + ' (ReplayTV)'

            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:
                items.append(
                    plugin.Item(
                        label=label,
                        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,
                                            ids=json.dumps(currow['ids']),
                                            label=label,
                                            start=0),
                    ))

                item_count += 1

    return {'items': items, 'count': count}
예제 #11
0
def process_vod_season(data, mediagroupid=None):
    items = []

    if sys.version_info >= (3, 0):
        data['mediaItems'] = list(data['mediaItems'])

    for row in data['mediaItems']:
        context = []
        label = ''
        description = ''
        program_image_large = ''
        duration = 0

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

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

        if check_key(row, 'earliestBroadcastStartTime'):
            startsplit = int(row['earliestBroadcastStartTime']) // 1000

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

            if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                label = date_to_nl_dag(startT) + startT.strftime(" %d ") + date_to_nl_maand(startT) + startT.strftime(" %Y %H:%M ") + row['title']
            else:
                label = (startT.strftime("%A %d %B %Y %H:%M ") + row['title']).capitalize()
        else:
            label = row['title']

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

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

        if check_key(row, 'videoStreams'):
            urldata = get_play_url(content=row['videoStreams'])

            if urldata and check_key(urldata, 'play_url') and check_key(urldata, 'locator'):
                if mediagroupid:
                    context.append((_.ADD_TO_WATCHLIST, 'RunPlugin({context_url})'.format(context_url=plugin.url_for(func_or_url=add_to_watchlist, id=mediagroupid, type='group')), ))

                items.append(plugin.Item(
                    label = label,
                    info = {
                        'plot': description,
                        'duration': duration,
                        'mediatype': 'video',
                    },
                    art = {'thumb': program_image_large},
                    path = plugin.url_for(func_or_url=play_video, type='vod', id=row['id'], duration=duration, _is_live=False),
                    playable = True,
                    context = context
                ))

    return items
예제 #12
0
    def check_data(self, resp, json=True):
        if json == True:
            data = resp.json()

            if data and check_key(data, 'resultCode') and data['resultCode'] == 'KO':
                return False

            if not data or not check_key(data, 'resultCode') or not data['resultCode'] == 'OK' or not check_key(data, 'resultObj'):
                return False

        return True
예제 #13
0
def channel_picker(type, **kwargs):
    if type=='live':
        title = _.LIVE_TV
        rows = get_live_channels(addon=False, all=True)
    elif type=='replay':
        title = _.CHANNELS
        rows = get_replay_channels(all=True)
    else:
        title = _.SIMPLEIPTV
        rows = get_live_channels(addon=False, all=True)

    folder = plugin.Folder(title=title)
    prefs = load_prefs(profile_id=1)
    results = load_tests(profile_id=1)
    type = unicode(type)

    for row in rows:
        id = unicode(row['channel'])

        if not prefs or not check_key(prefs, id) or prefs[id][type] == 1:
            color = 'green'
        else:
            color = 'red'

        label = _(row['label'], _bold=True, _color=color)

        if results and check_key(results, id):
            if results[id][type] == 1:
                label += _(' (' + _.TEST_SUCCESS + ')', _bold=False, _color='green')
            else:
                label += _(' (' + _.TEST_FAILED + ')', _bold=False, _color='red')
        else:
            label += _(' (' + _.NOT_TESTED + ')', _bold=False, _color='orange')

        if not prefs or not check_key(prefs, id) or prefs[id][type + '_auto'] == 1:
            choice = _(' ,' + _.AUTO_CHOICE + '', _bold=False, _color='green')
        else:
            choice = _(' ,' + _.MANUAL_CHOICE + '', _bold=False, _color='orange')

        label += choice

        folder.add_item(
            label = label,
            art = {'thumb': row['image']},
            path = plugin.url_for(func_or_url=change_channel, type=type, id=id, change=0),
            context = [
                (_.AUTO_CHOICE_SET, 'Container.Update({context_url})'.format(context_url=plugin.url_for(func_or_url=change_channel, type=type, id=id, change=1)), ),
                #(_.TEST_CHANNEL, 'RunPlugin({context_url})'.format(context_url=plugin.url_for(func_or_url=test_channel, channel=id)), ),
            ],
            playable = False,
        )

    return folder
예제 #14
0
    def get_channel_data(self, row):
        if self._debug_mode:
            log.debug('Executing: api.get_channel_data')
            log.debug('Vars: row={row}'.format(row=row))

        asset_id = ''

        channeldata = {
            'channel_id': '',
            'channel_number': '',
            'description': '',
            'label': '',
            'station_image_large': '',
        }

        if not check_key(row, 'metadata') or not check_key(
                row['metadata'], 'channelId') or not check_key(
                    row['metadata'], 'externalId') or not check_key(
                        row['metadata'], 'orderId') or not check_key(
                            row['metadata'], 'channelName'):
            if self._debug_mode:
                log.debug('Failure to retrieve expected data')
                log.debug('Execution Done: api.get_channel_data')

            return channeldata

        if check_key(row, 'assets'):
            for asset in row['assets']:
                if check_key(asset, 'videoType') and check_key(
                        asset,
                        'assetId') and asset['videoType'] == 'SD_DASH_PR':
                    asset_id = asset['assetId']
                    break

        path = ADDON_PROFILE + "images" + os.sep + unicode(
            row['metadata']['channelId']) + ".png"

        if os.path.isfile(path):
            image = path
        else:
            image = '{images_url}/logo/{external_id}/256.png'.format(
                images_url=CONST_IMAGE_URL,
                external_id=row['metadata']['externalId'])

        channeldata = {
            'channel_id': row['metadata']['channelId'],
            'channel_number': int(row['metadata']['orderId']),
            'description': '',
            'label': row['metadata']['channelName'],
            'station_image_large': image,
            'asset_id': asset_id
        }

        if self._debug_mode:
            log.debug(
                'Returned data: {channeldata}'.format(channeldata=channeldata))
            log.debug('Execution Done: api.get_channel_data')

        return channeldata
예제 #15
0
    def vod_seasons(self, id):
        seasons = []

        program_url = '{api_url}/CONTENT/DETAIL/GROUP_OF_BUNDLES/{id}'.format(api_url=settings.get(key='_api_url'), id=id)
        data = self.download(url=program_url, type='get', code=[200], data=None, json_data=False, data_return=True, return_json=True, retry=True, check_data=True)

        if not data or not check_key(data['resultObj'], 'containers'):
            return None

        for row in data['resultObj']['containers']:
            for currow in row['containers']:
                if check_key(currow, 'metadata') and check_key(currow['metadata'], 'season') and currow['metadata']['contentSubtype'] == 'SEASON':
                    seasons.append({'id': currow['metadata']['contentId'], 'seriesNumber': currow['metadata']['season'], 'desc': currow['metadata']['shortDescription'], 'image': currow['metadata']['pictureUrl']})

        return seasons
예제 #16
0
def play_video(type=None,
               channel=None,
               id=None,
               catchup=None,
               duration=0,
               **kwargs):
    properties = {}

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

    if (catchup and len(catchup) > 0) or type == 'program':
        if catchup and len(catchup) > 0:
            id = catchup

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

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

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

    CDMHEADERS = CONST_BASE_HEADERS
    CDMHEADERS['User-Agent'] = settings.get(key='_user_agent')

    if type == 'channel':
        playdata['path'] = playdata['path'].split("&", 1)[0]
    else:
        playdata['path'] = playdata['path'].split("&min_bitrate", 1)[0]

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

    settings.setInt(key='_stream_duration', value=duration)

    listitem = plugin.Item(
        properties=properties,
        path=playdata['path'],
        headers=CDMHEADERS,
        inputstream=item_inputstream,
    )

    return listitem
예제 #17
0
    def get_channels_for_user(self):
        self._session.headers = CONST_BASE_HEADERS
        self._session.headers.update({'Authorization': 'Bearer ' + self._session_token})

        if self._debug_mode:
            log.debug('Executing: api.get_channels_for_user')
            log.debug('Request Session Headers')
            log.debug(self._session.headers)

        channels_url = "{api_url}/assets?query=channels,3&limit=999&from=0".format(api_url=CONST_DEFAULT_API);

        data = self.download(url=channels_url, type="get", code=[200], data=None, json_data=False, data_return=True, return_json=True, retry=True, check_data=False, allow_redirects=False)

        if not data or not check_key(data, 'assets'):
            if self._debug_mode:
                log.debug('Failure to retrieve expected data')
                log.debug('Execution Done: api.get_channels_for_user')

            return False

        write_file(file="channels.json", data=data['assets'], isJSON=True)

        self.create_playlist()

        if self._debug_mode:
            log.debug('Execution Done: api.get_channels_for_user')

        return True
예제 #18
0
    def get_channels_for_user(self):
        if self._debug_mode:
            log.debug('Executing: api.get_channels_for_user')

        channels_url = '{api_url}/TRAY/LIVECHANNELS?orderBy=orderId&sortOrder=asc&from=0&to=999&dfilter_channels=subscription'.format(
            api_url=self._api_url)
        data = self.download(url=channels_url,
                             type='get',
                             code=[200],
                             data=None,
                             json_data=False,
                             data_return=True,
                             return_json=True,
                             retry=True,
                             check_data=True)

        if not data or not check_key(data['resultObj'], 'containers'):
            if self._debug_mode:
                log.debug('Failure to retrieve expected data')
                log.debug('Execution Done: api.get_channels_for_user')

            return False

        write_file(file="channels.json",
                   data=data['resultObj']['containers'],
                   isJSON=True)

        self.create_playlist()

        if self._debug_mode:
            log.debug('Execution Done: api.get_channels_for_user')

        return True
예제 #19
0
    def get_play_token(self, locator, force=False):
        if settings.getInt(key='_drm_token_age') < int(time.time() - 50) and (
                settings.getInt(key='_tokenrun') == 0 or
                settings.getInt(key='_tokenruntime') < int(time.time() - 30)):
            force = True

        if locator != settings.get(key='_drm_locator') or settings.getInt(
                key='_drm_token_age') < int(time.time() - 90) or force == True:
            settings.setInt(key='_tokenrun', value=1)
            settings.setInt(key='_tokenruntime', value=time.time())

            data = self.download(url=settings.get(key='_token_url'),
                                 type="post",
                                 code=[200],
                                 data={"contentLocator": locator},
                                 json_data=True,
                                 data_return=True,
                                 return_json=True,
                                 retry=True,
                                 check_data=False)

            if not data or not check_key(data, 'token'):
                settings.setInt(key="_tokenrun", value=0)
                return None

            settings.set(key='_drm_token', value=data['token'])
            settings.setInt(key='_drm_token_age', value=time.time())
            settings.set(key='_drm_locator', value=locator)
            settings.setInt(key="_tokenrun", value=0)

            return data['token']

        return settings.get(key='_drm_token')
예제 #20
0
    def add_to_watchlist(self, id, type):
        if type == "item":
            mediaitems_url = '{listings_url}/{id}'.format(
                listings_url=settings.get(key='_listings_url'), id=id)
            data = self.download(url=mediaitems_url,
                                 type="get",
                                 code=[200],
                                 data=None,
                                 json_data=False,
                                 data_return=True,
                                 return_json=True,
                                 retry=True,
                                 check_data=False)

            if not data or not check_key(data, 'mediaGroupId'):
                return False

            id = data['mediaGroupId']

        watchlist_url = '{watchlist_url}/entries'.format(
            watchlist_url=settings.get(key='_watchlist_url'))
        data = self.download(url=watchlist_url,
                             type="post",
                             code=[204],
                             data={"mediaGroup": {
                                 'id': id
                             }},
                             json_data=True,
                             data_return=False,
                             return_json=False,
                             retry=True,
                             check_data=False)

        return data
예제 #21
0
def vod(file, label, start=0, **kwargs):
    start = int(start)
    folder = plugin.Folder(title=label)

    processed = process_vod_content(data=file, start=start, type=label)

    if check_key(processed, 'items'):
        folder.add_items(processed['items'])

    if check_key(processed, 'total') and check_key(processed, 'count2') and processed['total'] > processed['count2']:
        folder.add_item(
            label = _(_.NEXT_PAGE, _bold=True),
            path = plugin.url_for(func_or_url=vod, file=file, label=label, start=processed['count2']),
        )

    return folder
예제 #22
0
def replaytv_item(label=None, idtitle=None, start=0, **kwargs):
    start = int(start)
    folder = plugin.Folder(title=label)

    processed = process_replaytv_list_content(label=label, idtitle=idtitle, start=start)

    if check_key(processed, 'items'):
        folder.add_items(processed['items'])

    if check_key(processed, 'total') and check_key(processed, 'count') and int(processed['total']) > int(processed['count']):
        folder.add_item(
            label = _(_.NEXT_PAGE, _bold=True),
            path = plugin.url_for(func_or_url=replaytv_item, label=label, idtitle=idtitle, start=start+processed['count']),
        )

    return folder
예제 #23
0
def replaytv_list(character, label='', start=0, **kwargs):
    start = int(start)
    folder = plugin.Folder(title=label)

    processed = process_replaytv_list(character=character, start=start)

    if check_key(processed, 'items'):
        folder.add_items(processed['items'])

    if check_key(processed, 'count') and check_key(processed, 'total') and processed['total'] > 50:
        folder.add_item(
            label = _(_.NEXT_PAGE, _bold=True),
            path = plugin.url_for(func_or_url=replaytv_list, character=character, label=label, start=start+processed['count']),
        )

    return folder
예제 #24
0
def replaytv_content(label, day, station='', start=0, **kwargs):
    day = int(day)
    start = int(start)
    folder = plugin.Folder(title=label)

    processed = process_replaytv_content(station=station, day=day, start=start)

    if check_key(processed, 'items'):
        folder.add_items(processed['items'])

    if check_key(processed, 'total') and check_key(processed, 'count') and processed['total'] > processed['count']:
        folder.add_item(
            label = _(_.NEXT_PAGE, _bold=True),
            path = plugin.url_for(func_or_url=replaytv_content, label=label, day=day, station=station, start=processed['count']),
        )

    return folder
예제 #25
0
    def get_session(self):
        profile_settings = load_profile(profile_id=1)

        if check_key(profile_settings, 'last_login_time'
                     ) and profile_settings['last_login_time'] > int(time.time(
                     ) - 3600) and profile_settings['last_login_success'] == 1:
            return True

        heartbeat_url = '{base_url}/VSP/V3/OnLineHeartbeat?from=inMSAAccess'.format(
            base_url=CONST_BASE_URL)

        headers = CONST_BASE_HEADERS
        headers.update({'Content-Type': 'application/json'})
        headers.update({'X_CSRFToken': profile_settings['csrf_token']})

        session_post_data = {}

        download = self.download(url=heartbeat_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':
            login_result = self.login()

            if not login_result['result']:
                return False

        try:
            query = "UPDATE `vars` SET `last_login_time`={last_login_time}, `last_login_success`=1 WHERE profile_id={profile_id}".format(
                last_login_time=int(time.time()), profile_id=1)
            query_settings(query=query,
                           return_result=False,
                           return_insert=False,
                           commit=True)
        except:
            pass

        return True
예제 #26
0
def get_live_channels(addon=False):
    global backend, query_channel

    channels = []
    rows = load_file(file='channels.json', isJSON=True)

    if rows:
        if addon == True:
            query_addons = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id": 1, "method": "Addons.GetAddons", "params": {"type": "xbmc.pvrclient"}}'))
            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}'))

        for row in rows:
            channeldata = api.get_channel_data(row=row)
            urldata = get_play_url(content=channeldata['stream'])

            if urldata and check_key(urldata, 'play_url') and check_key(urldata, 'locator'):
                path = plugin.url_for(play_video, type='channel', id=urldata['play_url'], locator=urldata['locator'], _is_live=True)
                playable = True

                if addon == True and 'result' in query_channel:
                    if 'channels' in query_channel['result']:
                        pvrchannels = query_channel['result']['channels']

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

                channels.append({
                    'label': channeldata['label'],
                    'channel': channeldata['channel_id'],
                    'chno': channeldata['channel_number'],
                    'description': channeldata['description'],
                    'image': channeldata['station_image_large'],
                    'path':  path,
                    'playable': playable,
                })

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

    return channels
예제 #27
0
def login(ask=1, **kwargs):
    ask = int(ask)

    profile_settings = load_profile(profile_id=1)

    if len(profile_settings['devicekey']) == 0:
        _devicekey = 'w{uuid}'.format(uuid=uuid.uuid4())
        query = "UPDATE `vars` SET `devicekey`='{devicekey}' WHERE profile_id={profile_id}".format(
            devicekey=_devicekey, profile_id=1)
        query_settings(query=query,
                       return_result=False,
                       return_insert=False,
                       commit=True)

    creds = get_credentials()

    if len(creds['username']) < 1 or len(creds['password']) < 1 or ask == 1:
        username = gui.input(message=_.ASK_USERNAME,
                             default=creds['username']).strip()

        if not len(username) > 0:
            gui.ok(message=_.EMPTY_USER, heading=_.LOGIN_ERROR_TITLE)
            return

        password = gui.input(message=_.ASK_PASSWORD, hide_input=True).strip()

        if not len(password) > 0:
            gui.ok(message=_.EMPTY_PASS, heading=_.LOGIN_ERROR_TITLE)
            return

        set_credentials(username=username, password=password)

    login_result = api.login()

    if login_result['result'] == False:
        query = "UPDATE `vars` SET `pswd`='', `last_login_success`='{last_login_success}' WHERE profile_id={profile_id}".format(
            last_login_success=0, profile_id=1)
        query_settings(query=query,
                       return_result=False,
                       return_insert=False,
                       commit=True)

        if check_key(login_result['data'],
                     'error') and login_result['data']['error'] == 'toomany':
            gui.ok(message=_.TOO_MANY_DEVICES, heading=_.LOGIN_ERROR_TITLE)
        else:
            gui.ok(message=_.LOGIN_ERROR, heading=_.LOGIN_ERROR_TITLE)
    else:
        gui.ok(message=_.LOGIN_SUCCESS)

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

    gui.refresh()
예제 #28
0
    def get_channels_for_user(self, location):
        channels_url = '{channelsurl}?byLocationId={location}&includeInvisible=true&personalised=true'.format(
            channelsurl=settings.get('_channels_url'), location=location)
        data = self.download(url=channels_url,
                             type="get",
                             code=[200],
                             data=None,
                             json_data=False,
                             data_return=True,
                             return_json=True,
                             retry=True,
                             check_data=False)

        if data and check_key(data, 'entryCount') and check_key(
                data, 'channels'):
            settings.setInt(key='_channels_age', value=time.time())

            write_file(file="channels.json",
                       data=data['channels'],
                       isJSON=True)

            playlist = u'#EXTM3U\n'

            for row in sorted(
                    data['channels'],
                    key=lambda r: float(r.get('channelNumber', 'inf'))):
                channeldata = self.get_channel_data(row=row)
                urldata = get_play_url(content=channeldata['stream'])

                if urldata and check_key(urldata, 'play_url') and check_key(
                        urldata, 'locator'):
                    path = 'plugin://{addonid}/?_=play_video&type=channel&id={play_url}&locator={locator}&_l=.pvr'.format(
                        addonid=ADDON_ID,
                        play_url=quote(urldata['play_url']),
                        locator=quote(urldata['locator']))

                    playlist += u'#EXTINF:-1 tvg-id="{id}" tvg-chno="{channel}" tvg-name="{name}" tvg-logo="{logo}" group-title="TV" radio="false",{name}\n{path}\n'.format(
                        id=channeldata['channel_id'],
                        channel=channeldata['channel_number'],
                        name=channeldata['label'],
                        logo=channeldata['station_image_large'],
                        path=path)

            write_file(file="tv.m3u8", data=playlist, isJSON=False)
            combine_playlist()
예제 #29
0
def login(ask=1, **kwargs):
    ask = int(ask)
    
    profile_settings = load_profile(profile_id=1)

    if len(profile_settings['devicekey']) == 0:
        devicekey = ''.join(random.choice(string.digits) for _ in range(10))
        query = "UPDATE `vars` SET `devicekey`='{devicekey}' WHERE profile_id={profile_id}".format(devicekey=devicekey, profile_id=1)
        query_settings(query=query, return_result=False, return_insert=False, commit=True)

    creds = get_credentials()

    if len(creds['username']) < 1 or len(creds['password']) < 1 or ask == 1:
        username = gui.numeric(message=_.ASK_USERNAME, default=creds['username']).strip()

        if not len(username) > 0:
            gui.ok(message=_.EMPTY_USER, heading=_.LOGIN_ERROR_TITLE)
            return

        password = gui.numeric(message=_.ASK_PASSWORD).strip()

        if not len(password) > 0:
            gui.ok(message=_.EMPTY_PASS, heading=_.LOGIN_ERROR_TITLE)
            return

        set_credentials(username=username, password=password)

    login_result = api.login()

    if login_result['result'] == False:
        query = "UPDATE `vars` SET `pswd`='', `last_login_success`='{last_login_success}' WHERE profile_id={profile_id}".format(last_login_success=0, profile_id=1)
        query_settings(query=query, return_result=False, return_insert=False, commit=True)

        if check_key(login_result['data'], 'result') and check_key(login_result['data']['result'], 'retCode') and login_result['data']['result']['retCode'] == "157022007":
            gui.ok(message=_.TOO_MANY_DEVICES, heading=_.LOGIN_ERROR_TITLE)
        else:
            gui.ok(message=_.LOGIN_ERROR, heading=_.LOGIN_ERROR_TITLE)
    else:
        query = "UPDATE `vars` SET `last_login_success`='{last_login_success}' WHERE profile_id={profile_id}".format(last_login_success=1, profile_id=1)
        query_settings(query=query, return_result=False, return_insert=False, commit=True)

        gui.ok(message=_.LOGIN_SUCCESS)

    gui.refresh()
예제 #30
0
    def get_channel_data(self, row, channelno=0):
        if self._debug_mode:
            log.debug('Executing: api.get_channel_data')
            log.debug('Vars: row={row}, channelno={channelno}'.format(row=row, channelno=channelno))

        channeldata = {
            'channel_id': '',
            'channel_number': int(channelno),
            'description': '',
            'label': '',
            'station_image_large': '',
        }

        if not check_key(row, 'id') or not check_key(row, 'title'):
            if self._debug_mode:
                log.debug('Failure to retrieve expected data')
                log.debug('Execution Done: api.get_channel_data')

            return channeldata

        #if '18+' in row['title']:
        #    if self._debug_mode:
        #        log.debug('Skipping XXX')
        #
        #    return channeldata

        path = ADDON_PROFILE + "images" + os.sep + unicode(row['id']) + ".png"
        image = ''

        if os.path.isfile(path):
            image = path
        else:
            if check_key(row, 'images') and check_key(row['images'][0], 'url'):
                image = row['images'][0]['url']

        channeldata['channel_id'] = row['id']
        channeldata['label'] = row['title']
        channeldata['station_image_large'] = image

        if self._debug_mode:
            log.debug('Returned data: {channeldata}'.format(channeldata=channeldata))
            log.debug('Execution Done: api.get_channel_data')

        return channeldata