def buildPlay(self, data, label=""): if data.get("vendor") == "hotstar": return Listitem().from_dict(**{ "label": label, "callback": data.get("playbackUrl"), "properties": { "IsPlayable": True, "inputstreamaddon": "inputstream.adaptive", "inputstream.adaptive.stream_headers": urlencode(data.get("headers", {})), "inputstream.adaptive.manifest_type": data.get("playbackProto"), } }) elif data.get("vendor") == "Sony Pictures": if data.get("licenceUrl"): is_helper = inputstreamhelper.Helper( "mpd", drm="com.widevine.alpha") if is_helper.check_inputstream(): Script.log("licenceUrl %s" % data.get("licenceUrl"), lvl=Script.INFO) return Listitem().from_dict(**{ "label": label, "callback": data.get("playbackUrl"), "properties": { "IsPlayable": True, "inputstreamaddon": is_helper.inputstream_addon, "inputstream.adaptive.manifest_type": data.get("playbackProto"), "inputstream.adaptive.license_type": "com.widevine.alpha", "inputstream.adaptive.license_key": data.get("licenceUrl") + "||R{SSM}|", } }) return Listitem().from_dict(**{ "label": label, "callback": data.get("playbackUrl"), "properties": { "IsPlayable": True, "inputstreamaddon": "inputstream.adaptive", "inputstream.adaptive.manifest_type": data.get("playbackProto"), } }) else: Script.log("licenceUrl %s" % data.get("licenceUrl"), lvl=Script.INFO) is_helper = inputstreamhelper.Helper( "mpd", drm="com.widevine.alpha") if is_helper.check_inputstream(): return Listitem().from_dict(**{ "label": label, "callback": data.get("playbackUrl"), "subtitles": data.get("subtitles"), "properties": { "IsPlayable": True, "inputstreamaddon": is_helper.inputstream_addon, "inputstream.adaptive.stream_headers": urlencode(data.get("headers", {})), "inputstream.adaptive.manifest_type": data.get("playbackProto"), "inputstream.adaptive.license_type": "com.widevine.alpha", "inputstream.adaptive.license_key": data.get("licenseUrl"), } }) return False
def do_GET(self): self.protocol_version = 'HTTP/1.1' try: ChannelRequestHandler(self) except Exception, e: Script.log(e, lvl=Script.DEBUG) pass
def get_fav_dict_from_json(): """Get favourites dict from favourites.json Returns: dict: Favourites dict """ def get_fresh_dict(): return { 'items': {}, 'format_version': FAV_FORMAT_VERSION } if not xbmcvfs.exists(FAV_JSON_FP): return get_fresh_dict() try: with open(FAV_JSON_FP) as f: fav_dict = json.load(f) current_fav_format = fav_dict.get('format_version', 0) if current_fav_format < FAV_FORMAT_VERSION: fav_dict = migrate_fav_format(current_fav_format, fav_dict) return fav_dict except Exception: Script.log('Failed to load favourites json data') xbmcvfs.delete(FAV_JSON_FP) return get_fresh_dict()
def import_ovpn(*args, **kwargs): path = xbmcgui.Dialog().browse(1, Script.localize(30342), 'files', mask='.ovpn|.conf', enableMultiple=False) if path and os.path.exists(path) and os.path.isfile(path): Script.log('OpenVPN: Import: [%s]' % path) keyboard = xbmc.Keyboard(default='', heading=Script.localize(30348), hidden=False) keyboard.doModal() if keyboard.isConfirmed() and len(keyboard.getText()) > 0: name = keyboard.getText() ovpnfiles = {} with storage.PersistentDict('vpn') as db: ovpnfiles = db['ovpnfiles'] db.flush() if name in ovpnfiles and not xbmcgui.Dialog().yesno( 'OpenVPN', Script.localize(30349)): xbmcgui.Dialog().ok('OpenVPN', Script.localize(30350)) else: ovpnfiles[name] = path with storage.PersistentDict('vpn') as db: db['ovpnfiles'] = ovpnfiles db.flush() else: xbmcgui.Dialog().ok('OpenVPN', Script.localize(30351))
def connect_openvpn(config, sudopassword=None): Script.log('OpenVPN: Connecting OpenVPN configuration: [%s]' % config) if Script.setting.get_boolean('vpn.sudo') and \ Script.setting.get_boolean('vpn.sudopsw') and sudopassword is None: keyboard = xbmc.Keyboard() keyboard.setHeading(Script.localize(30353)) keyboard.setHiddenInput(True) keyboard.doModal() if keyboard.isConfirmed(): sudopassword = keyboard.getText() else: return openvpn = vpnlib.OpenVPN( Script.setting.get_string('vpn.openvpnfilepath'), config, ip=IP, port=PORT, args=Script.setting.get_string('vpn.args'), sudo=Script.setting.get_boolean('vpn.sudo'), sudopwd=sudopassword) try: openvpn.connect() Script.notify( "OpenVPN", Script.localize(30354), display_time=3000) except Exception as e: xbmcgui.Dialog().ok( 'OpenVPN', Script.localize(30358)) Script.log('OpenVPN: OpenVPN error: ' + str(e))
def __init__(self, proxy): self.proxy = proxy p = urlparse(proxy.path) self.path = p.path self.params = parse_qs(p.query) play_url = self.path.endswith('master.m3u8') m3u8_url = self.path.endswith('.m3u8') ts_url = self.path.endswith('.ts') key_url = self.path.endswith('.key') self.ishls = 'packagerx' in self.path self.channel_name = self.path.split( '/')[3] if self.ishls else self.path.split('/')[2] self.maxq = 'maxq' in self.params and int(self.params['maxq'][0]) self.hlsrx = '' if not self.ishls else "/"+self.path.split('/')[2] self.quality = qmap[Settings.get_string('quality')] try: if play_url: self.getMaster() elif m3u8_url: self.getM3U8() elif key_url: self.resolveKey() elif ts_url: self.resolveTS() else: Script.log("Resource not found by proxy", lvl=Script.INFO) self.proxy.send_error(404, "Not Found") except Exception, e: Script.log(e, lvl=Script.INFO) if(self.proxy): self.proxy.send_error(500, "Internal Server Error") self.proxy.wfile.write(str(e).encode("utf-8"))
def migrate_from_pickled_fav(): """ This function moves existing pickled favourites in the new json file used for the favourites. The new format (json) appeared in 0.2.17~beta04 All user with version >= 0.2.17 will use favourites in the JSON format Maybe we can remove the migration check on version 0.2.20? """ # Move all pickled existing favs in json file fav_pickle_fp = os.path.join(Script.get_info('profile'), "favourites.pickle") if xbmcvfs.exists(fav_pickle_fp): Script.log('Start favourites migration from pickle file to json file') new_fav_dict = {} with storage.PersistentDict("favourites.pickle") as db: new_fav_dict = dict(db) # Fix old fav for item_hash, item_dict in new_fav_dict.items(): if 'params' in item_dict and isinstance(item_dict['params'], listing.Params): new_fav_dict[item_hash]['params'] = dict(new_fav_dict[item_hash]['params']) try: del new_fav_dict[item_hash]['params']['item_dict']['params'] except Exception: pass if 'properties' in item_dict: if isinstance(item_dict['properties'], listing.Property): new_fav_dict[item_hash]['properties'] = dict(new_fav_dict[item_hash]['properties']) fav_json_fp = os.path.join(Script.get_info('profile'), "favourites.json") with open(fav_json_fp, 'w') as f: json.dump(new_fav_dict, f, indent=4) xbmcvfs.delete(fav_pickle_fp)
def select_ovpn(): ovpnfiles = {} with storage.PersistentDict('vpn') as db: try: ovpnfiles = db['ovpnfiles'] except KeyError: db['ovpnfiles'] = ovpnfiles db.flush() if len(ovpnfiles) == 0: return None configs = [] ovpnfileslist = [] for name, configfilepath in list(ovpnfiles.items()): configs.append(name) ovpnfileslist.append(configfilepath) idx = xbmcgui.Dialog().select( Script.localize(30352), configs) if idx < 0: return '' Script.log('OpenVPN: Select conf: [%s]' % ovpnfileslist[idx]) return ovpnfileslist[idx]
def post(self, url, **kwargs): try: response = self.session.post(url, **kwargs) return response.json() except Exception, e: Script.log(e, lvl=Script.INFO) self._handleError(e, url, **kwargs)
def grab_current_programmes(country_id): """Retrieve current programmes of channels of country_id. Args: country_id (str) Returns: dict: (key: xmltv_id, value: current programme) """ if country_id not in xmltv_infos: return {} try: # Download, if needed, xmltv file of today xmltv_fp = download_xmltv_file(country_id) # Grab current programmes in xmltv file programmes = read_programmes(xmltv_fp, only_current_programmes=True) # Use the channel as key tv_guide = {} for programme in programmes: programme = programme_post_treatment(programme) tv_guide[programme['channel']] = programme return tv_guide except Exception as e: Script.notify(Script.localize(30722), Script.localize(30723), display_time=7000) Script.log('xmltv module failed with error: {}'.format(e), lvl=Script.ERROR) return {}
def select_ovpn(): ovpnfiles = {} with storage.PersistentDict('vpn') as db: try: ovpnfiles = db['ovpnfiles'] except KeyError: db['ovpnfiles'] = ovpnfiles db.flush() if len(ovpnfiles) == 0: return None else: response = vpnlib.is_running(ip, port) Script.log('OpenVPN: Response from is_running: [%s] [%s] [%s]' % (response[0], response[1], response[2])) if response[0]: # Le VPN est connecté disconnect_openvpn() configs = [] ovpnfileslist = [] for name, configfilepath in list(ovpnfiles.items()): configs.append(name) ovpnfileslist.append(configfilepath) idx = xbmcgui.Dialog().select( Script.localize(LABELS['Select OpenVPN configuration to run']), configs) if idx >= 0: Script.log('OpenVPN: Select conf: [%s]' % ovpnfileslist[idx]) return ovpnfileslist[idx] else: return ''
def delete_ovpn(*args, **kwargs): ovpnfiles = {} with storage.PersistentDict('vpn') as db: try: ovpnfiles = db['ovpnfiles'] except KeyError: db['ovpnfiles'] = ovpnfiles db.flush() if len(ovpnfiles) == 0: return None configs = [] ovpnfileslist = [] for name, configfilepath in list(ovpnfiles.items()): configs.append(name) ovpnfileslist.append(configfilepath) idx = xbmcgui.Dialog().select( Script.localize(30360), configs) if idx < 0: return '' Script.log('Select: [%s]' % ovpnfileslist[idx]) new_ovpnfiles = {} for name, configfilepath in list(ovpnfiles.items()): if configfilepath != ovpnfileslist[idx]: new_ovpnfiles[name] = configfilepath with storage.PersistentDict('vpn') as db: db['ovpnfiles'] = new_ovpnfiles db.flush()
def do_POST(self): if self.path == "/login": data_string = self.rfile.read(int(self.headers['Content-Length'])) qs = parse_qs(data_string.decode('utf-8')) error = None Script.log(qs, lvl=Script.INFO) try: if qs.get("type")[0] == "password": error = login(qs.get("username")[0], qs.get("password")[0]) elif qs.get("type")[0] == "otp": mobile = qs.get("mobile")[0] if qs.get("otp"): error = login(mobile, qs.get("otp")[0], mode="otp") else: error = sendOTP(mobile) else: error = "Invalid Type" except Exception as e: Script.log(e, lvl=Script.ERROR) error = str(e) if error: location = "/?error=" + str(error) elif qs.get("type")[0] == "otp" and qs.get("otp") is None: location = "/?otpsent=" + qs.get("mobile")[0] else: location = "/?success" self.send_response(302) self.send_header('Location', location) self.end_headers() else: self.send_error(404, "File not found")
def _handleError(self, e, url, **kwargs): if e.__class__.__name__ == "ValueError": Script.log("Can not parse response of request url %s" % url, lvl=Script.INFO) Script.notify("Internal Error", "") elif e.__class__.__name__ == "HTTPError": if e.code == 402: Script.notify("Subscription Error", "You don't have valid subscription to watch this content") elif e.code == 401: status = self._refreshToken() if(status is True): return self.get(url, **kwargs) else: Script.notify("Token Error", str(status)) elif e.code == 474 or e.code == 475: Script.notify( "VPN Error", "Your VPN provider does not support Hotstar") else: raise urlquick.HTTPError(e.filename, e.code, e.msg, e.hdrs) else: Script.log("Got unexpected response for request url %s" % url, lvl=Script.INFO) Script.notify( "API Error", "Raise issue if you are continuously facing this error")
def check_addon(addonid, minVersion=False): """Checks if selected add-on is installed.""" try: curVersion = Script.get_info("version", addonid) if minVersion and LooseVersion(curVersion) < LooseVersion(minVersion): Script.log( '{addon} {curVersion} doesn\'t setisfy required version {minVersion}.' .format(addon=addonid, curVersion=curVersion, minVersion=minVersion)) Dialog().ok( "Error", "{minVersion} version of {addon} is required to play this content." .format(addon=addonid, minVersion=minVersion)) return False return True except RuntimeError: Script.log('{addon} is not installed.'.format(addon=addonid)) if not _install_addon(addonid): # inputstream is missing on system Dialog().ok( "Error", "[B]{addon}[/B] is missing on your Kodi install. This add-on is required to play this content." .format(addon=addonid)) return False return True
def import_needed_module(): # Import needed module according to the # base URL and query string (Fix for Kodi favorite item and search) modules_to_import = [get_module_in_url(sys.argv[0])] if 'codequick/search' in sys.argv[0]: modules_to_import.append(get_module_in_query(sys.argv[2])) for module_to_import in modules_to_import: if module_to_import == '': # No additionnal module to load continue # Need to load additional module try: Script.log( '[cq_utils.import_needed_module] Import module {} on the fly'. format(module_to_import), lvl=Script.INFO) importlib.import_module(module_to_import) except Exception: Script.log( '[cq_utils.import_needed_module] Failed to import module {} on the fly' .format(module_to_import), lvl=Script.WARNING) return
def grab_programmes(country_id, day_delta): """Retrieve programmes of channels of country_id at day today + day_detla. Args: country_id (str) day_delta (int) Returns: list: Programmes. """ if country_id not in xmltv_infos: return [] try: # Download, if needed, xmltv file xmltv_fp = download_xmltv_file(country_id, day_delta=day_delta) # Grab programmes in xmltv file programmes = read_programmes(xmltv_fp, only_current_programmes=False) programmes_post_treated = [] for programme in programmes: programmes_post_treated.append( programme_post_treatment_iptvmanager(programme)) return programmes_post_treated except Exception as e: Script.log('xmltv module failed with error: {}'.format(e), lvl=Script.ERROR) return []
def list_videos(plugin, item_id, program_url, **kwargs): resp = urlquick.get(program_url) json_parser = json.loads(resp.text) # Get Program Name and Program Plot program_name = json_parser["name"] program_plot = json_parser["program_info"]["description"] has_contents = False try: url_videos = URL_ROOT + json_parser["blocks"][0]["sets"][0]["path_id"] has_contents = True except Exception: pass if has_contents: resp2 = urlquick.get(url_videos) json_parser2 = json.loads(resp2.text) for video_datas in json_parser2["items"]: video_title = program_name + ' ' + video_datas[ 'name'] + ' ' + video_datas['subtitle'] video_image = URL_ROOT + video_datas["images"][ "landscape"].replace('/resizegd/[RESOLUTION]', '') duration_value = video_datas['duration'].split(':') video_duration = 0 if len(duration_value) > 2: video_duration = int(duration_value[0]) * 3600 + int( duration_value[1]) * 60 + int(duration_value[2]) elif len(duration_value) > 1: video_duration = int(duration_value[0]) * 60 + int( duration_value[1]) video_url = video_datas['video_url'] item = Listitem() item.label = video_title item.art['thumb'] = item.art['landscape'] = video_image item.info['duration'] = video_duration item.info['plot'] = program_plot item.params['title'] = video_title # subtitles try: weblink = video_datas['weblink'] weblink = weblink.rsplit('.', 1)[0] + '.json' resp3 = urlquick.get(URL_ROOT + weblink) json_parser3 = json.loads(resp3.text) subtitles = json_parser3['video']['subtitlesArray'] item.params['subtitles'] = subtitles except Exception: Script.log('[raiplay.py] Problem getting subtitles.') item.set_callback(get_video_url, item_id=item_id, video_url=video_url) item_post_treatment(item, is_playable=True, is_downloadable=True) yield item
def download_xmltv_file(country_id, day_delta=0): """Try to download XMLTV file of country_id for today + day_delta. Args: country_id (str) day_delta (int): 0: Today, 1: Tomorrow,... Returns: str: xmltv filepath. """ # Retrieve URL xmltv_url = get_xmltv_url(country_id, day_delta=day_delta) Script.log('xmltv url of {} country with day_delta {}: {}'.format( country_id, day_delta, xmltv_url)) # Compute dst filepath xmltv_fn = os.path.basename(urlparse(xmltv_url).path) Script.log('xmltv filename: {}'.format(xmltv_fn)) xmltv_fp = os.path.join(Script.get_info('profile'), xmltv_fn) # Remove old xmltv files of this country dirs, files = xbmcvfs.listdir(Script.get_info('profile')) today = datetime.date.today() for fn in files: if xmltv_infos[country_id]['keyword'] not in fn: continue try: file_date_s = fn.split( xmltv_infos[country_id]['keyword'])[1].split('.xml')[0] file_date = datetime_strptime(file_date_s, '%Y%m%d').date() if file_date < today: Script.log('Remove old xmltv file: {}'.format(fn)) xbmcvfs.delete(os.path.join(Script.get_info('profile'), fn)) except Exception: pass # Check if we need to download a fresh xmltv file need_to_downlod_xmltv_file = False if not xbmcvfs.exists(xmltv_fp): Script.log( "xmltv file of {} for today does not exist, let's download it". format(country_id)) need_to_downlod_xmltv_file = True else: # Check if we have the last version of the file current_file_md5 = compute_md5(xmltv_fp) remote_file_md5 = get_remote_xmltv_md5(country_id, day_delta=day_delta) print(current_file_md5) print(remote_file_md5) if current_file_md5 != remote_file_md5: Script.log( "A new version of xmltv file of {} for today exists, let's download it" .format(country_id)) need_to_downlod_xmltv_file = True if need_to_downlod_xmltv_file: r = urlquick.get(xmltv_url, max_age=-1) with open(xmltv_fp, 'wb') as f: f.write(r.content) return xmltv_fp
def __init__(self, ip, port, openvpn=None): self.openvpn = openvpn self.ip = ip self.port = port Script.log('[OpenVPNManagementInterface] IP: [%s]' % ip) Script.log('[OpenVPNManagementInterface] Port: [%s]' % port) self.buf = b'' self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def disconnect(self): self.connect_to_interface() Script.log('Disconnecting OpenVPN') self.interface.send(b'signal SIGTERM\n') time.sleep(self.timeout) self.interface.disconnect() self.interface = None Script.log('Disconnect OpenVPN successful')
def disconnect(ip, port): interface = OpenVPNManagementInterface(ip, port) try: interface.connect() interface.send(b'signal SIGTERM\n') interface.disconnect() except socket.error: Script.log('[OpenVPNManagementInterface] Unable to disconnect OpenVPN', lvl=Script.ERROR)
def is_running(ip, port): interface = OpenVPNManagementInterface(ip, port) try: interface.connect() except socket.error: Script.log('[OpenVPNManagementInterface] is_running? -> False') return False Script.log('[OpenVPNManagementInterface] is_running? -> True') return True
def migrate_old_menus_settings(menus_settings_fp): """ This function moves old user settings concerning hidden menu and items order in the new json file used for that purpose. The feature (json) appeared in 0.2.17~betaXX All user with version >= 0.2.17 will use item settings in the JSON format Maybe we can remove the migration check on version 0.2.20? """ # If the json file already exists, the migration has already be done if xbmcvfs.exists(menus_settings_fp): return Script.log('Start item settings migration to json file') j = {} skeletons = [ "root", "live_tv", "replay", 'websites', "fr_live", "ch_live", "uk_live", "wo_live", "be_live", "jp_live", "ca_live", "us_live", "pl_live", "es_live", "tn_live", "it_live", "nl_live", "cn_live", "fr_replay", "ch_replay", "uk_replay", "wo_replay", "be_replay", "jp_replay", "ca_replay", "us_replay", "es_replay", "tn_replay", "it_replay", "nl_replay", "cn_replay" ] for skeleton in skeletons: current_menu = importlib.import_module('resources.lib.skeletons.' + skeleton).menu for item_id, item_infos in current_menu.items(): # Migrate old order old_order = Script.setting.get_string(item_id + '.order') try: old_order = int(old_order) if item_infos['order'] != old_order: if skeleton not in j: j[skeleton] = {} if item_id not in j[skeleton]: j[skeleton][item_id] = {} j[skeleton][item_id]['order'] = old_order except Exception: pass # Migrate old visibility old_visibility = Script.setting.get_string(item_id) if old_visibility.lower( ) == 'false' and item_infos['enabled'] is True: if skeleton not in j: j[skeleton] = {} if item_id not in j[skeleton]: j[skeleton][item_id] = {} j[skeleton][item_id]['hidden'] = True # Save new item settings json with open(menus_settings_fp, 'w') as f: json.dump(j, f, indent=4)
def delete_favourites(plugin): """ Callback function of 'Delete favourites' setting button """ Script.log('Delete favourites db') xbmcvfs.delete( os.path.join(Script.get_info('profile'), 'favourites.pickle')) Script.notify(Script.localize(30374), '')
def _findPlayback(playBackSets, encryption="widevine"): for each in playBackSets: if re.search("encryption:%s.*?ladder:tv.*?package:dash" % encryption, each.get("tagsCombination")): Script.log("Found Stream! URL : %s LicenceURL: %s" % (each.get("playbackUrl"), each.get("licenceUrl")), lvl=Script.INFO) return (each.get("playbackUrl"), each.get("licenceUrl"), "mpd") playbackUrl = playBackSets[0].get("playbackUrl") Script.log("No stream found for desired config. Using %s" % playbackUrl, lvl=Script.INFO) return (playbackUrl, None, "hls" if "master.m3u8" in playbackUrl else "mpd")
def error_handler(exception): """ This function is called each time run() trigger an Exception """ params = entrypoint_utils.get_params_in_query(sys.argv[2]) # If it's an HTTPError if isinstance(exception, urlquick.HTTPError): code = exception.code msg = exception.msg # hdrs = exception.hdrs # url = exception.filename Script.log( 'urlquick.get() failed with HTTPError code {} with message "{}"'. format(code, msg, lvl=Script.ERROR)) # Build dialog message dialog_message = msg if 'http_code_' + str(code) in LABELS: dialog_message = Script.localize(LABELS['http_code_' + str(code)]) # Build dialog title dialog_title = Script.localize( LABELS['HTTP Error code']) + ' ' + str(code) # Show xbmc dialog xbmcgui.Dialog().ok(dialog_title, dialog_message) # If error code is in avoid_log_uploader, then return # Else, let log_uploader run avoid_log_uploader = [403, 404] if code in avoid_log_uploader: return # If we come from fav menu we # suggest user to delete this item if 'from_fav' in params: fav.ask_to_delete_error_fav_item(params) # Else, we ask the user if he wants # to share his log to addon devs elif Script.setting.get_boolean('log_pop_up'): ask_to_share_log = True log_exceptions = [ 'No items found', 'Youtube-DL: Video geo-restricted by the owner' ] for log_exception in log_exceptions: if log_exception in str(exception): ask_to_share_log = False if ask_to_share_log: log_uploader = importlib.import_module( 'resources.lib.log_uploader') log_uploader.ask_to_share_log()
def _handleError(self, e, url, _rtype, **kwargs): if e.__class__.__name__ == "ValueError": Script.log("Can not parse response of request url %s" % url, lvl=Script.DEBUG) Script.notify("Internal Error", "") elif e.__class__.__name__ == "HTTPError": if e.response.status_code == 402 or e.response.status_code == 403: with PersistentDict("userdata.pickle") as db: if db.get("isGuest"): Script.notify("Login Error", "Please login to watch this content") executebuiltin( "RunPlugin(plugin://plugin.video.botallen.hotstar/resources/lib/main/login/)" ) else: Script.notify( "Subscription Error", "You don't have valid subscription to watch this content", display_time=2000) elif e.response.status_code == 401: new_token = self._refreshToken() if new_token: kwargs.get("headers") and kwargs['headers'].update( {"X-HS-UserToken": new_token}) if _rtype == "get": return self.get(url, **kwargs) else: return self.post(url, **kwargs) else: Script.notify("Token Error", "Token not found") elif e.response.status_code == 474 or e.response.status_code == 475: Script.notify("VPN Error", "Your VPN provider does not support Hotstar") elif e.response.status_code == 404 and e.response.headers.get( "Content-Type") == "application/json": if e.response.json().get("errorCode") == "ERR_PB_1412": Script.notify("Network Error", "Use Jio network to play this content") else: Script.notify( "Invalid Response", "{0}: Invalid response from server".format( e.response.status_code)) return False else: Script.log( "{0}: Got unexpected response for request url {1}".format( e.__class__.__name__, url), lvl=Script.DEBUG) Script.notify( "API Error", "Raise issue if you are continuously facing this error") raise e
def connect_to_interface(self): if self.interface is None: self.interface = OpenVPNManagementInterface( self.ip, self.port, self) try: self.interface.connect() except socket.error as exception: Script.log(exception) self.interface = None return False return True
def _handleError(self, e, url, **kwargs): if e.__class__.__name__ == "ValueError": Script.log("Can not parse response of request url %s" % url, lvl=Script.INFO) Script.notify("Internal Error", "") elif e.__class__.__name__ == "HTTPError": raise urlquick.HTTPError(e.filename, e.code, e.msg, e.hdrs) else: Script.log("Got unexpected response for request url %s" % url, lvl=Script.INFO) Script.notify( "API Error", "Raise issue if you are continuously facing this error")