def getServiceProvider(self, ref): if isinstance(ref, eServiceReference): str_ref = ref.toString() if str_ref.startswith('1:134:'): ref = getBestPlayableServiceReference(ref, eServiceReference()) if not ref: return _("N/A") typestr = ref.getData(0) in (2,10) and service_types_radio or service_types_tv pos = typestr.rfind(':') rootstr = '%s (channelID == %08x%04x%04x) && %s FROM PROVIDERS ORDER BY name'%(typestr[:pos+1], ref.getUnsignedData(4), # NAMESPACE ref.getUnsignedData(2), # TSID ref.getUnsignedData(3), # ONID typestr[pos+1:]) provider_root = eServiceReference(rootstr) serviceHandler = eServiceCenter.getInstance() providerlist = serviceHandler.list(provider_root) if not providerlist is None: while True: provider = providerlist.getNext() if not provider.valid(): break if provider.flags & eServiceReference.isDirectory: servicelist = serviceHandler.list(provider) if not servicelist is None: while True: service = servicelist.getNext() if not service.valid(): break if service == ref: info = serviceHandler.info(provider) name = info and info.getName(provider) or _("Unknown") return name return _("N/A")
def buildSTBchannellist(BouquetName=None): chlist = None chlist = [] mask = eServiceReference.isMarker | eServiceReference.isDirectory logDebug("SPC: read STB Channellist..") tvbouquets = getTVBouquets() logDebug("SPC: found %s bouquet: %s" % (len(tvbouquets), tvbouquets)) if not BouquetName: for bouquet in tvbouquets: bouquetlist = [] bouquetlist = getServiceList(bouquet[0]) for (serviceref, servicename) in bouquetlist: playable = not (eServiceReference(serviceref).flags & mask) if playable: chlist.append((servicename, re.sub("::.*", ":", serviceref), unifyChannel(servicename))) else: for bouquet in tvbouquets: if bouquet[1] == BouquetName: bouquetlist = [] bouquetlist = getServiceList(bouquet[0]) for (serviceref, servicename) in bouquetlist: playable = not (eServiceReference(serviceref).flags & mask) if playable: chlist.append((servicename, re.sub("::.*", ":", serviceref), unifyChannel(servicename))) break return chlist
def addFile(self, param, doPlay=False): # TODO: fix error handling mp = self.tryOpenMP() if mp is None: return (False, "Mediaplayer not installed") file = param["file"] doAdd = False if param["root"] == "playlist" else True if not file: return (False, "Missing or invalid parameter file") ref = eServiceReference(file) if not ref.valid(): if not os_path.isfile(file): return (False, "'%s' is neither a valid reference nor a valid file" % file) ref = eServiceReference(4097, 0, file) if doAdd: mp.playlist.addFile(ref) if doPlay: mp.playServiceRefEntry(ref) mp.playlist.updateList() if doPlay: return (True, "Playback of '%s' started" % (file)) else: return (True, "'%s' has been added to playlist" % (file))
def updateEventCache(self): try: from Screens.ChannelSelection import service_types_tv from Components.Sources.ServiceList import ServiceList bouquetlist = ServiceList( eServiceReference(service_types_tv + ' FROM BOUQUET "bouquets.tv" ORDER BY bouquet'), validate_commands=False, ).getServicesAsList() for bouquetitem in bouquetlist: serviceHandler = eServiceCenter.getInstance() list = serviceHandler.list(eServiceReference(str(bouquetitem[0]))) services = list and list.getContent("S") search = ["IBDCTSERNX"] if services: # It's a Bouquet search.extend([(service, 0, -1) for service in services]) events = self.epgcache.lookupEvent(search) for eventinfo in events: # 0 eventID | 4 eventname | 5 short descr | 6 long descr | 7 serviceref | 8 channelname self.eventcache.append((eventinfo[0], eventinfo[7], eventinfo[8], eventinfo[4])) except Exception: print "[TVCharts Plugin] Error creating eventcache!"
def serviceList(self, param): print "serviceList: ", param sRef = str(param["sRef"]) bouquet = str(param["bouquet"]) self.sRefFound = 0 if bouquet == '': returnList = [] bouquet = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet' ref = eServiceReference(bouquet) self.servicelist = ServiceList(ref, command_func=self.getServiceList, validate_commands=False) self.servicelist.setRoot(ref) for (ref2, name) in self.servicelist.getServicesAsList(): part = self.serviceListOne(ref2, sRef) if part: returnList = returnList + [["-- " + name + " --", "<" + name + ">", ""]] + part bouquet = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.radio" ORDER BY bouquet' ref = eServiceReference(bouquet) self.servicelist = ServiceList(ref, command_func=self.getServiceList, validate_commands=False) self.servicelist.setRoot(ref) for (ref2, name) in self.servicelist.getServicesAsList(): part = self.serviceListOne(ref2, sRef) if part: returnList = returnList + [["-- " + name + " --", "<" + name + ">", ""]] + part else: returnList = self.serviceListOne(bouquet, sRef) if self.sRefFound == 0 and sRef != '': returnListPart = ["Inserted", sRef, "selected"] returnList = [returnListPart] + returnList #print returnList return returnList
def addMarkerToBouquet(self, param): print "[WebComponents.BouquetEditor] addMarkerToBouquet with param = ", param sBouquetRef = param["sBouquetRef"] if sBouquetRef is None: return (False, "No bouquet given!") name = None if "Name" in param: if param["Name"] is not None: name =param["Name"] if name is None: return (False, "No marker-name given!") sRefBefore = eServiceReference() if "sRefBefore" in param: if param["sRefBefore"] is not None: sRefBefore = eServiceReference(param["sRefBefore"]) bouquet_ref = eServiceReference(sBouquetRef) mutableBouquetList = self.getMutableList(bouquet_ref) cnt = 0 while mutableBouquetList: service_str = '1:64:%d:0:0:0:0:0:0:0::%s'%(cnt, name) ref = eServiceReference(service_str) if not mutableBouquetList.addService(ref, sRefBefore): mutableBouquetList.flushChanges() self.setRoot(sBouquetRef) return (True, "Marker added.") cnt+=1 return (False, "Internal error!")
def restoreFiles(self, param): tarFilename = param backupFilename = tarFilename #join(self.BACKUP_PATH, tarFilename) if exists(backupFilename): if 'tmp/.webouquetedit' in check_output(['tar', '-tf', backupFilename]): eDVBDB.getInstance().removeServices() files = [] files += self.getPhysicalFilenamesFromServicereference(eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet')) files += self.getPhysicalFilenamesFromServicereference(eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.radio" ORDER BY bouquet')) for bouquetfiles in files: if exists(bouquetfiles): remove(bouquetfiles) call(['tar', '-xvf', backupFilename, '-C', '/']) nimmanager.readTransponders() eDVBDB.getInstance().reloadServicelist() eDVBDB.getInstance().reloadBouquets() infoBarInstance = InfoBar.instance if infoBarInstance is not None: servicelist = infoBarInstance.servicelist root = servicelist.getRoot() currentref = servicelist.getCurrentSelection() servicelist.setRoot(root) servicelist.setCurrentSelection(currentref) remove(backupFilename) return (True, "Bouquet-settings were restored successfully") else: return (False, "Error, %s was not created with WebBouquetEditor..." % backupFilename) else: return (False, "Error, %s does not exists, restore is not possible..." % backupFilename)
def moveService(self, param): print "[WebComponents.BouquetEditor] moveService with param = ", param sBouquetRef = param["sBouquetRef"] if sBouquetRef is None: return (False, "No bouquet given!") sRef = None if "sRef" in param: if param["sRef"] is not None: sRef =param["sRef"] if sRef is None: return (False, "No service given!") position = None if "position" in param: if param["position"] is not None: position = int(param["position"]) if position is None: return (False, "No position given!") mutableBouquetList = self.getMutableList(eServiceReference(sBouquetRef)) if mutableBouquetList is not None: ref = eServiceReference(sRef) mutableBouquetList.moveService(ref, position) mutableBouquetList.flushChanges() self.setRoot(sBouquetRef) return (True, "Service %s moved." % self.getName(ref)) return (False, "Service can not be moved.")
def addServiceToBouquet(self, param): print "[WebComponents.BouquetEditor] addService with param = ", param sBouquetRef = param["sBouquetRef"] if sBouquetRef is None: return (False, "No bouquet given!") sRef = None if "sRef" in param: if param["sRef"] is not None: sRef =param["sRef"] if sRef is None: return (False, "No service given!") sName = None if "Name" in param: if param["Name"] is not None: sName =param["Name"] sRefBefore = eServiceReference() if "sRefBefore" in param: if param["sRefBefore"] is not None: sRefBefore = eServiceReference(param["sRefBefore"]) bouquetRef = eServiceReference(sBouquetRef) mutableBouquetList = self.getMutableList(bouquetRef) if mutableBouquetList is not None: ref = eServiceReference(sRef) if sName: ref.setName(sName) if not mutableBouquetList.addService(ref, sRefBefore): mutableBouquetList.flushChanges() self.setRoot(sBouquetRef) return (True, "Service %s added." % self.getName(ref)) else: bouquetName = self.getName(bouquetRef) return (False, "Service %s already exists in bouquet %s." % (self.getName(ref), bouquetName)) return (False, "This service can not be added.")
def setCenterDvbSubs(self, configElement): if configElement.value: eDVBDB.getInstance().addFlag(eServiceReference(self.service_string), self.FLAG_CENTER_DVB_SUBS) config.subtitles.dvb_subtitles_centered.value = True else: eDVBDB.getInstance().removeFlag(eServiceReference(self.service_string), self.FLAG_CENTER_DVB_SUBS) config.subtitles.dvb_subtitles_centered.value = False
def removeService(self, param): print "[WebComponents.BouquetEditor] removeService with param = ", param sBouquetRef = param["sBouquetRef"] if sBouquetRef is None: return (False, "No bouquet given!") sRef = None if "sRef" in param: if param["sRef"] is not None: sRef =param["sRef"] if sRef is None: return (False, "No service given!") ref = eServiceReference(sRef) if ref.flags & eServiceReference.isGroup: # check if service is an alternative, if so delete it with removeBouquet new_param = {} new_param["sBouquetRef"] = sRef new_param["mode"] = None # of no interest when passing BouquetRefRoot new_param["BouquetRefRoot"] = sBouquetRef returnValue = self.removeBouquet(new_param) if returnValue[0]: return (True, "Service %s removed." % self.getName(ref)) else: bouquetRef = eServiceReference(sBouquetRef) mutableBouquetList = self.getMutableList(bouquetRef) if mutableBouquetList is not None: if not mutableBouquetList.removeService(ref): mutableBouquetList.flushChanges() self.setRoot(sBouquetRef) return (True, "Service %s removed from bouquet %s." % (self.getName(ref), self.getName(bouquetRef))) return (False, "Service %s can not be removed." % self.getName(ref))
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 subcargasat(self, sixml = True): if sixml: try: satXml = parse('/etc/tuxbox/satellites.xml').getroot() if satXml is not None: for sat in satXml.findall('sat'): name = sat.get('name') or None position = sat.get('position') or None if name is not None and position is not None: position = '%s.%s' % (position[:-1], position[-1:]) if position.startswith('-'): position = '%sW' % position[1:] else: position = '%sE' % position if position.startswith('.'): position = '0%s' % position self.satNames[position] = name except: pass try: self.tv_list = self.getListFromRef(eServiceReference('1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 195) || (type == 25) FROM BOUQUET "bouquets.tv" ORDER BY bouquet')) self.radio_list = self.getListFromRef(eServiceReference('1:7:2:0:0:0:0:0:0:0:(type == 2) FROM BOUQUET "bouquets.radio" ORDER BY bouquet')) except: pass self.seg_plano = None return
def getStream(session, request, m3ufile): if "ref" in request.args: sRef=unquote(unquote(request.args["ref"][0]).decode('utf-8', 'ignore')).encode('utf-8') else: sRef = "" currentServiceRef = None if m3ufile == "streamcurrent.m3u": currentServiceRef = session.nav.getCurrentlyPlayingServiceReference() sRef = currentServiceRef.toString() if sRef.startswith("1:134:"): if currentServiceRef is None: currentServiceRef = session.nav.getCurrentlyPlayingServiceReference() if currentServiceRef is None: currentServiceRef = eServiceReference() ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef) if ref is None: sRef = "" else: sRef = ref.toString() name = "stream" if "name" in request.args: name = request.args["name"][0] # #EXTINF:-1,%s\n remove not compatiple with old api if sRef != '': progopt="#EXTVLCOPT:program=%d\n" % (int(sRef.split(':')[3],16)) else: progopt="" response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/%s\n" % (progopt,request.getRequestHostname(),config.OpenWebif.streamport.value, sRef) request.setHeader('Content-Type', 'application/text') return response
def resolveAlternate(self, ref, timer_state=None): if ref and timer_state is not None and ref.flags & eServiceReference.isGroup: if timer_state == 2: ref = getBestPlayableServiceReference(ref, eServiceReference()) else: ref = eServiceReference(GetWithAlternative(ref.toString())) return ref
def setPiPService(self): if self.shown: service = self.source.getCurrentService() if self.currentRunningService is None or self.pipservice is None: self.currentRunningService = service # check, if tuner with the service is available service_center = eServiceCenter.getInstance() info = service_center.info(service) if info and info.isPlayable(service, self.currentRunningService): if service and (service.flags & eServiceReference.isGroup): ref = getBestPlayableServiceReference(service, eServiceReference()) else: ref = service if ref and not (ref.flags & (eServiceReference.isMarker|eServiceReference.isDirectory)): if self.pipServiceRelation is not None: n_service = self.pipServiceRelation.get(ref.toString(),None) if n_service is not None: self.pipservice = eServiceCenter.getInstance().play(eServiceReference(n_service)) else: self.pipservice = eServiceCenter.getInstance().play(ref) else: self.pipservice = eServiceCenter.getInstance().play(ref) if self.pipservice and not self.pipservice.setTarget(1): self.pipservice.start() return True self.pipservice = None return False
def getContent(self): contentList = [] ref = self.source.service info = ref and self.source.info if info is None: return [] curEvent = self.source.getCurrentEvent() if curEvent: if not self.epgcache.startTimeQuery(eServiceReference(ref.toString()), curEvent.getBeginTime() + curEvent.getDuration()): i = 1 while i <= (self.eventcount): event = self.epgcache.getNextTimeEntry() if event is not None: contentList.append(self.getEventTuple(event),) i +=1 if self.primetime == 1: now = localtime(time()) dt = datetime(now.tm_year, now.tm_mon, now.tm_mday, 20, 15) if time() > mktime(dt.timetuple()): dt += timedelta(days=1) # skip to next day... primeTime = int(mktime(dt.timetuple())) if not self.epgcache.startTimeQuery(eServiceReference(ref.toString()), primeTime): event = self.epgcache.getNextTimeEntry() if event and (event.getBeginTime() <= int(mktime(dt.timetuple()))): contentList.append(self.getEventTuple(event),) return contentList
def getText(self): ref = self.source.service info = ref and self.source.info if info is None: return "" textvalue = "" if self.type < self.PrimeTime: curEvent = self.source.getCurrentEvent() if curEvent: self.epgcache.startTimeQuery(eServiceReference(ref.toString()), curEvent.getBeginTime() + curEvent.getDuration()) nextEvents = [] for i in range(self.type): # Hole x-1 Eintraege aus dem EPG self.epgcache.getNextTimeEntry() #nextEvent.getEventId(), sRef, nextEvent.getBeginTime(), nextEvent.getDuration(), nextEvent.getEventName(), nextEvent.getShortDescription(), nextEvent.getExtendedDescription() next = self.epgcache.getNextTimeEntry() if next: textvalue = self.formatEvent(next) elif self.type == self.PrimeTime: curEvent = self.source.getCurrentEvent() if curEvent: now = localtime(time()) dt = datetime(now.tm_year, now.tm_mon, now.tm_mday, 20, 15) primeTime = int(mktime(dt.timetuple())) self.epgcache.startTimeQuery(eServiceReference(ref.toString()), primeTime) next = self.epgcache.getNextTimeEntry() if next and (next.getBeginTime() <= int(mktime(dt.timetuple()))): textvalue = self.formatEvent(next) return textvalue
def __init__(self, session, entry, configPSR): self.session = session Screen.__init__(self, session) self.title = _("PipServiceRelation - Entry Config") self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "green": self.keySave, "red": self.keyCancel, "cancel": self.keyCancel, "ok": self.keySelect, }, -2) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("OK")) self.configPSR = configPSR self.entry = entry if entry is None: self.currentKey = None self.ref1 = NoSave(ConfigDirectory(default = _("Press OK to select a service"))) self.ref2 = NoSave(ConfigDirectory(default = _("Press OK to select a related PiP service"))) else: self.currentKey = entry[0] self.ref1 = NoSave(ConfigDirectory(default = ServiceReference(eServiceReference(entry[0])).getServiceName())) self.ref2 = NoSave(ConfigDirectory(default = ServiceReference(eServiceReference(entry[1])).getServiceName())) self.list = [ ] self.serviceref1 = getConfigListEntry(_("Service"), self.ref1) self.serviceref2 = getConfigListEntry(_("Related Pip Service"), self.ref2) self.list.append(self.serviceref1) self.list.append(self.serviceref2) ConfigListScreen.__init__(self, self.list, session)
def go(self): if len(self.mediaList) == 0 or self["list"].getSelectionIndex() > len(self.mediaList) - 1: return if self.isSbs: if self.level == self.UG_LEVEL_ALL: tmp = self.mediaList[self["list"].getSelectionIndex()][self.UG_STREAMURL] self.session.open(OpenUg, ['sbs' , tmp , self.channel]) elif self.level == self.UG_LEVEL_SERIE: tmp = self.sbsGetMediaUrl(self.mediaList[self["list"].getSelectionIndex()][self.UG_STREAMURL]) if tmp != '': myreference = eServiceReference(4097, 0, tmp) myreference.setName(self.mediaList[self["list"].getSelectionIndex()][self.UG_PROGNAME]) self.session.open(UGMediaPlayer, myreference, 'sbs') elif self.isRtl: if self.level == self.UG_LEVEL_ALL: tmp = self.mediaList[self["list"].getSelectionIndex()][self.UG_STREAMURL] self.session.open(OpenUg, ['rtlseason' , tmp]) elif self.level == self.UG_LEVEL_SEASON: tmp = self.mediaList[self["list"].getSelectionIndex()][self.UG_STREAMURL] self.session.open(OpenUg, ['rtlepisode' , tmp[0], tmp[1]]) elif self.level == self.UG_LEVEL_SERIE: tmp = self.getRTLStream(self.mediaList[self["list"].getSelectionIndex()][self.UG_STREAMURL]) if tmp != '': myreference = eServiceReference(4097, 0, tmp) myreference.setName(self.mediaList[self["list"].getSelectionIndex()][self.UG_PROGNAME]) self.session.open(UGMediaPlayer, myreference, 'rtl') else: self.session.openWithCallback(self.close, MessageBox, _("Voor deze aflevering moet waarschijnlijk betaald worden."), MessageBox.TYPE_ERROR, timeout=5, simple = True) else: self.doUGPlay()
def switchToAll(self): refStr = self.service_ref.ref.toString() from Screens.InfoBar import InfoBar if refStr.startswith('1:0:2:'): if InfoBar.instance.servicelist.mode != 1: InfoBar.instance.servicelist.setModeRadio() InfoBar.instance.servicelist.radioTV = 1 InfoBar.instance.servicelist.clearPath() rootbouquet = eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.radio" ORDER BY bouquet') bouquet = eServiceReference('%s ORDER BY name'% service_types_radio) else: if InfoBar.instance.servicelist.mode != 0: InfoBar.instance.servicelist.setModeTV() InfoBar.instance.servicelist.radioTV = 0 InfoBar.instance.servicelist.clearPath() rootbouquet = eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet') bouquet = eServiceReference('%s ORDER BY name'% service_types_tv) if InfoBar.instance.servicelist.bouquet_root != rootbouquet: InfoBar.instance.servicelist.bouquet_root = rootbouquet InfoBar.instance.servicelist.enterPath(bouquet) InfoBar.instance.servicelist.setCurrentSelection(self.service_ref.ref) InfoBar.instance.servicelist.zap(enable_pipzap = True) InfoBar.instance.servicelist.correctChannelNumber() InfoBar.instance.servicelist.startRoot = bouquet InfoBar.instance.servicelist.addToHistory(self.service_ref.ref)
def addServices(self, fromList, toList, channelIds): for scanservice in fromList: service = eServiceReference(scanservice.sref) if (service.flags & eServiceReference.isGroup): service = getBestPlayableServiceReference(eServiceReference(scanservice.sref), eServiceReference()) # service can be a "NoneType" without attribute "valid" -> Crash try: if not service.valid(): continue except: continue if (service.flags & (eServiceReference.isMarker|eServiceReference.isDirectory)): continue channelID = '%08x%04x%04x' % ( service.getUnsignedData(4), # NAMESPACE service.getUnsignedData(2), # TSID service.getUnsignedData(3), # ONID ) if channelID not in channelIds: toList.append(scanservice) channelIds.append(channelID)
def getBouquetChannelList(): channels = [ ] serviceHandler = enigma.eServiceCenter.getInstance() mask = (enigma.eServiceReference.isMarker | enigma.eServiceReference.isDirectory) if config.usage.multibouquet.value: bouquet_rootstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet' bouquet_root = enigma.eServiceReference(bouquet_rootstr) list = serviceHandler.list(bouquet_root) if list: while True: s = list.getNext() if not s.valid(): break if s.flags & enigma.eServiceReference.isDirectory: info = serviceHandler.info(s) if info: clist = serviceHandler.list(s) if clist: while True: service = clist.getNext() if not service.valid(): break if not (service.flags & mask): channels.append(service.toString()) else: bouquet_rootstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet' bouquet_root = enigma.eServiceReference(bouquet_rootstr) services = serviceHandler.list(bouquet_root) if not services is None: while True: service = services.getNext() if not service.valid(): break if not (service.flags & mask): channels.append(service.toString()) return channels
def mediaPlayerAdd(session, filename): mp = getOrCreateMpInstance(session) if mp is None: return { "result": False, "message": "Mediaplayer not installed" } if fileExists(filename): service = eServiceReference(4097, 0, filename) else: service = eServiceReference(filename) if not service.valid(): return { "result": False, "message": "'%s' is neither a valid reference nor a valid file" % filename } mp.playlist.addFile(service) mp.playlist.updateList() return { "result": True, "message": "'%s' has been added to playlist" % filename }
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 checkChan(self, provider): parts = nab_Get_EpgProvider(provider) chanref = parts[3] chname = parts[2] serviceHandler = eServiceCenter.getInstance() services = serviceHandler.list(eServiceReference('%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet' % service_types_tv)) bouquets = services and services.getContent('SN', True) for bouquet in bouquets: services = serviceHandler.list(eServiceReference(bouquet[0])) channels = services and services.getContent('SN', True) for channel in channels: if channel[0] == chanref: return True services = serviceHandler.list(eServiceReference('%s FROM BOUQUET "bouquets.radio" ORDER BY bouquet' % service_types_radio)) bouquets = services and services.getContent('SN', True) for bouquet in bouquets: services = serviceHandler.list(eServiceReference(bouquet[0])) channels = services and services.getContent('SN', True) for channel in channels: if channel[0] == chanref: return True mes = 'Sorry %s not found in your channel list' % chname self.session.open(MessageBox, mes, MessageBox.TYPE_INFO) return False
def __init__(self, session, actionlist): Screen.__init__(self, session) self.skinName = ["NumberZapExtSetup", "Setup"] self.setup_title = _("Extended NumberZap Setup") self.actionlist = actionlist self["key_green"] = StaticText(_("Save")) self["key_red"] = StaticText(_("Cancel")) self["actions"] = NumberActionMap(["SetupActions"], { "cancel": self.keyRed, # KEY_RED, KEY_EXIT "ok": self.keyOk, # KEY_OK "save": self.keyGreen, # KEY_GREEN }, -1) ConfigListScreen.__init__(self, []) if config.usage.multibouquet.value: self.bouquet_root_tv = eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet') self.bouquet_root_radio = eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.radio" ORDER BY bouquet') else: self.bouquet_root_tv = eServiceReference('%s FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet'%(service_types_tv)) self.bouquet_root_radio = eServiceReference('%s FROM BOUQUET "userbouquet.favourites.radio" ORDER BY bouquet'%(service_types_radio)) self.Bouquetlist = self.getBouquetList(self.bouquet_root_tv) + self.getBouquetList(self.bouquet_root_radio) self.prev_hotkeys_bouquets = eval(config.plugins.NumberZapExt.hotkeys_bouquets.value) self.initConfig() self.createSetup() self.onClose.append(self.__closed) self.onLayoutFinish.append(self.__layoutFinished)
def endMarkedEdit(self, abort): if not abort and self.mutableList is not None: self.bouquetNumOffsetCache = { } new_marked = set(self.servicelist.getMarked()) old_marked = set(self.__marked) removed = old_marked - new_marked added = new_marked - old_marked changed = False for x in removed: changed = True self.mutableList.removeService(eServiceReference(x)) for x in added: changed = True self.mutableList.addService(eServiceReference(x)) if changed: self.mutableList.flushChanges() self.__marked = [] self.clearMarks() self.bouquet_mark_edit = OFF self.mutableList = None self.setTitle(self.saved_title) self.saved_title = None # self.servicePath is just a reference to servicePathTv or Radio... # so we never ever do use the asignment operator in self.servicePath del self.servicePath[:] # remove all elements self.servicePath += self.savedPath # add saved elements del self.savedPath self.setRoot(self.servicePath[-1])
def P_calcpos(self, request): type = 0 if "type" in request.args.keys(): type = request.args["type"][0] bRef = '%s FROM BOUQUET "bouquets.tv" ORDER BY bouquet' % (service_types_tv) if type == 1: bRef = '%s FROM BOUQUET "bouquets.radio" ORDER BY bouquet' % (service_types_radio) serviceHandler = eServiceCenter.getInstance() serviceslist = serviceHandler.list(eServiceReference(bRef)) bqlist = serviceslist and serviceslist.getContent("RN", True) pos = 0 services = [] for bq in bqlist: bqref = bq[0].toString() service = {} service['servicereference'] = bqref service['startpos'] = pos serviceslist = serviceHandler.list(eServiceReference(bqref)) fulllist = serviceslist and serviceslist.getContent("RN", True) for item in fulllist: sref = item[0].toString() hs = (int(sref.split(":")[1]) & 512) sp = (sref[:7] == '1:832:D') if not hs or sp: # 512 is hidden service on sifteam image. Doesn't affect other images pos = pos + 1 if not sp and item[0].flags & eServiceReference.isMarker: pos = pos - 1 services.append(service) return {"services": services}
def __init__(self, type): Converter.__init__(self, type) self.i = 0 self.SatLst = {} self.SatLst2 = {} self.SatNameLst = {} self.getServList(eServiceReference('1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 195) || (type == 25) FROM BOUQUET "bouquets.tv" ORDER BY bouquet')) self.getServList(eServiceReference('1:7:2:0:0:0:0:0:0:0:(type == 2) FROM BOUQUET "bouquets.radio" ORDER BY bouquet')) self.CreateSatList() if type == "All": self.type = self.ALL elif type == "Freq": self.type = self.FREQ elif type == "SR": self.type = self.SR elif type == "Polar": self.type = self.POLAR elif type == "FEC": self.type = self.FEC elif type == "Ver": self.type = self.VER elif type == "ServNum": self.type = self.SERVNUM elif type == "SatName": self.type = self.SATNAME elif type == "ServRef": self.type = self.SERVREF elif type == "Tst": self.type = self.TST else: self.type = self.ALL
def __init__(self, session, key, args=None): Screen.__init__(self, session) self.session = session self.key = key self.setTitle(_("Hotkey Setup") + " " + key[0][0]) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["key_yellow"] = StaticText("") self["h_red"] = Pixmap() self["h_green"] = Pixmap() self["h_yellow"] = Pixmap() self["h_yellow"].hide() self["h_prev"] = Pixmap() self["h_next"] = Pixmap() self.mode = "list" self.hotkeyFunctions = getHotkeyFunctions() self.config = eval("config.misc.hotkey." + key[0][1]) self.expanded = [] self.selected = [] for x in self.config.value.split(','): if x[:8] == "ZapPanic": self.selected.append( ChoiceEntryComponent( '', ((_("Panic to") + " " + ServiceReference( eServiceReference(x.split( "/", 1)[1]).toString()).getServiceName()), x))) elif x[:3] == "Zap": self.selected.append( ChoiceEntryComponent( '', ((_("Zap to") + " " + ServiceReference( eServiceReference(x.split( "/", 1)[1]).toString()).getServiceName()), x))) else: function = list(function for function in self.hotkeyFunctions if function[1] == x) if function: self.selected.append( ChoiceEntryComponent( '', ((function[0][0]), function[0][1]))) self.prevselected = self.selected[:] if self.prevselected: self["key_yellow"].setText(_("Edit selection")) self["choosen"] = ChoiceList(list=self.selected, selection=0) self["list"] = ChoiceList(list=self.getFunctionList(), selection=0) self["actions"] = ActionMap( [ "OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions", "MenuActions" ], { "ok": self.keyOk, "cancel": self.cancel, "red": self.cancel, "green": self.save, "yellow": self.toggleMode, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "upRepeated": self.keyUp, "downRepeated": self.keyDown, "leftRepeated": self.keyLeft, "rightRepeated": self.keyRight, "pageUp": self.toggleMode, "pageDown": self.toggleMode, "moveUp": self.moveUp, "moveDown": self.moveDown, "menu": boundFunction(self.close, True), }, -1) self.showPrevNext() self.onLayoutFinish.append(self.__layoutFinished)
def getText(self): service = self.source.service if isinstance(service, iPlayableServicePtr): info = service and service.info() ref = None else: # reference info = service and self.source.info ref = service if not info: return "" if ref: refstr = ref.toString() else: refstr = info.getInfoString(iServiceInformation.sServiceref) if refstr is None: refstr = '' if self.AlternativeControl: if ref and refstr.startswith("1:134:") and self.ref is None: nref = self.resolveAlternate(ref) if nref: self.ref = nref self.info = eServiceCenter.getInstance().info(self.ref) self.refstr = self.ref.toString() if not self.info: return "" if self.IPTVcontrol: if '%3a//' in refstr or (self.refstr and '%3a//' in self.refstr ) or refstr.startswith("4097:"): self.isStream = True if self.type == self.NAME: name = ref and (info.getName(ref) or 'N/A') or (info.getName() or 'N/A') prefix = '' if self.ref: prefix = " (alter)" name += prefix return name.replace('\xc2\x86', '').replace('\xc2\x87', '') elif self.type == self.NUMBER: try: service = self.source.serviceref num = service and service.getChannelNum() or None except: num = None if num: return str(num) else: num, bouq = self.getServiceNumber(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) return num and str(num) or '' elif self.type == self.BOUQUET: num, bouq = self.getServiceNumber(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) return bouq elif self.type == self.PROVIDER: if self.isStream: if self.refstr and ('%3a//' in self.refstr or '%3a//' in self.refstr): return self.getIPTVProvider(self.refstr) return self.getIPTVProvider(refstr) else: if self.ref: return self.getProviderName(self.ref) if ref: return self.getProviderName(ref) else: return info.getInfoString( iServiceInformation.sProvider) or '' elif self.type == self.REFERENCE: if self.refstr: return self.refstr return refstr elif self.type == self.ORBPOS: if self.isStream: return "Stream" else: if self.ref and self.info: return self.getTransponderInfo(self.info, self.ref, 'O') return self.getTransponderInfo(info, ref, 'O') elif self.type == self.TPRDATA: if self.isStream: return _("Streaming") else: if self.ref and self.info: return self.getTransponderInfo(self.info, self.ref, 'T') return self.getTransponderInfo(info, ref, 'T') elif self.type == self.SATELLITE: if self.isStream: return _("Internet") else: if self.ref: return self.getSatelliteName(self.ref) #test# return self.getSatelliteName(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) elif self.type == self.ALLREF: tmpref = self.getReferenceType(refstr, ref) if 'Bouquet' in tmpref or 'Satellit' in tmpref or 'Provider' in tmpref: return ' ' elif '%3a' in tmpref: return ':'.join(refstr.split(':')[:10]) return tmpref elif self.type == self.FORMAT: num = bouq = '' tmp = self.sfmt[:].split("%") if tmp: ret = tmp[0] tmp.remove(ret) else: return "" for line in tmp: f = line[:1] if f == 'N': # %N - Name name = ref and (info.getName(ref) or 'N/A') or (info.getName() or 'N/A') postfix = '' if self.ref: postfix = " (alter)" name += postfix ret += name.replace('\xc2\x86', '').replace('\xc2\x87', '') elif f == 'n': # %n - Number try: service = self.source.serviceref num = service and service.getChannelNum() or None except: num = None if num: ret += str(num) else: num, bouq = self.getServiceNumber( ref or eServiceReference( info.getInfoString( iServiceInformation.sServiceref))) ret += num and str(num) or '' elif f == 'B': # %B - Bouquet num, bouq = self.getServiceNumber(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) ret += bouq elif f == 'P': # %P - Provider if self.isStream: if self.refstr and '%3a//' in self.refstr: ret += self.getIPTVProvider(self.refstr) else: ret += self.getIPTVProvider(refstr) else: if self.ref: ret += self.getProviderName(self.ref) else: if ref: ret += self.getProviderName(ref) else: ret += info.getInfoString( iServiceInformation.sProvider) or '' elif f == 'R': # %R - Reference if self.refstr: ret += self.refstr else: ret += refstr elif f == 'S': # %S - Satellite if self.isStream: ret += _("Internet") else: if self.ref: ret += self.getSatelliteName(self.ref) else: ret += self.getSatelliteName( ref or eServiceReference( info.getInfoString( iServiceInformation.sServiceref))) elif f == 'A': # %A - AllRef tmpref = self.getReferenceType(refstr, ref) if 'Bouquet' in tmpref or 'Satellit' in tmpref or 'Provider' in tmpref: ret += ' ' elif '%3a' in tmpref: ret += ':'.join(refstr.split(':')[:10]) else: ret += tmpref elif f in 'TtsFfiOMpYroclhmgbe': if self.ref: ret += self.getTransponderInfo(self.info, self.ref, f) else: ret += self.getTransponderInfo(info, ref, f) ret += line[1:] return '%s' % (ret.replace('N/A', '').strip())
def resolveAlternate(self, ref): nref = getBestPlayableServiceReference(ref, self.getPlayingref(ref)) if not nref: nref = getBestPlayableServiceReference(ref, eServiceReference(), True) return nref
def playService(self, ref, checkParentalControl=True, forceRestart=False, adjust=True): oldref = self.currentlyPlayingServiceOrGroup if ref and oldref and ref == oldref and not forceRestart: print "ignore request to play already running service(1)" return 1 print "playing", ref and ref.toString() if path.exists("/proc/stb/lcd/symbol_signal" ) and config.lcd.mode.value == '1': try: if '0:0:0:0:0:0:0:0:0' not in ref.toString(): signal = 1 else: signal = 0 f = open("/proc/stb/lcd/symbol_signal", "w") f.write(str(signal)) f.close() except: f = open("/proc/stb/lcd/symbol_signal", "w") f.write("0") f.close() elif path.exists("/proc/stb/lcd/symbol_signal" ) and config.lcd.mode.value == '0': f = open("/proc/stb/lcd/symbol_signal", "w") f.write("0") f.close() if ref is None: self.stopService() return 0 from Components.ServiceEventTracker import InfoBarCount InfoBarInstance = InfoBarCount == 1 and InfoBar.instance if not checkParentalControl or parentalControl.isServicePlayable( ref, boundFunction(self.playService, checkParentalControl=False, forceRestart=forceRestart, adjust=adjust)): if ref.flags & eServiceReference.isGroup: oldref = self.currentlyPlayingServiceReference or eServiceReference( ) playref = getBestPlayableServiceReference(ref, oldref) print "playref", playref if playref and oldref and playref == oldref and not forceRestart: print "ignore request to play already running service(2)" return 1 if not playref: alternativeref = getBestPlayableServiceReference( ref, eServiceReference(), True) self.stopService() if alternativeref and self.pnav and self.pnav.playService( alternativeref): print "Failed to start", alternativeref return 0 elif checkParentalControl and not parentalControl.isServicePlayable( playref, boundFunction(self.playService, checkParentalControl=False)): if self.currentlyPlayingServiceOrGroup and InfoBarInstance and InfoBarInstance.servicelist.servicelist.setCurrent( self.currentlyPlayingServiceOrGroup, adjust): self.currentlyPlayingServiceOrGroup = InfoBarInstance.servicelist.servicelist.getCurrent( ) return 1 else: playref = ref if self.pnav: self.pnav.stopService() self.currentlyPlayingServiceReference = playref self.currentlyPlayingServiceOrGroup = ref if InfoBarInstance and InfoBarInstance.servicelist.servicelist.setCurrent( ref, adjust): self.currentlyPlayingServiceOrGroup = InfoBarInstance.servicelist.servicelist.getCurrent( ) if self.pnav.playService(playref): print "Failed to start", playref self.currentlyPlayingServiceReference = None self.currentlyPlayingServiceOrGroup = None return 0 elif oldref and InfoBarInstance and InfoBarInstance.servicelist.servicelist.setCurrent( oldref, adjust): self.currentlyPlayingServiceOrGroup = InfoBarInstance.servicelist.servicelist.getCurrent( ) return 1
def load(self, root, filter_tags): # this lists our root service, then building a # nice list del self.list[:] serviceHandler = eServiceCenter.getInstance() numberOfDirs = 0 reflist = root and serviceHandler.list(root) if reflist is None: print("listing of movies failed") return realtags = set() tags = {} rootPath = os.path.normpath(root.getPath()) parent = None # Don't navigate above the "root" if len(rootPath) > 1 and (os.path.realpath(rootPath) != config.movielist.root.value): parent = os.path.split(os.path.normpath(rootPath))[0] currentfolder = os.path.normpath(rootPath) + '/' if parent and (parent not in defaultInhibitDirs ) and not currentfolder.endswith( config.usage.default_path.value): # enigma wants an extra '/' appended if not parent.endswith('/'): parent += '/' ref = eServiceReference(eServiceReference.idFile, eServiceReference.flagDirectory, eServiceReferenceFS.directory) ref.setPath(parent) ref.flags = eServiceReference.flagDirectory self.list.append((ref, None, 0, -1)) numberOfDirs += 1 while True: serviceref = reflist.getNext() if not serviceref.valid(): break info = serviceHandler.info(serviceref) if info is None: info = justStubInfo begin = info.getInfo(serviceref, iServiceInformation.sTimeCreate) if serviceref.flags & eServiceReference.mustDescent: dirname = info.getName(serviceref) if not dirname.endswith( '.AppleDouble/') and not dirname.endswith( '.AppleDesktop/') and not dirname.endswith( '.AppleDB/') and not dirname.endswith( 'Network Trash Folder/' ) and not dirname.endswith('Temporary Items/'): self.list.append((serviceref, info, begin, -1)) numberOfDirs += 1 continue # convert space-seperated list of tags into a set this_tags = info.getInfoString( serviceref, iServiceInformation.sTags).split(' ') name = info.getName(serviceref) # OSX put a lot of stupid files ._* everywhere... we need to skip them if name[:2] == "._": continue if this_tags == ['']: # No tags? Auto tag! this_tags = name.replace(',', ' ').replace('.', ' ').replace( '_', ' ').replace(':', ' ').split() else: realtags.update(this_tags) for tag in this_tags: if len(tag) >= 4: if tag in tags: tags[tag].append(name) else: tags[tag] = [name] # filter_tags is either None (which means no filter at all), or # a set. In this case, all elements of filter_tags must be present, # otherwise the entry will be dropped. if filter_tags is not None: this_tags_fullname = [" ".join(this_tags)] this_tags_fullname = set(this_tags_fullname) this_tags = set(this_tags) if not this_tags.issuperset( filter_tags) and not this_tags_fullname.issuperset( filter_tags): # print "Skipping", name, "tags=", this_tags, " filter=", filter_tags continue self.list.append((serviceref, info, begin, -1)) self.firstFileEntry = numberOfDirs self.parentDirectory = 0 self.list.sort(key=self.buildGroupwiseSortkey) if self.sort_type == MovieList.SORT_ALPHANUMERIC: self.list = sorted(self.list[:numberOfDirs], key=self.buildAlphaNumericSortKey) + sorted( self.list[numberOfDirs:], key=self.buildAlphaNumericSortKey) elif self.sort_type == MovieList.SORT_ALPHANUMERIC_REVERSE: self.list = sorted(self.list[:numberOfDirs], key=self.buildAlphaNumericSortKey, reverse=True) + sorted( self.list[numberOfDirs:], key=self.buildAlphaNumericSortKey, reverse=True) elif self.sort_type == MovieList.SORT_ALPHANUMERIC_FLAT: self.list.sort(key=self.buildAlphaNumericFlatSortKey) elif self.sort_type == MovieList.SORT_ALPHANUMERIC_FLAT_REVERSE: self.list.sort(key=self.buildAlphaNumericFlatSortKey, reverse=True) elif self.sort_type == MovieList.SORT_RECORDED: self.list = sorted(self.list[:numberOfDirs], key=self.buildBeginTimeSortKey) + sorted( self.list[numberOfDirs:], key=self.buildBeginTimeSortKey) elif self.sort_type == MovieList.SORT_RECORDED_REVERSE: self.list = sorted(self.list[:numberOfDirs], key=self.buildBeginTimeSortKey, reverse=True) + sorted( self.list[numberOfDirs:], key=self.buildBeginTimeSortKey, reverse=True) elif self.sort_type == MovieList.SHUFFLE: dirlist = self.list[:numberOfDirs] shufflelist = self.list[numberOfDirs:] random.shuffle(shufflelist) self.list = dirlist + shufflelist elif self.sort_type == MovieList.SORT_ALPHA_DATE_OLDEST_FIRST: self.list = sorted(self.list[:numberOfDirs], key=self.buildAlphaDateSortKey) + sorted( self.list[numberOfDirs:], key=self.buildAlphaDateSortKey) elif self.sort_type == MovieList.SORT_ALPHAREV_DATE_NEWEST_FIRST: self.list = sorted(self.list[:numberOfDirs], key=self.buildAlphaDateSortKey, reverse=True) + sorted( self.list[numberOfDirs:], key=self.buildAlphaDateSortKey, reverse=True) for x in self.list: if x[1]: tmppath = x[1].getName(x[0])[:-1] if x[1].getName( x[0]).endswith('/') else x[1].getName(x[0]) if tmppath.endswith('.Trash'): self.list.insert(0, self.list.pop(self.list.index(x))) break if self.root and numberOfDirs > 0: rootPath = os.path.normpath(self.root.getPath()) if not rootPath.endswith('/'): rootPath += '/' if rootPath != parent: # with new sort types directories may be in between files, so scan whole # list for parentDirectory index. Usually it is the first one anyway for index, item in enumerate(self.list): if item[0].flags & eServiceReference.mustDescent: itempath = os.path.normpath(item[0].getPath()) if not itempath.endswith('/'): itempath += '/' if itempath == rootPath: self.parentDirectory = index break self.root = root # finally, store a list of all tags which were found. these can be presented # to the user to filter the list # ML: Only use the tags that occur more than once in the list OR that were # really in the tag set of some file. # reverse the dictionary to see which unique movie each tag now references rtags = {} for tag, movies in list(tags.items()): if (len(movies) > 1) or (tag in realtags): movies = tuple(movies) # a tuple can be hashed, but a list not item = rtags.get(movies, []) if not item: rtags[movies] = item item.append(tag) self.tags = {} for movies, tags in list(rtags.items()): movie = movies[0] # format the tag lists so that they are in 'original' order tags.sort(key=movie.find) first = movie.find(tags[0]) last = movie.find(tags[-1]) + len(tags[-1]) match = movie start = 0 end = len(movie) # Check if the set has a complete sentence in common, and how far for m in movies[1:]: if m[start:end] != match: if not m.startswith(movie[:last]): start = first if not m.endswith(movie[first:]): end = last match = movie[start:end] if m[start:end] != match: match = '' break if match: self.tags[match] = set(tags) continue else: match = ' '.join(tags) if len(match) > 2: #Omit small words self.tags[match] = set(tags)
def changeDir(self, directory, select=None): self.list = [] # if we are just entering from the list of mount points: if self.current_directory is None: if directory and self.showMountpoints: self.current_mountpoint = self.getMountpointLink(directory) else: self.current_mountpoint = None self.current_directory = directory directories = [] files = [] if directory is None and self.showMountpoints: # present available mountpoints for p in harddiskmanager.getMountedPartitions(): path = os.path.join(p.mountpoint, "") if path not in self.inhibitMounts and not self.inParentDirs( path, self.inhibitDirs): self.list.append( MultiFileSelectEntryComponent(name=p.description, absolute=path, isDir=True)) files = [] directories = [] elif directory is None: files = [] directories = [] elif self.useServiceRef: root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory) if self.additional_extensions: root.setName(self.additional_extensions) serviceHandler = eServiceCenter.getInstance() list = serviceHandler.list(root) while 1: s = list.getNext() if not s.valid(): del list break if s.flags & s.mustDescent: directories.append(s.getPath()) else: files.append(s) directories.sort() files.sort() else: if fileExists(directory): try: files = os.listdir(directory) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os.path.isdir(directory + x): directories.append(directory + x + "/") files.remove(x) if self.showDirectories: if directory: if self.showMountpoints and directory == self.current_mountpoint: self.list.append( FileEntryComponent(name="<" + _("List of storage devices") + ">", absolute=None, isDir=True)) elif (directory != self.topDirectory) and not ( self.inhibitMounts and self.getMountpoint(directory) in self.inhibitMounts): self.list.append( FileEntryComponent( name="<" + _("Parent directory") + ">", absolute='/'.join(directory.split('/')[:-2]) + '/', isDir=True)) for x in directories: if not (self.inhibitMounts and self.getMountpoint(x) in self.inhibitMounts) and not self.inParentDirs( x, self.inhibitDirs): name = x.split('/')[-2] alreadySelected = (x in self.selectedFiles) or ( os.path.normpath(x) in self.selectedFiles) self.list.append( MultiFileSelectEntryComponent( name=name, absolute=x, isDir=True, selected=alreadySelected)) if self.showFiles: for x in files: if self.useServiceRef: path = x.getPath() name = path.split('/')[-1] else: path = directory + x name = x if (self.matchingPattern is None) or self.matchingPattern.search(path): alreadySelected = False for entry in self.selectedFiles: if os.path.basename(entry) == x: alreadySelected = True self.list.append( MultiFileSelectEntryComponent( name=name, absolute=x, isDir=False, selected=alreadySelected)) self.l.setList(self.list) if select is not None: i = 0 self.moveToIndex(0) for x in self.list: p = x[0][0] if isinstance(p, eServiceReference): p = p.getPath() if p == select: self.moveToIndex(i) i += 1
def execHotkey(self, selected): if selected: selected = selected[1].split("/") if selected[0] == "Plugins": twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins( PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if plugin.path[24:] in twinPaths: twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 if plugin.path[24:] + "/" + str(twinPaths[ plugin.path[24:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([ PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU ]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if plugin.path[24:] in twinPaths: twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 if plugin.path[24:] + "/" + str(twinPaths[ plugin.path[24:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) elif selected[0] == "MenuPlugin": for plugin in plugins.getPluginsForMenu(selected[1]): if plugin[2] == selected[2]: self.runPlugin(plugin[1]) return elif selected[0] == "Infobar": if hasattr(self, selected[1]): exec "self." + ".".join(selected[1:]) + "()" else: return 0 elif selected[0] == "Module": try: exec "from " + selected[1] + " import " + selected[2] exec "self.session.open(" + ",".join(selected[2:]) + ")" except: print "[Hotkey] error during executing module %s, screen %s" % ( selected[1], selected[2]) elif selected[0] == "Setup": from Screens.Setup import * exec "self.session.open(Setup, \"" + selected[1] + "\")" elif selected[0][:3] == "Zap": if selected[0] == "ZapPanic": self.servicelist.history = [] self.servicelist.servicelist.setCurrent( eServiceReference("/".join(selected[1:]))) self.servicelist.zap(enable_pipzap=True) if hasattr(self, "lastservice"): self.lastservice = eServiceReference("/".join( selected[1:])) self.close() else: self.show() from Screens.MovieSelection import defaultMoviePath moviepath = defaultMoviePath() if moviepath: config.movielist.last_videodir.value = moviepath elif selected[0] == "PPanel": ppanelFileName = '/etc/ppanels/' + selected[1] + ".xml" if os.path.isfile(ppanelFileName) and os.path.isdir( '/usr/lib/enigma2/python/Plugins/Extensions/PPanel'): from Plugins.Extensions.PPanel.ppanel import PPanel self.session.open(PPanel, name=selected[1] + ' PPanel', node=None, filename=ppanelFileName, deletenode=None) elif selected[0] == "Shellscript": command = '/usr/script/' + selected[1] + ".sh" if os.path.isfile(command): if ".hidden." in command: from enigma import eConsoleAppContainer eConsoleAppContainer().execute(command) else: from Screens.Console import Console self.session.open( Console, selected[1] + " shellscript", command, closeOnSuccess=selected[1].startswith('!'), showStartStopText=False) elif selected[0] == "Menu": from Screens.Menu import MainMenu, mdom root = mdom.getroot() for x in root.findall("menu"): y = x.find("id") if y is not None: id = y.get("val") if id and id == selected[1]: menu_screen = self.session.open(MainMenu, x) break
def execButtonSetup(self, selected): if selected: selected = selected[1].split("/") if selected[0] == "Plugins": twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins( PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if twinPaths.has_key( plugin.path[plugin.path.rfind("Plugins"):]): twinPaths[plugin.path[plugin.path.rfind("Plugins" ):]] += 1 else: twinPaths[ plugin.path[plugin.path.rfind("Plugins"):]] = 1 if plugin.path[ plugin.path.rfind("Plugins"):] + "/" + str( twinPaths[plugin.path[plugin.path.rfind( "Plugins"):]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([ PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU ]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if twinPaths.has_key( plugin.path[plugin.path.rfind("Plugins"):]): twinPaths[plugin.path[plugin.path.rfind("Plugins" ):]] += 1 else: twinPaths[ plugin.path[plugin.path.rfind("Plugins"):]] = 1 if plugin.path[ plugin.path.rfind("Plugins"):] + "/" + str( twinPaths[plugin.path[plugin.path.rfind( "Plugins"):]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) elif selected[0] == "MenuPlugin": for plugin in plugins.getPluginsForMenu(selected[1]): if plugin[2] == selected[2]: self.runPlugin(plugin[1]) return elif selected[0] == "Infobar": if hasattr(self, selected[1]): exec "self." + ".".join(selected[1:]) + "()" else: return 0 elif selected[0] == "Module": try: exec "from " + selected[1] + " import *" exec "self.session.open(" + ",".join(selected[2:]) + ")" except: print "[ButtonSetup] error during executing module %s, screen %s" % ( selected[1], selected[2]) elif selected[0] == "Setup": exec "from Screens.Setup import *" exec "self.session.open(Setup, \"" + selected[1] + "\")" elif selected[0].startswith("Zap"): if selected[0] == "ZapPanic": self.servicelist.history = [] self.pipShown() and self.showPiP() self.servicelist.servicelist.setCurrent( eServiceReference("/".join(selected[1:]))) self.servicelist.zap(enable_pipzap=True) if hasattr(self, "lastservice"): self.lastservice = eServiceReference("/".join( selected[1:])) self.close() else: self.show() from Screens.MovieSelection import defaultMoviePath moviepath = defaultMoviePath() if moviepath: config.movielist.last_videodir.value = moviepath elif selected[0] == "PPanel": ppanelFileName = '/etc/ppanels/' + selected[1] + ".xml" if os.path.isfile(ppanelFileName) and os.path.isdir( '/usr/lib/enigma2/python/Plugins/Extensions/PPanel'): from Plugins.Extensions.PPanel.ppanel import PPanel self.session.open(PPanel, name=selected[1] + ' PPanel', node=None, filename=ppanelFileName, deletenode=None) elif selected[0] == "Shellscript": command = '/usr/script/' + selected[1] + ".sh" if os.path.isfile(command) and os.path.isdir( '/usr/lib/enigma2/python/Plugins/Extensions/PPanel'): from Plugins.Extensions.PPanel.ppanel import Execute self.session.open(Execute, selected[1] + " shellscript", None, command) else: from Screens.Console import Console exec "self.session.open(Console,_(selected[1]),[command])" elif selected[0] == "EMC": try: from Plugins.Extensions.EnhancedMovieCenter.plugin import showMoviesNew from Screens.InfoBar import InfoBar open(showMoviesNew(InfoBar.instance)) except Exception as e: print('[EMCPlayer] showMovies exception:\n' + str(e)) elif selected[0] == "ScriptRunner": if os.path.isfile( "/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/ScriptRunner.pyo" ): from Plugins.Extensions.Infopanel.ScriptRunner import ScriptRunner self.session.open(ScriptRunner) elif selected[0] == "QuickMenu": if os.path.isfile( "/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/QuickMenu.pyo" ): from Plugins.Extensions.Infopanel.QuickMenu import QuickMenu self.session.open(QuickMenu) elif selected[0] == "Kodi": if os.path.isfile( "/usr/lib/enigma2/python/Plugins/Extensions/Kodi/plugin.pyo" ): from Plugins.Extensions.Kodi.plugin import KodiMainScreen self.session.open(KodiMainScreen) elif selected[0] == "Bluetooth": if os.path.isfile( "/usr/lib/enigma2/python/Plugins/SystemPlugins/BluetoothSetup/plugin.pyo" ): from Plugins.SystemPlugins.BluetoothSetup.plugin import BluetoothSetup self.session.open(BluetoothSetup) elif selected[0] == "YoutubeTV": if os.path.isfile( "/usr/lib/enigma2/python/Plugins/Extensions/Chromium/plugin.pyo" ): from Plugins.Extensions.Chromium.youtube import YoutubeTVWindow self.session.open(YoutubeTVWindow)
def execButtonSetup(self, selected): if selected: selected = selected[1].split("/") if selected[0] == "Plugins": twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins( PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if plugin.path[24:] in twinPaths: twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 if plugin.path[24:] + "/" + str(twinPaths[ plugin.path[24:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([ PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU ]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if plugin.path[24:] in twinPaths: twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 if plugin.path[24:] + "/" + str(twinPaths[ plugin.path[24:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) elif selected[0] == "MenuPlugin": for plugin in plugins.getPluginsForMenu(selected[1]): if plugin[2] == selected[2]: self.runPlugin(plugin[1]) return elif selected[0] == "Infobar": if hasattr(self, selected[1]): exec "self." + ".".join(selected[1:]) + "()" else: return 0 elif selected[0] == "Module": try: exec "from " + selected[1] + " import *" exec "self.session.open(" + ",".join(selected[2:]) + ")" except: print "[ButtonSetup] error during executing module %s, screen %s" % ( selected[1], selected[2]) elif selected[0] == "Setup": exec "from Screens.Setup import *" exec "self.session.open(Setup, \"" + selected[1] + "\")" elif selected[0].startswith("Zap"): if selected[0] == "ZapPanic": self.servicelist.history = [] self.pipShown() and self.showPiP() self.servicelist.servicelist.setCurrent( eServiceReference("/".join(selected[1:]))) self.servicelist.zap(enable_pipzap=True) if hasattr(self, "lastservice"): self.lastservice = eServiceReference("/".join( selected[1:])) self.close() else: self.show() from Screens.MovieSelection import defaultMoviePath moviepath = defaultMoviePath() if moviepath: config.movielist.last_videodir.value = moviepath elif selected[0] == "Menu": from Screens.Menu import MainMenu, mdom root = mdom.getroot() for x in root.findall("menu"): y = x.find("id") if y is not None: id = y.get("val") if id and id == selected[1]: menu_screen = self.session.open(MainMenu, x) break
def isValidServiceId(id): testSRef = eServiceReference(id, 0, "Just a TestReference") info = eServiceCenter.getInstance().info(testSRef) return info is not None
def getPrev(self): r = eServiceReference() self.l.getPrev(r) return r
def showMovies(self, defaultRef=None): self.lastservice = self.session.nav.getCurrentlyPlayingServiceOrGroup() if self.lastservice and self.lastservice.toString().find(':0:/') != -1: self.lastservice = enigma.eServiceReference(config.movielist.curentlyplayingservice.getValue()) self.session.openWithCallback(self.movieSelected, Screens.MovieSelection.MovieSelection, defaultRef, timeshiftEnabled = self.timeshiftEnabled())
def getServiceNumber(self, ref): def searchHelper(serviceHandler, num, bouquet): servicelist = serviceHandler.list(bouquet) if servicelist is not None: while True: s = servicelist.getNext() if not s.valid(): break if not s.flags & (eServiceReference.isMarker | eServiceReference.isDirectory): num += 1 if s == ref: return (s, num) return (None, num) if isinstance(ref, eServiceReference): isRadioService = ref.getData(0) in (2, 10) lastpath = isRadioService and config.radio.lastroot.value or config.tv.lastroot.value if lastpath.find('FROM BOUQUET') == -1: if 'FROM PROVIDERS' in lastpath: return ('P', 'Provider') if 'FROM SATELLITES' in lastpath: return ('S', 'Satellites') if ') ORDER BY name' in lastpath: return ('A', 'All Services') return (0, 'N/A') try: acount = config.plugins.NumberZapExt.enable.value and config.plugins.NumberZapExt.acount.value except: acount = False rootstr = '' for x in lastpath.split(';'): if x != '': rootstr = x serviceHandler = eServiceCenter.getInstance() if acount is True or not config.usage.multibouquet.value: bouquet = eServiceReference(rootstr) service, number = searchHelper(serviceHandler, 0, bouquet) else: if isRadioService: bqrootstr = '1:7:2:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.radio" ORDER BY bouquet' else: bqrootstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet' number = 0 cur = eServiceReference(rootstr) bouquet = eServiceReference(bqrootstr) bouquetlist = serviceHandler.list(bouquet) if bouquetlist is not None: while True: bouquet = bouquetlist.getNext() if not bouquet.valid(): break if bouquet.flags & eServiceReference.isDirectory: service, number = searchHelper( serviceHandler, number, bouquet) if service is not None and cur == bouquet: break if service is not None: info = serviceHandler.info(bouquet) name = info and info.getName(bouquet) or '' return (number, name) return (0, '')
def getNext(self): r = eServiceReference() self.l.getNext(r) return r
def addFile(self, filename): from enigma import eServiceReference ref = eServiceReference(1, 0, filename) self.addService(ref) self.project.session.openWithCallback(self.titleEditDone, TitleCutter.CutlistReader, self)
def getCurrent(self): r = eServiceReference() self.l.getCurrent(r) return r
def getMovieList(rargs=None, locations=None): movieliste = [] tag = None directory = None fields = None bookmarklist = [] if rargs and "tag" in rargs.keys(): tag = rargs["tag"][0] if rargs and "dirname" in rargs.keys(): directory = rargs["dirname"][0] if rargs and "fields" in rargs.keys(): fields = rargs["fields"][0] if directory is None: directory = MovieSelection.defaultMoviePath() else: try: directory.decode('utf-8') except UnicodeDecodeError: try: directory = directory.decode("cp1252").encode("utf-8") except UnicodeDecodeError: directory = directory.decode("iso-8859-1").encode("utf-8") if not directory: directory = MOVIE_LIST_ROOT_FALLBACK if directory[-1] != "/": directory += "/" if not os.path.isdir(directory): return { "movies": [], "locations": [], "bookmarks": [], "directory": [], } root = eServiceReference(MOVIE_LIST_SREF_ROOT + directory) for item in sorted(os.listdir(directory)): abs_p = os.path.join(directory, item) if os.path.isdir(abs_p): bookmarklist.append(item) folders = [root] if rargs and "recursive" in rargs.keys(): for f in bookmarklist: if f[-1] != "/": f += "/" ff = eServiceReference(MOVIE_LIST_SREF_ROOT + directory + f) folders.append(ff) # get all locations if locations is not None: folders = [] for f in locations: if f[-1] != "/": f += "/" ff = eServiceReference(MOVIE_LIST_SREF_ROOT + f) folders.append(ff) if config.OpenWebif.parentalenabled.value: dir_is_protected = checkParentalProtection(directory) else: dir_is_protected = False if not dir_is_protected: for root in folders: movielist = MovieList(None) movielist.load(root, None) if tag is not None: movielist.reload(root=root, filter_tags=[tag]) for (serviceref, info, begin, unknown) in movielist.list: if serviceref.flags & eServiceReference.mustDescent: continue length_minutes = 0 txtdesc = "" filename = '/'.join(serviceref.toString().split("/")[1:]) filename = '/' + filename name, ext = os.path.splitext(filename) sourceRef = ServiceReference( info.getInfoString( serviceref, iServiceInformation.sServiceref)) rtime = info.getInfo( serviceref, iServiceInformation.sTimeCreate) movie = { 'filename': filename, 'filename_stripped': filename.split("/")[-1], 'serviceref': serviceref.toString(), 'length': "?:??", 'lastseen': 0, 'filesize_readable': '', 'recordingtime': rtime, 'begintime': 'undefined', 'eventname': ServiceReference(serviceref).getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', ''), 'servicename': sourceRef.getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', ''), 'tags': info.getInfoString(serviceref, iServiceInformation.sTags), 'fullname': serviceref.toString(), } if rtime > 0: fuzzy_rtime = FuzzyTime(rtime) movie['begintime'] = fuzzy_rtime[0] + ", " + fuzzy_rtime[1] try: length_minutes = info.getLength(serviceref) except: pass if length_minutes: movie['length'] = "%d:%02d" % (length_minutes / 60, length_minutes % 60) if fields is None or 'pos' in fields: movie['lastseen'] = getPosition(filename + '.cuts', length_minutes) if fields is None or 'desc' in fields: txtfile = name + '.txt' if ext.lower() != '.ts' and os.path.isfile(txtfile): with open(txtfile, "rb") as handle: txtdesc = ''.join(handle.readlines()) event = info.getEvent(serviceref) extended_description = event and event.getExtendedDescription() or "" if extended_description == '' and txtdesc != '': extended_description = txtdesc movie['descriptionExtended'] = unicode(extended_description,'utf_8', errors='ignore').encode('utf_8', 'ignore') desc = info.getInfoString(serviceref, iServiceInformation.sDescription) movie['description'] = unicode(desc,'utf_8', errors='ignore').encode('utf_8', 'ignore') if fields is None or 'size' in fields: size = 0 sz = '' try: size = os.stat(filename).st_size if size > 1073741824: sz = "%.2f %s" % ((size / 1073741824.),_("GB")) elif size > 1048576: sz = "%.2f %s" % ((size / 1048576.),_("MB")) elif size > 1024: sz = "%.2f %s" % ((size / 1024.),_("kB")) except: pass movie['filesize'] = size movie['filesize_readable'] = sz movieliste.append(movie) if locations is None: return { "movies": movieliste, "bookmarks": bookmarklist, "directory": directory } return { "movies": movieliste, "locations": locations }
def getText(self): service = self.source.service if isinstance(service, iPlayableServicePtr): info = service and service.info() ref = None else: info = service and self.source.info ref = service self.poll_enabled = False if info is None: return '' if self.type == self.NAME: name = ref and (info.getName(ref) or 'N/A') or info.getName() or 'N/A' return name.replace('\xc2\x86', '').replace('\xc2\x87', '') if self.type == self.NUMBER: num, bouq = self.getServiceNumber(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) return num and str(num) or '' if self.type == self.BOUQUET: num, bouq = self.getServiceNumber(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) return bouq if self.type == self.PROVIDER: return ref and self.getProviderName(ref) or info.getInfoString( iServiceInformation.sProvider) if self.type == self.REFERENCE: return ref and ref.toString() or info.getInfoString( iServiceInformation.sServiceref) if self.type == self.ORBPOS: return self.getTransponderInfo(info, ref, '%O') if self.type == self.TPRDATA: return self.getTransponderInfo(info, ref, '%T') if self.type == self.SATELLITE: return self.getSatelliteName(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) if self.type == self.FORMAT: ret = num = bouq = '' if '%n' in self.sfmt or '%B' in self.sfmt: num, bouq = self.getServiceNumber(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) tmp = self.sfmt[:] while True: pos = tmp.find('%') if pos == -1: ret += tmp break ret += tmp[:pos] pos += 1 l = len(tmp) f = pos < l and tmp[pos] or '%' if f == 'N': name = ref and (info.getName(ref) or 'N/A') or info.getName() or 'N/A' ret += name.replace('\xc2\x86', '').replace('\xc2\x87', '') elif f == 'n': ret += num and str(num) or '' elif f == 'B': ret += bouq elif f == 'P': ret += ref and self.getProviderName( ref) or info.getInfoString( iServiceInformation.sProvider) elif f == 'R': ret += ref and ref.toString() or info.getInfoString( iServiceInformation.sServiceref) elif f == 'S': ret += self.getSatelliteName(ref or eServiceReference( info.getInfoString(iServiceInformation.sServiceref))) elif f in 'TtsFfiOMpYroclhmgbe': ret += self.getTransponderInfo(info, ref, '%' + f) else: ret += f if pos + 1 >= l: break tmp = tmp[pos + 1:] return '%s' % ret.replace('N/A', '')
def resolveAlternatePipService(self, service): if service and (service.flags & eServiceReference.isGroup): oldref = self.currentServiceReference or eServiceReference() return getBestPlayableServiceReference(service, oldref) return service
def parseTimer(self, timer, epgcache, serviceHandler, recordHandler, checkEvtLimit, evtLimit, timers, conflicting, similars, skipped, timerdict, moviedict, simulateOnly=False): new = 0 modified = 0 # Workaround to allow search for umlauts if we know the encoding #match = timer.match match = timer.match.replace('\xc2\x86', '').replace('\xc2\x87', '') if timer.encoding != 'UTF-8': try: match = match.decode('UTF-8').encode(timer.encoding) except UnicodeDecodeError: pass if timer.searchType == "description": epgmatches = [] casesensitive = timer.searchCase == "sensitive" if not casesensitive: match = match.lower() test = [] if timer.services: test = [(service, 0, -1, -1) for service in timer.services] elif timer.bouquets: for bouquet in timer.bouquets: services = serviceHandler.list(eServiceReference(bouquet)) if services: while True: service = services.getNext() if not service.valid(): break playable = not (service.flags & (eServiceReference.isMarker|eServiceReference.isDirectory)) or (service.flags & eServiceReference.isNumberedMarker) if playable: test.append((service.toString(), 0, -1, -1)) else: # Get all bouquets bouquetlist = [] if config.usage.multibouquet.value: refstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet' bouquetroot = eServiceReference(refstr) bouquets = serviceHandler.list(bouquetroot) if bouquets: while True: s = bouquets.getNext() if not s.valid(): break if s.flags & eServiceReference.isDirectory and not s.flags & eServiceReference.isInvisible: info = serviceHandler.info(s) if info: bouquetlist.append(s) else: service_types_tv = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 31) || (type == 134) || (type == 195)' refstr = '%s FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet' % (service_types_tv) bouquetroot = eServiceReference(refstr) info = serviceHandler.info(bouquetroot) if info: bouquetlist.append(bouquetroot) if bouquetlist: for bouquet in bouquetlist: if not bouquet.valid(): break if bouquet.flags & eServiceReference.isDirectory: services = serviceHandler.list(bouquet) if services: while True: service = services.getNext() if not service.valid(): break playable = not (service.flags & (eServiceReference.isMarker|eServiceReference.isDirectory)) or (service.flags & eServiceReference.isNumberedMarker) if playable: test.append((service.toString(), 0, -1, -1)) if test: # Get all events # eEPGCache.lookupEvent( [ format of the returned tuples, ( service, 0 = event intersects given start_time, start_time -1 for now_time), ] ) test.insert(0, 'RITBDSE') allevents = epgcache.lookupEvent(test) or [] # Filter events for serviceref, eit, name, begin, duration, shortdesc, extdesc in allevents: if match in (shortdesc if casesensitive else shortdesc.lower()) or match in (extdesc if casesensitive else extdesc.lower()): epgmatches.append((serviceref, eit, name, begin, duration, shortdesc, extdesc)) else: # Search EPG, default to empty list epgmatches = epgcache.search( ('RITBDSE', 2500, typeMap[timer.searchType], match, caseMap[timer.searchCase]) ) or [] # Sort list of tuples by begin time 'B' epgmatches.sort(key=itemgetter(3)) # Contains the the marked similar eits and the conflicting strings similardict = defaultdict(list) # Loop over all EPG matches for idx, ( serviceref, eit, name, begin, duration, shortdesc, extdesc ) in enumerate( epgmatches ): startLog() # timer destination dir dest = timer.destination evtBegin = begin evtEnd = end = begin + duration doLog("[AutoTimer] possible epgmatch %s" % (name)) doLog("[AutoTimer] Serviceref %s" % (str(serviceref))) eserviceref = eServiceReference(serviceref) evt = epgcache.lookupEventId(eserviceref, eit) if not evt: doLog("[AutoTimer] Could not create Event!") skipped.append((name, begin, end, str(serviceref), timer.name, getLog())) continue # Try to determine real service (we always choose the last one) n = evt.getNumOfLinkageServices() if n > 0: i = evt.getLinkageService(eserviceref, n-1) serviceref = i.toString() doLog("[AutoTimer] Serviceref2 %s" % (str(serviceref))) # If event starts in less than 60 seconds skip it if begin < time() + 60: doLog("[AutoTimer] Skipping an event because it starts in less than 60 seconds") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue # Set short description to equal extended description if it is empty. if not shortdesc and timer.descShortEqualExt: shortdesc = extdesc # Convert begin time timestamp = localtime(begin) # Update timer timer.update(begin, timestamp) # Check if eit is in similar matches list # NOTE: ignore evtLimit for similar timers as I feel this makes the feature unintuitive similarTimer = False if eit in similardict: similarTimer = True dayofweek = None # NOTE: ignore day on similar timer else: # If maximum days in future is set then check time if checkEvtLimit: if begin > evtLimit: doLog("[AutoTimer] Skipping an event because of maximum days in future is reached") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue dayofweek = str(timestamp.tm_wday) # Check timer conditions # NOTE: similar matches do not care about the day/time they are on, so ignore them if timer.checkServices(serviceref): doLog("[AutoTimer] Skipping an event because of check services") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue if timer.checkDuration(duration): doLog("[AutoTimer] Skipping an event because of duration check") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue if not similarTimer: if timer.checkTimespan(timestamp): doLog("[AutoTimer] Skipping an event because of timestamp check") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue if timer.checkTimeframe(begin): doLog("[AutoTimer] Skipping an event because of timeframe check") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue # Initialize newEntry = None oldEntry = None oldExists = False allow_modify = True newAT = None # Eventually change service to alternative if timer.overrideAlternatives: serviceref = timer.getAlternative(serviceref) if timer.series_labeling and sp_getSeasonEpisode is not None: allow_modify = False doLog("[AutoTimer SeriesPlugin] Request name, desc, path %s %s %s" % (name, shortdesc, dest)) sp = sp_getSeasonEpisode(serviceref, name, evtBegin, evtEnd, shortdesc, dest) if sp and type(sp) in (tuple, list) and len(sp) == 4: name = sp[0] or name shortdesc = sp[1] or shortdesc dest = sp[2] or dest doLog(str(sp[3])) allow_modify = True doLog("[AutoTimer SeriesPlugin] Returned name, desc, path %s %s %s" % (name, shortdesc, dest)) else: # Nothing found doLog(str(sp)) # If AutoTimer name not equal match, do a second lookup with the name if timer.name.lower() != timer.match.lower(): doLog("[AutoTimer SeriesPlugin] Request name, desc, path %s %s %s" % (timer.name, shortdesc, dest)) sp = sp_getSeasonEpisode(serviceref, timer.name, evtBegin, evtEnd, shortdesc, dest) if sp and type(sp) in (tuple, list) and len(sp) == 4: name = sp[0] or name shortdesc = sp[1] or shortdesc dest = sp[2] or dest doLog(str(sp[3])) allow_modify = True doLog("[AutoTimer SeriesPlugin] Returned name, desc, path %s %s %s" % (name, shortdesc, dest)) else: doLog(str(sp)) if timer.checkFilter(name, shortdesc, extdesc, dayofweek): doLog("[AutoTimer] Skipping an event because of filter check") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue if timer.hasOffset(): # Apply custom Offset begin, end = timer.applyOffset(begin, end) else: # Apply E2 Offset begin -= config.recording.margin_before.value * 60 end += config.recording.margin_after.value * 60 # Overwrite endtime if requested if timer.justplay and not timer.setEndtime: end = begin # Check for existing recordings in directory if timer.avoidDuplicateDescription == 3: # Reset movie Exists movieExists = False if dest and dest not in moviedict: self.addDirectoryToMovieDict(moviedict, dest, serviceHandler) for movieinfo in moviedict.get(dest, ()): if self.checkDuplicates(timer, name, movieinfo.get("name"), shortdesc, movieinfo.get("shortdesc"), extdesc, movieinfo.get("extdesc")): doLog("[AutoTimer] We found a matching recorded movie, skipping event:", name) movieExists = True break if movieExists: doLog("[AutoTimer] Skipping an event because movie already exists") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue # Check for double Timers # We first check eit and if user wants us to guess event based on time # we try this as backup. The allowed diff should be configurable though. for rtimer in timerdict.get(serviceref, ()): if rtimer.eit == eit: oldExists = True doLog("[AutoTimer] We found a timer based on eit") newEntry = rtimer oldEntry = rtimer break elif config.plugins.autotimer.try_guessing.value: if timer.hasOffset(): # Remove custom Offset rbegin = rtimer.begin + timer.offset[0] * 60 rend = rtimer.end - timer.offset[1] * 60 else: # Remove E2 Offset rbegin = rtimer.begin + config.recording.margin_before.value * 60 rend = rtimer.end - config.recording.margin_after.value * 60 # As alternative we could also do a epg lookup #revent = epgcache.lookupEventId(rtimer.service_ref.ref, rtimer.eit) #rbegin = revent.getBeginTime() or 0 #rduration = revent.getDuration() or 0 #rend = rbegin + rduration or 0 if getTimeDiff(rbegin, rend, evtBegin, evtEnd) > ((duration/10)*8) or timeSimilarityPercent(rtimer, evtBegin, evtEnd, timer) > 80: oldExists = True doLog("[AutoTimer] We found a timer based on time guessing") newEntry = rtimer oldEntry = rtimer break if timer.avoidDuplicateDescription >= 1 and not rtimer.disabled: if self.checkDuplicates(timer, name, rtimer.name, shortdesc, rtimer.description, extdesc, rtimer.extdesc): # if searchForDuplicateDescription > 1 then check short description oldExists = True doLog("[AutoTimer] We found a timer (similar service) with same description, skipping event") break # We found no timer we want to edit if newEntry is None: # But there is a match if oldExists: doLog("[AutoTimer] Skipping an event because a timer on same service exists") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue # We want to search for possible doubles if timer.avoidDuplicateDescription >= 2: for rtimer in chain.from_iterable( itervalues(timerdict) ): if not rtimer.disabled: if self.checkDuplicates(timer, name, rtimer.name, shortdesc, rtimer.description, extdesc, rtimer.extdesc): oldExists = True doLog("[AutoTimer] We found a timer (any service) with same description, skipping event") break if oldExists: doLog("[AutoTimer] Skipping an event because a timer on any service exists") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue if timer.checkCounter(timestamp): doLog("[AutoTimer] Not adding new timer because counter is depleted.") skipped.append((name, begin, end, serviceref, timer.name, getLog())) continue # Append to timerlist and abort if simulating timers.append((name, begin, end, serviceref, timer.name, getLog())) if simulateOnly: continue if newEntry is not None: # Abort if we don't want to modify timers or timer is repeated if config.plugins.autotimer.refresh.value == "none" or newEntry.repeated: doLog("[AutoTimer] Won't modify existing timer because either no modification allowed or repeated timer") continue if "autotimer" in newEntry.flags: msg = "[AutoTimer] AutoTimer %s modified this automatically generated timer." % (timer.name) doLog(msg) newEntry.log(501, msg) else: if config.plugins.autotimer.refresh.value != "all": doLog("[AutoTimer] Won't modify existing timer because it's no timer set by us") continue msg = "[AutoTimer] Warning, AutoTimer %s messed with a timer which might not belong to it: %s ." % (timer.name, newEntry.name) doLog(msg) newEntry.log(501, msg) if allow_modify: if self.modifyTimer(newEntry, name, shortdesc, begin, end, serviceref, eit, base_timer=timer): msg = "[AutoTimer] AutoTimer modified timer: %s ." % (newEntry.name) doLog(msg) newEntry.log(501, msg) modified += 1 else: msg = "[AutoTimer] AutoTimer modification not allowed for timer %s because conflicts or double timer." % (newEntry.name) doLog(msg) if oldEntry: self.setOldTimer(newEntry, oldEntry) doLog("[AutoTimer] conflict for modification timer %s detected return to old timer" % (newEntry.name)) continue else: msg = "[AutoTimer] AutoTimer modification not allowed for timer: %s ." % (newEntry.name) doLog(msg) continue else: newEntry = RecordTimerEntry(ServiceReference(serviceref), begin, end, name, shortdesc, eit) newAT = True msg = "[AutoTimer] Try to add new timer based on AutoTimer %s." % (timer.name) doLog(msg) newEntry.log(500, msg) # Mark this entry as AutoTimer newEntry.flags.add("autotimer") # Apply afterEvent if timer.hasAfterEvent(): afterEvent = timer.getAfterEventTimespan(localtime(end)) if afterEvent is None: afterEvent = timer.getAfterEvent() if afterEvent is not None: newEntry.afterEvent = afterEvent newEntry.dirname = dest newEntry.calculateFilename() newEntry.justplay = timer.justplay newEntry.vpsplugin_enabled = timer.vps_enabled newEntry.vpsplugin_overwrite = timer.vps_overwrite newEntry.conflict_detection = timer.conflict_detection newEntry.always_zap = timer.always_zap newEntry.zap_wakeup = timer.zap_wakeup tags = timer.tags[:] if config.plugins.autotimer.add_autotimer_to_tags.value: if 'AutoTimer' not in tags: tags.append('AutoTimer') if config.plugins.autotimer.add_name_to_tags.value: tagname = timer.name.strip() if tagname: tagname = tagname[0].upper() + tagname[1:].replace(" ", "_") if tagname not in tags: tags.append(tagname) newEntry.tags = tags if oldExists and newAT is None: if self.isResolvedConflict(newEntry): recordHandler.timeChanged(newEntry) else: if oldEntry: self.setOldTimer(newEntry, oldEntry) doLog("[AutoTimer] rechecking - conflict for timer %s detected return to old timer" % (newEntry.name)) continue elif newAT: newAT = newEntry conflictString = "" if similarTimer: conflictString = similardict[eit].conflictString msg = "[AutoTimer] Try to add similar Timer because of conflicts with %s." % (conflictString) doLog(msg) newEntry.log(504, msg) # add new timer in AT timer list atDoubleTimer = False refstr = ':'.join(newEntry.service_ref.ref.toString().split(':')[:11]) for at in addNewTimers: needed_ref = ':'.join(at.service_ref.ref.toString().split(':')[:11]) == refstr if needed_ref and at.eit == newEntry.eit and (newEntry.begin < at.begin <= newEntry.end or at.begin <= newEntry.begin <= at.end): atDoubleTimer = True break if atDoubleTimer: doLog("[AutoTimer] ignore double new auto timer %s." % newEntry.name) continue else: addNewTimers.append(newEntry) # Try to add timer conflicts = recordHandler.record(newEntry) if conflicts and not timer.hasOffset() and not config.recording.margin_before.value and not config.recording.margin_after.value and len(conflicts) > 1: change_end = change_begin = False conflict_begin = conflicts[1].begin conflict_end = conflicts[1].end if conflict_begin == newEntry.end: newEntry.end -= 30 change_end = True elif newEntry.begin == conflict_end: newEntry.begin += 30 change_begin = True if change_end or change_begin: conflicts = recordHandler.record(newEntry) if conflicts: if change_end: newEntry.end += 30 elif change_begin: newEntry.begin -= 30 else: doLog("[AutoTimer] The conflict is resolved by offset time begin/end (30 sec) for %s." % newEntry.name) if conflicts: # Maybe use newEntry.log conflictString += ' / '.join(["%s (%s)" % (x.name, strftime("%Y%m%d %H%M", localtime(x.begin))) for x in conflicts]) doLog("[AutoTimer] conflict with %s detected" % (conflictString)) if config.plugins.autotimer.addsimilar_on_conflict.value: # We start our search right after our actual index # Attention we have to use a copy of the list, because we have to append the previous older matches lepgm = len(epgmatches) for i in xrange(lepgm): servicerefS, eitS, nameS, beginS, durationS, shortdescS, extdescS = epgmatches[ (i+idx+1)%lepgm ] if self.checkDuplicates(timer, name, nameS, shortdesc, shortdescS, extdesc, extdescS, force=True): # Check if the similar is already known if eitS not in similardict: doLog("[AutoTimer] Found similar Timer: " + name) # Store the actual and similar eit and conflictString, so it can be handled later newEntry.conflictString = conflictString similardict[eit] = newEntry similardict[eitS] = newEntry similarTimer = True if beginS <= evtBegin: # Event is before our actual epgmatch so we have to append it to the epgmatches list epgmatches.append((servicerefS, eitS, nameS, beginS, durationS, shortdescS, extdescS)) # If we need a second similar it will be found the next time else: similarTimer = False newEntry = similardict[eitS] break if conflicts is None: timer.decrementCounter() if newEntry in (recordHandler.timer_list[:] + recordHandler.processed_timers[:]): new += 1 newEntry.extdesc = extdesc timerdict[serviceref].append(newEntry) # Similar timers are in new timers list and additionally in similar timers list if similarTimer: similars.append((name, begin, end, serviceref, timer.name)) similardict.clear() else: doLog("[AutoTimer] ignore double timer %s." % newEntry.name) # Don't care about similar timers elif not similarTimer: conflicting.append((name, begin, end, serviceref, timer.name)) if config.plugins.autotimer.disabled_on_conflict.value: msg = "[AutoTimer] Timer disabled because of conflicts with %s." % (conflictString) doLog(msg) newEntry.log(503, msg) newEntry.disabled = True if newEntry in (recordHandler.timer_list[:] + recordHandler.processed_timers[:]): recordHandler.timeChanged(newEntry) else: # We might want to do the sanity check locally so we don't run it twice - but I consider this workaround a hack anyway conflicts = recordHandler.record(newEntry) elif newAT != newEntry and newEntry in (recordHandler.timer_list[:] + recordHandler.processed_timers[:]): if not self.isResolvedConflict(newEntry): newEntry.disabled = True recordHandler.timeChanged(newEntry) doLog("[AutoTimer] Unknown conflict, disable this timer %s." % newEntry.name) return (new, modified)
def getStream(session, request, m3ufile): sRef = getUrlArg(request, "ref") if sRef != None: if PY3: sRef = unquote(unquote(sRef)) else: sRef = unquote( unquote(request.args["ref"][0]).decode( 'utf-8', 'ignore')).encode('utf-8') else: sRef = "" currentServiceRef = None if m3ufile == "streamcurrent.m3u": currentServiceRef = session.nav.getCurrentlyPlayingServiceReference() sRef = currentServiceRef.toString() if sRef.startswith("1:134:"): if currentServiceRef is None: currentServiceRef = session.nav.getCurrentlyPlayingServiceReference( ) if currentServiceRef is None: currentServiceRef = eServiceReference() ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef) if ref is None: sRef = "" else: sRef = ref.toString() # #EXTINF:-1,%s\n adding back to show service name in programs like VLC progopt = '' name = getUrlArg(request, "name") if name != None: if config.OpenWebif.service_name_for_stream.value: progopt = "#EXTINF:-1,%s\n" % name name = "stream" portNumber = config.OpenWebif.streamport.value info = getInfo() model = info["model"] procmodel = info["procmodel"] urlparam = '&' transcoder_port = None args = "" device = getUrlArg(request, "device") if fileExists("/dev/bcm_enc0"): try: transcoder_port = int(config.plugins.transcodingsetup.port.value) except Exception: # Transcoding Plugin is not installed or your STB does not support transcoding transcoder_port = None if device == "phone": portNumber = transcoder_port _port = getUrlArg(request, "port") if _port != None: portNumber = _port elif fileExists("/dev/encoder0") or fileExists( "/proc/stb/encoder/0/apply"): transcoder_port = portNumber if fileExists("/dev/bcm_enc0") or fileExists( "/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"): if device == "phone": try: bitrate = config.plugins.transcodingsetup.bitrate.value resolution = config.plugins.transcodingsetup.resolution.value (width, height) = tuple(resolution.split('x')) # framerate = config.plugins.transcodingsetup.framerate.value aspectratio = config.plugins.transcodingsetup.aspectratio.value interlaced = config.plugins.transcodingsetup.interlaced.value if fileExists("/proc/stb/encoder/0/vcodec"): vcodec = config.plugins.transcodingsetup.vcodec.value args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % ( bitrate, width, height, vcodec, aspectratio, interlaced) else: args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % ( bitrate, width, height, aspectratio, interlaced) args = args.replace('__', urlparam) except Exception: pass # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port: progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3], 16)) if config.OpenWebif.auth_for_streaming.value: asession = GetSession() if asession.GetAuth(request) is not None: auth = ':'.join(asession.GetAuth(request)) + "@" else: auth = '-sid:' + str(asession.GetSID(request)) + "@" else: auth = '' response = "#EXTM3U \n#EXTVLCOPT:http-reconnect=true \n%shttp://%s%s:%s/%s%s\n" % ( progopt, auth, request.getRequestHostname(), portNumber, sRef, args) if config.OpenWebif.playiptvdirect.value: if "http://" in sRef or "https://" in sRef: l = sRef.split(":http")[1] response = "#EXTM3U \n#EXTVLCOPT:http-reconnect=true\n%shttp%s\n" % ( progopt, l) request.setHeader('Content-Type', 'application/x-mpegurl') # Note: do not rename the m3u file all the time fname = getUrlArg(request, "fname") if fname != None: request.setHeader('Content-Disposition', 'inline; filename=%s.%s;' % (fname, 'm3u8')) return response
def P_timeradd(self, request): res = self.testMandatoryArguments(request, ["sRef", "begin", "end", "name"]) if res: return res disabled = False if "disabled" in request.args.keys(): disabled = request.args["disabled"][0] == "1" justplay = False if "justplay" in request.args.keys(): justplay = request.args["justplay"][0] == "1" afterevent = 3 if "afterevent" in request.args.keys() and request.args["afterevent"][0] in ["1", "2", "3"]: afterevent = int(request.args["afterevent"][0]) dirname = None if "dirname" in request.args.keys() and len(request.args["dirname"][0]) > 0: dirname = request.args["dirname"][0] tags = [] if "tags" in request.args.keys(): tags = request.args["tags"][0].split(' ') repeated = 0 if "repeated" in request.args.keys(): repeated = int(request.args["repeated"][0]) description = "" if "description" in request.args.keys(): description = request.args["description"][0] eit = 0 if "eit" in request.args.keys() and type(request.args["eit"][0]) is int: eventid = request.args["eit"][0] else: from enigma import eEPGCache, eServiceReference queryTime = int(request.args["begin"][0]) + (int(request.args["end"][0]) - int(request.args["begin"][0])) / 2 event = eEPGCache.getInstance().lookupEventTime(eServiceReference(request.args["sRef"][0]), queryTime) eventid = event and event.getEventId() if eventid is not None: eit = int(eventid) always_zap = -1 if "always_zap" in request.args.keys(): always_zap = int(request.args["always_zap"][0]) return addTimer( self.session, request.args["sRef"][0], request.args["begin"][0], request.args["end"][0], request.args["name"][0], description, disabled, justplay, afterevent, dirname, tags, repeated, self.vpsparams(request), None, eit, always_zap )
def __init__(self, session, infobar): Screen.__init__(self, session) self.skin = QuickSubtitlesConfigMenu.skin self.infobar = infobar or self.session.infobar self.wait = eTimer() self.wait.timeout.get().append(self.resyncSubtitles) self.service = self.session.nav.getCurrentlyPlayingServiceReference() servicepath = self.service and self.service.getPath() if servicepath and servicepath.startswith( "/") and self.service.toString().startswith("1:"): info = eServiceCenter.getInstance().info(self.service) self.service_string = info and info.getInfoString( self.service, iServiceInformation.sServiceref) else: self.service_string = self.service.toString() self.center_dvb_subs = ConfigYesNo( default=(eDVBDB.getInstance().getFlag( eServiceReference(self.service_string)) & self.FLAG_CENTER_DVB_SUBS) and True) self.center_dvb_subs.addNotifier(self.setCenterDvbSubs) self["videofps"] = Label("") sub = self.infobar.selected_subtitle if sub[0] == 0: # dvb menu = [ getConfigMenuItem("config.subtitles.dvb_subtitles_yellow"), getConfigMenuItem("config.subtitles.dvb_subtitles_backtrans"), getConfigMenuItem( "config.subtitles.dvb_subtitles_original_position"), (_("Center DVB subtitles"), self.center_dvb_subs), getConfigMenuItem("config.subtitles.subtitle_position"), getConfigMenuItem( "config.subtitles.subtitle_bad_timing_delay"), getConfigMenuItem( "config.subtitles.subtitle_noPTSrecordingdelay"), ] elif sub[0] == 1: # teletext menu = [ getConfigMenuItem("config.subtitles.ttx_subtitle_colors"), getConfigMenuItem( "config.subtitles.ttx_subtitle_original_position"), getConfigMenuItem("config.subtitles.subtitle_fontsize"), getConfigMenuItem("config.subtitles.subtitle_position"), getConfigMenuItem("config.subtitles.subtitle_rewrap"), getConfigMenuItem("config.subtitles.subtitle_borderwidth"), getConfigMenuItem("config.subtitles.showbackground"), getConfigMenuItem("config.subtitles.subtitle_alignment"), getConfigMenuItem( "config.subtitles.subtitle_bad_timing_delay"), getConfigMenuItem( "config.subtitles.subtitle_noPTSrecordingdelay"), ] else: # pango menu = [ getConfigMenuItem("config.subtitles.pango_subtitles_delay"), getConfigMenuItem("config.subtitles.pango_subtitle_colors"), getConfigMenuItem( "config.subtitles.pango_subtitle_fontswitch"), getConfigMenuItem("config.subtitles.colourise_dialogs"), getConfigMenuItem("config.subtitles.subtitle_fontsize"), getConfigMenuItem("config.subtitles.subtitle_position"), getConfigMenuItem("config.subtitles.subtitle_alignment"), getConfigMenuItem("config.subtitles.subtitle_rewrap"), getConfigMenuItem("config.subtitles.subtitle_borderwidth"), getConfigMenuItem("config.subtitles.showbackground"), getConfigMenuItem("config.subtitles.pango_subtitles_fps"), ] self["videofps"].setText( _("Video: %s fps") % (self.getFps().rstrip(".000"))) ConfigListScreen.__init__(self, menu, self.session, on_change=self.changedEntry) self["actions"] = NumberActionMap(["SetupActions"], { "cancel": self.cancel, "ok": self.ok, }, -2) self.onLayoutFinish.append(self.layoutFinished)
def getLists(self): self.tv_list = self.getListFromRef(eServiceReference('1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 195) || (type == 25) FROM BOUQUET "bouquets.tv" ORDER BY bouquet')) self.radio_list = self.getListFromRef(eServiceReference('1:7:2:0:0:0:0:0:0:0:(type == 2) FROM BOUQUET "bouquets.radio" ORDER BY bouquet'))
def execHotkey(self, selected): if selected: selected = selected[1].split("/") if selected[0] == "Plugins": twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins(PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if plugin.path[pathLen:] in twinPaths: twinPaths[plugin.path[pathLen:]] += 1 else: twinPaths[plugin.path[pathLen:]] = 1 if plugin.path[pathLen:] + "/" + str(twinPaths[plugin.path[pathLen:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if plugin.path[pathLen:] in twinPaths: twinPaths[plugin.path[pathLen:]] += 1 else: twinPaths[plugin.path[pathLen:]] = 1 if plugin.path[pathLen:] + "/" + str(twinPaths[plugin.path[pathLen:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) elif selected[0] == "MenuPlugin": for plugin in plugins.getPluginsForMenu(selected[1]): if plugin[2] == selected[2]: self.runPlugin(plugin[1]) return elif selected[0] == "Infobar": if hasattr(self, selected[1]): exec "self." + ".".join(selected[1:]) + "()" else: return 0 elif selected[0] == "Module": try: exec "from %s import %s" % (selected[1], selected[2]) exec "self.session.open(%s)" % ",".join(selected[2:]) except: print "[Hotkey] error during executing module %s, screen %s" % (selected[1], selected[2]) elif selected[0] == "Setup": from Screens.Setup import Setup exec "self.session.open(Setup, \"%s\")" % selected[1] elif selected[0].startswith("Zap"): if selected[0] == "ZapPanic": self.servicelist.history = [] self.pipShown() and self.showPiP() self.servicelist.servicelist.setCurrent(eServiceReference("/".join(selected[1:]))) self.servicelist.zap(enable_pipzap=True) if hasattr(self, "lastservice"): self.lastservice = eServiceReference("/".join(selected[1:])) self.close() else: self.show() elif selected[0] == "PPanel": ppanelFileName = '/etc/ppanels/' + selected[1] + ".xml" if os.path.isfile(ppanelFileName) and os.path.isdir(ppath + "/Plugins/Extensions/PPanel"): from Plugins.Extensions.PPanel.ppanel import PPanel self.session.open(PPanel, name=selected[1] + ' PPanel', node=None, filename=ppanelFileName, deletenode=None) elif selected[0] == "Shellscript": command = '/usr/scripts/' + selected[1] + ".sh" if os.path.isfile(command) and os.path.isdir(ppath + "/Plugins/Extensions/PPanel"): from Plugins.Extensions.PPanel.ppanel import Execute self.session.open(Execute, selected[1] + " shellscript", None, command) else: os.system(command) elif selected[0] == "EMC": try: from Plugins.Extensions.EnhancedMovieCenter.plugin import showMoviesNew from Screens.InfoBar import InfoBar open(showMoviesNew(InfoBar.instance)) except Exception as e: print('[EMCPlayer] showMovies exception:\n' + str(e)) elif selected[0] == "Kodi": if os.path.isfile(ppath + "/Plugins/Extensions/Kodi/plugin.pyo"): from Plugins.Extensions.Kodi.plugin import KodiMainScreen self.session.open(KodiMainScreen) elif selected[0] == "DeviceManager": from Plugins.SystemPlugins.DeviceManager.HddSetup import * self.session.open(HddSetup)
def getTS(self, request): file = getUrlArg(request, "file") if file != None: if PY3: filename = unquote(file) else: filename = unquote(file).decode('utf-8', 'ignore').encode('utf-8') if not os.path.exists(filename): return "File '%s' not found" % (filename) # ServiceReference is not part of filename so look in the '.ts.meta' file sRef = "" progopt = '' if os.path.exists(filename + '.meta'): metafile = open(filename + '.meta', "r") name = '' seconds = -1 # unknown duration default line = metafile.readline() # service ref if line: sRef = eServiceReference(line.strip()).toString() line2 = metafile.readline() # name if line2: name = line2.strip() line6 = metafile.readline() # description line6 = metafile.readline() # recording time line6 = metafile.readline() # tags line6 = metafile.readline() # length if line6: seconds = float(line6.strip()) / 90000 # In seconds if config.OpenWebif.service_name_for_stream.value: progopt = "%s#EXTINF:%d,%s\n" % (progopt, seconds, name) metafile.close() portNumber = None proto = 'http' info = getInfo() model = info["model"] procmodel = info["procmodel"] transcoder_port = None args = "" urlparam = '&' device = getUrlArg(request, "device") if fileExists("/dev/bcm_enc0") or fileExists( "/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"): try: transcoder_port = int( config.plugins.transcodingsetup.port.value) except Exception: # Transcoding Plugin is not installed or your STB does not support transcoding transcoder_port = None if device == "phone": portNumber = transcoder_port _port = getUrlArg(request, "port") if _port != None: portNumber = _port if fileExists("/dev/bcm_enc0") or fileExists( "/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"): if device == "phone": try: bitrate = config.plugins.transcodingsetup.bitrate.value resolution = config.plugins.transcodingsetup.resolution.value (width, height) = tuple(resolution.split('x')) # framerate = config.plugins.transcodingsetup.framerate.value aspectratio = config.plugins.transcodingsetup.aspectratio.value interlaced = config.plugins.transcodingsetup.interlaced.value if fileExists("/proc/stb/encoder/0/vcodec"): vcodec = config.plugins.transcodingsetup.vcodec.value args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % ( bitrate, width, height, vcodec, aspectratio, interlaced) else: args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % ( bitrate, width, height, aspectratio, interlaced) args = args.replace('__', urlparam) except Exception: pass # Add position parameter to m3u link position = getUrlArg(request, "position") if position != None: args = args + "&position=" + position # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port: progopt = "%s#EXTVLCOPT:program=%d\n" % ( progopt, int(sRef.split(':')[3], 16)) if portNumber is None: portNumber = config.OpenWebif.port.value if request.isSecure(): portNumber = config.OpenWebif.https_port.value proto = 'https' ourhost = request.getHeader('host') m = re.match('.+\:(\d+)$', ourhost) if m is not None: portNumber = m.group(1) if config.OpenWebif.auth_for_streaming.value: asession = GetSession() if asession.GetAuth(request) is not None: auth = ':'.join(asession.GetAuth(request)) + "@" else: auth = '-sid:' + str(asession.GetSID(request)) + "@" else: auth = '' response = "#EXTM3U \n#EXTVLCOPT:http-reconnect=true \n%s%s://%s%s:%s/file?file=%s%s\n" % ( (progopt, proto, auth, request.getRequestHostname(), portNumber, quote(filename), args)) request.setHeader('Content-Type', 'application/x-mpegurl') return response else: return "Missing file parameter"
def addServiceToAlternative(self, param): sBouquetRef = param["sBouquetRef"] if sBouquetRef is None: return (False, "No bouquet given!") sRef = None if "sRef" in param: if param["sRef"] is not None: sRef = param["sRef"] # service to add to the alternative if sRef is None: return (False, "No service given!") sCurrentRef = param["sCurrentRef"] # alternative service if sCurrentRef is None: return (False, "No current service given!") cur_ref = eServiceReference(sCurrentRef) # check if service is already an alternative if not (cur_ref.flags & eServiceReference.isGroup): # sCurrentRef is not an alternative service yet, so do this and add itself to new alternative liste mode = MODE_TV # init if "mode" in param: if param["mode"] is not None: mode = int(param["mode"]) mutableBouquetList = self.getMutableList( eServiceReference(sBouquetRef)) if mutableBouquetList: cur_service = ServiceReference(cur_ref) name = cur_service.getServiceName() if mode == MODE_TV: sref = '1:134:1:0:0:0:0:0:0:0:FROM BOUQUET \"alternatives.%s.tv\" ORDER BY bouquet' % ( self.buildBouquetID(name, "alternatives.", mode)) else: sref = '1:134:2:0:0:0:0:0:0:0:FROM BOUQUET \"alternatives.%s.radio\" ORDER BY bouquet' % ( self.buildBouquetID(name, "alternatives.", mode)) new_ref = eServiceReference(sref) if not mutableBouquetList.addService(new_ref, cur_ref): mutableBouquetList.removeService(cur_ref) mutableBouquetList.flushChanges() eDVBDB.getInstance().reloadBouquets() mutableAlternatives = self.getMutableList(new_ref) if mutableAlternatives: mutableAlternatives.setListName(name) if mutableAlternatives.addService(cur_ref): print "add", cur_ref.toString( ), "to new alternatives failed" mutableAlternatives.flushChanges() self.setRoot(sBouquetRef) sCurrentRef = sref # currentRef is now an alternative (bouquet) else: return ( False, "Get mutable list for new created alternative failed!" ) else: return (False, "Alternative %s created failed." % name) else: return (False, "Bouquetlist is not editable!") # add service to alternative-bouquet new_param = {} new_param["sBouquetRef"] = sCurrentRef new_param["sRef"] = sRef returnValue = self.addServiceToBouquet(new_param) if returnValue[0]: cur_ref = eServiceReference(sCurrentRef) cur_service = ServiceReference(cur_ref) name = cur_service.getServiceName() service_ref = ServiceReference(sRef) service_name = service_ref.getServiceName() return (True, "Added %s to alternative service %s." % (service_name, name)) else: return returnValue
def getAlternativeChannels(service): alternativeServices = eServiceCenter.getInstance().list( eServiceReference(service)) return alternativeServices and alternativeServices.getContent("S", True)
def isServicePlayable(self, ref, callback, session=None): self.session = session if not config.ParentalControl.configured.value or not config.ParentalControl.servicepinactive.value: return True #Check if configuration has already been read or if the significant values have changed. #If true: read the configuration if self.configInitialized == False or self.storeServicePin != config.ParentalControl.storeservicepin.value: self.getConfigValues() service = ref.toCompareString() info = eServiceCenter.getInstance().info(ref) age = 0 if service.startswith("1:") and service.rsplit(":", 1)[1].startswith("/"): refstr = info and info.getInfoString( ref, iServiceInformation.sServiceref) service = refstr and eServiceReference(refstr).toCompareString() else: event = info and info.getEvent(ref) rating = event and event.getParentalData() age = rating and rating.getRating() + 3 or 0 if (age and age >= int(config.ParentalControl.age.value)) or service and ( (config.ParentalControl.type.value == LIST_WHITELIST and not self.whitelist.has_key(service)) or (config.ParentalControl.type.value == LIST_BLACKLIST and self.blacklist.has_key(service))): #Check if the session pin is cached if self.sessionPinCached == True: return True self.callback = callback #Someone started to implement different levels of protection. Seems they were never completed #I did not throw out this code, although it is of no use at the moment levelNeeded = 0 if self.serviceLevel.has_key(service): levelNeeded = self.serviceLevel[service] pinList = self.getPinList()[:levelNeeded + 1] title = 'FROM BOUQUET "userbouquet.' in service and _( "this bouquet is protected by a parental control pin") or _( "this service is protected by a parental control pin") if session: Notifications.RemovePopup("Parental control") if self.PinDlg: self.PinDlg.close() self.PinDlg = session.openWithCallback( boundFunction(self.servicePinEntered, ref), PinInput, triesEntry=config.ParentalControl.retries.servicepin, pinList=pinList, service=ServiceReference(ref).getServiceName(), title=title, windowTitle=_("Parental control"), simple=False) else: Notifications.AddNotificationParentalControl( boundFunction(self.servicePinEntered, ref), PinInput, triesEntry=config.ParentalControl.retries.servicepin, pinList=pinList, service=ServiceReference(ref).getServiceName(), title=title, windowTitle=_("Parental control")) return False else: return True
def getMutableBouquetList(self, mode): if mode == MODE_TV: self.bouquet_rootstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet' else: self.bouquet_rootstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.radio" ORDER BY bouquet' return self.getMutableList(eServiceReference(self.bouquet_rootstr))