def getActiveDnsText(self): nameservers = list(self._service.nameservers()) text = "" if nameservers: text = _("Active Nameservers:\n%s") %(", ".join(nameservers)) Log.i(text) return text
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 _checkPackageRestore(self): from Plugins.SystemPlugins.SoftwareManager.SoftwareTools import iSoftwareTools bak = self._backupFile if not fileExists(bak): Log.i("Package backup does not exist... (%s)" %(bak,)) return def doRestore(unused): available = [] for p in iSoftwareTools.available_packetlist: available.append(p[0]) with open(bak) as f: packagesAvailable = [] packagesMissing = [] for packagename in f: packagename = packagename.strip() if packagename in available: if not iSoftwareTools.installed_packetlist.has_key(packagename): packagesAvailable.append(packagename) Log.w("%s is NOT installed!" %packagename) else: packagesMissing.append(packagename) if packagesAvailable: self._session.open(PackageRestoreWizard, packagesAvailable, packagesMissing) self._moveBackupList() if iSoftwareTools.installed_packetlist and iSoftwareTools.available_packetlist: doRestore(None) else: def loadInstalled(unused): iSoftwareTools.startIpkgListInstalled(callback=doRestore) iSoftwareTools.startIpkgListAvailable(loadInstalled)
def _onPixmapReady(self, picInfo=None): Log.d(picInfo) self._picInfo = picInfo self._nextPixmap = self._picload.getData() if self._immediateShow: self._immediateShow = False self._onTimeout()
def play(self): Log.i() self.setSeekState(self.SEEK_STATE_PLAY, onlyGUI=True) self.__delayed_close_timer.stop() self.setMetadata() if self.shown: self.checkSkipShowHideLock()
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 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 __init__(self, *args, **kwargs): #we do have http basic auth, so whenever the user manages to load the page he is already authenticated self._authenticated = True self._failedAuthCount = 0 self._sessionId = None self._requestID = 0 Log.i("Protocol instance spawned!")
def _applyShare(self, data, callback): Log.i("activeMounts: %s" %(self._numActive,)) if data['active']: mountpoint = AutoMount.MOUNT_BASE + data['sharename'] if os_path.exists(mountpoint) is False: createDir(mountpoint) tmpsharedir = data['sharedir'].replace(" ", "\\ ").replace("$", "\\$") if data['mounttype'] == 'nfs': opts = self.sanitizeOptions(data['options'].split(',')) remote = '%s:/%s' % (data['ip'], tmpsharedir) harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="nfs") elif data['mounttype'] == 'cifs': opts = self.sanitizeOptions(data['options'].split(','), cifs=True) password = data['password'] username = data['username'].replace(" ", "\\ ") if password: username = data['username'].replace(" ", "\\ ") opts.extend([ 'username=%s' % (data['username']), 'password=%s' % (data['password']), ]) else: opts.extend(['guest']) opts.extend(['sec=ntlmv2']) remote = "//%s/%s" % (data['ip'], tmpsharedir) harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="cifs") else: mountpoint = AutoMount.MOUNT_BASE + data['sharename'] self.removeMount(mountpoint) if callback: callback(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 isAuthenticated(self, request): self._assignLocalNetworks(iNetworkInfo.getConfiguredInterfaces()) if request.transport: host = IPNetwork(request.transport.getPeer().host) #If streamauth is disabled allow all acces from localhost if not config.plugins.Webinterface.streamauth.value: if self._isLocalHost(host.ip): Log.i("Streaming auth is disabled - Bypassing Authcheck because host '%s' is local!" %host) return True if not config.plugins.Webinterface.localauth.value: if self._isLocalClient(host.ip): Log.i("Local auth is disabled - Bypassing Authcheck because host '%s' is local!" %host) return True # get the Session from the Request http_session = request.getSession().sessionNamespaces # if the auth-information has not yet been stored to the http_session if not http_session.has_key('authenticated'): if request.getUser() and request.getPassword(): http_session['authenticated'] = check_passwd(request.getUser(), request.getPassword()) else: http_session['authenticated'] = False #if the auth-information already is in the http_session else: if http_session['authenticated'] is False: http_session['authenticated'] = check_passwd(request.getUser(), request.getPassword() ) #return the current authentication status return http_session['authenticated']
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 addCurrentToPlaylist(self, play=False): Log.i("called") if self.canAddSelected(): if self._list.canDescend(): folder = self._list.getSelectedItem() if self.addFolderToPlaylist(folder): self.setStatus(self.getItemName(folder)) return True else: self.setStatus(self.getItemName(folder), error=True) else: item, itemName, ref, extra = self.getSelectedItemData() if not item: self.setStatus(_("Nothing to add...")) else: if self._list.isValidType(item): if play: fnc = self.addAndPlay else: fnc = self.addToPlaylist if fnc(ref, extra): self.setStatus(itemName) return True else: self.setStatus(itemName, error=True) else: if self._type == MediaCore.TYPE_AUDIO: self.setStatus(_("Cannot add this file. It's not audio!"), error=True) if self._type == MediaCore.TYPE_VIDEO: self.setStatus(_("Cannot add this file. It's no video!"), error=True) return False
def _applyShare(self, data, callback): Log.d() if data['active']: mountpoint = AutoMount.MOUNT_BASE + data['sharename'] Log.i("mountpoint: %s" %(mountpoint,)) createDir(mountpoint) tmpsharedir = data['sharedir'].replace(" ", "\\040") if data['mounttype'] == 'nfs': opts = self.sanitizeOptions(data['options'].split(',')) remote = '%s:%s' % (data['ip'], tmpsharedir) harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="nfs") elif data['mounttype'] == 'cifs': opts = self.sanitizeOptions(data['options'].split(','), cifs=True) if data['password']: opts.extend([ 'username=%s' % (data['username']), 'password=%s' % (data['password']), ]) else: opts.extend(['guest']) remote = "//%s/%s" % (data['ip'], tmpsharedir) harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="cifs") else: mountpoint = AutoMount.MOUNT_BASE + data['sharename'] self.removeMount(mountpoint) if callback: callback(True)
def _openGUI(self): if self.mimetype is None: self.mimetype = "video/mpeg" #picture are using the picviewer plugin if self.mimetype.startswith("image"): self.showPicture() else:#video or audio self._isPic = False if self._picView is not None: self._picView.close() #audio & video if not self._oldService: self._oldService = self.session.nav.getCurrentlyPlayingServiceReference() if self.mimetype.startswith('audio'): if self._audioGUI == None: Log.i("Starting AudioGUI") self._audioGUI = self.session.open(AudioGUI, self) self._audioGUI.onClose.append(self._reset) self._currentGui = self._audioGUI return self._audioGUI elif self.mimetype.startswith('video'): #if True: if self._videoGUI == None: Log.i("Starting VideoGUI") self._videoGUI = self.session.open(VideoGUI, self) self._videoGUI.onClose.append(self._reset) self._currentGui = self._videoGUI return self._videoGUI
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 openMountEdit(self, item): if item and item.type != NetworkItem.TYPE_HOST: mounts = iAutoMount.getMounts() self.sharecache_file = None if item.type == NetworkItem.TYPE_NFS: # share entry selected data = iAutoMount.DEFAULT_OPTIONS_NFS if item.type == NetworkItem.TYPE_SMB: # share entry selected data = iAutoMount.DEFAULT_OPTIONS_CIFS self.sharecache_file = eEnv.resolve("${sysconfdir}/enigma2/") + item.name.strip() + '.cache' #Path to cache directory if os_path.exists(self.sharecache_file): print '[Networkbrowser] Loading userinfo from ',self.sharecache_file try: self.hostdata = load_cache(self.sharecache_file) data['username'] = self.hostdata['username'] data['password'] = self.hostdata['password'] except: pass data['active'] = True data['ip'] = item.host data['sharename'] = item.name data['sharedir'] = item.path for sharename, sharedata in mounts.items(): if sharedata['ip'] == item.host and sharedata['sharedir'] == item.path: data = sharedata break Log.i(data) self.session.openWithCallback(self.MountEditClosed,AutoMountEdit, self.skin_path, data)
def addToPlaylist(self, ref, extra=None): if ref and ref.valid(): self._player.addToPlaylist(ref, extra) return True else: Log.i("ERROR: No valid ref!") return False
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 _onCredentialsPollBodyReady(self, body): if self._canceled: Log.d("Auth Request canceled") return result = json.loads(body) error = result.get("error", None) if error: if error == "authorization_pending": print "not ready, yet" reactor.callLater(self._user_code.interval, self._pollForResult) elif error == "slow_down": print "too fast, slowing down" self._device_code.interval = self._device_code.interval * 2 elif error == "expired_token": self._onError(self.ERROR_CREDENTIALS_REQUEST_EXPIRED) else: print result self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error) elif "access_token" in result: access_token = result.get("access_token") refresh_token = result.get("refresh_token") token_expiry = str( int(time()) + int(result.get("expires_in")) ) self._credentials = OAuth2Credentials(access_token, self.CLIENT_ID, self.CLIENT_SECRET, refresh_token, token_expiry, self.AUTH_REQUEST_URI, self.USER_AGENT) for fnc in self.onCredentialsReady: fnc(self._credentials) else: self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error)
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 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 resolve(self, service, uri): Log.i(uri) watch_url = None try: uri = uri.split("://")[1] uri = uri.split("/") if uri[0] == "live": watch_url = "https://youtube.com/user/%s/live" %(uri[1],) else: video_id = uri[0] watch_url = "https://youtube.com/watch?v=%s" % (video_id,) except: pass def onUrlReady(uri, format): Log.d("%s (%s)" %(uri, format)) try: if not service.ptrValid(): Log.w("Service became invalid!") return if uri: if VideoUrlRequest.isHls(format): service.setResolvedUri(uri, eServiceReference.idDVB) else: service.setResolvedUri(uri, eServiceReference.idGST) else: service.failedToResolveUri() except: service.failedToResolveUri() Log.i(watch_url) if watch_url: VideoUrlRequest(watch_url, [onUrlReady], async=True) else: service.failedToResolveUri() return True
def sendJSON(self, msg): if not msg.has_key("id"): self._requestID += 1 msg['id'] = self._requestID msg = json.dumps(msg).encode('utf8') Log.d("< %s" % (msg)) self.sendMessage(msg)
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 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 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 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 reload(self, force=True): self._isReloading = True if force: self._ipv4Changed = False self._ipv6Changed = False if not self._ipv6Changed: ip4 = self._service.ipv4() if not dict(ip4): ip6 = self._service.ipv4Config() self._config_ip4_method.value = ip4.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF) self._config_ip4_address.value = toIP4List( ip4.get("Address", "0.0.0.0") ) self._config_ip4_mask.value = toIP4List( ip4.get(eNetworkService.KEY_NETMASK, "0.0.0.0") ) self._config_ip4_gw.value = toIP4List( ip4.get(eNetworkService.KEY_GATEWAY, "0.0.0.0") ) if not self._ipv6Changed: ip6 = self._service.ipv6() Log.i("%s / %s" %(dict(ip6), dict(self._service.ipv6Config())) ) if not dict(ip6): ip6 = self._service.ipv6Config() self._config_ip6_method.value = ip6.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF) self._config_ip6_address.value = ip6.get(eNetworkService.KEY_ADDRESS, "::") self._config_ip6_prefix_length.value = ord( ip6.get(eNetworkService.KEY_PREFIX_LENGTH, chr(1)) or chr(1) ) self._config_ip6_gw.value = ip6.get(eNetworkService.KEY_GATEWAY, "::") self._config_ip6_privacy.value = ip6.get(eNetworkService.KEY_PRIVACY, eNetworkService.IPV6_PRIVACY_DISABLED) self._isReloading = False self._changed(None)
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 _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) except Exception as e: Log.w(e) self._onResult(False, None, -1)
def startCmd(self, cmd, args=None): self.args = args if cmd == self.CMD_UPDATE: self.runCmd("update") self.update_done = True elif cmd == self.CMD_UPGRADE: append = "" if args["use_maintainer"]: append += " --force-maintainer" if args["test_only"]: append += " -test" self.runCmd("upgrade" + append) elif cmd == self.CMD_LIST: if args['installed_only']: self.runCmd("list-installed") else: self.runCmd("list") elif cmd == self.CMD_INSTALL: if args['package'].startswith('/'): self.preInstCmd = eConsoleAppContainer() self.preInstCmd_appClosed_conn = self.preInstCmd.appClosed.connect( self.preInstCmdFinished) self.preInstCmd_dataAvail_conn = self.preInstCmd.dataAvail.connect( self.cmdData) Log.i( "A local package is to be installed: executing apt-get update before doing so" ) self.preInstCmd.execute("apt-get update") else: self.runCmd("install " + args['package']) elif cmd == self.CMD_REMOVE: append = "" if args["autoremove"]: append = "--autoremove " self.runCmd("remove " + append + args['package']) self.setCurrentCommand(cmd)
def resolve(self, service, uri): Log.i(uri) uri = uri.replace('mp_euronews://','').lower().strip() if uri == 'en': uri = 'www' uri = "https://%s.euronews.com/api/watchlive.json" % uri def onUrlReady(uri): try: if not service.ptrValid(): Log.w("Service became invalid!") return if uri: service.setResolvedUri(uri, eServiceReference.idGST) else: service.failedToResolveUri() except: service.failedToResolveUri() if uri: twAgentGetPage(uri).addCallback(self.parseLive, service) else: service.failedToResolveUri() return True
def resolve(self, service, uri): Log.i(uri) uri = uri.replace('mp_hlsproxy://','').replace('mp_hlsp://','') def onUrlReady(uri): try: if not service.ptrValid(): Log.w("Service became invalid!") return if uri: self._bitrate = self._getBandwidth() path = config_mp.mediaportal.storagepath.value ip = "127.0.0.1" #".".join(str(x) for x in config_mp.mediaportal.hls_proxy_ip.value) import uuid uid = uuid.uuid1() uri = 'http://%s:%d/?url=%s&bitrate=%d&path=%s&uid=%s' % (ip, mp_globals.hls_proxy_port, uri, self._bitrate, path, uid) service.setResolvedUri(uri, eServiceReference.idGST) else: service.failedToResolveUri() except: service.failedToResolveUri() onUrlReady(uri) return True
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 _onData(self, data): Log.i(data) pre = _("Working...") isVerifying = False isFlashing = False if data.strip().startswith("flashing"): pre = _("Flashing firmware...") isFlashing = True elif data.strip().startswith("verifying"): pre = _("Verifying firmware...") isVerifying = True if self._isFrontProcessor: pre += _("\n\nDO NOT TURN OFF YOUR DREAMBOX!") if pre: if isFlashing or isVerifying: splitted = data.split(" ") address = splitted[3] if isFlashing: self.blockFlashed += 1 text = _("%s\n\n%03d blocks written (%s)") % ( pre, self.blockFlashed, address) elif isVerifying: self.blocksVerified += 1 text = _( "%s\n\n%03d blocks written\n%03d blocks verified (%s)" ) % (pre, self.blockFlashed, self.blocksVerified, address) else: text = "%s\n\n%s" % (pre, data) else: text = pre self["Text"].setText(text) self["text"].setText(text) if data.find("success:") >= 0: self._success = True
def onUrlReady(uri): try: if not service.ptrValid(): Log.w("Service became invalid!") return if uri: if ".m3u8" in 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.setResolvedUri(uri, eServiceReference.idGST) else: service.failedToResolveUri() except: service.failedToResolveUri()
def getNetworkIPs(self): Log.w() info = None sharelist = [] if len(self._ip): strIP = "%s.0/24" %( ".".join(self._ip[0:3]) ) info = [x for x in netscan.netInfo(strIP) if x[2] != '.'.join(self._ip)] Log.i(info) else: Log.w("IP FAULTY! %s" %self._ip) reactor.callFromThread(self._onNetworkIPsReady, info)
def _getTunerCount(self, ip, type): if not ip in self._check_count_lut: Log.w("ip not in lut!") return 0 host_entry = self._check_count_lut[ip] if not type in host_entry: Log.w("type not in lut!") return 0 count = host_entry[type] Log.w(count) return count
def _reloadFromDiskCache(self): f = resolveFilename(SCOPE_CONFIG, "%s/%s" % (self.CACHE_DIR_NAME, "genres")) if fileExists(f): Log.w("Reloading services from disk cache") data = None with open(f) as fdesc: data = json.load(fdesc) for key, data in data.iteritems(): genre = StalkerGenre(data) self._genres[key] = genre self._allServices.update(genre.services) Log.i("Loaded genre %s from cache!" % (genre, )) self._isFinishedLoadingGenres = True self._isFinishedLoadingChannels = True Log.w("Loaded %s services from cache!" % (len(self._allServices, ))) else: Log.w("No Cache available!")
def _mainMenuItemSanityCheck(self, item): #check if the given item is a list like this: ( "Menu Text", ScreenSubclass, { "key" : "menukey", "iconpath" : "blabla", featuresPlaylist: True/False } ) if len(item) < 3: Log.i("item doesn't have enough entries") return False if not issubclass(item[1], Screen): Log.i("item[1] is not a Screen") return False if not isinstance(item[2], dict): Log.i("item[2] is NOT a dict") return False return True
def writeToDatabase(self, imageResultDict): ''' information write to database :param infoDict: :return: ''' if imageResultDict is None: logger.error("imageResultDict is None") return None try: result = self._database.queryIsExist("image", {"md5": imageResultDict["md5"]}) progressBar = self.computeProgressBar(self.completed, self.totalDownload) if not result: logger.info("Image completed: {progressBar: <10}".format(progressBar=progressBar) + \ "Title:{title}".format(title=imageResultDict['title']), level="ALL") self._database.insert("image", imageResultDict) except BaseException: logger.error(traceback.format_exc()) logger.error("An error occurred in the function ---> wirteToDataBase") return None
def getNetworkIPs(self, host): Log.i("Detecting availablility of NFS or SMB services on host %s" % host) item = None services = [] if self._probeTcpPort(host, 445) or self._probeTcpPort(host, 139): Log.i("Found SMB server on %s" % host) services.append("smb") if rpcinfo.progping('udp', host, 'nfs') or rpcinfo.progping( 'tcp', host, 'nfs'): Log.i("Found NFS server on %s" % host) services.append("nfs") if services: hostname = self._lookupHostname(host) item = NetworkItemHost(hostname, host, services) Log.i(item) reactor.callFromThread(self._onNetworkIPsReady, item)
def _onSharesApplied(self): Log.d() for sharename, data in self._mounts.items(): mountpoint = AutoMount.MOUNT_BASE + sharename Log.d("mountpoint: %s" % (mountpoint, )) if os_path.exists(mountpoint): if os_path.ismount(mountpoint): Log.d("'%s' is mounted" % (mountpoint, )) data['isMounted'] = True desc = data['sharename'] if data['hdd_replacement']: #hdd replacement hack self._linkAsHdd(mountpoint) harddiskmanager.addMountedPartition(mountpoint, desc) else: Log.d("'%s' is NOT mounted" % (mountpoint, )) sharename = self._mounts.get(data['sharename'], None) if sharename: data['isMounted'] = False if os_path.exists(mountpoint): if not os_path.ismount(mountpoint): removeDir(mountpoint) harddiskmanager.removeMountedPartition(mountpoint)
def bodyCB(body): if isinstance(body, Failure): if isinstance(body.value, PartialDownloadError): body = body.value.response else: Log.w(body) callback(None) return try: result = json.loads(unicode(body)) Log.d(result) callback(result) except Exception as e: Log.w(body) callback(None)
def getDetailsByRef(self, ref): path = ref.getPath() #if we get only a reference or an entry with "extra data" but no file id yet we ask the database to enrich the data if path.startswith("/"): Log.i("Asking database for details!") db = eMediaDatabase.getInstance() res = db.getFileByPath(path) if res and res.data() and not res.error() : return dict(res.data()[0]) else: Log.i("ERROR: %s :: %s" %(res.errorDatabaseText(), res.errorDriverText())) else: Log.i("%s is not an absolute local path, skip querying the database" % path) return None
def save(self): if self._ipv4Changed: Log.i("IPv4 Changed, saving!") if self._config_ip4_method.value == eNetworkService.METHOD_MANUAL: ip4_config = { eNetworkService.KEY_METHOD : self._config_ip4_method.value, eNetworkService.KEY_ADDRESS : toIP4String(self._config_ip4_address), eNetworkService.KEY_NETMASK : toIP4String(self._config_ip4_mask), eNetworkService.KEY_GATEWAY : toIP4String(self._config_ip4_gw), } else: ip4_config = { eNetworkService.KEY_METHOD : self._config_ip4_method.value } Log.i(ip4_config) self._service.setIpv4Config(ip4_config) if self._ipv6Changed: Log.i("IPv6 Changed, saving!") if self._config_ip6_method.value == eNetworkService.METHOD_MANUAL: ip6_config = { eNetworkService.KEY_METHOD : self._config_ip6_method.value, eNetworkService.KEY_ADDRESS : self._config_ip6_address.value, eNetworkService.KEY_PREFIX_LENGTH : self._config_ip6_prefix_length.value, eNetworkService.KEY_GATEWAY : self._config_ip6_gw.value, eNetworkService.KEY_PRIVACY : self._config_ip6_privacy.value, } else: val = self._config_ip6_method.value #avoid config element overhead here #one can not configure 6to4, it will automatically be applied by connman if applicable -> change it to auto if val == eNetworkService.METHOD_6TO4: val = eNetworkService.METHOD_AUTO ip6_config = { eNetworkService.KEY_METHOD : val } if val != eNetworkService.METHOD_OFF: ip6_config[eNetworkService.KEY_PRIVACY] = self._config_ip6_privacy.value Log.i(ip6_config) self._service.setIpv6Config(ip6_config)
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 onCheckDevices(self, allDevices = False): for d in self._devices.values(): if not allDevices: if not d.logicalAddress in (eCec.ADDR_AUDIO_SYSTEM, eCec.ADDR_TV): return commands = [] if allDevices and d.physicalAddress == (0xff,0xff): Log.i("requesting physical address of %s" %(d.logicalAddress,)) commands.append(eCec.MSG_GIVE_PHYS_ADDR) if d.vendor == eCec.VENDOR_UNKNOWN: Log.i("requesting vendor of %s" %(d.logicalAddress)) commands.append(eCec.MSG_GIVE_DEVICE_VENDOR_ID) if allDevices and not d.name: Log.i("requesting name of %s" %(d.logicalAddress,)) commands.append(eCec.MSG_GIVE_OSD_NAME) commands.append(eCec.MSG_GIVE_DEVICE_POWER_STATUS) [self.send(d.logicalAddress, cmd) for cmd in commands]
def _onPictureReady(self, nothing): Log.i("file=%s" %self._imageFile) try: from PictureGUI import PictureGUI path = "%s/" %( "/".join( self._imageFile.split("/")[0:-1] ) ) name = self._imageFile.split("/")[-1] filelist = [((self._imageFile, False), None)] Log.i("path=%s, name=%s, filelist=%s" %(path, name, filelist)) if self._picView is None: self._picView = self.session.open(PictureGUI, filelist, 0, path) self._currentGui = self._picView else: self._picView.setFileList(filelist, 0, path) self._picView.onClose.append(self._reset) except Exception as e: Log.w(e) msgbox = self.session.open(MessageBox, _("Showing a picture from '%s' failed!") %self.uri, type=MessageBox.TYPE_ERROR, timeout=20) msgbox.setTitle( _("UPnP/DLNA - Failed to show picture") )
def _applyUriParameters(self, params): ref = str(params.get(self.URI_PARAM_REF, [""])[0]) ref = eServiceReference(ref) if ref.valid(): Log.i("setting encoder service to %s" % ref.toString()) self.setEncoderService(ref) vb = params.get(self.URI_PARAM_VIDEO_BITRATE, [-1])[0] if vb > 0: try: Log.i("setting video bitrate to %s" % vb) self.videoBitrate = int(vb) except: pass ab = params.get(self.URI_PARAM_AUDIO_BITRATE, [-1])[0] if ab > 0: try: Log.i("setting audio bitrate to %s" % ab) self.audioBitrate = int(ab) except: pass
def _onMediaDeviceDectected(self, device): if device.udn in self.__mediaDevices: return self.__mediaDevices[device.udn] = device device_type = device.get_friendly_device_type() if device_type == self.DEVICE_TYPE_SATIP_SERVER: Log.i("New SAT>IP Server found: %s (%s - %s)" % (device.get_friendly_name(), device.get_friendly_device_type(), device.get_satipcap())) for fnc in self.onSatIpServerDetected: fnc(device) elif device_type == self.DEVICE_TYPE_DREAMBOX: Log.i( "New Dreambox found: %s (%s - %s)" % (device.get_friendly_name(), device.get_friendly_device_type(), device.get_presentation_url())) for fnc in self.onDreamboxDetected: fnc(device) else: Log.i("New Device found: %s (%s)" % (device.get_friendly_name(), device.get_friendly_device_type()))
def checkUpgrade(self): if config.misc.firstrun.value: return requiresSetup = False if config.timezone.version.value == 0: try: currentZone = self.getCurrentTimezone() Log.w(currentZone) if currentZone.endswith('Istanbul'): Log.w( "Current timezone is Europe/Istanbul. User needs to verify!" ) requiresSetup = True except: pass config.timezone.version.value = 1 if config.timezone.version.value == 1: requiresSetup = True config.timezone.version.value = 2 if requiresSetup: Log.w("Upgraded to new timezone handling - Require setup!") Notifications.AddNotification(Setup, "timezone") config.timezone.version.save()
def _startEncoderService(self, service): if not self.isAnyEnabled() \ or int(config.streamserver.source.value) != self.INPUT_MODE_BACKGROUND \ or self.sourceState <= eStreamServer.SOURCE_STATE_READY: self.stopEncoderService() Log.i( "Streamserver disabled, not in TV Service mode or no client connected, will not allocate service (%s, %s, %s, %s, %s)" % (config.streamserver.rtsp.enabled.value, config.streamserver.hls.enabled.value, config.streamserver.mediator.enabled.value, config.streamserver.source.value, self._streamServer.sourceState())) return self.ENCODER_SERVICE_INVALID_MODE ref = self._getRef(service) if ref: cur_ref = self._encoderService cur_ref = cur_ref and cur_ref.info() cur_ref = cur_ref and cur_ref.getInfoString( iServiceInformation.sServiceref) if cur_ref == ref.toString(): Log.i( "ignore request to play already running background streaming service (%s)" % cur_ref) return self.ENCODER_SERVICE_ALREADY_ACTIVE else: self.stopEncoderService() self._encoderService = eServiceCenter.getInstance().play(ref) if self._encoderService and not self._encoderService.setTarget( self.ENCODER_TARGET): Log.i("Starting encoder service [%s]!" % (service.toCompareString())) self._encoderService.start() return self.ENCODER_SERVICE_SET else: return self.ENCODER_SERVICE_INSUFFICIENT_RESOURCES return self.ENCODER_SERVICE_INVALID
def _onReady(self, logicalAddress, physicalAddress, force=False): oldPhysical = self._physicalAddress self._logicalAddress = logicalAddress self._physicalAddress = tuple(physicalAddress) if self._activeSource == oldPhysical and self.isReady(): self.handleActiveSource(physicalAddress) Log.i("Physical address: %s # Logical address: %s" %(self.physicalToString(self._physicalAddress), self._logicalAddress)) if not self.getDevice(eCec.ADDR_TV): self.givePhysicalAddress(eCec.ADDR_TV) if self.isReady(): if oldPhysical != self._physicalAddress or force: self.reportPhysicalAddress() self.givePhysicalAddress(eCec.ADDR_AUDIO_SYSTEM) self.giveSystemAudioModeStatus() if isPendingOrVisibleNotificationID("Standby"): Log.i("Standby pending. Doing nothing") return if Standby.inStandby == None: self.powerOn() else: Log.i("Standby, not waking up.")
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(eServiceReference.idM2TS, 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 log(self, data): Log.w("# %s" % (data,))
def stopEncoderService(self): if self._encoderService: Log.i("Stopping encoder service (%s)" % (self._currentService.toCompareString())) self._encoderService.stop() self._encoderService = None
def _onDBusError(self, error): Log.w("DBUS ERROR! %s" % (error, )) Notifications.AddPopup("%s" % (error, ), MessageBox.TYPE_ERROR, -1, domain=NOTIFICATION_DOMAIN_STREAMSERVER)
def _onUriParametersChanged(self, parameters): Log.i("%s" % (parameters)) params = parse_qs(parameters) self._applyUriParameters(params) for fnc in self.onUriParametersChanged: fnc(params)