def test_channel(channel, **kwargs): profile_settings = load_profile(profile_id=1) test_running = profile_settings['test_running'] while not api._abortRequested and not xbmc.Monitor().abortRequested( ) and test_running == 1: query = "UPDATE `vars` SET `last_playing`='{last_playing}' WHERE profile_id={profile_id}".format( last_playing=int(time.time()), profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if xbmc.Monitor().waitForAbort(1): api._abortRequested = True break profile_settings = load_profile(profile_id=1) test_running = profile_settings['test_running'] if api._abortRequested or xbmc.Monitor().abortRequested(): return None query = "UPDATE `vars` SET `last_playing`=0 WHERE profile_id={profile_id}".format( profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) api.test_channels(tested=True, channel=channel)
def do_GET(self): try: self._stream_url except: profile_settings = load_profile(profile_id=1) self._stream_url = profile_settings['stream_hostname'] try: self._last_playing except: self._last_playing = 0 if ".mpd" in self.path: profile_settings = load_profile(profile_id=1) self._stream_url = profile_settings['stream_hostname'] session = Session(cookies_key='cookies', save_cookies=False) r = session.get(self._stream_url + str(self.path)) xml = r.text xml = set_duration(xml=xml) if settings.getBool(key='force_highest_bandwidth'): xml = force_highest_bandwidth(xml=xml) self.send_response(r.status_code) r.headers['Content-Length'] = len(xml) for header in r.headers: if not 'Content-Encoding' in header and not 'Transfer-Encoding' in header: self.send_header(header, r.headers[header]) self.end_headers() try: xml = xml.encode('utf-8') except: pass try: self.wfile.write(xml) except: pass else: self._now_playing = int(time.time()) if self._last_playing + 60 < self._now_playing: self._last_playing = int(time.time()) query = "UPDATE `vars` SET `last_playing`='{last_playing}' WHERE profile_id={profile_id}".format( last_playing=self._last_playing, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) self.send_response(302) self.send_header('Location', self._stream_url + str(self.path)) self.end_headers()
def search_menu(**kwargs): folder = plugin.Folder(title=_.SEARCHMENU) label = _.NEWSEARCH folder.add_item( label = label, info = {'plot': _.NEWSEARCHDESC}, path = plugin.url_for(func_or_url=search), ) profile_settings = load_profile(profile_id=1) for x in range(1, 10): searchstr = profile_settings['search' + unicode(x)] if searchstr != '': label = searchstr folder.add_item( label = label, info = {'plot': _(_.SEARCH_FOR, query=searchstr)}, path = plugin.url_for(func_or_url=search, query=searchstr), ) return folder
def __init__(self, headers=None, cookies_key=None, save_cookies=True, base_url='{}', timeout=None, attempts=None): super(Session, self).__init__() profile_settings = load_profile(profile_id=1) user_agent = profile_settings['user_agent'] CONST_BASE_HEADERS.update({'User-Agent': user_agent}) if headers: CONST_BASE_HEADERS.update(headers) self._headers = CONST_BASE_HEADERS or {} self._cookies_key = cookies_key self._save_cookies = save_cookies self._base_url = base_url self._timeout = timeout or (5, 10) self._attempts = attempts or 2 self.headers.update(self._headers) if self._cookies_key: try: cookies = json.loads(profile_settings[cookies_key]) except: cookies = {} self.cookies.update(cookies)
def home(**kwargs): profile_settings = load_profile(profile_id=1) if profile_settings['first_boot'] == 1: first_boot() folder = plugin.Folder() if len(profile_settings['pswd']) > 0 and len( profile_settings['devicekey']) > 0: folder.add_item(label=_(_.LIVE_TV, _bold=True), path=plugin.url_for(func_or_url=live_tv)) folder.add_item(label=_(_.CHANNELS, _bold=True), path=plugin.url_for(func_or_url=replaytv)) #if settings.getBool('showMoviesSeries'): # folder.add_item(label=_(_.SERIES, _bold=True), path=plugin.url_for(func_or_url=vod, file='series', label=_.SERIES, start=0)) # folder.add_item(label=_(_.MOVIES, _bold=True), path=plugin.url_for(func_or_url=vod, file='movies', label=_.MOVIES, start=0)) # folder.add_item(label=_(_.KIDS_SERIES, _bold=True), path=plugin.url_for(func_or_url=vod, file='kidsseries', label=_.KIDS_SERIES, start=0)) # folder.add_item(label=_(_.KIDS_MOVIES, _bold=True), path=plugin.url_for(func_or_url=vod, file='kidsmovies', label=_.KIDS_MOVIES, start=0)) folder.add_item(label=_(_.SEARCH, _bold=True), path=plugin.url_for(func_or_url=search_menu)) folder.add_item(label=_(_.LOGIN, _bold=True), path=plugin.url_for(func_or_url=login)) folder.add_item(label=_.SETTINGS, path=plugin.url_for(func_or_url=settings_menu)) return folder
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
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()
def _reset(**kwargs): if not gui.yes_no(_.PLUGIN_RESET_YES_NO): return _close() try: xbmc.executeJSONRPC( '{{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{{"addonid":"{}","enabled":false}}}}' .format(ADDON_ID)) profile_settings = load_profile(profile_id=1) proxyserver_port = int(profile_settings['proxyserver_port']) system = profile_settings['system'] arch = profile_settings['arch'] shutil.rmtree(ADDON_PROFILE) directory = os.path.dirname(ADDON_PROFILE + os.sep + "images") try: if not os.path.exists(directory): os.makedirs(directory) except: pass directory = os.path.dirname(ADDON_PROFILE + os.sep + "cache") try: if not os.path.exists(directory): os.makedirs(directory) except: pass query = "UPDATE `vars` SET `arch`='{arch}', `system`='{system}', `test_running`=0, `proxyserver_port`={proxyserver_port} WHERE profile_id={profile_id}".format( arch=arch, system=system, proxyserver_port=proxyserver_port, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) download_files() update_settings() update_prefs() except: pass xbmc.executeJSONRPC( '{{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{{"addonid":"{}","enabled":true}}}}' .format(ADDON_ID)) gui.notification(_.PLUGIN_RESET_OK) signals.emit(signals.AFTER_RESET) gui.refresh()
def vod_seasons(self, id): profile_settings = load_profile(profile_id=1) seasons = [] program_url = '{api_url}/CONTENT/DETAIL/GROUP_OF_BUNDLES/{id}'.format( api_url=profile_settings['api_url'], id=id) file = "cache" + os.sep + "vod_seasons_" + unicode(id) + ".json" if settings.getBool( key='enable_cache') and not is_file_older_than_x_minutes( file=ADDON_PROFILE + file, minutes=10): data = load_file(file=file, isJSON=True) else: if not self.get_session(): return None download = self.download(url=program_url, type='get', headers=None, data=None, 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, 'resultCode') and data['resultCode'] == 'OK' and check_key( data, 'resultObj') and check_key( data['resultObj'], 'containers') and settings.getBool( key='enable_cache'): write_file(file=file, data=data, isJSON=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
def _download_epg(**kwargs): _close() try: profile_settings = load_profile(profile_id=1) if int(profile_settings['epgrun']) == 0 or int( profile_settings['epgruntime']) < (int(time.time()) - 300): download_epg() gui.notification(_.DONE_NOREBOOT) except: pass
def startHTTPServer(self): if self.isShutdown: return self.stopHTTPServer() try: profile_settings = load_profile(profile_id=1) self.HTTPServer = HTTPServer( self, ('', int(profile_settings['proxyserver_port']))) except IOError as e: pass threadStarting = threading.Thread(target=self.HTTPServer.serve_forever) threadStarting.start() self.HTTPServerThread = threadStarting
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
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()
def update_settings(): profile_settings = load_profile(profile_id=1) user_agent = profile_settings['user_agent'] browser_name = uaparser.detect(user_agent)['browser']['name'] browser_version = uaparser.detect(user_agent)['browser']['version'] os_name = uaparser.detect(user_agent)['os']['name'] os_version = uaparser.detect(user_agent)['os']['version'] query = "UPDATE `vars` SET `browser_name`='{browser_name}', `browser_version`='{browser_version}', `os_name`='{os_name}', `os_version`='{os_version}' WHERE profile_id={profile_id}".format( browser_name=browser_name, browser_version=browser_version, os_name=os_name, os_version=os_version, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True)
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 devices_url = '{api_url}/USER/DEVICES'.format( api_url=profile_settings['api_url']) download = self.download(url=devices_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': 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
def update_settings(): profile_settings = load_profile(profile_id=1) settingsJSON = load_file(file='settings.json', isJSON=True) try: api_url = settingsJSON['api_url'] if len(api_url) == 0: api_url = CONST_DEFAULT_API except: api_url = CONST_DEFAULT_API try: img_size = settingsJSON['img_size'] if len(img_size) == 0: img_size = CONST_DEFAULT_IMG_SIZE except: img_size = CONST_DEFAULT_IMG_SIZE user_agent = profile_settings['user_agent'] browser_name = uaparser.detect(user_agent)['browser']['name'] browser_version = uaparser.detect(user_agent)['browser']['version'] os_name = uaparser.detect(user_agent)['os']['name'] os_version = uaparser.detect(user_agent)['os']['version'] query = "UPDATE `vars` SET `api_url`='{api_url}', `img_size`='{img_size}', `browser_name`='{browser_name}', `browser_version`='{browser_version}', `os_name`='{os_name}', `os_version`='{os_version}' WHERE profile_id={profile_id}".format( api_url=api_url, img_size=img_size, browser_name=browser_name, browser_version=browser_version, os_name=os_name, os_version=os_version, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True)
def get_session(self): profile_settings = load_profile(profile_id=1) devices_url = '{api_url}/USER/DEVICES'.format( api_url=profile_settings['api_url']) download = self.download(url=devices_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': login_result = self.login() if not login_result['result']: return False return True
def get_session(self): profile_settings = load_profile(profile_id=1) headers = CONST_BASE_HEADERS capi_url = '{base_url}/m7be2iphone/capi.aspx?z=pg&a=cds&lng=nl'.format( base_url=CONST_BASE_URL) download = self.download(url=capi_url, type='get', headers=headers, data=None, json_data=False, return_json=False, allow_redirects=False) resp = download['resp'] if not resp or not resp.status_code == 200: login_result = self.login() if not login_result['result']: return False return True
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
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
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
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
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
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
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
def vod_season(self, id): profile_settings = load_profile(profile_id=1) season = [] episodes = [] program_url = '{api_url}/CONTENT/DETAIL/BUNDLE/{id}'.format( api_url=profile_settings['api_url'], id=id) file = "cache" + os.sep + "vod_season_" + unicode(id) + ".json" if settings.getBool( key='enable_cache') and not is_file_older_than_x_minutes( file=ADDON_PROFILE + file, minutes=10): data = load_file(file=file, isJSON=True) else: if not self.get_session(): return None download = self.download(url=program_url, type='get', headers=None, data=None, 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, 'resultCode') and data['resultCode'] == 'OK' and check_key( data, 'resultObj') and check_key( data['resultObj'], 'containers') and settings.getBool( key='enable_cache'): write_file(file=file, data=data, isJSON=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'] == 'EPISODE' and not currow[ 'metadata']['episodeNumber'] in episodes: asset_id = '' for asset in currow['assets']: if check_key( asset, 'videoType' ) and asset['videoType'] == 'SD_DASH_PR' and check_key( asset, 'assetType' ) and asset['assetType'] == 'MASTER': asset_id = asset['assetId'] break episodes.append(currow['metadata']['episodeNumber']) season.append({ 'id': currow['metadata']['contentId'], 'assetid': asset_id, 'duration': currow['metadata']['duration'], 'title': currow['metadata']['episodeTitle'], 'episodeNumber': '{season}.{episode}'.format( season=currow['metadata']['season'], episode=currow['metadata']['episodeNumber']), 'desc': currow['metadata']['shortDescription'], 'image': currow['metadata']['pictureUrl'] }) return season
def vod_season(self, id): season = [] file = "cache" + os.sep + "vod_season_" + unicode(id) + ".json" if settings.getBool( key='enable_cache') and not is_file_older_than_x_minutes( file=ADDON_PROFILE + file, minutes=10): data = load_file(file=file, isJSON=True) else: profile_settings = load_profile(profile_id=1) headers = CONST_BASE_HEADERS headers.update({'Content-Type': 'application/json'}) headers.update({'X_CSRFToken': profile_settings['csrf_token']}) session_post_data = { 'VODID': unicode(id), 'offset': '0', 'count': '35', } seasons_url = '{base_url}/VSP/V3/QueryEpisodeList?from=throughMSAAccess'.format( base_url=CONST_BASE_URL) download = self.download(url=seasons_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, 'result') and check_key( data['result'], 'retCode') and data['result'][ 'retCode'] == '000000000' and check_key( data, 'episodes') and settings.getBool( key='enable_cache'): write_file(file=file, data=data, isJSON=True) if not data or not check_key(data, 'episodes'): return None for row in data['episodes']: if check_key( row, 'VOD') and check_key(row['VOD'], 'ID') and check_key( row['VOD'], 'name') and check_key(row, 'sitcomNO'): image = '' duration = 0 if not check_key(row['VOD'], 'mediaFiles') or not check_key( row['VOD']['mediaFiles'][0], 'ID'): continue if check_key(row['VOD']['mediaFiles'][0], 'elapseTime'): duration = row['VOD']['mediaFiles'][0]['elapseTime'] if check_key(row['VOD'], 'picture') and check_key( row['VOD']['picture'], 'posters'): image = row['VOD']['picture']['posters'][0] season.append({ 'id': row['VOD']['ID'], 'media_id': row['VOD']['mediaFiles'][0]['ID'], 'duration': duration, 'title': row['VOD']['name'], 'episodeNumber': row['sitcomNO'], 'desc': '', 'image': image }) return season
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
def play_url(self, type, channel=None, id=None, test=False, from_beginning=False): if not self.get_session(): return None profile_settings = load_profile(profile_id=1) playdata = { 'path': '', 'license': '', 'token': '', 'type': '', 'info': '' } license = '' asset_id = '' militime = int(time.time() * 1000) typestr = 'PROGRAM' info = [] program_id = None 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 if type == 'channel': if not test: info_url = '{api_url}/TRAY/SEARCH/LIVE?maxResults=1&filter_airingTime=now&filter_channelIds={channel}&orderBy=airingStartTime&sortOrder=desc'.format( api_url=profile_settings['api_url'], channel=channel) download = self.download(url=info_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 playdata for row in data['resultObj']['containers']: program_id = row['id'] info = data play_url = '{api_url}/CONTENT/VIDEOURL/LIVE/{channel}/{id}/?deviceId={device_key}&profile=G02&time={time}'.format( api_url=profile_settings['api_url'], channel=channel, id=id, device_key=profile_settings['devicekey'], time=militime) else: if type == 'program': typestr = "PROGRAM" else: typestr = "VOD" program_id = id program_url = '{api_url}/CONTENT/USERDATA/{type}/{id}'.format( api_url=profile_settings['api_url'], type=typestr, id=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 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 playdata for row in data['resultObj']['containers']: if check_key(row, 'entitlement') and check_key( row['entitlement'], 'assets'): for asset in row['entitlement']['assets']: if type == 'program': if check_key(asset, 'videoType') and check_key( asset, 'programType' ) and asset['videoType'] == 'SD_DASH_PR' and asset[ 'programType'] == 'CUTV': asset_id = asset['assetId'] break else: if check_key(asset, 'videoType') and check_key( asset, 'assetType' ) and asset['videoType'] == 'SD_DASH_PR' and asset[ 'assetType'] == 'MASTER': if check_key( asset, 'rights') and asset['rights'] == 'buy': gui.ok(message=_.NO_STREAM_AUTH, heading=_.PLAY_ERROR) return playdata asset_id = asset['assetId'] break if len(unicode(asset_id)) == 0: return playdata play_url = '{api_url}/CONTENT/VIDEOURL/{type}/{id}/{asset_id}/?deviceId={device_key}&profile=G02&time={time}'.format( api_url=profile_settings['api_url'], type=typestr, id=id, asset_id=asset_id, device_key=profile_settings['devicekey'], time=militime) if self._abortRequested or xbmc.Monitor().abortRequested(): return playdata if program_id and not test: info_url = '{api_url}/CONTENT/DETAIL/{type}/{id}'.format( api_url=profile_settings['api_url'], type=typestr, id=program_id) download = self.download(url=info_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 playdata info = data if self._abortRequested or xbmc.Monitor().waitForAbort(1): return playdata download = self.download(url=play_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'], 'token') or not check_key( data['resultObj'], 'src') or not check_key( data['resultObj']['src'], 'sources') or not check_key( data['resultObj']['src']['sources'], 'src'): return playdata if check_key( data['resultObj']['src']['sources'], 'contentProtection') and check_key( data['resultObj']['src']['sources']['contentProtection'], 'widevine') and check_key( data['resultObj']['src']['sources'] ['contentProtection']['widevine'], 'licenseAcquisitionURL'): license = data['resultObj']['src']['sources']['contentProtection'][ 'widevine']['licenseAcquisitionURL'] path = data['resultObj']['src']['sources']['src'] token = data['resultObj']['token'] 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, 'token': token, 'type': typestr, 'info': info } return playdata
def login(self): creds = get_credentials() username = creds['username'] password = creds['password'] query = "UPDATE `vars` SET `cookies`='' WHERE profile_id={profile_id}".format( profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) profile_settings = load_profile(profile_id=1) session_url = '{api_url}/USER/SESSIONS/'.format( api_url=profile_settings['api_url']) email_or_pin = settings.getBool(key='email_instead_of_customer') if email_or_pin: session_post_data = { "credentialsExtAuth": { 'credentials': { 'loginType': 'UsernamePassword', 'username': username, 'password': password, 'appId': 'KPN', }, 'remember': 'Y', 'deviceInfo': { 'deviceId': profile_settings['devicekey'], 'deviceIdType': 'DEVICEID', 'deviceType': 'PCTV', 'deviceVendor': profile_settings['browser_name'], 'deviceModel': profile_settings['browser_version'], 'deviceFirmVersion': profile_settings['os_name'], 'appVersion': profile_settings['os_version'] } }, } else: session_post_data = { "credentialsStdAuth": { 'username': username, 'password': password, 'remember': 'Y', 'deviceRegistrationData': { 'deviceId': profile_settings['devicekey'], 'accountDeviceIdType': 'DEVICEID', 'deviceType': 'PCTV', 'vendor': profile_settings['browser_name'], 'model': profile_settings['browser_version'], 'deviceFirmVersion': profile_settings['os_name'], 'appVersion': profile_settings['os_version'] } }, } download = self.download(url=session_url, type='post', headers=None, 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, 'resultCode') or not data['resultCode'] == 'OK': if not data: data = {} return {'data': data, 'result': False} return {'data': data, 'result': True}