def _create_cookie(self, name, value, domain): if self._cookie is None: cookiefile = xbmc.translatePath( 'special://profile/addon_data/%s/cookie' % commons.AddonId()).decode('utf-8') if xbmcvfs.exists(cookiefile): self._cookie = cookielib.MozillaCookieJar() self._cookie.load(cookiefile, ignore_discard=True) commons.debug("Loaded cookie %s from file: %s" % (str(self._cookie), cookiefile)) else: self._cookie = cookielib.MozillaCookieJar() self._cookie.set_cookie( cookielib.Cookie(version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=True, domain_initial_dot=False, path="/", path_specified=True, secure=False, expires=None, discard=False, comment=None, comment_url=None, rest=None)) self._cookie.save(cookiefile) commons.debug("Created cookie %s and saved to file: %s" % (str(self._cookie), cookiefile))
def save_database_object(state): debug(save_database_object.__name__, "obj:", state.data) obj = state.data if not obj.id: state.session.add(obj) state.session.commit() state.session.refresh(obj) return change("data", obj)(state)
def transform_to_json(state): debug(transform_to_json.__name__, "data:", state.data) obj = value("data")(state) json = {} transformer_cls = transformers[state.type.__name__] transformer = transformer_cls() transformer.to_json(json, obj) return change("data", json)(state)
def transform_from_json(state): debug(transform_from_json.__name__, "json:", state.json) obj = state.data json = state.json transformer_cls = transformers[state.type.__name__] transformer = transformer_cls() transformer.from_json(json, obj) return state
def get_database_object(state): debug(get_database_object.__name__, "json:", state.json) database_obj=None json = state.json if json.has_key("id") and (isinstance(json["id"],int) or isinstance(json["id"],long)): database_obj = state.session.query(state.type).get(json["id"]) if not database_obj: database_obj = state.type() return change("data", database_obj)(state)
def __init__(self): self.userdata = xbmc.translatePath('special://userdata/keymaps') self.userkeymapfile = os.path.join(self.userdata, 'gen.xml') self.userkeymap = [] self.syskeymapfile = xbmc.translatePath( 'special://xbmc/system/keymaps/keyboard.xml') self.syskeymap = [] try: if not os.path.exists(self.userdata): os.makedirs(self.userdata) else: # make sure there are no user defined keymaps for name in os.listdir(self.userdata): if name.endswith('.xml') and name != os.path.basename( self.userkeymapfile): src = os.path.join(self.userdata, name) for i in xrange(100): dst = os.path.join(self.userdata, "%s.bak.%d" % (name, i)) if os.path.exists(dst): continue shutil.move(src, dst) # successfully renamed break except Exception as ex: KeyEditor.rpc('GUI.ShowNotification', title="Keymap Editor", message=commons.translate(30011), image='error') commons.debug("Failed to remove old keymap file: %s" % str(ex)) # load system keymap if os.path.exists(self.syskeymapfile): try: self.syskeymap = self.getKeymap(self.syskeymapfile) except Exception as ex: KeyEditor.rpc('GUI.ShowNotification', title="Keymap Editor", message=commons.translate(30012), image='error') commons.error("Failed to load system keymap file: %s" % str(ex)) # load user keymap if os.path.exists(self.userkeymapfile): try: self.userkeymap = self.getKeymap(self.userkeymapfile) except Exception as ex: KeyEditor.rpc('GUI.ShowNotification', title="Keymap Editor", message=commons.translate(30013), image='error') commons.error("Failed to load user keymap file: %s" % str(ex))
def onPlay(self, context, re_match): params = context.getParams() version = commons.any2int(params["version"]) channel = self.getChannel(version, params["channel"]) # 1. Get channel if version == 1: channel = self.getChannelV1(channel) else: raise DigiOnlineException( "Channels v2 or v3 are not implemented yet, stay tuned for the next updates!" ) # 2. Display info if commons.setting('digionline.playback.epginfo') and channel.get( "plot") is not None: if channel["label"] is None or channel["label"] == "": xbmc.executebuiltin("Notification(Digi-Online, " + channel["plot"] + ", 10000)") else: xbmc.executebuiltin("Notification(" + channel["label"] + ", " + channel["plot"] + ", 10000)") # 3. Play video commons.debug("Preparing to play video URL: %s" % channel["url"]) self._play(context, channel)
def run_queries(state): debug("run_queries") queries = state.queries query_ids = queries["query_ids"] query = queries["query"] first_property = queries["first_property"] debug(" query_ids", str(query_ids)) ids = query_ids.all() if len(ids) > 0: query = query.filter(first_property.in_(map(lambda id: id[0], ids))) debug(" query", str(query)) results = query.all() else: results = [] return change("data", results)(state)
def to_json(state): debug(to_json.__name__, "json:", state.data) if len(state.errors) == 0: return jsonify(data=state.data) else: return jsonify(errors=state.errors), 500
def getChannelV1(self, channel): # 0. Initialize browser browser = urllib2.build_opener( urllib2.HTTPCookieProcessor(self.getCookie())) commons.debug("Initializing browser using cookie: %s" % str(self._cookie)) # 1. Run data collection process: epg info, channel scope and master key try: url = HTMLParser.HTMLParser().unescape(channel["url"]) commons.debug( "Executing HTTP GET call to collect channel data: %s" % url) httpget = browser.open(url) content = httpget.read() except: content = '' pass # 1.1 Identify epg info if content is not None and '<div class="info" epg-data=' in content: seps = ["[", "]", "'", "{", "}", "start:", "stop:", "title:"] tagdata = str( re.compile('<div class="info" epg-data="(.+?)"').findall( content)).replace(""", "") for i in range(len(seps)): tagdata = tagdata.replace(str(seps[i]), "") if len(tagdata) > 0: parts = tagdata.split(',') nowinfo = None nextinfo = None try: nowinfo = commons.translate(30010) + ": " + time.strftime( "%H:%M", time.localtime(int( parts[1]))) + " - " + time.strftime( "%H:%M", time.localtime(int( parts[2]))) + " " + str(parts[0]) nextinfo = commons.translate(30011) + ": " + time.strftime( "%H:%M", time.localtime(int( parts[4]))) + " - " + time.strftime( "%H:%M", time.localtime(int( parts[5]))) + " " + str(parts[3]) except: pass if nowinfo is not None and nextinfo is not None: channel["plot"] = nowinfo + " | " + nextinfo elif nowinfo is not None and nextinfo is None: channel["plot"] = nowinfo if channel.get("plot") is not None: commons.debug("Added [plot] property to '%s' channel: %s" % (channel["id"], channel["plot"])) # 1.2 Identify channel scope match = re.compile('data-balancer-scope-name="(.+?)"').findall(content) if len(match) > 0: channel["scope"] = str(match[0]).strip() else: channel["scope"] = channel["id"] commons.debug("Added [scope] property to '%s' channel: %s" % (channel["id"], channel["scope"])) # 1.3 Identify master key match = re.compile('data-balancer-key="(.+?)"').findall(content) if len(match) > 0: channel["key"] = str(match[0]).strip() commons.debug("Added [key] property to '%s' channel: %s" % (channel["id"], channel["key"])) # 2. Run Authentication process for configured account if commons.any2bool(channel["auth"]) and commons.setting( "digionline.login.enabled"): url = "http://www.digi-online.ro/xhr-login.php" browser.addheaders = [('Host', "www.digi-online.ro"), ('Accept', '*/*'), ('Origin', "http://www.digi-online.ro"), ('X-Requested-With', 'XMLHttpRequest'), ('User-Agent', self.getAgent()), ('Content-type', 'application/x-www-form-urlencoded'), ('Referer', "http://www.digi-online.ro"), ('Accept-Encoding', 'identity'), ('Accept-Language', 'en-ie'), ('Connection', 'close')] formdata = urllib.urlencode({ 'user': commons.getSetting('digionline.login.username'), 'password': commons.getSetting('digionline.login.password'), 'browser': self._appname, 'model': self._appversion, 'os': self._osname }) try: commons.debug( "Executing HTTP POST for authentication: %s, form data: %s" % (url, formdata)) httppost = browser.open(url, formdata) response = httppost.read() commons.debug("Received HTTP POST answer: %s" % response) except: raise LoginException(commons.translate(30051)) if commons.any2bool(response): for cookie in self._cookie: if str(cookie.name) == 'sid': channel["sid"] = str(cookie.value).strip() commons.debug( "Added [sid] property to '%s' channel: %s" % (channel["id"], channel["sid"])) else: raise LoginException(commons.translate(30050)) elif commons.any2bool(channel["auth"]) and not commons.setting( "digionline.login.enabled"): raise LoginException(commons.translate(30052)) # 3.1 Execute authorization to access resources url = 'http://www.digi-online.ro/xhr-gen-stream.php' browser.addheaders = [('X-Requested-With', 'XMLHttpRequest')] formdata = urllib.urlencode({'scope': channel["scope"]}) try: commons.debug( "Executing HTTP POST call to authorize the scope: %s, form data: %s" % (url, formdata)) httppost = browser.open(url, formdata) response = httppost.read() commons.debug("Received HTTP GET answer: %s" % response) except: pass # 3.2 Generates master key if is not already detected if channel.get("key") is None: url = "http://balancer.digi24.ro/streamer/make_key.php" browser.addheaders = [('Host', "balancer.digi24.ro"), ('Accept', '*/*'), ('Origin', "http://www.digi-online.ro"), ('User-Agent', self.getAgent()), ('Referer', channel["url"]), ('Accept-Encoding', 'identity'), ('Accept-Language', 'en-GB,en;q=0.5'), ('Connection', 'close')] try: commons.debug("Executing HTTP GET call to get master key: %s" % url) httpget = browser.open(url) content = httpget.read() commons.debug("Received HTTP GET answer: %s" % content) except: content = '' pass if len(content) > 0: channel["key"] = str(content) commons.debug("Added [key] property to '%s' channel: %s" % (channel["id"], channel["key"])) # 3.3 Get video information url = 'http://balancer.digi24.ro/streamer.php?&scope=' + channel[ "scope"] + '&key=' + channel[ "key"] + '&outputFormat=json&type=hls&quality=' + commons.getSetting( "digionline.playback.quality") try: commons.debug( "Executing HTTP GET call to obtain video information: %s" % url) content = browser.open(url).read() commons.debug("Received HTTP GET answer: %s" % content) except: raise DigiOnlineException(commons.translate(30053)) data = json.loads(content) if data.get("file") is not None and "http:" not in data["file"]: channel["url"] = "http:" + data["file"] elif data.get("file") is not None and "http:" not in data["file"]: channel["url"] = data["file"] else: raise DigiOnlineException(commons.translate(30054)) commons.debug("Updated [url] property to '%s' channel: %s" % (channel["id"], channel["url"])) return channel
def transform_results_to_json(state, results): # global index # index=0 fields = state.json["find"] # print 1, fields, index def get_id_dict(parent_dict, unique_key): # unique_key = row.id if not parent_dict.has_key(unique_key): parent_dict[unique_key] = {} return parent_dict[unique_key] def transform_row_to_json(row, json, element_list, transform_field_function=property_to_json, relation=None, path=[], column_index=0): # global index global counter # print 2,index,relation,path, element_list if relation: path.append(relation) for element in element_list: #property if isinstance(element, str) or isinstance(element, unicode): transform_field_function(json, element, row[column_index]) column_index += 1 #relation elif isinstance(element, dict): # print 33, ".".join(path) relation_key = element.keys()[0] relation_list = element[relation_key] #create relation_dict relation_name = get_property_name(relation_key) relation_dic = get_id_dict(json, relation_name) if row[column_index] != None: inner_dic = get_id_dict(relation_dic, row[column_index]) #recursive column_index = transform_row_to_json( row, inner_dic, relation_list, relation=relation_name, path=path, column_index=column_index) else: counter = 0 column_index += count_fields(relation_list) return column_index results_json = {} debug("transform_results_to_json", len(results)) for res in results: json = get_id_dict(results_json, res[0]) index = 0 index = transform_row_to_json(res, json, fields, path=[], column_index=0) return results_json
def debug(self, text): commons.debug(text)