def __decodeHash(sHash): sHash = sHash.replace("!BeF", "R") sHash = sHash.replace("@jkp", "Ax") try: return base64.b64decode(sHash) except: logger.error("Invalid Base64: %s" % sHash)
def _parseMedia(sUrl, sRootUrl, iPage, sPattern, oGui): logger.error("parse %s with pattern %s" % (sUrl, sPattern)) oRequestHandler = cRequestHandler(sUrl) sHtmlContent = oRequestHandler.request() _parseMovie(sHtmlContent, sUrl, sRootUrl, iPage, sPattern, oGui)
def __getHtmlContent(sUrl=None, sSecurityValue=None, ignoreErrors=False): oParams = ParameterHandler() # Test if a url is available and set it if sUrl is None and not oParams.exist('sUrl'): logger.error("There is no url we can request.") return False elif sUrl is None: sUrl = oParams.getValue('sUrl') # Test if a security value is available if sSecurityValue is None: if oParams.exist("securityCookie"): sSecurityValue = oParams.getValue("securityCookie") else: sSecurityValue = '' # preferred language sPrefLang = __getPreferredLanguage() # Make the request oRequest = cRequestHandler(sUrl, ignoreErrors=ignoreErrors) oRequest.addHeaderEntry( 'Cookie', sPrefLang + str(sSecurityValue) + 'ListDisplayYears=Always;') oRequest.addHeaderEntry('Referer', URL_MAIN) oRequest.addHeaderEntry('Accept', '*/*') oRequest.addHeaderEntry('Host', domain) return oRequest.request()
def onPlayBackStopped(self): logger.info('Playback stopped') if self.playedTime == 0 and self.totalTime == 999999: self.streamSuccess = False logger.error('Kodi failed to open stream') self.streamFinished = True if cConfig().getSetting('metahandler') == 'true': META = True try: from metahandler import metahandlers except Exception as e: META = False logger.info("Could not import package 'metahandler'") logger.info(e) else: META = False if META: try: percent = self.playedTime / self.totalTime logger.info('Watched percent ' + str(int(percent * 100))) if percent >= 0.80: logger.info('Attemt to change watched status') meta = metahandlers.MetaData() params = ParameterHandler() season = '' episode = '' mediaType = params.getValue('mediaType') imdbID = params.getValue('imdbID') name = params.getValue('Title') TVShowTitle = params.getValue('TVShowTitle') if params.exist('season'): season = params.getValue('season') if int(season) > 0: mediaType = 'season' if params.exist('episode'): episode = params.getValue('episode') if int(episode) > 0: mediaType = 'episode' if imdbID and mediaType: if mediaType == 'movie' or mediaType == 'tvshow': metaInfo = meta.get_meta(self._mediaType, self.__sTitle, imdbID) elif mediaType == 'season': metaInfo = meta.get_seasons( TVShowTitle, imdbID, str(season)) elif mediaType == 'episode' and TVShowTitle: metaInfo = meta.get_episode_meta( TVShowTitle, imdbID, str(season), str(episode)) if metaInfo and int(metaInfo['overlay']) == 6: meta.change_watched(mediaType, name, imdbID, season=season, episode=episode) xbmc.executebuiltin("XBMC.Container.Refresh") else: logger.info( 'Could not change watched status; imdbID or mediaType missing' ) except Exception as e: logger.info(e)
def showHosters(): logger.info('load showHosters') oParams = ParameterHandler() hosters = [] __login() try: sHtmlContent = __getHtmlContent() video_id = re.findall('var video_id.*?(\d+)', sHtmlContent)[0] # 720p seems to be the best on this site, even if 1080p is avaible for selection, only the 720p stream2k links contain a 1080p stream part_name = '720p' parts = re.findall('class="changePart" data-part="(\d+p)">', sHtmlContent) for part in parts: json_data = __getVideoPage(video_id, part, '0') try: part_count = json_data['part_count'] except: part_count = 0 hosters = parseHosterResponse(json_data, hosters, part) if part_count > 1: for i in range(1, part_count): json_data = __getVideoPage(video_id, part_name, str(i)) hosters = parseHosterResponse(json_data, hosters, part) hosters.sort() except Exception, e: logger.error(e)
def __callRequest(self): cookieJar = mechanize.LWPCookieJar() try: #TODO ohne try evtl. cookieJar.load(self._cookiePath, self.__bIgnoreDiscard, self.__bIgnoreExpired) except Exception as e: logger.info(e) sParameters = urllib.urlencode(self.__aParameters) opener = mechanize.build_opener(SmartRedirectHandler, mechanize.HTTPEquivProcessor, mechanize.HTTPRefreshProcessor) if (len(sParameters) > 0): oRequest = mechanize.Request(self.__sUrl, sParameters) else: oRequest = mechanize.Request(self.__sUrl) for aHeader in self.__aHeaderEntries: for sHeaderKey, sHeaderValue in aHeader.items(): oRequest.add_header(sHeaderKey, sHeaderValue) cookieJar.add_cookie_header(oRequest) if self.caching and self.cacheTime > 0: sContent = self.readCache(self.getRequestUri()) if sContent: return sContent try: oResponse = opener.open(oRequest,timeout = 60) except mechanize.HTTPError, e: if not self.ignoreErrors: xbmcgui.Dialog().ok('xStream','Fehler beim Abrufen der Url:',self.__sUrl, str(e)) logger.error("HTTPError "+str(e)+" Url: "+self.__sUrl) return '' else: oResponse = e
def __createMenuEntry(oGui, sFunction, sLabel, dOutputParameter): parms = ParameterHandler() try: for param, value in dOutputParameter.items(): parms.setParam(param, value) except Exception, e: logger.error("Can't add parameter to menu entry with label: %s: %s" % (sLabel, e))
def __init__(self): try: fetcher = FileFetcher('guides.ini', ADDON) if fetcher.fetchFile() < 0: xbmcgui.Dialog().ok(strings(FETCH_ERROR_TITLE), strings(FETCH_ERROR_LINE1), strings(FETCH_ERROR_LINE2)) print self.filePath self.guideParser.read(self.filePath) guideTypes = [] defaultGuideId = 0 # fallback to the first guide in case no default is actually set in the ini file for section in self.guideParser.sections(): sectMap = self.SectionMap(section) id = int(sectMap['id']) fName = sectMap['file'] sortOrder = int(sectMap['sort_order']) default = False if 'default' in sectMap and sectMap['default'] == 'true': default = True defaultGuideId = id guideTypes.append((id, sortOrder, section, fName, default)) self.guideTypes = sorted(guideTypes, key=itemgetter(self.GUIDE_SORT)) logger.debug('GuideTypes collected: %s' % str(self.guideTypes), __name__) ADDON.setSetting('xmltv.type', str(defaultGuideId)) except: logger.error('unable to parse guides.ini', __name__)
def _parseMedia(sUrl,sRootUrl,iPage,sPattern, oGui): logger.error("parse %s with pattern %s" % (sUrl, sPattern)) oRequestHandler = cRequestHandler(sUrl) sHtmlContent = oRequestHandler.request() _parseMovie(sHtmlContent,sUrl,sRootUrl,iPage,sPattern,oGui)
def __getHtmlContent(sUrl = None, sSecurityValue = None): oParams = ParameterHandler() # Test if a url is available and set it if sUrl is None and not oParams.exist('sUrl'): logger.error("There is no url we can request.") return False else: if sUrl is None: sUrl = oParams.getValue('sUrl') # Test if a security value is available if sSecurityValue is None: if oParams.exist("securityCookie"): sSecurityValue = oParams.getValue("securityCookie") if not sSecurityValue: sSecurityValue = '' # preferred language sPrefLang = __getPreferredLanguage() # Make the request oRequest = cRequestHandler(sUrl) oRequest.addHeaderEntry('Cookie', sPrefLang+sSecurityValue+'ListDisplayYears=Always;') oRequest.addHeaderEntry('Referer', URL_MAIN) oRequest.addHeaderEntry('Accept', '*/*') oRequest.addHeaderEntry('Host', domain) return oRequest.request()
def menu(): route = sys.argv[0] addon_handle = int(sys.argv[1]) base_url = sys.argv[0] command = sys.argv[2][1:] parsed = parse_qs(command) logger.debug( "Menu started. route: {}, handle: {}, command: {}, parsed: {}, Arguments: {}" .format(route, addon_handle, command, parsed, sys.argv)) if route == "plugin://script.service.hue/": if not command: build_menu(base_url, addon_handle) elif command == "settings": logger.debug("Opening settings") ADDON.openSettings() elif command == "toggle": if cache.get("script.service.hue.service_enabled" ) and get_status() != "Disabled by daylight": logger.info("Disable service") cache.set("script.service.hue.service_enabled", False) elif get_status() != "Disabled by daylight": logger.info("Enable service") cache.set("script.service.hue.service_enabled", True) else: logger.info("Disabled by daylight, ignoring") xbmc.executebuiltin('Container.Refresh') elif route == "plugin://script.service.hue/actions": action = parsed['action'][0] kgroupid = parsed['kgroupid'][0] logger.debug("Actions: {}, kgroupid: {}".format(action, kgroupid)) if action == "menu": items = [ (base_url + "?action=play&kgroupid=" + kgroupid, ListItem(_("Play"))), (base_url + "?action=pause&kgroupid=" + kgroupid, ListItem(_("Pause"))), (base_url + "?action=stop&kgroupid=" + kgroupid, ListItem(_("Stop"))), ] xbmcplugin.addDirectoryItems(addon_handle, items, len(items)) xbmcplugin.endOfDirectory(handle=addon_handle, cacheToDisc=True) else: cache.set("script.service.hue.action", (action, kgroupid), expiration=(timedelta(seconds=5))) else: logger.error( "Unknown command. Handle: {}, route: {}, Arguments: {}".format( addon_handle, route, sys.argv))
def __importPlugin(self, fileName): pluginData = {} try: plugin = __import__(fileName, globals(), locals()) pluginData['name'] = plugin.SITE_NAME except Exception, e: logger.error("Can't import plugin: %s :%s" % (fileName, e)) return False
def __decodeHash(sHash): sHash = sHash.replace("!BeF", "R") sHash = sHash.replace("@jkp", "Ax") try: url = base64.b64decode(sHash) return url except: logger.error("Invalid Base64: %s" % sHash)
def __getPluginData(self, fileName): pluginData = {} try: plugin = __import__(fileName, globals(), locals()) pluginData['name'] = plugin.SITE_NAME except Exception, e: logger.error("Can't import plugin: %s :%s" % (fileName, e)) return False
def flash(self): logger.debug("in KodiGroup Flash") try: self.groupResource.action(alert="select") except QhueException() as exc: logger.error("Hue Error: {}".format(exc)) reporting.process_exception(exc) except ConnectTimeout as exc: logger.error("Hue Error: {}".format(exc))
def __createMenuEntry(oGui, sFunction, sLabel, dOutputParameter): oParams = ParameterHandler() # Create all paramters out of lOuputParameter try: for param, value in dOutputParameter.items(): oParams.setParam(param, value) except Exception, e: logger.error("Can't add parameter to menu entry with label: %s: %s" % (sLabel, e))
def run_play(self): try: self.groupResource.action(scene=self.startScene) except QhueException as e: logger.error("onAVStarted: Hue call fail: {}".format(e)) if e.args[0][0] == 7: logger.error("Scene not found") xbmcgui.Dialog().notification(_("Hue Service"), _("ERROR: Scene not found"), icon=xbmcgui.NOTIFICATION_ERROR) else: reporting.process_exception(e)
def __getPluginDB(self): if not os.path.exists(self.pluginDBFile): return dict() file = open(self.pluginDBFile, 'r') try: data = json.load(file) except ValueError: logger.error("pluginDB seems corrupt, creating new one") data = dict() file.close() return data
def __callRequest(self): if self.caching and self.cacheTime > 0: sContent = self.readCache(self.getRequestUri()) if sContent: return sContent cookieJar = mechanize.LWPCookieJar(filename=self._cookiePath) try: # TODO ohne try evtl. cookieJar.load(ignore_discard=self.__bIgnoreDiscard, ignore_expires=self.__bIgnoreExpired) except Exception as e: logger.info(e) sParameters = urllib.urlencode(self.__aParameters, True) handlers = [ SmartRedirectHandler, mechanize.HTTPEquivProcessor, mechanize.HTTPRefreshProcessor ] if sys.version_info >= (2, 7, 9) and sys.version_info < (2, 7, 11): handlers.append(newHTTPSHandler) opener = mechanize.build_opener(*handlers) if (len(sParameters) > 0): oRequest = mechanize.Request(self.__sUrl, sParameters) else: oRequest = mechanize.Request(self.__sUrl) for key, value in self.__headerEntries.items(): oRequest.add_header(key, value) cookieJar.add_cookie_header(oRequest) user_agent = self.__headerEntries.get( 'User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de-DE; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' ) try: oResponse = opener.open(oRequest, timeout=self.requestTimeout) except mechanize.HTTPError, e: if e.code == 503 and e.headers.get("Server") == 'cloudflare-nginx': html = e.read() oResponse = self.__check_protection(html, user_agent, cookieJar) if not oResponse: logger.error("Failed to get CF-Cookie for Url: " + self.__sUrl) return '' elif not self.ignoreErrors: xbmcgui.Dialog().ok('xStream', 'Fehler beim Abrufen der Url:', self.__sUrl, str(e)) logger.error("HTTPError " + str(e) + " Url: " + self.__sUrl) return '' else: oResponse = e
def __getSecurityCookieValue(): oRequestHandler = cRequestHandler(URL_NEWS, False) oRequestHandler.removeNewLines(False) oRequestHandler.removeBreakLines(False) sHtmlContent = oRequestHandler.request() sPattern = "var hash=\[(.*?)\]" oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if aResult[0] == False: logger.error("Can't find script file for cookie") result = jsunprotect.jsunprotect(sHtmlContent) if not result: logger.error("Not protected or Deactivator not found") return False else: logger.info(result) oRequestHandler = cRequestHandler(URL_MAIN+'/?'+result, False) oRequestHandler.addHeaderEntry('Referer', URL_MAIN) #oRequestHandler.addHeaderEntry('Accept', '*/*') oRequestHandler.addHeaderEntry('Host', domain) oRequestHandler.request() return False for aEntry in aResult[1][0].split(","): sScriptFile = URL_MAIN +'/'+ str(aEntry).replace("'","").strip() sScriptFile.replace(" ","") logger.info("scriptfile: %s" % sScriptFile) oRequestHandler = cRequestHandler(sScriptFile) oRequestHandler.addHeaderEntry('Referer', URL_MAIN) oRequestHandler.addHeaderEntry('Accept', '*/*') oRequestHandler.addHeaderEntry('Host', domain) sHtmlContent = oRequestHandler.request() sPattern = "escape\(hsh \+ \"([^\"]+)\"\)" oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if not aResult[0]: logger.info("No hash value found for the cookie") return False sHash = aResult[1][0] sHash = sHashSnippet + sHash sSecurityCookieValue = "sitechrx=" + str(sHash) + ";Path=/" oRequestHandler = cRequestHandler(URL_MAIN) oRequestHandler.addHeaderEntry("Cookie", sSecurityCookieValue) oRequestHandler.request() logger.info("Token: %s" % sSecurityCookieValue) return sSecurityCookieValue
def __getSecurityCookieValue(): oRequestHandler = cRequestHandler(URL_NEWS, False) oRequestHandler.removeNewLines(False) oRequestHandler.removeBreakLines(False) sHtmlContent = oRequestHandler.request() sPattern = "var hash=\[(.*?)\]" oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if aResult[0] == False: logger.error("Can't find script file for cookie") result = jsunprotect.jsunprotect(sHtmlContent) if not result: logger.error("Not protected or Deactivator not found") return False else: logger.info(result) oRequestHandler = cRequestHandler(URL_MAIN + '/?' + result, False) oRequestHandler.addHeaderEntry('Referer', URL_MAIN) #oRequestHandler.addHeaderEntry('Accept', '*/*') oRequestHandler.addHeaderEntry('Host', domain) oRequestHandler.request() return False for aEntry in aResult[1][0].split(","): sScriptFile = URL_MAIN + '/' + str(aEntry).replace("'", "").strip() sScriptFile.replace(" ", "") logger.info("scriptfile: %s" % sScriptFile) oRequestHandler = cRequestHandler(sScriptFile) oRequestHandler.addHeaderEntry('Referer', URL_MAIN) oRequestHandler.addHeaderEntry('Accept', '*/*') oRequestHandler.addHeaderEntry('Host', domain) sHtmlContent = oRequestHandler.request() sPattern = "escape\(hsh \+ \"([^\"]+)\"\)" oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if not aResult[0]: logger.info("No hash value found for the cookie") return False sHash = aResult[1][0] sHash = sHashSnippet + sHash sSecurityCookieValue = "sitechrx=" + str(sHash) + ";Path=/" oRequestHandler = cRequestHandler(URL_MAIN) oRequestHandler.addHeaderEntry("Cookie", sSecurityCookieValue) oRequestHandler.request() logger.info("Token: %s" % sSecurityCookieValue) return sSecurityCookieValue
def run_stop(self): try: xbmc.sleep(100) # sleep for any left over ambilight calls to complete first. self.groupResource.action(scene=self.stopScene) logger.info("In KodiGroup[{}], onPlaybackStop() Stop scene activated") except QhueException as e: logger.error("onPlaybackStopped: Hue call fail: {}".format(e)) if e.args[0][0] == 7: logger.error("Scene not found") xbmcgui.Dialog().notification(_("Hue Service"), _("ERROR: Scene not found"), icon=xbmcgui.NOTIFICATION_ERROR) else: reporting.process_exception(e)
def __callRequest(self): if self.caching and self.cacheTime > 0: sContent = self.readCache(self.getRequestUri()) if sContent: return sContent cookieJar = cookielib.LWPCookieJar(filename=self._cookiePath) try: cookieJar.load(ignore_discard=self.__bIgnoreDiscard, ignore_expires=self.__bIgnoreExpired) except Exception as e: logger.info(e) sParameters = urllib.urlencode(self.__aParameters, True) handlers = [ urllib2.HTTPHandler(), urllib2.HTTPSHandler(), urllib2.HTTPCookieProcessor(cookiejar=cookieJar) ] if (2, 7, 9) <= sys.version_info < (2, 7, 11): handlers.append(newHTTPSHandler) opener = urllib2.build_opener(*handlers) if (len(sParameters) > 0): oRequest = urllib2.Request(self.__sUrl, sParameters) else: oRequest = urllib2.Request(self.__sUrl) for key, value in self.__headerEntries.items(): oRequest.add_header(key, value) cookieJar.add_cookie_header(oRequest) user_agent = self.__headerEntries.get('User-Agent', common.FF_USER_AGENT) try: oResponse = opener.open(oRequest, timeout=self.requestTimeout) except urllib2.HTTPError, e: if e.code == 503 and e.headers.get("Server") == 'cloudflare': html = e.read() oResponse = self.__check_protection(html, user_agent, cookieJar) if not oResponse: logger.error("Failed to get CF-Cookie for Url: " + self.__sUrl) return '' elif not self.ignoreErrors: xbmcgui.Dialog().ok('xStream', 'Fehler beim Abrufen der Url:', self.__sUrl, str(e)) logger.error("HTTPError " + str(e) + " Url: " + self.__sUrl) return '' else: oResponse = e
def _getSiteKey(): sHtmlContent = _getRequestHandler(URL_MAIN, True).request() pattern = '<script [^>]*src="([^"]*basic.min.js[^"]*)"[^>]*></script[>].*?' aResult = cParser().parse(sHtmlContent, pattern) if aResult[0]: sHtmlContent = _getRequestHandler(aResult[1][0], True).request() aResult = cParser().parse(sHtmlContent, "'sitekey':'(.*?)'") if aResult[0]: return aResult[1][0] else: logger.error("error while getting sitekey: sitekey not found in basic.min.js") else: logger.error("error while getting sitekey: basic.min.js not found")
def _getSiteKey(): sHtmlContent = _getRequestHandler(URL_MAIN, True).request() pattern = '<script [^>]*src="([^"]*basic.(?:min.)?js[^"]*)"[^>]*></script[>].*?' aResult = cParser().parse(sHtmlContent, pattern) if aResult[0]: sHtmlContent = _getRequestHandler(aResult[1][0], True).request() aResult = cParser().parse(sHtmlContent, "'sitekey'\s?:\s?'(.*?)'") if aResult[0]: return aResult[1][0] else: logger.error("error while getting sitekey: sitekey not found in basic.min.js") else: logger.error("error while getting sitekey: basic.min.js not found")
def _validate_ambilight(): logger.debug("Validate ambilight config. Enabled: {}".format( settings_storage['ambiEnabled'])) if settings_storage['ambiEnabled']: light_ids = ADDON.getSetting("group3_Lights") if light_ids == "-1": logger.error("No ambilights selected") xbmcgui.Dialog().notification( _("Hue Service"), _("No lights selected for Ambilight."), icon=xbmcgui.NOTIFICATION_ERROR) ADDON.setSettingBool("group3_enabled", False) settings_storage['ambiEnabled'] = False
def onPlayBackStopped(self): if self.enabled: logger.info("In KodiGroup[{}], onPlaybackStopped() , mediaType: {}, lastMediaType: {} ".format(self.kgroupID, self.mediaType, settings_storage['lastMediaType'])) self.state = STATE_STOPPED try: if self.mediaType == VIDEO and not self.checkVideoActivation( self.videoInfoTag): # If video group, check video activation. Otherwise it's audio so ignore this and check other conditions. return except AttributeError: logger.error("No videoInfoTag") if (self.checkActiveTime() or self.checkAlreadyActive(self.stopScene)) and self.checkKeepLightsOffRule(self.stopScene) and self.stopBehavior and self.mediaType == settings_storage['lastMediaType']: self.run_stop()
def __getHtmlContent(sUrl=None, ignoreErrors=False): parms = ParameterHandler() if sUrl is None and not parms.exist('sUrl'): logger.error("There is no url we can request.") return False elif sUrl is None: sUrl = parms.getValue('sUrl') sPrefLang = __getPreferredLanguage() oRequest = cRequestHandler(sUrl, ignoreErrors=ignoreErrors) oRequest.addHeaderEntry('Cookie', sPrefLang + 'ListDisplayYears=Always;') oRequest.addHeaderEntry('Referer', URL_MAIN) oRequest.addHeaderEntry('Accept', '*/*') oRequest.addHeaderEntry('Host', domain) return oRequest.request()
def __displayItems(oGui, sHtmlContent): # Test if a cookie was set, else define the default empty one sSecurityValue = False oParams = ParameterHandler() if oParams.exist("securityCookie"): sSecurityValue = oParams.getValue("securityCookie") # The pattern to filter every item of the list sPattern = '<td class="Icon"><img width="16" height="11" src="/gr/sys/lng/(\d+).png" alt="language"></td>'+\ '.*?title="([^\"]+)".*?<td class="Title">.*?<a href="([^\"]+)" onclick="return false;">([^<]+)</a> <span class="Year">([0-9]+)</span>' # Parse to get all items of the list oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if not aResult[0]: logger.error("Could not find an item") return # Go throught all items and create a gui element for them. total = len(aResult[1]) for aEntry in aResult[1]: sTitle = cUtil().unescape(aEntry[3]) # split title and subtitle language sTitle, subLang = __checkSubLanguage(sTitle) # get audio language sLang = __createLanguage(aEntry[0]) sUrl = URL_MAIN + aEntry[2] mediaType = '' if aEntry[1] == 'movie' or aEntry[1] == 'cinema': mediaType = 'movie' elif aEntry[1] == 'series': mediaType = 'series' else: mediaType = 'documentation' oGuiElement = cGuiElement(sTitle, SITE_IDENTIFIER, 'parseMovieEntrySite') oGuiElement.setLanguage(sLang) oGuiElement.setSubLanguage(subLang) oGuiElement.setYear(aEntry[4]) oParams.setParam('sUrl', sUrl) oParams.setParam('mediaType', mediaType) if mediaType == 'series': oGuiElement.setMediaType('tvshow') oGui.addFolder(oGuiElement, oParams, iTotal=total) elif mediaType == 'movie': oGuiElement.setMediaType('movie') oGui.addFolder(oGuiElement, oParams, bIsFolder=False, iTotal=total) else: oGui.addFolder(oGuiElement, oParams, bIsFolder=False, iTotal=total)
def showHosters(): logger.info('load showHosters') oParams = ParameterHandler() hosters = [] try: sHtmlContent = __getHtmlContent() video_id = re.findall('var video_id.*?(\d+)', sHtmlContent)[0] # 720p seems to be the best on this site, even if 1080p is avaible for selection, only the 720p stream2k links contain a 1080p stream part_name = '720p' parts = re.findall('class="changePart" data-part="(.*?)">', sHtmlContent) if len(parts) == 1: part_name = parts[0] if oParams.exist('from_moviesever') and len(parts) == 2: part_name = parts[1] app = re.findall( '<script src="(%sassets/js/app.js.*?)"></script>' % URL_MAIN, sHtmlContent) domain_list = [] try: domain_list = __get_domain_list(app, domain_list) except: logger.info('Could not get domain list') if not domain_list: domain_list = ['se1.seriesever.net', 'se2.seriesever.net'] import random random.shuffle(domain_list) json_data = __getVideoPage(video_id, part_name, '0') try: part_count = json_data['part_count'] except: part_count = 0 hosters = parseHosterResponse(json_data, hosters) if part_count > 1: for i in range(1, part_count): json_data = __getVideoPage(video_id, part_name, str(i)) hosters = parseHosterResponse(json_data, hosters) hosters.sort() except Exception, e: logger.error(e)
def __getHtmlContent(sUrl=None): oParams = ParameterHandler() # Test if a url is available and set it if sUrl is None and not oParams.exist('sUrl'): logger.error("There is no url we can request.") return False else: if sUrl is None: sUrl = oParams.getValue('sUrl') # Make the request oRequest = cRequestHandler(sUrl) oRequest.addHeaderEntry('Referer', URL_MAIN) oRequest.addHeaderEntry('Accept', '*/*') return oRequest.request()
def __displayItems(oGui, sHtmlContent): # Test if a cookie was set, else define the default empty one sSecurityValue = False oParams = ParameterHandler() if oParams.exist("securityCookie"): sSecurityValue = oParams.getValue("securityCookie") # The pattern to filter every item of the list sPattern = '<td class="Icon"><img width="16" height="11" src="/gr/sys/lng/(\d+).png" alt="language"></td>'+\ '.*?title="([^\"]+)".*?<td class="Title">.*?<a href="([^\"]+)" onclick="return false;">([^<]+)</a> <span class="Year">([0-9]+)</span>' # Parse to get all items of the list oParser = cParser() aResult = oParser.parse(sHtmlContent, sPattern) if not aResult[0]: logger.error("Could not find an item") return # Go throught all items and create a gui element for them. total = len(aResult[1]) for aEntry in aResult[1]: sTitle = cUtil().unescape(aEntry[3]) # split title and subtitle language sTitle, subLang = __checkSubLanguage(sTitle) # get audio language sLang = __createLanguage(aEntry[0]) sUrl = URL_MAIN + aEntry[2] mediaType = '' if aEntry[1] == 'movie' or aEntry[1] == 'cinema': mediaType = 'movie' elif aEntry[1] == 'series': mediaType = 'series' else: mediaType = 'documentation' oGuiElement = cGuiElement(sTitle, SITE_IDENTIFIER, 'parseMovieEntrySite') oGuiElement.setLanguage(sLang) oGuiElement.setSubLanguage(subLang) oGuiElement.setYear(aEntry[4]) oParams.setParam('sUrl',sUrl) oParams.setParam('mediaType',mediaType) if mediaType == 'series': oGuiElement.setMediaType('tvshow') oGui.addFolder(oGuiElement, oParams, iTotal = total) elif mediaType == 'movie': oGuiElement.setMediaType('movie') oGui.addFolder(oGuiElement,oParams,bIsFolder=False, iTotal = total) else: oGui.addFolder(oGuiElement,oParams,bIsFolder=False, iTotal = total)
def __getHtmlContent(sUrl=None): oParams = ParameterHandler() # Test if a url is available and set it if sUrl is None and not oParams.exist('sUrl'): logger.error("There is no url we can request.") return False else: if sUrl is None: sUrl = oParams.getValue('sUrl') # Make the request oRequest = cRequestHandler(sUrl) oRequest.addHeaderEntry('User-Agent', 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.99 Safari/535.1') oRequest.addHeaderEntry('Referer', URL_MAIN) oRequest.addHeaderEntry('Accept', '*/*') return oRequest.request()
def __getOldurl(sLink): sHtmlContent = __getHtmlContent(sLink) url = re.findall('url="(.*?)"', sHtmlContent) if len(url) == 0: url = re.findall('src="(.*?)"', sHtmlContent) if len(url) == 0: logger.error("Unknown Response: %s" % sHtmlContent) else: if "play/se.php" in url[0]: sHtmlContent = __getHtmlContent(url[0]) sHash = re.findall('link:"(.*?)"', sHtmlContent)[0] return __decodeHash(sHash) else: logger.error("Unknown url: %s" % url) else: return url[0]
def showHosters(): logger.info('load showHosters') oParams = ParameterHandler() hosters = [] try: sHtmlContent = __getHtmlContent() video_id = re.findall('var video_id.*?(\d+)', sHtmlContent)[0] # 720p seems to be the best on this site, even if 1080p is avaible for selection, only the 720p stream2k links contain a 1080p stream part_name = '720p' parts = re.findall('class="changePart" data-part="(.*?)">', sHtmlContent) if len(parts) == 1: part_name = parts[0] if oParams.exist('from_moviesever') and len(parts) == 2: part_name = parts[1] app = re.findall('<script src="(%sassets/js/app.js.*?)"></script>' % URL_MAIN, sHtmlContent) domain_list = [] #try: # domain_list = __get_domain_list(app, domain_list) #except: # logger.info('Could not get domain list') #if not domain_list: # domain_list = ['se1.seriesever.net', 'se2.seriesever.net'] #import random #random.shuffle(domain_list) json_data = __getVideoPage(video_id, part_name, '0') try: part_count = json_data['part_count'] except: part_count = 0 hosters = parseHosterResponse(json_data, hosters) if part_count > 1: for i in range(1, part_count): json_data = __getVideoPage(video_id, part_name, str(i)) hosters = parseHosterResponse(json_data, hosters) hosters.sort() except Exception, e: logger.error(e)
def _validate_schedule(): logger.debug("Validate schedule. Schedule Enabled: {}".format( settings_storage['enableSchedule'])) if settings_storage['enableSchedule']: try: convert_time(settings_storage['startTime']) convert_time(settings_storage['endTime']) logger.debug("Time looks valid") except ValueError as e: logger.error("Invalid time settings: {}".format(e)) xbmcgui.Dialog().notification( _("Hue Service"), _("Invalid start or end time, schedule disabled"), icon=xbmcgui.NOTIFICATION_ERROR) ADDON.setSettingBool("EnableSchedule", False) settings_storage['enableSchedule'] = False
def checkAlreadyActive(self, scene): if not scene: return False logger.debug("Check if scene light already active, settings: enable {}".format(settings_storage['enable_if_already_active'])) if settings_storage['enable_if_already_active']: try: sceneData = self.bridge.scenes[scene]() for light in sceneData["lights"]: l = self.bridge.lights[light]() if l["state"]["on"] == True: # one light is on, the scene can be applied logger.debug("Check if scene light already active: True") return True logger.debug("Check if scene light already active: False") except QhueException as e: logger.error("checkAlreadyActive: Hue call fail: {}".format(e)) return False
def checkKeepLightsOffRule(self, scene): if not scene: return True logger.debug("Check if lights should stay off, settings: enable {}".format(settings_storage['keep_lights_off'])) if settings_storage['keep_lights_off']: try: sceneData = self.bridge.scenes[scene]() for light in sceneData["lights"]: l = self.bridge.lights[light]() if l["state"]["on"] == False: # one light is off, the scene should not be applied logger.debug("Check if lights should stay off: True") return False logger.debug("Check if lights should stay off: False") except QhueException as e: logger.error("checkKeepLightsOffRule: Hue call fail: {}".format(e)) return True
def __callRequest(self): cookieJar = mechanize.LWPCookieJar() try: #TODO ohne try evtl. cookieJar.load(self._cookiePath, self.__bIgnoreDiscard, self.__bIgnoreExpired) except Exception as e: logger.info(e) sParameters = urllib.urlencode(self.__aParameters, True) handlers = [ SmartRedirectHandler, mechanize.HTTPEquivProcessor, mechanize.HTTPRefreshProcessor ] if sys.version_info >= (2, 7, 9) and sys.version_info < (2, 7, 11): handlers.append(newHTTPSHandler) opener = mechanize.build_opener(*handlers) if (len(sParameters) > 0): oRequest = mechanize.Request(self.__sUrl, sParameters) else: oRequest = mechanize.Request(self.__sUrl) for key, value in self.__headerEntries.items(): oRequest.add_header(key, value) cookieJar.add_cookie_header(oRequest) if self.caching and self.cacheTime > 0: sContent = self.readCache(self.getRequestUri()) if sContent: return sContent try: oResponse = opener.open(oRequest, timeout=self.requestTimeout) except mechanize.HTTPError, e: if e.code == 503 and e.headers.get("Server") == 'cloudflare-nginx': oResponse, cookieJar = cCFScrape().resolve( oRequest, e, cookieJar) elif not self.ignoreErrors: xbmcgui.Dialog().ok('xStream', 'Fehler beim Abrufen der Url:', self.__sUrl, str(e)) logger.error("HTTPError " + str(e) + " Url: " + self.__sUrl) return '' else: oResponse = e
def __getHtmlContent(sUrl=None): oParams = ParameterHandler() # Test if a url is available and set it if sUrl is None and not oParams.exist('sUrl'): logger.error("There is no url we can request.") return False else: if sUrl is None: sUrl = oParams.getValue('sUrl') # Make the request oRequest = cRequestHandler(sUrl) oRequest.addHeaderEntry( 'User-Agent', 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.99 Safari/535.1' ) oRequest.addHeaderEntry('Referer', URL_MAIN) oRequest.addHeaderEntry('Accept', '*/*') return oRequest.request()
def parseHosterResponse(json_data, hosters): if (json_data['part']['source'] != 'url') and (json_data['part']['source'] != 'other'): logger.error("Unknown data: %s" % json_data['part']['source']) return code = None try: code = json_data['part']['code'] except: pass if code: hoster = dict() if json_data['part']['source'] == 'url': if "http" not in code: hoster['link'] = __decodeHash(code) else: hoster['link'] = code elif json_data['part']['source'] == 'other': link1 = re.findall('src="(http.*?)"', code)[0] if "/play/old/seframer.php" in link1: hoster['link'] = urllib.unquote(__getOldurl(link1)) else: hoster['link'] = link1 hname = 'Unknown Hoster' try: hname = re.compile('^(?:https?:\/\/)?(?:www\.)?(?:[^@\n]+@)?([^:\/\n]+)', flags=re.I | re.M).findall(hoster['link']) except Exception, e: logger.error(e) hoster['name'] = hname[0] hoster['link'] = hoster['link'] hosters.append(hoster)
def parseHosterResponse(json_data, hosters): if json_data['part']['source'] == 'other': code = None try: code = json_data['part']['code'] except: pass if code: hoster = dict() hoster['link'] = re.findall('src="(http.*?)"', code)[0] hname = 'Unknown Hoster' try: hname = re.compile('^(?:https?:\/\/)?(?:[^@\n]+@)?([^:\/\n]+)', flags=re.I | re.M).findall( hoster['link']) except Exception, e: logger.error(e) hoster['name'] = hname[0] hoster['displayedName'] = hname[0] hosters.append(hoster)
try: oResponse = opener.open(oRequest,timeout = 60) except mechanize.HTTPError, e: if not self.ignoreErrors: xbmcgui.Dialog().ok('xStream','Fehler beim Abrufen der Url:',self.__sUrl, str(e)) logger.error("HTTPError "+str(e)+" Url: "+self.__sUrl) return '' else: oResponse = e except mechanize.URLError, e: xbmcgui.Dialog().ok('xStream',str(e.reason), 'Fehler') logger.error("URLError "+str(e.reason)+" Url: "+self.__sUrl) return '' except httplib.HTTPException, e: xbmcgui.Dialog().ok('xStream', str(e)) logger.error("HTTPException "+str(e)+" Url: "+self.__sUrl) return '' cookieJar.extract_cookies(oResponse, oRequest) cookieJar = self.__checkCookie(cookieJar) cookieJar.save(self._cookiePath, self.__bIgnoreDiscard, self.__bIgnoreExpired) sContent = oResponse.read() self.__sResponseHeader = oResponse.info() # handle gzipped content if self.__sResponseHeader.get('Content-Encoding') == 'gzip': import gzip import StringIO data = StringIO.StringIO(sContent) gzipper = gzip.GzipFile(fileobj=data, mode='rb')