def get(id=-1, name=None, type=MediaCore.TYPE_AUDIO, create=False): # If we'er called with only the name given we'll try to get the id. # If we cannot find a matching playlist, we return None db = eMediaDatabase.getInstance() if id < 0: res = db.getPlaylistByName(name, type) else: res = db.getPlaylist(id) if res.error( ) or not res.data(): #Playlist unkown (not yet saved/created!) Log.w("%s / %s" % (res.errorDatabaseText(), res.errorDriverText())) if create: Log.i("creating new playlist") return DatabasePlaylist.create(name, type) else: Log.w("Unkown Playlist for id=%s, name=%s and type=%s" % (id, name, type)) return None data = res.data()[0] id = int(data[eMediaDatabase.FIELD_ID]) name = data[eMediaDatabase.FIELD_NAME] Log.i("Playlist %s found. Id is %s" % (name, id)) playlist = DatabasePlaylist(id, name=name, type=type) playlist.reload() return playlist
def playService(self, ref, root=None): from Screens.InfoBar import InfoBar if root and InfoBar.instance: try: InfoBar.instance.servicelist.zap(ref, root) return except: try: from types import MethodType def zap(self, nref=None, root=None): self.revertMode=None ref = self.session.nav.getCurrentlyPlayingServiceReference() if not nref: nref = self.getCurrentSelection() if root: if not self.preEnterPath(root): self.clearPath() self.enterPath(eServiceReference(root)) if ref is None or ref != nref: self.new_service_played = True self.session.nav.playService(nref) self.saveRoot() self.saveChannel(nref) config.servicelist.lastmode.save() self.addToHistory(nref) InfoBar.instance.servicelist.zap = MethodType(zap, InfoBar.instance.servicelist) InfoBar.instance.servicelist.zap(ref, root) return except: Log.w("Patch failed! Will fallback primitive zap") pass self.session.nav.playService(ref)
def __init__(self, rcUsed, boundKeys): GUIComponent.__init__(self) self.onSelectionChanged = [] self.l = eListboxPythonMultiContent() self._rcUsed = rcUsed sizes = componentSizes[componentSizes.HELP_MENU_LIST] textX = sizes.get("textX", 5) textWidth = sizes.get("textWidth", 1000) textHeight = sizes.get("textHeight", 35) l = [] for key in self.KEY_ORDER: if key not in boundKeys: continue try: keyID = keyDescriptions[self._rcUsed][KEYIDS[key]][0] description = self.KEY_NAMES.get(key, keyID) entry = [(keyID, key)] entry.append( (eListboxPythonMultiContent.TYPE_TEXT, textX, 0, textWidth, textHeight, 0, RT_VALIGN_CENTER, description)) l.append(entry) except: Log.w("Key %s is unknown and skipped!" % (key, )) self.l.setList(l) tlf = TemplatedListFonts() self.l.setFont(0, gFont(tlf.face(tlf.BIG), tlf.size(tlf.BIG))) self.l.setFont(1, gFont(tlf.face(tlf.MEDIUM), tlf.size(tlf.MEDIUM))) self.l.setItemHeight(sizes.get(componentSizes.ITEM_HEIGHT, 30))
def play(self, val, isUri): Log.w("%s %s" %(val, isUri)) if isUri: val = val.split("#") uri = val[0] if len(val) > 1: name = val[1] else: name = uri.split("/")[-1] if uri.startswith("file://") or uri.startswith("/"): #Local File if uri.lower().endswith(".ts"): serviceType = eServiceReference.idDVB elif uri.lower().endswith(".m2ts"): serviceType = eServiceReference.idM2TS else: serviceType = eServiceReference.idGST uri = uri.replace("file://", "") ref = eServiceReference(serviceType, 0, uri) else: ref = eServiceReference(eServiceReference.idURI, 0, uri) ref.setName(name) else: ref = eServiceReference(val) if not ref.valid(): return False if not self._player: self._player = self._session.openWithCallback(self._onPlayerClosed, MoviePlayer, ref) else: self._player.playService(ref) return True
def resolve(self, service, uri): Log.i(uri) watch_url = None try: uri = uri.split("://")[1] uri = uri.split("/") if len(uri) > 1 and uri[0] == "video": uri = "videos/%s" % (uri[1]) else: uri = uri[0] watch_url = "http://twitch.tv/%s" % (uri, ) except Exception as e: Log.w(e) def onUrlReady(uri, fmt): Log.w("%s (%s)" % (uri, fmt)) try: if not service.ptrValid(): Log.w("Service became invalid!") return if uri: service.setResolvedUri(uri, eServiceReference.idDVB) else: service.failedToResolveUri() except: service.failedToResolveUri() Log.i(watch_url) if watch_url: TwitchVideoUrlResolver(watch_url, [onUrlReady], async=True) else: service.failedToResolveUri() return True
def upnp_X_GetFeatureList(self, **kwargs): Log.w() attrib = { "xmlns": "urn:schemas-upnp-org:av:avs", "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation": "urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd" } features = ET.Element("Features") features.attrib.update(attrib) attrib = {"name": "samsung.com_BASICVIEW", "version": "1"} feature = ET.SubElement(features, "Feature") feature.attrib.update(attrib) #audio/video container id definition tag = ET.SubElement(feature, "container") tag.attrib.update({ "type": DIDLLite.AudioItem.upnp_class, "id": str(self._audio.get_id()) }) tag = ET.SubElement(feature, "container") tag.attrib.update({ "type": DIDLLite.VideoItem.upnp_class, "id": str(self._video.get_id()) }) return {"FeatureList": ET.tostring(features, "utf-8")}
def doStart(*args, **kwargs): if self._controlPoint: Log.w("already running!") return Log.i("starting now!") self._startPending = False self.coherence = Coherence({ 'logging': { 'level' : 'warning', 'subsystem' : [ {'name' : 'msearch', 'level' : 'warning'}, {'name' : 'ssdp', 'level' : 'warning'} ]} }) self._controlPoint = ControlPoint(self.coherence, auto_client=['MediaServer','MediaRenderer']) self.coherence.ctrl = self._controlPoint self.__mediaServerClients = {} self.__mediaRendererClients = {} self.__mediaDevices = {} self.__devices = [] self._controlPoint.connect(self._onMediaServerDetected, 'Coherence.UPnP.ControlPoint.MediaServer.detected') self._controlPoint.connect(self._onMediaServerRemoved, 'Coherence.UPnP.ControlPoint.MediaServer.removed') self._controlPoint.connect(self._onMediaRendererDetected, 'Coherence.UPnP.ControlPoint.MediaRenderer.detected') self._controlPoint.connect(self._onMediaRendererRemoved, 'Coherence.UPnP.ControlPoint.MediaRenderer.removed') self._controlPoint.connect(self._onMediaDeviceDectected, 'Coherence.UPnP.Device.detection_completed') self._controlPoint.connect(self._onMediaDeviceRemoved, 'Coherence.UPnP.RootDevice.removed') self.__deferredShutDown = None if self._session: self._callPlugins(reason=0)
def _request(self): ie_key = "YoutubeLive" if "live" in self._baseurl.lower( ) else "Youtube" try: self._setupFormatMap() with YoutubeDL(self._params) as ytdl: result = ytdl.extract_info(self._baseurl, ie_key=ie_key, download=False, process=True) if self.KEY_ENTRIES in result: # Can be a playlist or a list of videos entry = result[self.KEY_ENTRIES][0] #TODO handle properly else: # Just a video entry = result fmt = entry.get(self.KEY_FORMAT_ID) url = "" suburi = "" for f in entry.get(self.KEY_REQUESTED_FORMATS, []): if not url and f.get(self.KEY_VCODEC, u"none") != u"none": url = str(f.get(self.KEY_URL, "")) elif not suburi and f.get(self.KEY_ACODEC, u"none") != u"none": suburi = str(f.get(self.KEY_URL, "")) if not url: url = str(entry.get(self.KEY_URL, "")) self._onResult(True, url, fmt, suburi) return except Exception as e: Log.w(e) self._onResult(False, None, -1)
def readKeymap(filename): p = enigma.eActionMap.getInstance() assert p source = open(filename, 're') try: dom = xml.etree.cElementTree.parse(source) except: raise KeymapError("keymap %s not well-formed." % filename) keymap = dom.getroot() for cmap in keymap.findall("map"): context = cmap.attrib.get("context") assert context, "map must have context" advanced = None hasBle = False for device in cmap.findall("device"): devices = device.attrib.get("name") parseKeys(context, filename, p, devices, device) if devices.find("dreambox advanced remote control (native)") >= 0: advanced = device if devices.find("dreambox remote control (bluetooth le)") >= 0: hasBle = True if not hasBle and advanced: Log.w("BLE Keymap fallback to advanced remote for context %s" %(context,)) parseKeys(context, filename, p, "dreambox remote control (bluetooth le)", advanced) parseKeys(context, filename, p, "generic", cmap)
def shutdown(self): Log.i("%s" % (self.coherence, )) if True: Log.w( "shutdown is broken... will continue running. please restart enigma2 instead!" ) return if self.coherence: self._callPlugins(reason=1) self.__mediaServerClients = {} self.__mediaRendererClients = {} self.__mediaDevices = {} self.__devices = [] self.__deferredShutDown = self.coherence.shutdown(force=True) self.__deferredShutDown.addCallback(self._onShutdownFinished) self._controlPoint.disconnect( self._onMediaServerDetected, 'Coherence.UPnP.ControlPoint.MediaServer.detected') self._controlPoint.disconnect( self._onMediaServerRemoved, 'Coherence.UPnP.ControlPoint.MediaServer.removed') self._controlPoint.disconnect( self._onMediaRendererDetected, 'Coherence.UPnP.ControlPoint.MediaRenderer.detected') self._controlPoint.disconnect( self._onMediaRendererRemoved, 'Coherence.UPnP.ControlPoint.MediaRenderer.removed') self._controlPoint.disconnect( self._onMediaDeviceDectected, 'Coherence.UPnP.Device.detection_completed') self._controlPoint.disconnect(self._onMediaDeviceRemoved, 'Coherence.UPnP.RootDevice.removed') self.coherence = None self._controlPoint = None
def main(reason, *args): Log.w(main.listeningPort) if main.listeningPort: return f = protocol.ServerFactory() f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol, insults.ServerProtocol, ColoredManhole) main.listeningPort = reactor.listenTCP(8007, f, interface='localhost')
def buildProtocol(data): protocol = data["protocol"] protocolHandler = ProtocolMaster.HANDLER_LUT.get(protocol, None) if not protocolHandler: Log.w("No Handler for Protocol %s" %(protocol,)) return [(False,False,False)] return protocolHandler.build(data)
def reload(self): if not fileExists(self.CONFIG_FILE): return True try: with open(self.CONFIG_FILE) as f: self._config = {} for line in f: Log.i("parsing: %s" % (line, )) if line.startswith("#"): Log.d("skipping comment") continue try: num, data = line.strip().split("=") pairs = data.split(",") tuner_data = {} for pair in pairs: key, value = pair.split(":") tuner_data[key] = value self._config[int(num)] = TunerEntry(tuner_data) except Exception as e: Log.w(e) continue except Exception as e: Log.w(e) return False Log.i(self._config) return True
def parseData(self, data, service): self.bandwith_list = [] match_sec_m3u8 = re.findall('BANDWIDTH=(\d+).*?\n(.*?m3u8.*?)\n', data, re.S) max = 0 for x in match_sec_m3u8: if int(x[0]) > max: max = int(x[0]) videoPrio = int(config_mp.mediaportal.videoquali_others.value) if videoPrio == 2: bw = max elif videoPrio == 1: bw = max / 2 else: bw = max / 3 for each in match_sec_m3u8: bandwith, url = each self.bandwith_list.append((int(bandwith), url)) _, best = min((abs(int(x[0]) - bw), x) for x in self.bandwith_list) uri = best[1] try: if not service.ptrValid(): Log.w("Service became invalid!") return if uri: service.setResolvedUri(uri, eServiceReference.idDVB) else: service.failedToResolveUri() except: service.failedToResolveUri()
def uninstall(): Log.i() if fileExists(CecBoot.UBOOT_SCRIPT_FILE): try: remove(CecBoot.UBOOT_SCRIPT_FILE) except: Log.w("Could not delete CeC u-boot script")
def install(logical, physical): Log.i("physical address: %s | logical address: %s" %(physical, logical)) try: with open(CecBoot.UBOOT_SCRIPT_FILE, "w") as f: f.write(CecBoot.UBOOT_SCRIPT.format(logical=logical, physical=physical)) except: Log.w("Could not write bootloader script!")
def onMessage(self, payload, isBinary): if isBinary: Log.w("Binary message received: {0} bytes".format(len(payload))) else: msg = json.loads(payload, 'utf8') Log.d("> %s" % (msg)) self.onJSONMessage(msg)
def upnpMeta2DBMeta(meta): mapping = { Statics.META_ALBUM : eMediaDatabase.FIELD_ALBUM, #Statics.META_ALBUM_ART_URI : Statics.META_ALBUM_ART_URI, #TODO Statics.META_ARTIST : eMediaDatabase.FIELD_ARTIST, #Statics.META_BITRATE : Statics.META_BITRATE, #TODO Statics.META_DATE : eMediaDatabase.FIELD_DATE, Statics.META_DURATION : eMediaDatabase.FIELD_DURATION, Statics.META_GENRE : eMediaDatabase.FIELD_GENRE, #Statics.META_METATYPE : Statics.META_METATYPE, #TODO #Statics.META_RESOLUTION : Statics.META_RESOLUTION, #CONVERSION required! Statics.META_SIZE : eMediaDatabase.FIELD_SIZE, Statics.META_TITLE : eMediaDatabase.FIELD_TITLE, Statics.META_URI : eMediaDatabase.FIELD_FILE_URI, } meta_db = {} for key, value in meta.iteritems(): if key == Statics.META_RESOLUTION: try: width, height = value.split("x") meta_db[eMediaDatabase.FIELD_WIDTH] = width meta_db[eMediaDatabase.FIELD_HEIGHT] = height except: Log.w("'%s' is no valid resolution!" %(value)) else: newkey = mapping.get(key, None) if newkey: meta_db[newkey] = value return meta_db
def do_auth(self, msg): msg = self.validate(msg, self.AUTH_MESSAGE_SCHEMA) if not msg: return id = msg['id'] if 'session' in msg: session = msg['session'] if self.server.checkSession(session): Log.w("session: %s" %(session)) self._sessionId = session self.sendAuthOk() return else: self.sendAuthRequest() return token = msg['token'] login = b64decode(token) user, password = login.split(":", 1) if check_passwd(user, password): self._authenticated = True self.sendAuthOk() return self._authenticated = False self._failedAuthCount += 1 if self._failedAuthCount >= self.AUTH_FAIL_LIMIT: self._disconnect() result = {} self.sendError(id, 401, "Login failed! Wrong Credentials?")
def go(self): item = self["list"].getCurrent()[0] if item is None or not isinstance(item, NetworkItem): return self.hostcache_file = "%s%s.cache" %(eEnv.resolve("${sysconfdir}/enigma2/"), item.name) #Path to cache directory if item.type == NetworkItem.TYPE_HOST: # host entry selected if item.host in self.expanded: self.expanded.remove(item.host) self.updateNetworkList() return else: if os_path.exists(self.hostcache_file): print '[Networkbrowser] Loading userinfo cache from ',self.hostcache_file try: self.hostdata = load_cache(self.hostcache_file) self.passwordQuestion(False) return except: Log.w("error loading host cache!") if "smb" in item.services: self.session.openWithCallback(self.passwordQuestion, MessageBox, text=_("Do you want to enter a username and password for this host?\n"), default=False ) else: self.passwordQuestion(False) else: self.openMountEdit(item)
def _parse(self, tree, types, defaults): def setFromTag(parent, key, data, bool=False): elements = parent.findall(key) if len(elements): val = elements[0].text if bool: val = val == "True" if val != None: data[key] = val keys = [ 'active', 'hdd_replacement', 'ip', 'sharedir', 'sharename', 'options', 'username', 'password' ] bool_keys = ['active', 'hdd_replacement'] for i in range(0, len(types)): mounttype = types[i] for parent in tree.findall(mounttype): for mount in parent.findall("mount"): data = deepcopy(defaults[i]) try: for key in keys: setFromTag(mount, key, data, key in bool_keys) Log.d("%s share %s" % ( mounttype.upper(), data, )) if data["active"]: self._numActive += 1 self._mounts[data['sharename']] = data except Exception, e: Log.w("Error reading %s share: %s" % (mounttype.upper(), e))
def save(self): #c-ify vector = StringMapVector() pos = 1 for item in self._list: item = item[2] stringMap = StringMap() for k, v in item.iteritems(): stringMap[k] = str(v) stringMap[eMediaDatabase.FIELD_POS] = str(pos) pos += 1 vector.append(stringMap) db = eMediaDatabase.getInstance() res = db.savePlaylist(self._id, self._name, self._type, vector) error = res.error() if error: Log.w("Error saving playlist %s\n%s\n%s" % (self._id, res.errorDatabaseText(), res.errorDriverText())) return not error #if self._id <= 0: data = res.data() self._id = -1 if data and len(data) > 0: self._id = int(res.data()[0].get(eMediaDatabase.FIELD_ID, -1)) if self._id == -1: error = True self._valid = not error if not error: Log.i("Playlist '%s (%s)' saved" %(self._name, self._id)) else: Log.w("Error saving playlist!") return not error
def setZPosition(self, z): if not self.instance: self._zPosition = z else: Log.w( "setZPosition has to be called before applySkin (e.g. in __init__)!" )
def play(self, val, isUri): Log.w("%s %s" % (val, isUri)) if isUri: val = val.split("#") uri = val[0] if len(val) > 1: name = val[1] else: name = uri.split("/")[-1] if uri.startswith("file://") or uri.startswith("/"): #Local File if uri.lower().endswith(".ts"): serviceType = eServiceReference.idDVB elif uri.lower().endswith(".m2ts"): serviceType = eServiceReference.idM2TS else: serviceType = eServiceReference.idGST uri = uri.replace("file://", "") ref = eServiceReference(serviceType, 0, uri) else: ref = eServiceReference(eServiceReference.idURI, 0, uri) ref.setName(name) else: ref = eServiceReference(val) if not ref.valid(): return False if not self._player: self._player = self._session.openWithCallback( self._onPlayerClosed, MoviePlayer, ref) else: self._player.playService(ref) return True
def isBouquetAndOrRoot(csel): inBouquet = csel.getMutableList() is not None current_root = csel.getRoot() current_root_path = current_root and current_root.getPath() inBouquetRootList = current_root_path and current_root_path.find('FROM BOUQUET "bouquets.') != -1 #FIXME HACK Log.w("inBouquet: %s, current_root_path %s, inBouquetRootList %s" %(inBouquet, current_root_path, inBouquetRootList)) return (inBouquet, inBouquetRootList)
def addDefaultMenuItems(): mediaCore.addToMainMenu(( _("Music and Audiobooks"), AudioPlayer, { "key" : "music", "icon": getIcon("music"), "featuresPlaylist" : True } )) mediaCore.addToMainMenu(( _("Videos"), VideoPlayer, { "key" : "movies", "icon" : getIcon("movies"), "featuresPlaylist" : True } )) try: from Plugins.Extensions.PicturePlayer.plugin import picshow mediaCore.addToMainMenu(( _("Pictures"), picshow, { "key" : "pictures", "icon": getIcon("pictures"), "featuresPlaylist" : False } )) except: Log.w("PicturePlayer is not available")
def go(self): item = self["list"].getCurrent()[0] if item is None or not isinstance(item, NetworkItem): return self.hostcache_file = "%s%s.cache" % ( eEnv.resolve("${sysconfdir}/enigma2/"), item.name ) #Path to cache directory if item.type == NetworkItem.TYPE_HOST: # host entry selected if item.host in self.expanded: self.expanded.remove(item.host) self.updateNetworkList() return else: if os_path.exists(self.hostcache_file): print '[Networkbrowser] Loading userinfo cache from ', self.hostcache_file try: self.hostdata = load_cache(self.hostcache_file) self.passwordQuestion(False) return except: Log.w("error loading host cache!") if "smb" in item.services: self.session.openWithCallback( self.passwordQuestion, MessageBox, text= _("Do you want to enter a username and password for this host?\n" ), default=False) else: self.passwordQuestion(False) else: self.openMountEdit(item)
def _onLiveStreamDetails(self, html, callback): details_json = json.loads(html) Log.w(details_json) stream = None if details_json["stream"]: stream = TwitchStream(details_json["stream"]) callback(stream)
def readKeymap(filename): p = enigma.eActionMap.getInstance() assert p source = open(filename, 're') try: dom = xml.etree.cElementTree.parse(source) except: raise KeymapError("keymap %s not well-formed." % filename) keymap = dom.getroot() for cmap in keymap.findall("map"): context = cmap.attrib.get("context") assert context, "map must have context" advanced = None hasBle = False for device in cmap.findall("device"): devices = device.attrib.get("name") parseKeys(context, filename, p, devices, device) if devices.find("dreambox advanced remote control (native)") >= 0: advanced = device if devices.find("dreambox remote control (bluetooth le)") >= 0: hasBle = True if not hasBle and advanced: Log.w("BLE Keymap fallback to advanced remote for context %s" % (context, )) parseKeys(context, filename, p, "dreambox remote control (bluetooth le)", advanced) parseKeys(context, filename, p, "generic", cmap)
def setBlink(value=BLINK_DEFAULT): if value > 0xffffff or value < 0: Log.w( "LED blink has to be between 0x0 and 0xffffff (on, total, repeats)! Using default value (%x)" % (FrontPanelLed.BLINK_DEFAULT)) value = FrontPanelLed.BLINK_DEFAULT FrontPanelLed._write(FrontPanelLed.BLINK_PATH, value)
def reload(self): self._list = [] db = eMediaDatabase.getInstance() res = None if self._id < 0: #no @staticmethod get() used, probably.... self._valid = False self.listChanged() Log.w("A Playlist with the name/id %s/%s does not exist!" %(self._name, self._id)) return res = db.getPlaylistItemsById(self._id) if res and not res.error(): for data in res.data(): data = dict(data) file_uri = data.get(eMediaDatabase.FIELD_FILE_URI, None) if not file_uri: Log.w("Playlist entry invalid, %s" % data) continue if file_uri.endswith('.ts'): ref = eServiceReference(eServiceReference.idDVB, 0, file_uri) elif file_uri.endswith('.m2ts'): ref = eServiceReference(3, 0, file_uri) else: ref = eServiceReference(eServiceReference.idGST, 0, file_uri) self.add(ref, data, True) self._valid = True else: Log.i("Error loading playlist %s:%s\n%s\n%s" % (self._id, self._name, res.errorDatabaseText(), res.errorDriverText())) self._valid = False self.listChanged()
def setBrightness(value=BRIGHTNESS_DEFAULT): if value > 0xff or value < 0: Log.w( "LED brightness has to be between 0x0 and 0xff! Using default value (%x)" % (FrontPanelLed.BRIGHTNESS_DEFAULT)) value = FrontPanelLed.BRIGHTNESS_DEFAULT FrontPanelLed._write(FrontPanelLed.BRIGHTNESS_PATH, value)
def setColor(value=COLOR_DEFAULT): if value > 0xffffff or value < 0: Log.w( "LED color has to be between 0x0 and 0xffffff (r, g b)! Using default value (%x)" % (FrontPanelLed.COLOR_DEFAULT)) value = FrontPanelLed.COLOR_DEFAULT FrontPanelLed._write(FrontPanelLed.COLOR_PATH, value)
def play(self, val, isUri): Log.w("%s %s" %(val, isUri)) if not self.player: return if isUri: val = val.split("#") uri = val[0] if len(val) > 1: name = val[1] else: name = uri.split("/")[-1] if uri.startswith("file://") or uri.startswith("/"): #Local File if uri.lower().endswith(".ts"): serviceType = eServiceReference.idDVB elif uri.lower().endswith(".m2ts"): serviceType = eServiceReference.idM2TS else: serviceType = eServiceReference.idGST uri = uri.replace("file://", "") ref = eServiceReference(serviceType, 0, uri) else: ref = eServiceReference(eServiceReference.idURI, 0, uri) ref.setName(name) else: ref = eServiceReference(val) if not ref.valid(): return False self.stop() self.player.playStream(ref); return True
def _parse(self, tree, types, defaults): def setFromTag(parent, key, data, bool=False): elements = parent.findall(key) if len(elements): val = elements[0].text if bool: val = val == "True" if val != None: data[key] = val keys = ['active', 'hdd_replacement', 'ip', 'sharedir', 'sharename', 'options', 'username', 'password'] bool_keys = ['active', 'hdd_replacement'] for i in range(0, len(types)): mounttype = types[i] for parent in tree.findall(mounttype): for mount in parent.findall("mount"): data = deepcopy(defaults[i]) try: for key in keys: setFromTag(mount, key, data, key in bool_keys) Log.d("%s share %s" %(mounttype.upper(), data,)) if data["active"]: self._numActive += 1 #Workaround for nfs shares previously being saved without their leading / if mounttype == "nfs" and not data['sharedir'].startswith("/"): data['sharedir'] = "/%s" %(data['sharedir'],) self._mounts[data['sharename']] = data except Exception, e: Log.w("Error reading %s share: %s" %(mounttype.upper(), e))
def parseLive(self, data, service): data = data.replace('\\/', '/').replace('\\"', '"') urls = re.findall('hlsManifestUrl":"(http.*?\.m3u8)"(?:}|,)', data, re.S) if urls: uri = urls[-1] try: if not service.ptrValid(): Log.w("Service became invalid!") return if uri: if "hls_variant" in uri: getPage(uri).addCallback(self.parseData, service) else: uri = uri.replace('%252F', '%2F').replace( '%253D', '%3D').replace('%252B', '%2B').replace('%253B', '%3B') service.setResolvedUri(uri, eServiceReference.idDVB) else: service.failedToResolveUri() except: service.failedToResolveUri() else: service.failedToResolveUri()
def start(self): Log.w("Streamserver Watchdog is starting!") self._ping_conn = eStreamServer.getInstance().ping.connect( self._onPing) self._timer = eTimer() self._timer_conn = self._timer.timeout.connect(self._onTimeout) self._console = Console()
def reload(self): if not fileExists(self.CONFIG_FILE): return True try: with open(self.CONFIG_FILE) as f: self._config = {} for line in f: Log.i("parsing: %s" % (line,)) if line.startswith("#"): Log.d("skipping comment") continue try: num, data = line.strip().split("=") pairs = data.split(",") tuner_data = {} for pair in pairs: key, value = pair.split(":") tuner_data[key] = value self._config[int(num)] = TunerEntry(tuner_data) except Exception as e: Log.w(e) continue except Exception as e: Log.w(e) return False Log.i(self._config) return True
def setFade(value=FADE_DEFAULT): if value > 0xff or value < 0: value = FrontPanelLed.FADE_DEFAULT Log.w( "LED fade has to be between 0x0 and 0xff! Using default value (%x)" % (FrontPanelLed.FADE_DEFAULT)) FrontPanelLed._write(FrontPanelLed.FADE_PATH, value)
def _onUnboundRemoteKeyPressed(self, address, key): if key < 2 or key > 11 or key == self._lastUnboundKey: return self._lastUnboundKey = key Log.i("pressed %s on %s" %(key, address)) # compare device addresses device = self._currentInputDevice if not device or (address != device.address()): self._setPendingPin("") Log.w("wrong address! %s" %(address)) return pin = self._pins.get(address, None) if pin is None: self._setPendingPin("") return value = { 2 : 1, 3 : 2, 4 : 3, 5 : 4, 6 : 5, 7 : 6, 8 : 7, 9 : 8, 10 : 9, 11: 0 }.get(key, -1) pending = self._pendingPin.text.replace("-", "") if not pin.startswith(pending): self._setPendingPin(str(value)) else: self._setPendingPin("%s%s" %(pending, value)) if self._pendingPin.text == pin: self._pendingPin.text = _("PIN MATCH!") self._pins[device.address()] = self._genPin() self._connectDevice(device)
def hide(self, screen): if screen == self._currentToast: self._onTimeout() elif screen in self._queue: self._queue.remove(screen) else: Log.w("Screen is not a toast or already about to be deleted %s" %(screen,))
def getService(self): Log.i("self._playing=%s" % self._playing) if self._playing >= 0 and len(self.list) > self._playing: service = self._list[self._playing][0] if service: return service Log.w("NO SERVICE!") return None
def _onLocalChannelName(self, name): Log.w("uri=%s, name=%s" % (self._tubeUri, name)) if name and self._tubeUri: ref = eServiceReference(eServiceReference.idURI, 0, self._tubeUri) ref.setName(name) self._finish(ref) else: self._finish(None)
def _onArpScanData(self, data): for line in data.splitlines(): try: (address, mac) = line.split() except: Log.w('Unexpected line: %s' % line) else: self._arpscan_hosts.append(address)
def _errorReported(self, svcpath, error): Log.w("Network service %s report an error: %s" %(svcpath, error)) service = self._nm.getService(svcpath) svcname = svcpath if service: svcname = service.name() title = _("Network error on %s" %svcname) self.session.open(MessageBox, error, type=MessageBox.TYPE_ERROR, title=title)
def _onPlaylistSelected(self, entry): playlist = entry and entry[1] if playlist != None: self._playlist.load(playlist.id, playlist.name) config.plugins.mediacenter.audio.last_playlist_id.value = playlist.id config.plugins.mediacenter.audio.save() else: Log.w("ERROR LOADING PLAYLIST")
def _processResult(self, res): if res and not res.error(): data = res.data() self._setList(data) return elif res: Log.w("%s\n%s" %(res.errorDriverText(), res.errorDatabaseText())) self._setList([])
def fromXML(self, filesource=None, xml=None): if filesource: root = ET.parse(filesource).getroot() else: root = ET.fromstring(xml) for animation in root: try: attrib = animation.attrib key = attrib["key"] name = _(attrib.get("title", key)) internal = "internal" in attrib duration = int(attrib.get("duration", 0)) alpha = pos = size = matrix = 0 alpha_hide = pos_hide = size_hide = rotate_hide = 0 for item in animation: if item.tag == "alpha": alpha = self._buildFloatAnimation(item, duration, self._buildInterpolator(attrib)) elif item.tag == "position": pos = self._buildPointAnimation(item, duration, self._buildInterpolator(attrib)) elif item.tag == "size": size = self._buildSizeAnimation(item, duration, self._buildInterpolator(attrib)) elif item.tag == "rotate": matrix = self._buildMatrixAnimation(item, duration, self._buildInterpolator(attrib)) elif item.tag == "alpha_hide": alpha_hide = self._buildFloatAnimation(item, duration, self._buildInterpolator(attrib)) elif item.tag == "position_hide": pos_hide = self._buildPointAnimation(item, duration, self._buildInterpolator(attrib)) elif item.tag == "size_hide": size_hide = self._buildSizeAnimation(item, duration, self._buildInterpolator(attrib)) elif item.tag == "rotate_hide": rotate_hide = self._buildMatrixAnimation(item, duration, self._buildInterpolator(attrib)) if alpha or pos or size or matrix or alpha_hide or pos_hide or size_hide or rotate_hide: animset = eWindowAnimationSet.create() animset.setKey(key) animset.setName(name) animset.setInternal(internal) if alpha: animset.setAlpha(alpha) if pos: animset.setPos(pos) if size: animset.setSize(size) if matrix: animset.setMatrix(matrix) if alpha_hide: animset.setAlphaReverse(alpha_hide) if pos_hide: animset.setPosReverse(pos_hide) if size_hide: animset.setSizeReverse(size_hide) if rotate_hide: animset.setMatrixReverse(rotate_hide) eWindowAnimationManager.setAnimationSet(animset) except Exception as ex: Log.w("FAILED to parse an xml defined animation! %s: %s\n%s" %(animation.tag, animation.attrib, ex))
def addProvider(key, cls): Log.w("%s, %s" % (key, cls)) assert(isinstance(cls, ChannelListServiceProviderBase)) mykey = key i = 1 while ChannelListTubeServiceHelper.PROVIDER.has_key(mykey): mykey = "%s_%s" % (key, i) i += 1 ChannelListTubeServiceHelper.PROVIDER[mykey] = cls
def _request(self): ie_key = "TwitchStream" try: result = self._ytdl.extract_info(self._baseurl, ie_key=ie_key, download=False, process=True) url, fmt = self._selectFormat(result) self._onResult(True, url, fmt) except Exception as e: Log.w(e) self._onResult(False, None, -1)
def isBouquetAndOrRoot(csel): if csel.movemode: return (False, False) inBouquet = csel.getMutableList() is not None current_root = csel.getRoot() current_root_path = current_root and current_root.getPath() inBouquetRootList = current_root_path and current_root_path.find('FROM BOUQUET "bouquets.') != -1 #FIXME HACK Log.w("inBouquet: %s, current_root_path %s, inBouquetRootList %s" %(inBouquet, current_root_path, inBouquetRootList)) return (inBouquet, inBouquetRootList)
def _onResetAcknowledged(self, confirmed): if confirmed: if self._db.resetDatabase(): self.session.toastManager.showToast(_("Database has been reset successfully!")) Log.w(_("MediaDatabase RESET!")) self._reload() else: self.session.toastManager.showToast(_("Database reset FAILED!")) Log.w(_("MediaDatabase was NOT reset!"))
def _doPlay(self, service): if service: if not self.service or service.toCompareString() != self.service.toCompareString(): self.service = service self.play(False) else: Log.w("{%s} is already playing!" %service.toCompareString()) else: self.stop()
def removeTuner(self, index, tunerEntry): if index in self._config: tE = self._config[index] if tE.ipAddress == tunerEntry.ipAddress and tE.tunerType == tunerEntry.tunerType and tE.entryType == tunerEntry.entryType: del self._config[index] return True else: Log.w("%s not equal %s, so not deleted!") return False