def update_settings(): profile_settings = load_profile(profile_id=1) settingsJSON = load_file(file='settings.json', isJSON=True) base = settingsJSON['settings']['urls']['base'] if profile_settings['base_v3'] == 1: basethree = settingsJSON['settings']['urls']['alternativeAjaxBase'] else: basethree = base complete_base_url = '{base_url}/{country_code}/{language_code}'.format(base_url=basethree, country_code=settingsJSON['settings']['countryCode'], language_code=settingsJSON['settings']['languageCode']) try: client_id = settingsJSON['client_id'] except: client_id = CONST_DEFAULT_CLIENTID user_agent = profile_settings['user_agent'] if len(user_agent) == 0: user_agent = DEFAULT_USER_AGENT query = "UPDATE `vars` SET `base_url`='{base_url}', `client_id`='{client_id}', `devices_url`='{devices_url}', `search_url`='{search_url}', `session_url`='{session_url}', `channels_url`='{channels_url}', `token_url`='{token_url}', `widevine_url`='{widevine_url}', `listings_url`='{listings_url}', `mediaitems_url`='{mediaitems_url}', `mediagroupsfeeds_url`='{mediagroupsfeeds_url}', `watchlist_url`='{watchlist_url}', `user_agent`='{user_agent}' WHERE profile_id={profile_id}".format(base_url=complete_base_url + '/web', client_id=client_id, devices_url=settingsJSON['settings']['routes']['devices'].replace(base, basethree), search_url=settingsJSON['settings']['routes']['search'].replace(base, basethree), session_url=settingsJSON['settings']['routes']['session'].replace(base, basethree), channels_url=settingsJSON['settings']['routes']['channels'].replace(base, basethree), token_url='{complete_base_url}/web/license/token'.format(complete_base_url=complete_base_url), widevine_url='{complete_base_url}/web/license/eme'.format(complete_base_url=complete_base_url), listings_url=settingsJSON['settings']['routes']['listings'].replace(base, basethree), mediaitems_url=settingsJSON['settings']['routes']['mediaitems'].replace(base, basethree), mediagroupsfeeds_url=settingsJSON['settings']['routes']['mediagroupsfeeds'].replace(base, basethree), watchlist_url=settingsJSON['settings']['routes']['watchlist'].replace(base, basethree), user_agent=user_agent, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=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 user_agent = profile_settings['user_agent'] if len(user_agent) == 0: user_agent = DEFAULT_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}', `browser_name`='{browser_name}', `browser_version`='{browser_version}', `os_name`='{os_name}', `os_version`='{os_version}', `user_agent`='{user_agent}' WHERE profile_id={profile_id}".format( api_url=api_url, browser_name=browser_name, browser_version=browser_version, os_name=os_name, os_version=os_version, user_agent=user_agent, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True)
def api_get_watchlist_id(): if not api_get_session(): return None profile_settings = load_profile(profile_id=1) watchlist_url = 'https://prod.spark.ziggogo.tv/nld/web/watchlist-service/v1/watchlists/profile/{profile_id}?language=nl&maxResults=1&order=DESC&sharedProfile=true&sort=added'.format( profile_id=profile_settings['ziggo_profile_id']) download = api_download(url=watchlist_url, type='get', headers=api_get_headers(), data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'watchlistId'): return False query = "UPDATE `vars` SET `watchlist_id`='{watchlist_id}' WHERE profile_id={profile_id}".format( watchlist_id=data['watchlistId'], profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return True
def api_get_session(force=0): force = int(force) profile_settings = load_profile(profile_id=1) if not force ==1 and 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 elif force == 1 and not profile_settings['last_login_success'] == 1: return False token_url_base = '{base_url}/v6/favorites/items'.format(base_url=CONST_API_URL) token_parameter = 'oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&oauth_verifier=' + unicode(profile_settings['resource_verifier']) + '&oauth_token={token}&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}&count=1&expand=false&expandlist=false&maxResults=1&offset=0' url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter) download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=False) data = download['data'] code = download['code'] if not code or not code == 200: login_result = api_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 api_get_session(force=0): force = int(force) profile_settings = load_profile(profile_id=1) if not force ==1 and 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 elif force == 1 and not profile_settings['last_login_success'] == 1: return False heartbeat_url = '{base_url}/VSP/V3/OnLineHeartbeat?from=inMSAAccess'.format(base_url=CONST_BASE_URL) headers = {'Content-Type': 'application/json', 'X_CSRFToken': profile_settings['csrf_token']} session_post_data = {} download = api_download(url=heartbeat_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000': login_result = api_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 _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 update_settings(): profile_settings = load_profile(profile_id=1) user_agent = profile_settings['user_agent'] if len(user_agent) == 0: user_agent = DEFAULT_USER_AGENT query = "UPDATE `vars` SET `user_agent`='{user_agent}' WHERE profile_id={profile_id}".format( user_agent=user_agent, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True)
def api_get_session(force=0): force = int(force) profile_settings = load_profile(profile_id=1) if not force == 1 and 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 elif force == 1 and not profile_settings['last_login_success'] == 1: return False capi_url = '{base_url}/m7be2iphone/capi.aspx?z=pg&a=cds&lng=nl'.format( base_url=CONST_BASE_URL) download = api_download(url=capi_url, type='get', headers=None, data=None, json_data=False, return_json=False, allow_redirects=False) data = download['data'] code = download['code'] if not code or not code == 200: login_result = api_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 api_get_session(force=0): force = int(force) profile_settings = load_profile(profile_id=1) if not force == 1 and 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 elif force == 1 and not profile_settings['last_login_success'] == 1: return False devices_url = '{api_url}/USER/DEVICES'.format( api_url=profile_settings['api_url']) download = api_download(url=devices_url, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'resultCode') or not data['resultCode'] == 'OK': login_result = api_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 startup(): 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 system, arch = get_system_arch() proxyserver_port = find_free_port() 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) hourly(type=0) daily() change_icon() update_prefs() hourly(type=2) service_timer('startup')
def update_settings(): profile_settings = load_profile(profile_id=1) user_agent = profile_settings['user_agent'] if len(user_agent) == 0: user_agent = DEFAULT_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}', `user_agent`='{user_agent}' WHERE profile_id={profile_id}".format( browser_name=browser_name, browser_version=browser_version, os_name=os_name, os_version=os_version, user_agent=user_agent, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True)
def save_cookies(self): if not self._cookies_key: raise Exception('A cookies key needs to be set to save cookies') query = "UPDATE `vars` SET `cookies`='{cookies}' WHERE profile_id={profile_id}".format(cookies=json.dumps(self.cookies.get_dict()), profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True)
def api_test_channels(tested=False, channel=None): profile_settings = load_profile(profile_id=1) if channel: channel = unicode(channel) try: if not profile_settings['last_login_success'] == 1 or not settings.getBool(key='run_tests') or not api_get_session(): return 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=1,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "SELECT * FROM `channels`" channels = query_epg(query=query, return_result=True, return_insert=False, commit=False) results = load_tests(profile_id=1) count = 0 first = True last_tested_found = False test_run = False user_agent = profile_settings['user_agent'] if not results: results = {} for row in channels: if count == 5 or (count == 1 and tested): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count id = unicode(row['id']) if len(id) > 0: if channel: if not id == channel: continue elif tested: if unicode(profile_settings['last_tested']) == id: last_tested_found = True continue elif last_tested_found: pass else: continue if check_key(results, id) and not tested and not first: continue livebandwidth = 0 replaybandwidth = 0 live = 0 replay = 0 epg = 0 guide = 0 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='channel', channel=id, id=None, test=True) if first and not profile_settings['last_login_success']: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if len(playdata['path']) > 0: CDMHEADERS = { 'User-Agent': user_agent, 'X_CSRFToken': profile_settings['csrf_token'], 'Cookie': playdata['license']['cookie'], } if check_key(playdata, 'license') and check_key(playdata['license'], 'triggers') and check_key(playdata['license']['triggers'][0], 'licenseURL'): if check_key(playdata['license']['triggers'][0], 'customData'): CDMHEADERS['AcquireLicense.CustomData'] = playdata['license']['triggers'][0]['customData'] CDMHEADERS['CADeviceType'] = 'Widevine OTT client' session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: livebandwidth = find_highest_bandwidth(xml=resp.text) live = 1 if check_key(results, id) and first and not tested: first = False if live == 1: continue else: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 first = False counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 militime = int(int(time.time() - 86400) * 1000) session_post_data = { 'needChannel': '0', 'queryChannel': { 'channelIDs': [ id, ], 'isReturnAllMedia': '1', }, 'queryPlaybill': { 'count': '1', 'endTime': militime, 'isFillProgram': '1', 'offset': '0', 'startTime': militime, 'type': '0', } } headers = {'Content-Type': 'application/json', 'X_CSRFToken': profile_settings['csrf_token']} channel_url = '{base_url}/VSP/V3/QueryPlaybillListStcProps?SID=queryPlaybillListStcProps3&DEVICE=PC&DID={deviceID}&from=throughMSAAccess'.format(base_url=CONST_BASE_URL, deviceID=profile_settings['devicekey']) download = api_download(url=channel_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if code and code == 200 and data and check_key(data, 'channelPlaybills') and check_key(data['channelPlaybills'][0], 'playbillLites') and check_key(data['channelPlaybills'][0]['playbillLites'][0], 'ID'): profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='program', channel=id, id=data['channelPlaybills'][0]['playbillLites'][0]['ID'], test=True) if len(playdata['path']) > 0: CDMHEADERS = { 'User-Agent': user_agent, 'X_CSRFToken': profile_settings['csrf_token'], 'Cookie': playdata['license']['cookie'], } if check_key(playdata, 'license') and check_key(playdata['license'], 'triggers') and check_key(playdata['license']['triggers'][0], 'licenseURL'): if check_key(playdata['license']['triggers'][0], 'customData'): CDMHEADERS['AcquireLicense.CustomData'] = playdata['license']['triggers'][0]['customData'] CDMHEADERS['CADeviceType'] = 'Widevine OTT client' session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: replaybandwidth = find_highest_bandwidth(xml=resp.text) replay = 1 query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format(channel=id) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if len(data) > 0: guide = 1 if live == 1: epg = 1 if not xbmc.Monitor().abortRequested(): query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format(last_tested=id,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format(profile_id=1, id=id, live=live, livebandwidth=livebandwidth, replay=replay, replaybandwidth=replaybandwidth, epg=epg, guide=guide) query_settings(query=query, return_result=False, return_insert=False, commit=True) test_run = True counter = 0 while not xbmc.Monitor().abortRequested() and counter < 15: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 count += 1 except: if test_run: update_prefs() count = 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count
def api_login(): creds = get_credentials() username = creds['username'] password = creds['password'] query = "UPDATE `vars` SET `csrf_token`='', `cookies`='', `user_filter`='' 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) 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) login_url = '{base_url}/VSP/V3/Authenticate?from=throughMSAAccess'.format(base_url=CONST_BASE_URL) session_post_data = { "authenticateBasic": { 'VUID': '6_7_{devicekey}'.format(devicekey=profile_settings['devicekey']), 'clientPasswd': password, 'isSupportWebpImgFormat': '0', 'lang': 'nl', 'needPosterTypes': [ '1', '2', '3', '4', '5', '6', '7', ], 'timeZone': 'Europe/Amsterdam', 'userID': username, 'userType': '0', }, 'authenticateDevice': { 'CADeviceInfos': [ { 'CADeviceID': profile_settings['devicekey'], 'CADeviceType': '7', }, ], 'deviceModel': '3103_PCClient', 'physicalDeviceID': profile_settings['devicekey'], 'terminalID': profile_settings['devicekey'], }, 'authenticateTolerant': { 'areaCode': '', 'bossID': '', 'subnetID': '', 'templateName': '', 'userGroup': '', }, } download = api_download(url=login_url, type='post', headers=None, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'csrfToken'): if check_key(data, 'result') and check_key(data['result'], 'retCode') and data['result']['retCode'] == "157022007" and check_key(data, 'devices'): for row in data['devices']: if not check_key(row, 'name') and check_key(row, 'deviceModel') and check_key(row, 'status') and check_key(row, 'onlineState') and check_key(row, 'physicalDeviceID') and row['deviceModel'] == '3103_PCClient' and row['status'] == '1' and row['onlineState'] == '0': query = "UPDATE `vars` SET `devicekey`='{devicekey}' WHERE profile_id={profile_id}".format(devicekey=row['physicalDeviceID'], profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return api_login() return { 'code': code, 'data': data, 'result': False } query = "UPDATE `vars` SET `csrf_token`='{csrf_token}', `user_filter`='{user_filter}' WHERE profile_id={profile_id}".format(csrf_token=data['csrfToken'], user_filter=data['userFilter'], profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return { 'code': code, 'data': data, 'result': True }
def api_play_url(type, channel=None, id=None, video_data=None, test=False, from_beginning=0, pvr=0): playdata = {'path': '', 'license': '', 'info': '', 'alt_path': '', 'alt_license': ''} if not api_get_session(): return playdata alt_path = '' alt_license = '' from_beginning = int(from_beginning) pvr = int(pvr) profile_settings = load_profile(profile_id=1) headers = {'Content-Type': 'application/json', 'X_CSRFToken': profile_settings['csrf_token']} mediaID = None info = {} if not type or not len(unicode(type)) > 0: return playdata if not test: counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: profile_settings = load_profile(profile_id=1) if profile_settings['test_running'] == 0: break counter += 1 query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format(last_playing=int(time.time()),profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if xbmc.Monitor().waitForAbort(1): break if xbmc.Monitor().abortRequested(): return playdata militime = int(time.time() * 1000) if not type == 'vod': if video_data: try: video_data = json.loads(video_data) mediaID = int(video_data['media_id']) + 1 except: pass query = "SELECT assetid FROM `channels` WHERE id='{channel}'".format(channel=channel) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if data: for row in data: mediaID = row['assetid'] if type == 'channel' and channel: if test: pass elif not pvr == 1 or settings.getBool(key='ask_start_from_beginning') or from_beginning == 1: session_post_data = { 'needChannel': '0', 'queryChannel': { 'channelIDs': [ channel, ], 'isReturnAllMedia': '1', }, 'queryPlaybill': { 'count': '1', 'endTime': militime, 'isFillProgram': '1', 'offset': '0', 'startTime': militime, 'type': '0', } } channel_url = '{base_url}/VSP/V3/QueryPlaybillListStcProps?SID=queryPlaybillListStcProps3&DEVICE=PC&DID={deviceID}&from=throughMSAAccess'.format(base_url=CONST_BASE_URL, deviceID=profile_settings['devicekey']) download = api_download(url=channel_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'channelPlaybills') or not check_key(data['channelPlaybills'][0], 'playbillLites') or not check_key(data['channelPlaybills'][0]['playbillLites'][0], 'ID'): return playdata id = data['channelPlaybills'][0]['playbillLites'][0]['ID'] session_post_data = { 'playbillID': id, 'channelNamespace': '310303', 'isReturnAllMedia': '1', } program_url = '{base_url}/VSP/V3/QueryPlaybill?from=throughMSAAccess'.format(base_url=CONST_BASE_URL) download = api_download(url=program_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playbillDetail'): info = {} else: info = data['playbillDetail'] if settings.getBool(key='ask_start_from_beginning') or from_beginning == 1: session_post_data = { "businessType": "PLTV", "channelID": channel, "checkLock": { "checkType": "0", }, "isHTTPS": "1", "isReturnProduct": "1", "mediaID": mediaID, 'playbillID': id, } play_url_path = '{base_url}/VSP/V3/PlayChannel?from=throughMSAAccess'.format(base_url=CONST_BASE_URL) download = api_download(url=play_url_path, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playURL'): pass else: alt_path = data['playURL'] if check_key(data, 'authorizeResult'): profile_settings = load_profile(profile_id=1) data['authorizeResult']['cookie'] = api_getCookies(profile_settings['cookies'], '') alt_license = data['authorizeResult'] session_post_data = { "businessType": "BTV", "channelID": channel, "checkLock": { "checkType": "0", }, "isHTTPS": "1", "isReturnProduct": "1", "mediaID": mediaID, } elif type == 'program' and id: if not test and not pvr == 1: session_post_data = { 'playbillID': id, 'channelNamespace': '310303', 'isReturnAllMedia': '1', } program_url = '{base_url}/VSP/V3/QueryPlaybill?from=throughMSAAccess'.format(base_url=CONST_BASE_URL) download = api_download(url=program_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playbillDetail'): info = {} else: info = data['playbillDetail'] session_post_data = { "businessType": "CUTV", "channelID": channel, "checkLock": { "checkType": "0", }, "isHTTPS": "1", "isReturnProduct": "1", "mediaID": mediaID, "playbillID": id, } elif type == 'vod' and id: session_post_data = { 'VODID': id } program_url = '{base_url}/VSP/V3/QueryVOD?from=throughMSAAccess'.format(base_url=CONST_BASE_URL) download = api_download(url=program_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'VODDetail') or not check_key(data['VODDetail'], 'VODType'): return playdata info = data['VODDetail'] session_post_data = { "VODID": id, "checkLock": { "checkType": "0", }, "isHTTPS": "1", "isReturnProduct": "1", "mediaID": '', } if not check_key(info, 'mediaFiles') or not check_key(info['mediaFiles'][0], 'ID'): return playdata if check_key(info, 'series') and check_key(info['series'][0], 'VODID'): session_post_data["seriesID"] = info['series'][0]['VODID'] session_post_data["mediaID"] = info['mediaFiles'][0]['ID'] if not len(unicode(session_post_data["mediaID"])) > 0: return playdata if type == 'vod': play_url_path = '{base_url}/VSP/V3/PlayVOD?from=throughMSAAccess'.format(base_url=CONST_BASE_URL) else: play_url_path = '{base_url}/VSP/V3/PlayChannel?from=throughMSAAccess'.format(base_url=CONST_BASE_URL) if xbmc.Monitor().abortRequested(): return playdata download = api_download(url=play_url_path, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'result') or not check_key(data['result'], 'retCode') or not data['result']['retCode'] == '000000000' or not check_key(data, 'playURL'): return playdata path = data['playURL'] if check_key(data, 'authorizeResult'): profile_settings = load_profile(profile_id=1) data['authorizeResult']['cookie'] = api_getCookies(profile_settings['cookies'], '') license = data['authorizeResult'] playdata = {'path': path, 'license': license, 'info': info, 'alt_path': alt_path, 'alt_license': alt_license} return playdata
def api_get_play_token(locator=None, path=None, force=0): if not api_get_session(): return None force = int(force) profile_settings = load_profile(profile_id=1) if profile_settings['drm_token_age'] < int(time.time() - 50) and ( profile_settings['tokenrun'] == 0 or profile_settings['tokenruntime'] < int(time.time() - 30)): force = 1 if locator != profile_settings['drm_locator'] or profile_settings[ 'drm_token_age'] < int(time.time() - 90) or force == 1: query = "UPDATE `vars` SET `tokenrun`=1, `tokenruntime`='{tokenruntime}' WHERE profile_id={profile_id}".format( tokenruntime=int(time.time()), profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if profile_settings['base_v3'] == 1 and 'sdash' in path: jsondata = { "contentLocator": locator, "drmScheme": "sdash:BR-AVC-DASH" } else: jsondata = {"contentLocator": locator} download = api_download(url=profile_settings['token_url'], type='post', headers=api_get_headers(), data=jsondata, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'token'): query = "UPDATE `vars` SET `tokenrun`=0 WHERE profile_id={profile_id}".format( profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return None query = "UPDATE `vars` SET `tokenrun`=0, `drm_token`='{drm_token}', `drm_token_age`='{drm_token_age}', `drm_locator`='{drm_locator}' WHERE profile_id={profile_id}".format( drm_token=data['token'], drm_token_age=int(time.time()), drm_locator=locator, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return data['token'] else: return profile_settings['drm_token']
def api_play_url(type, channel=None, id=None, video_data=None, test=False, from_beginning=0, pvr=0): playdata = { 'path': '', 'license': '', 'token': '', 'locator': '', 'type': '', 'alt_path': '', 'alt_license': '', 'alt_locator': '' } if not api_get_session(): return playdata from_beginning = int(from_beginning) pvr = int(pvr) profile_settings = load_profile(profile_id=1) if type == "channel": id = channel alt_path = '' alt_license = '' alt_locator = '' info = {} base_listing_url = profile_settings['listings_url'] urldata = None urldata2 = None path = None locator = None if not type or not len(unicode(type)) > 0 or not id or not len( unicode(id)) > 0: return playdata if not test: counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: profile_settings = load_profile(profile_id=1) if profile_settings['test_running'] == 0: break counter += 1 query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format( last_playing=int(time.time()), profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if xbmc.Monitor().waitForAbort(1): break if xbmc.Monitor().abortRequested(): return playdata if type == 'channel': query = "SELECT assetid FROM `channels` WHERE id='{channel}'".format( channel=id) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if data: for row in data: split = row['assetid'].rsplit('&%%&', 1) if len(split) == 2: urldata = {'play_url': split[0], 'locator': split[1]} else: return playdata listing_url = '{listings_url}?byEndTime={time}~&byStationId={channel}&range=1-1&sort=startTime'.format( listings_url=base_listing_url, time=int(time.time() * 1000), channel=id) download = api_download(url=listing_url, type='get', headers=api_get_headers(), data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if code and code == 200 and data and check_key(data, 'listings'): for row in data['listings']: if check_key(row, 'program'): info = row['program'] elif type == 'program': listings_url = "{listings_url}/{id}".format( listings_url=base_listing_url, id=id) download = api_download(url=listings_url, type='get', headers=api_get_headers(), data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'program'): return playdata info = data['program'] elif type == 'vod': mediaitems_url = '{mediaitems_url}/{id}'.format( mediaitems_url=profile_settings['mediaitems_url'], id=id) download = api_download(url=mediaitems_url, type='get', headers=api_get_headers(), data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data: return playdata info = data if check_key(info, 'videoStreams'): urldata2 = get_play_url(content=info['videoStreams']) if not type == 'channel' and ( not urldata2 or not check_key(urldata2, 'play_url') or not check_key(urldata2, 'locator') or urldata2['play_url'] == 'http://Playout/using/Session/Service' ) and profile_settings['base_v3'] == 1: urldata2 = {} if type == 'program': playout_str = 'replay' elif type == 'vod': playout_str = 'vod' else: return playdata playout_url = '{base_url}/playout/{playout_str}/{id}?abrType=BR-AVC-DASH'.format( base_url=profile_settings['base_url'], playout_str=playout_str, id=id) download = api_download(url=playout_url, type='get', headers=api_get_headers(), data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'url') or not check_key(data, 'contentLocator'): return playdata urldata2['play_url'] = data['url'] urldata2['locator'] = data['contentLocator'] if urldata and urldata2 and check_key(urldata, 'play_url') and check_key( urldata, 'locator') and check_key( urldata2, 'play_url') and check_key(urldata2, 'locator'): path = urldata['play_url'] locator = urldata['locator'] alt_path = urldata2['play_url'] alt_locator = urldata2['locator'] else: if urldata and check_key(urldata, 'play_url') and check_key( urldata, 'locator'): path = urldata['play_url'] locator = urldata['locator'] elif urldata2 and check_key(urldata2, 'play_url') and check_key( urldata2, 'locator'): path = urldata2['play_url'] locator = urldata2['locator'] if not locator or not len(unicode(locator)) > 0: return playdata license = profile_settings['widevine_url'] alt_license = profile_settings['widevine_url'] if xbmc.Monitor().abortRequested(): return playdata token = api_get_play_token(locator=locator, path=path, force=1) if not token or not len(unicode(token)) > 0: if not test: gui.ok(message=_.NO_STREAM_AUTH, heading=_.PLAY_ERROR) return playdata if not test: token = 'WIDEVINETOKEN' token_regex = re.search(r"(?<=;vxttoken=)(.*?)(?=/)", path) if token_regex and token_regex.group(1) and len(token_regex.group(1)) > 0: path = path.replace(token_regex.group(1), token) else: if 'sdash/' in path: spliturl = path.split('sdash/', 1) if len(spliturl) == 2: if profile_settings['base_v3'] == 1: path = '{urlpart1}sdash;vxttoken={token}/{urlpart2}'.format( urlpart1=spliturl[0], token=token, urlpart2=spliturl[1]) else: path = '{urlpart1}sdash;vxttoken={token}/{urlpart2}?device=Orion-Replay-DASH'.format( urlpart1=spliturl[0], token=token, urlpart2=spliturl[1]) else: spliturl = path.rsplit('/', 1) if len(spliturl) == 2: path = '{urlpart1};vxttoken={token}/{urlpart2}'.format( urlpart1=spliturl[0], token=token, urlpart2=spliturl[1]) playdata = { 'path': path, 'license': license, 'token': token, 'locator': locator, 'info': info, 'type': type, 'alt_path': alt_path, 'alt_license': alt_license, 'alt_locator': alt_license } return playdata
def api_login(): creds = get_credentials() username = creds['username'] password = creds['password'] query = "UPDATE `vars` SET `access_token`='', `household_id`='', `ziggo_profile_id`='' 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) user_agent = profile_settings['user_agent'] HEADERS = { 'User-Agent': user_agent, 'X-Client-Id': profile_settings['client_id'] + "||" + user_agent, } download = api_download(url=profile_settings['session_url'], type='post', headers=HEADERS, data={ "username": username, "password": password }, json_data=True, return_json=True) data = download['data'] code = download['code'] if code and data and check_key( data, 'reason') and data['reason'] == 'wrong backoffice': if profile_settings['base_v3'] == 0: query = "UPDATE `vars` SET `base_v3`=1 WHERE profile_id={profile_id}".format( profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) else: query = "UPDATE `vars` SET `base_v3`=0 WHERE profile_id={profile_id}".format( profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) update_settings() download_files() profile_settings = load_profile(profile_id=1) download = api_download(url=profile_settings['session_url'], type='post', headers=HEADERS, data={ "username": username, "password": password }, json_data=True, return_json=True) if not code or not data or not check_key(data, 'oespToken'): if not code: code = {} if not data: data = {} return {'code': code, 'data': data, 'result': False} ziggo_profile_id = '' household_id = '' if profile_settings['base_v3'] == 1: ziggo_profile_id = data['customer']['sharedProfileId'] household_id = data['customer']['householdId'] query = "UPDATE `vars` SET `access_token`='{access_token}', `ziggo_profile_id`='{ziggo_profile_id}', `household_id`='{household_id}' WHERE profile_id={profile_id}".format( access_token=data['oespToken'], ziggo_profile_id=ziggo_profile_id, household_id=household_id, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if profile_settings['base_v3'] == 1: if len(unicode(profile_settings['watchlist_id'])) == 0: api_get_watchlist_id() return {'code': code, 'data': data, 'result': True}
def api_test_channels(tested=False, channel=None): profile_settings = load_profile(profile_id=1) if channel: channel = unicode(channel) try: if not profile_settings['last_login_success'] == 1 or not settings.getBool(key='run_tests') or not api_get_session(): return 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=1,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "SELECT * FROM `channels`" channels = query_epg(query=query, return_result=True, return_insert=False, commit=False) results = load_tests(profile_id=1) count = 0 first = True last_tested_found = False test_run = False user_agent = profile_settings['user_agent'] if not results: results = {} for row in channels: if count == 5 or (count == 1 and tested): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count id = unicode(row['id']) if len(id) > 0: if channel: if not id == channel: continue elif tested: if unicode(profile_settings['last_tested']) == id: last_tested_found = True continue elif last_tested_found: pass else: continue if check_key(results, id) and not tested and not first: continue livebandwidth = 0 replaybandwidth = 0 live = 0 replay = 0 epg = 0 guide = 0 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='channel', channel=id, id=None, test=True) if first and not profile_settings['last_login_success']: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if len(playdata['path']) > 0: CDMHEADERS = {} if check_key(playdata, 'license') and check_key(playdata['license'], 'drmConfig') and check_key(playdata['license']['drmConfig'], 'widevine'): if 'nlznl.solocoo.tv' in playdata['license']['drmConfig']['widevine']['drmServerUrl']: if xbmc.Monitor().waitForAbort(1): return 5 if check_key(playdata['license']['drmConfig']['widevine'], 'customHeaders'): for row in playdata['license']['drmConfig']['widevine']['customHeaders']: CDMHEADERS[row] = playdata['license']['drmConfig']['widevine']['customHeaders'][row] session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: livebandwidth = find_highest_bandwidth(xml=resp.text) live = 1 if check_key(results, id) and first and not tested: first = False if live == 1: continue else: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 first = False counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 yesterday = datetime.datetime.now() - datetime.timedelta(1) fromtime = datetime.datetime.strftime(yesterday, "%Y-%m-%dT%H%M%S") channel_url = '{base_url}/v6/epg/locations/{friendly}/live/1?fromDate={date}'.format(base_url=CONST_API_URL, friendly=channeldata['channel_friendly'], date=fromtime) download = api_download(url=channel_url, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if code and code == 200 and data: for row in data: if check_key(row, 'Channel') and check_key(row, 'Locations'): for row2 in row['Locations']: program_id = row2['LocationId'] if program_id: profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='program', channel=id, id=program_id, test=True) if len(playdata['path']) > 0: CDMHEADERS = {} if check_key(playdata, 'license') and check_key(playdata['license'], 'drmConfig') and check_key(playdata['license']['drmConfig'], 'widevine'): if 'nlznl.solocoo.tv' in playdata['license']['drmConfig']['widevine']['drmServerUrl']: if xbmc.Monitor().waitForAbort(1): return 5 if check_key(playdata['license']['drmConfig']['widevine'], 'customHeaders'): for row in playdata['license']['drmConfig']['widevine']['customHeaders']: CDMHEADERS[row] = playdata['license']['drmConfig']['widevine']['customHeaders'][row] session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: replaybandwidth = find_highest_bandwidth(xml=resp.text) replay = 1 query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format(channel=id) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if len(data) > 0: guide = 1 if live == 1: epg = 1 if not xbmc.Monitor().abortRequested(): query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format(last_tested=id,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format(profile_id=1, id=id, live=live, livebandwidth=livebandwidth, replay=replay, replaybandwidth=replaybandwidth, epg=epg, guide=guide) query_settings(query=query, return_result=False, return_insert=False, commit=True) test_run = True counter = 0 while not xbmc.Monitor().abortRequested() and counter < 15: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 count += 1 except: if test_run: update_prefs() count = 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format(test_running=0,profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count
def api_login(force=False): creds = get_credentials() username = creds['username'] password = creds['password'] use_old = False profile_settings = load_profile(profile_id=1) if not check_key(profile_settings, 'base_resource_key') or not check_key(profile_settings, 'base_resource_secret') or len(profile_settings['base_resource_key']) == 0 or len(profile_settings['base_resource_secret']) == 0 or force == True: query = "UPDATE `vars` SET `cookies`='', `resource_key`='', `resource_secret`='', `resource_verifier`='' WHERE profile_id={profile_id}".format(profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) request_token_url = '{base_url}/OAuth/GetRequestToken'.format(base_url=CONST_BASE_URL) oauth = OAuth1('key', client_secret='secret', callback_uri='null') download = api_download(url=request_token_url, type='post', headers=None, data=None, json_data=False, return_json=False, auth=oauth) data = download['data'] code = download['code'] credentials = parse_qs(data) base_resource_owner_key = credentials.get('oauth_token')[0] base_resource_owner_secret = credentials.get('oauth_token_secret')[0] login_url = '{base_url}/account/applogin'.format(base_url=CONST_BASE_URL) session_post_data = { "username": username, "password": password, } headers = { 'content-type': 'application/x-www-form-urlencoded' } download = api_download(url=login_url, type='post', headers=headers, data=session_post_data, json_data=False, return_json=False) data = download['data'] code = download['code'] if code != 200 and code != 302: return { 'code': code, 'data': data, 'result': False } authorization_url = "{base_url}/OAuth/Authorize?oauth_token={token}".format(base_url=CONST_BASE_URL, token=base_resource_owner_key) download = api_download(url=authorization_url, type='get', headers=None, data=None, json_data=False, return_json=False, allow_redirects=False) data = download['data'] code = download['code'] regex = r"oauth_verifier=([a-zA-Z0-9]+)" matches = re.finditer(regex, data, re.MULTILINE) resource_verifier = '' try: for match in matches: resource_verifier = match.group(1) except: pass if len(resource_verifier) == 0: return { 'code': code, 'data': data, 'result': False } else: use_old = True base_resource_owner_key = profile_settings['base_resource_key'] base_resource_owner_secret = profile_settings['base_resource_secret'] resource_verifier = profile_settings['resource_key'] access_token_url = '{base_url}/OAuth/GetAccessToken'.format(base_url=CONST_BASE_URL) oauth = OAuth1('key', client_secret='secret', callback_uri='null', resource_owner_key=base_resource_owner_key, resource_owner_secret=base_resource_owner_secret, verifier=resource_verifier) download = api_download(url=access_token_url, type='post', headers=None, data=None, json_data=False, return_json=False, auth=oauth) data = download['data'] code = download['code'] credentials = parse_qs(data) try: resource_owner_key = credentials.get('oauth_token')[0] resource_owner_secret = credentials.get('oauth_token_secret')[0] except: if use_old == True: return api_login(force=True) return { 'code': code, 'data': data, 'result': False } query = "UPDATE `vars` SET `base_resource_key`='{base_resource_key}', `base_resource_secret`='{base_resource_secret}', `resource_key`='{resource_key}', `resource_secret`='{resource_secret}', `resource_verifier`='{resource_verifier}' WHERE profile_id={profile_id}".format(base_resource_key=base_resource_owner_key, base_resource_secret=base_resource_owner_secret, resource_key=resource_owner_key, resource_secret=resource_owner_secret, resource_verifier=resource_verifier, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return { 'code': code, 'data': data, 'result': True }
def api_test_channels(tested=False, channel=None): profile_settings = load_profile(profile_id=1) if channel: channel = unicode(channel) try: if not profile_settings[ 'last_login_success'] == 1 or not settings.getBool( key='run_tests') or not api_get_session(): return 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=1, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "SELECT * FROM `channels`" channels = query_epg(query=query, return_result=True, return_insert=False, commit=False) results = load_tests(profile_id=1) count = 0 first = True last_tested_found = False test_run = False user_agent = profile_settings['user_agent'] listing_url = profile_settings['listings_url'] if not results: results = {} for row in channels: if count == 5 or (count == 1 and tested): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count id = unicode(row['id']) if len(id) > 0: if channel: if not id == channel: continue elif tested: if unicode(profile_settings['last_tested']) == id: last_tested_found = True continue elif last_tested_found: pass else: continue if check_key(results, id) and not tested and not first: continue livebandwidth = 0 replaybandwidth = 0 live = 0 replay = 0 epg = 0 guide = 0 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='channel', id=row['id'], test=True) if first and not profile_settings['last_login_success']: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if len(playdata['path']) > 0: CDMHEADERS = { 'User-Agent': user_agent, 'X-Client-Id': profile_settings['client_id'] + '||' + user_agent, 'X-OESP-Token': profile_settings['access_token'], 'X-OESP-Username': profile_settings['username'], 'X-OESP-License-Token': profile_settings['drm_token'], 'X-OESP-DRM-SchemeIdUri': 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', 'X-OESP-Content-Locator': playdata['locator'], } session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: livebandwidth = find_highest_bandwidth(xml=resp.text) live = 1 if check_key(results, id) and first and not tested: first = False if live == 1: continue else: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 first = False counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 listing_url = '{listings_url}?byEndTime={time}~&byStationId={channel}&range=1-1&sort=startTime'.format( listings_url=listing_url, time=int(int(time.time() - 86400) * 1000), channel=id) download = api_download(url=listing_url, type='get', headers=api_get_headers(), data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] program_id = None if code and code == 200 and data and check_key( data, 'listings'): for row in data['listings']: program_id = row['id'] if program_id: profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='program', id=program_id, test=True) if len(playdata['path']) > 0: CDMHEADERS = { 'User-Agent': user_agent, 'X-Client-Id': profile_settings['client_id'] + '||' + user_agent, 'X-OESP-Token': profile_settings['access_token'], 'X-OESP-Username': profile_settings['username'], 'X-OESP-License-Token': profile_settings['drm_token'], 'X-OESP-DRM-SchemeIdUri': 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', 'X-OESP-Content-Locator': playdata['locator'], } session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: replaybandwidth = find_highest_bandwidth( xml=resp.text) replay = 1 query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format( channel=id) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if len(data) > 0: guide = 1 if live == 1: epg = 1 if not xbmc.Monitor().abortRequested(): query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format( last_tested=id, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format( profile_id=1, id=id, live=live, livebandwidth=livebandwidth, replay=replay, replaybandwidth=replaybandwidth, epg=epg, guide=guide) query_settings(query=query, return_result=False, return_insert=False, commit=True) test_run = True counter = 0 while not xbmc.Monitor().abortRequested() and counter < 15: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 count += 1 except: if test_run: update_prefs() count = 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count
def api_login(): 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) if len(profile_settings['devicekey']) == 0: devicekey = ''.join( random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(64)) 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) 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 = api_download(url=session_url, type='post', headers=None, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'resultCode') or not data['resultCode'] == 'OK': return {'code': code, 'data': data, 'result': False} return {'code': code, 'data': data, 'result': True}
def api_play_url(type, channel=None, id=None, video_data=None, test=False, from_beginning=0, pvr=0): playdata = { 'path': '', 'license': '', 'info': '', 'alt_path': '', 'alt_license': '' } if not api_get_session(): return playdata alt_path = '' alt_license = '' from_beginning = int(from_beginning) pvr = int(pvr) profile_settings = load_profile(profile_id=1) info = [] headers = {'Authorization': 'Bearer ' + profile_settings['session_token']} if not test: counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: profile_settings = load_profile(profile_id=1) if profile_settings['test_running'] == 0: break counter += 1 query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format( last_playing=int(time.time()), profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if xbmc.Monitor().waitForAbort(1): break if xbmc.Monitor().abortRequested(): return playdata if type == 'channel': info_url = '{api_url}/assets/{channel}'.format( api_url=CONST_DEFAULT_API, channel=channel) else: info_url = '{api_url}/assets/{id}'.format(api_url=CONST_DEFAULT_API, id=id) play_url = info_url + '/play' playfrombeginning = False if test: pass elif not pvr == 1 or settings.getBool( key='ask_start_from_beginning') or from_beginning == 1: download = api_download(url=info_url, type='get', headers=headers, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'id'): return playdata info = data session_post_data = { "player": { "name": "Bitmovin", "version": "8.22.0", "capabilities": { "mediaTypes": ["DASH", "HLS", "MSSS", "Unspecified"], "drmSystems": ["Widevine"], }, "drmSystems": ["Widevine"], }, } if type == 'channel' and check_key(data, 'params') and check_key( data['params'], 'now') and check_key(data['params']['now'], 'id'): play_url2 = '{api_url}/assets/{id}/play'.format( api_url=CONST_DEFAULT_API, id=data['params']['now']['id']) info = data['params']['now'] download = api_download(url=play_url2, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if code and code == 200 and data and check_key(data, 'url'): if check_key(data, 'drm') and check_key( data['drm'], 'licenseUrl'): alt_license = data['drm']['licenseUrl'] alt_path = data['url'] if xbmc.Monitor().abortRequested(): return playdata if not playfrombeginning: download = api_download(url=play_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'url'): return playdata if check_key(data, 'drm') and check_key(data['drm'], 'licenseUrl'): license = data['drm']['licenseUrl'] path = data['url'] playdata = { 'path': path, 'license': license, 'info': info, 'alt_path': alt_path, 'alt_license': alt_license } return playdata
def api_login(): creds = get_credentials() username = creds['username'] password = creds['password'] query = "UPDATE `vars` SET `cookies`='', `session_token`='' 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) 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) oauth = '' auth_url = '{login_url}/authenticate?redirect_uri=https%3A%2F%2Flivetv.canaldigitaal.nl%2Fauth.aspx&state={state}&response_type=code&scope=TVE&client_id=StreamGroup'.format( login_url=CONST_LOGIN_URL, state=int(time.time())) download = api_download(url=auth_url, type='get', headers=None, data=None, json_data=False, return_json=False, allow_redirects=False) data = download['data'] code = download['code'] if not code or not code == 200 or not data: return {'code': code, 'data': data, 'result': False} headers = CONST_LOGIN_HEADERS headers.update({'Referer': auth_url}) session_post_data = { "Password": password, "Username": username, } download = api_download(url=CONST_LOGIN_URL, type='post', headers=headers, data=session_post_data, json_data=False, return_json=False, allow_redirects=False) data = download['data'] code = download['code'] headers = download['headers'] if not code or not code == 302: return {'code': code, 'data': data, 'result': False} params = parse_qs(urlparse(headers['Location']).query) if check_key(params, 'code'): oauth = params['code'][0] if len(oauth) == 0: return {'code': code, 'data': data, 'result': False} challenge_url = "{base_url}/m7be2iphone/challenge.aspx".format( base_url=CONST_BASE_URL) session_post_data = { "autotype": "nl", "app": "cds", "prettyname": profile_settings['browser_name'], "model": "web", "serial": profile_settings['devicekey'], "oauthcode": oauth } headers = {'Content-Type': 'application/json;charset=UTF-8'} download = api_download(url=challenge_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True, allow_redirects=False) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'id') or not check_key(data, 'secret'): return {'code': code, 'data': data, 'result': False} login_url = "{base_url}/m7be2iphone/login.aspx".format( base_url=CONST_BASE_URL) headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } secret = '{id}\t{secr}'.format(id=data['id'], secr=data['secret']) session_post_data = { "secret": secret, "uid": profile_settings['devicekey'], "app": "cds", } download = api_download(url=login_url, type='post', headers=headers, data=session_post_data, json_data=False, return_json=False, allow_redirects=False) data = download['data'] code = download['code'] if not code or not code == 302: return {'code': code, 'data': data, 'result': False} ssotoken_url = "{base_url}/m7be2iphone/capi.aspx?z=ssotoken".format( base_url=CONST_BASE_URL) download = api_download(url=ssotoken_url, type='get', headers=None, data=None, json_data=False, return_json=True, allow_redirects=False) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key( data, 'ssotoken'): return {'code': code, 'data': data, 'result': False} session_url = "{api_url}/session".format(api_url=CONST_DEFAULT_API) session_post_data = { "sapiToken": data['ssotoken'], "deviceType": "PC", "deviceModel": profile_settings['browser_name'], "osVersion": '{name} {version}'.format(name=profile_settings['os_name'], version=profile_settings['os_version']), "deviceSerial": profile_settings['devicekey'], "appVersion": profile_settings['browser_version'], "brand": "cds" } headers = {'Content-Type': 'application/json;charset=UTF-8'} download = api_download(url=session_url, type='post', headers=headers, data=session_post_data, json_data=True, return_json=True, allow_redirects=False) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'token'): return {'code': code, 'data': data, 'result': False} query = "UPDATE `vars` SET `session_token`='{session_token}' WHERE profile_id={profile_id}".format( session_token=data['token'], profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return {'code': code, 'data': data, 'result': True}
def api_test_channels(tested=False, channel=None): profile_settings = load_profile(profile_id=1) if channel: channel = unicode(channel) try: if not profile_settings[ 'last_login_success'] == 1 or not settings.getBool( key='run_tests') or not api_get_session(): return 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=1, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "SELECT * FROM `channels`" channels = query_epg(query=query, return_result=True, return_insert=False, commit=False) results = load_tests(profile_id=1) count = 0 first = True last_tested_found = False test_run = False user_agent = profile_settings['user_agent'] if not results: results = {} for row in channels: if count == 5 or (count == 1 and tested): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count id = unicode(row['id']) if len(id) > 0: if channel: if not id == channel: continue elif tested: if unicode(profile_settings['last_tested']) == id: last_tested_found = True continue elif last_tested_found: pass else: continue if check_key(results, id) and not tested and not first: continue livebandwidth = 0 replaybandwidth = 0 live = 0 replay = 0 epg = 0 guide = 0 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='channel', channel=id, id=id, test=True) if first and not profile_settings['last_login_success']: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if len(playdata['path']) > 0: CDMHEADERS = CONST_BASE_HEADERS CDMHEADERS['User-Agent'] = user_agent session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: livebandwidth = find_highest_bandwidth(xml=resp.text) live = 1 if check_key(results, id) and first and not tested: first = False if live == 1: continue else: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 first = False counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 headers = { 'Authorization': 'Bearer ' + profile_settings['session_token'] } yesterday = datetime.datetime.now() - datetime.timedelta(1) fromtime = datetime.datetime.strftime( yesterday, '%Y-%m-%dT%H:%M:%S.000Z') tilltime = datetime.datetime.strftime( yesterday, '%Y-%m-%dT%H:%M:59.999Z') program_url = "{api_url}/schedule?channels={id}&from={fromtime}&until={tilltime}".format( api_url=CONST_DEFAULT_API, id=id, fromtime=fromtime, tilltime=tilltime) download = api_download(url=program_url, type='get', headers=headers, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if code and code == 200 and data and check_key( data, 'epg') and check_key(data['epg'][0], 'id'): profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='program', channel=id, id=data['epg'][0]['id'], test=True) if len(playdata['path']) > 0: CDMHEADERS = CONST_BASE_HEADERS CDMHEADERS['User-Agent'] = user_agent session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: replaybandwidth = find_highest_bandwidth( xml=resp.text) replay = 1 query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format( channel=id) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if len(data) > 0: guide = 1 if live == 1: epg = 1 if not xbmc.Monitor().abortRequested(): query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format( last_tested=id, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format( profile_id=1, id=id, live=live, livebandwidth=livebandwidth, replay=replay, replaybandwidth=replaybandwidth, epg=epg, guide=guide) query_settings(query=query, return_result=False, return_insert=False, commit=True) test_run = True counter = 0 while not xbmc.Monitor().abortRequested() and counter < 15: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 count += 1 except: if test_run: update_prefs() count = 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count
def api_play_url(type, channel=None, id=None, video_data=None, test=False, from_beginning=0, pvr=0): playdata = {'path': '', 'license': '', 'info': '', 'alt_path': '', 'alt_license': ''} if not api_get_session(): return None alt_path = '' alt_license = '' found_alt = False from_beginning = int(from_beginning) pvr = int(pvr) profile_settings = load_profile(profile_id=1) friendly = '' query = "SELECT assetid FROM `channels` WHERE id='{channel}'".format(channel=channel) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if data: for row in data: friendly = row['assetid'] if not test: counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: profile_settings = load_profile(profile_id=1) if profile_settings['test_running'] == 0: break counter += 1 query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format(last_playing=int(time.time()),profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if xbmc.Monitor().waitForAbort(1): break if xbmc.Monitor().abortRequested(): return playdata if test: pass elif not type == 'vod' and (pvr == 0 or settings.getBool(key='ask_start_from_beginning') or from_beginning == 1): if type == 'channel' and friendly: channel_url = '{base_url}/v6/epg/locations/{friendly}/live/1?fromDate={date}'.format(base_url=CONST_API_URL, friendly=friendly, date=datetime.datetime.now().strftime("%Y-%m-%dT%H%M%S")) download = api_download(url=channel_url, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data: return playdata for row in data: if not check_key(row, 'Channel') or not check_key(row, 'Locations'): return playdata for row2 in row['Locations']: id = row2['LocationId'] if not id: return playdata token_url_base = '{base_url}/v6/epg/location/{location}'.format(base_url=CONST_API_URL, location=id) token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}' url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter) download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data: return playdata info = data timeshift = '' if check_key(info, 'VodContentId') and len(unicode(info['VodContentId'])) > 0: token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/VOD/{id}'.format(base_url=CONST_API_URL, id=info['VodContentId']) timeshift = info['VodContentId'] token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&playerName=NLZIET%20Meister%20Player%20Web&profile=default&maxResolution=×hift=' + unicode(timeshift) + '&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}' url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter) download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'uri'): pass else: alt_license = data alt_path = data['uri'] found_alt = True elif type == 'channel' and channel and friendly: token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/Restart/{id}'.format(base_url=CONST_API_URL, id=id) timeshift = 'false' token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&playerName=NLZIET%20Meister%20Player%20Web&profile=default&maxResolution=×hift=' + unicode(timeshift) + '&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}' url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter) download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'uri'): pass else: alt_license = data alt_path = data['uri'] found_alt = True if type == 'vod': token_url_base = '{base_url}/v6/playnow/ondemand/0/{location}'.format(base_url=CONST_API_URL, location=id) token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}' url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter) download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'VideoInformation'): return playdata info = data['VideoInformation'] token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/VOD/{id}'.format(base_url=CONST_API_URL, id=info['Id']) timeshift = info['Id'] elif type == 'channel' and channel and friendly: token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/Live/{friendly}'.format(base_url=CONST_API_URL, friendly=friendly) timeshift = 'false' else: if len(unicode(alt_path)) == 0: token_url_base = '{base_url}/v6/stream/handshake/Widevine/dash/Replay/{id}'.format(base_url=CONST_API_URL, id=id) timeshift = id else: license = alt_license = data path = alt_path alt_license = '' alt_path = '' if not type == 'program' or found_alt == False: token_parameter = 'oauth_token={token}&oauth_consumer_key=key&oauth_signature_method=HMAC-SHA1&playerName=NLZIET%20Meister%20Player%20Web&profile=default&maxResolution=×hift=' + unicode(timeshift) + '&oauth_version=1.0&oauth_timestamp={timestamp}&oauth_nonce={nonce}' url_encoded = api_oauth_encode(type="GET", base_url=token_url_base, parameters=token_parameter) download = api_download(url=url_encoded, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data or not check_key(data, 'uri'): return playdata license = data path = data['uri'] if not len(unicode(license)) > 0: return playdata playdata = {'path': path, 'license': license, 'info': info, 'alt_path': alt_path, 'alt_license': alt_license} return playdata
def api_test_channels(tested=False, channel=None): profile_settings = load_profile(profile_id=1) if channel: channel = unicode(channel) try: if not profile_settings[ 'last_login_success'] == 1 or not settings.getBool( key='run_tests') or not api_get_session(): return 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=1, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "SELECT * FROM `channels`" channels = query_epg(query=query, return_result=True, return_insert=False, commit=False) results = load_tests(profile_id=1) count = 0 first = True last_tested_found = False test_run = False user_agent = profile_settings['user_agent'] if not results: results = {} for row in channels: if count == 5 or (count == 1 and tested): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count id = unicode(row['id']) if len(id) > 0: if channel: if not id == channel: continue elif tested: if unicode(profile_settings['last_tested']) == id: last_tested_found = True continue elif last_tested_found: pass else: continue if check_key(results, id) and not tested and not first: continue livebandwidth = 0 replaybandwidth = 0 live = 0 replay = 0 epg = 0 guide = 0 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url(type='channel', channel=id, id=row['assetid'], test=True) if first and not profile_settings['last_login_success']: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if len(playdata['path']) > 0: CDMHEADERS = CONST_BASE_HEADERS CDMHEADERS['User-Agent'] = user_agent playdata['path'] = playdata['path'].split("&", 1)[0] session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: livebandwidth = find_highest_bandwidth(xml=resp.text) live = 1 if check_key(results, id) and first and not tested: first = False if live == 1: continue else: if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 first = False counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 program_url = '{api_url}/TRAY/AVA/TRENDING/YESTERDAY?maxResults=1&filter_channelIds={channel}'.format( api_url=profile_settings['api_url'], channel=channeldata['channel_id']) download = api_download(url=program_url, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if code and code == 200 and data and check_key( data, 'resultCode' ) and data['resultCode'] == 'OK' and check_key( data, 'resultObj') and check_key( data['resultObj'], 'containers') and check_key( data['resultObj']['containers'][0], 'id'): profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 playdata = api_play_url( type='program', channel=id, id=data['resultObj']['containers'][0]['id'], test=True) if len(playdata['path']) > 0: CDMHEADERS = CONST_BASE_HEADERS CDMHEADERS['User-Agent'] = user_agent playdata['path'] = playdata['path'].split( "&min_bitrate", 1)[0] session = Session(headers=CDMHEADERS) resp = session.get(playdata['path']) if resp.status_code == 200: replaybandwidth = find_highest_bandwidth( xml=resp.text) replay = 1 query = "SELECT id FROM `epg` WHERE channel='{channel}' LIMIT 1".format( channel=id) data = query_epg(query=query, return_result=True, return_insert=False, commit=False) if len(data) > 0: guide = 1 if live == 1: epg = 1 if not xbmc.Monitor().abortRequested(): query = "UPDATE `vars` SET `last_tested`='{last_tested}' WHERE profile_id={profile_id}".format( last_tested=id, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) query = "REPLACE INTO `tests_{profile_id}` VALUES ('{id}', '{live}', '{livebandwidth}', '{replay}', '{replaybandwidth}', '{epg}', '{guide}')".format( profile_id=1, id=id, live=live, livebandwidth=livebandwidth, replay=replay, replaybandwidth=replaybandwidth, epg=epg, guide=guide) query_settings(query=query, return_result=False, return_insert=False, commit=True) test_run = True counter = 0 while not xbmc.Monitor().abortRequested() and counter < 15: if xbmc.Monitor().waitForAbort(1): break counter += 1 profile_settings = load_profile(profile_id=1) if profile_settings['last_playing'] > int(time.time() - 300): if test_run: update_prefs() query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return 5 if xbmc.Monitor().abortRequested(): return 5 count += 1 except: if test_run: update_prefs() count = 5 query = "UPDATE `vars` SET `test_running`={test_running} WHERE profile_id={profile_id}".format( test_running=0, profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) return count
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 "status" in self.path: self.send_response(200) self.send_header('X-TEST', 'OK') self.end_headers() elif proxy_get_match(self.path): profile_settings = load_profile(profile_id=1) self._stream_url = profile_settings['stream_hostname'] URL = proxy_get_url(self) session = proxy_get_session(self) r = session.get(URL) xml = r.text xml = set_duration(xml=xml) if settings.getBool(key='disable_subtitle'): xml = remove_subs(xml=xml) if settings.getBool(key='force_highest_bandwidth'): xml = force_highest_bandwidth(xml=xml) xml = proxy_xml_mod(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: URL = proxy_get_url(self) 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', URL) self.end_headers()
def api_play_url(type, channel=None, id=None, video_data=None, test=False, from_beginning=0, pvr=0): playdata = { 'path': '', 'license': '', 'token': '', 'type': '', 'info': '', 'alt_path': '', 'alt_license': '' } if not api_get_session(): return playdata from_beginning = int(from_beginning) pvr = int(pvr) profile_settings = load_profile(profile_id=1) alt_path = '' alt_license = '' license = '' asset_id = '' militime = int(time.time() * 1000) typestr = 'PROGRAM' info = [] program_id = None if not test: counter = 0 while not xbmc.Monitor().abortRequested() and counter < 5: profile_settings = load_profile(profile_id=1) if profile_settings['test_running'] == 0: break counter += 1 query = "UPDATE `vars` SET `last_playing`={last_playing} WHERE profile_id={profile_id}".format( last_playing=int(time.time()), profile_id=1) query_settings(query=query, return_result=False, return_insert=False, commit=True) if xbmc.Monitor().waitForAbort(1): break if xbmc.Monitor().abortRequested(): return playdata if type == 'channel': 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 = api_download(url=program_url, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data 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': 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 xbmc.Monitor().abortRequested(): return playdata if program_id and not test and not pvr == 1: info_url = '{api_url}/CONTENT/DETAIL/{type}/{id}'.format( api_url=profile_settings['api_url'], type=typestr, id=program_id) download = api_download(url=info_url, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data 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 xbmc.Monitor().abortRequested(): return playdata download = api_download(url=play_url, type='get', headers=None, data=None, json_data=False, return_json=True) data = download['data'] code = download['code'] if not code or not code == 200 or not data 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 len(unicode(token)) > 0: return playdata if type == 'channel': path = path.split("&", 1)[0] else: path = path.split("&min_bitrate", 1)[0] playdata = { 'path': path, 'license': license, 'token': token, 'type': typestr, 'info': info, 'alt_path': alt_path, 'alt_license': alt_license } return playdata