def getSearchSimilarEpg(ref, eventid): ref = unquote(ref) ret = [] epgcache = eEPGCache.getInstance() events = epgcache.search( ('IBDTSENR', 128, eEPGCache.SIMILAR_BROADCASTINGS_SEARCH, ref, eventid)) if events is not None: for event in events: day_val = strftime("%w", (localtime(event[1]))) date_val = strftime("%d.%m.%Y", (localtime(event[1]))) ev = {} ev['id'] = event[0] ev['date'] = "%s %s" % (tstrings[("day_" + day_val)], date_val) ev['begin_timestamp'] = event[1] ev['begin'] = strftime("%H:%M", (localtime(event[1]))) ev['duration_sec'] = event[2] ev['duration'] = int(event[2] / 60) ev['end'] = strftime("%H:%M", (localtime(event[1] + event[2]))) ev['title'] = event[3] ev['shortdesc'] = event[4] ev['longdesc'] = event[5] ev['sref'] = event[7] ev['sname'] = mangle_epg_text(event[6]) ev['picon'] = getPicon(event[7]) ev['now_timestamp'] = None ret.append(ev) return {"events": ret, "result": True}
def getEvent(ref, idev): epgcache = eEPGCache.getInstance() events = epgcache.lookupEvent(['IBDTSENRX', (ref, 2, int(idev))]) info = {} for event in events: info['id'] = event[0] info['begin_str'] = strftime("%H:%M", (localtime(event[1]))) info['begin'] = event[1] info['end'] = strftime("%H:%M", (localtime(event[1] + event[2]))) info['duration'] = event[2] info['title'] = mangle_epg_text(event[3]) info['shortdesc'] = event[4] info['longdesc'] = event[5] info['channel'] = mangle_epg_text(event[6]) info['sref'] = event[7] break return {'event': info}
def recordNow(session, infinite): rt = session.nav.RecordTimer serviceref = session.nav.getCurrentlyPlayingServiceReference().toString() try: event = session.nav.getCurrentService().info().getEvent(0) except Exception: event = None if not event and not infinite: return { "result": False, "message": _("No event found! Not recording!") } if event: (begin, end, name, description, eit) = parseEvent(event) begin = time() msg = _("Instant record for current Event started") else: name = "instant record" description = "" eit = 0 if infinite: begin = time() end = begin + 3600 * 10 msg = _("Infinite Instant recording started") timer = RecordTimerEntry(ServiceReference(serviceref), begin, end, name, description, eit, False, False, 0, dirname=preferredInstantRecordPath()) timer.dontSave = True if rt.record(timer): return { "result": False, "message": _("Timer conflict detected! Not recording!") } nt = { "serviceref": str(timer.service_ref), "servicename": mangle_epg_text(timer.service_ref.getServiceName()), "eit": timer.eit, "name": timer.name, "begin": timer.begin, "end": timer.end, "duration": timer.end - timer.begin } return {"result": True, "message": msg, "newtimer": nt}
def __init__(self, raw_data, now_next_mode=False, mangle_html=True): dict.__init__(self) for key in SERVICES_KEY_MAP: idx = SERVICES_KEY_MAP[key] self[key] = raw_data[idx] if mangle_html: self['sname'] = mangle_epg_text(self['sname']) if now_next_mode: if self['begin_timestamp'] == 0: self['duration_sec'] = 0 self['title'] = 'N/A' self['shortdesc'] = '' self['longdesc'] = '' self['now_timestamp'] = 0 self['remaining'] = 0 else: current_timestamp = self['now_timestamp'] if current_timestamp > self['begin_timestamp']: self['remaining'] = self['begin_timestamp'] + self[ 'duration_sec'] - current_timestamp else: self['remaining'] = self['duration_sec']
def getPicon(sname): if not PICON_PATH: return FALLBACK_PICON_LOCATION # remove URL part if ("://" in sname) or ("%3a//" in sname) or ("%3A//" in sname): sname = unquote(sname) sname = ":".join(sname.split(":")[:10]) + "::" + sname.split(":")[-1] sname = GetWithAlternative(sname) if sname is not None: pos = sname.rfind(':') else: return FALLBACK_PICON_LOCATION cname = None if pos != -1: cname = ServiceReference(sname[:pos].rstrip(':')).getServiceName() sname = sname[:pos].rstrip(':').replace(':', '_') + PICON_EXT filename = PICON_PATH + sname if os.path.isfile(filename): return PICON_ENDPOINT_PATH + sname fields = sname.split('_', 8) if len(fields) > 7 and not fields[6].endswith("0000"): # remove "sub-network" from namespace fields[6] = fields[6][:-4] + "0000" sname = '_'.join(fields) filename = PICON_PATH + sname if os.path.isfile(filename): return PICON_ENDPOINT_PATH + sname if len(fields) > 1 and fields[0] != '1': # fallback to 1 for other reftypes fields[0] = '1' sname = '_'.join(fields) filename = PICON_PATH + sname if os.path.isfile(filename): return PICON_ENDPOINT_PATH + sname if len(fields) > 3 and fields[2] != '1': # fallback to 1 for tv services with nonstandard servicetypes fields[2] = '1' sname = '_'.join(fields) filename = PICON_PATH + sname if os.path.isfile(filename): return PICON_ENDPOINT_PATH + sname if cname is not None: # picon by channel name cname1 = mangle_epg_text(cname).replace('/', '_').encode('utf-8', 'ignore') if os.path.isfile(PICON_PATH + cname1 + PICON_EXT): return PICON_ENDPOINT_PATH + cname1 + PICON_EXT cname = unicodedata.normalize('NFKD', unicode(cname, 'utf_8', errors='ignore')).encode( 'ASCII', 'ignore') cname = re.sub( '[^a-z0-9]', '', cname.replace('&', 'and').replace('+', 'plus').replace('*', 'star').lower()) if len(cname) > 0: filename = PICON_PATH + cname + PICON_EXT if os.path.isfile(filename): return PICON_ENDPOINT_PATH + cname + PICON_EXT if len(cname) > 2 and cname.endswith('hd') and os.path.isfile( PICON_PATH + cname[:-2] + PICON_EXT): return PICON_ENDPOINT_PATH + cname[:-2] + PICON_EXT
def getSearchEpg(sstr, endtime=None, fulldesc=False, bouquetsonly=False): """ Search for EPG events. Args: sstr (basestring): search term endtime (int): timetamp fulldesc (bool): search in event's description field too bouquetsonly (bool): limit results to services in known bouquets Returns: list: event datasets """ bsref = {} events = [] epgcache = eEPGCache.getInstance() search_type = eEPGCache.PARTIAL_TITLE_SEARCH if config.OpenWebif.epg_encoding.value != 'utf-8': try: sstr = sstr.encode(config.OpenWebif.epg_encoding.value) except UnicodeEncodeError: pass if fulldesc: if hasattr(eEPGCache, 'FULL_DESCRIPTION_SEARCH'): search_type = eEPGCache.FULL_DESCRIPTION_SEARCH results = epgcache.search(('IBDTSENR', 128, search_type, sstr, 1)) if results: if bouquetsonly: # collect service references from TV bouquets for service in getAllServices('tv')['services']: for service2 in service['subservices']: bsref[service2['servicereference']] = True else: bsref[service['servicereference']] = True for event in results: if bouquetsonly and not event[7] in bsref: continue day_val = strftime("%w", (localtime(event[1]))) date_val = strftime("%d.%m.%Y", (localtime(event[1]))) ev = dict() ev['id'] = event[0] ev['date'] = "%s %s" % (tstrings[("day_" + day_val)], date_val) ev['begin_timestamp'] = event[1] ev['begin'] = strftime("%H:%M", (localtime(event[1]))) ev['duration_sec'] = event[2] ev['duration'] = int(event[2] / 60) ev['end'] = strftime("%H:%M", (localtime(event[1] + event[2]))) ev['title'] = mangle_epg_text(event[3]) ev['shortdesc'] = event[4] ev['longdesc'] = event[5] ev['sref'] = event[7] ev['sname'] = mangle_epg_text(event[6]) ev['picon'] = getPicon(event[7]) ev['now_timestamp'] = None if endtime: # don't show events if begin is after endtime if event[1] <= endtime: events.append(ev) else: events.append(ev) return {"events": events, "result": True}
def getCurrentService(session): try: info = session.nav.getCurrentService().info() return { "result": True, "name": mangle_epg_text(info.getName()), "namespace": getServiceInfoString(info, iServiceInformation.sNamespace), "aspect": getServiceInfoString(info, iServiceInformation.sAspect), "provider": getServiceInfoString(info, iServiceInformation.sProvider), "width": getServiceInfoString(info, iServiceInformation.sVideoWidth), "height": getServiceInfoString(info, iServiceInformation.sVideoHeight), "apid": getServiceInfoString(info, iServiceInformation.sAudioPID), "vpid": getServiceInfoString(info, iServiceInformation.sVideoPID), "pcrpid": getServiceInfoString(info, iServiceInformation.sPCRPID), "pmtpid": getServiceInfoString(info, iServiceInformation.sPMTPID), "txtpid": getServiceInfoString(info, iServiceInformation.sTXTPID), "tsid": getServiceInfoString(info, iServiceInformation.sTSID), "onid": getServiceInfoString(info, iServiceInformation.sONID), "sid": getServiceInfoString(info, iServiceInformation.sSID), "ref": quote(getServiceInfoString(info, iServiceInformation.sServiceref), safe=' ~@#$&()*!+=:;,.?/\''), "iswidescreen": info.getInfo(iServiceInformation.sAspect) in (3, 4, 7, 8, 0xB, 0xC, 0xF, 0x10) } except Exception: return { "result": False, "name": "", "namespace": "", "aspect": 0, "provider": "", "width": 0, "height": 0, "apid": 0, "vpid": 0, "pcrpid": 0, "pmtpid": 0, "txtpid": "N/A", "tsid": 0, "onid": 0, "sid": 0, "ref": "", "iswidescreen": False }
def getChannelEpg(ref, begintime=-1, endtime=-1): ret = [] ev = {} use_empty_ev = False if ref: ref = unquote(ref) # When quering EPG we dont need URL, also getPicon doesn't like URL if "://" in ref: ref = ":".join(ref.split(":")[:10]) + "::" + ref.split(":")[-1] picon = getPicon(ref) epgcache = eEPGCache.getInstance() events = epgcache.lookupEvent( ['IBDTSENC', (ref, 0, begintime, endtime)]) if events is not None: for event in events: ev = {} ev['picon'] = picon ev['id'] = event[0] if event[1]: ev['date'] = "%s %s" % (tstrings[ ("day_" + strftime("%w", (localtime(event[1]))))], strftime("%d.%m.%Y", (localtime(event[1])))) ev['begin'] = strftime("%H:%M", (localtime(event[1]))) ev['begin_timestamp'] = event[1] ev['duration'] = int(event[2] / 60) ev['duration_sec'] = event[2] ev['end'] = strftime("%H:%M", (localtime(event[1] + event[2]))) ev['title'] = mangle_epg_text(event[3]) ev['shortdesc'] = event[4] ev['longdesc'] = event[5] ev['sref'] = ref ev['sname'] = mangle_epg_text(event[6]) ev['tleft'] = int(((event[1] + event[2]) - event[7]) / 60) if ev['duration_sec'] == 0: ev['progress'] = 0 else: ev['progress'] = int( ((event[7] - event[1]) * 100 / event[2]) * 4) ev['now_timestamp'] = event[7] ret.append(ev) else: use_empty_ev = True ev['sref'] = ref else: use_empty_ev = True ev['sref'] = "" if use_empty_ev: ev['date'] = 0 ev['begin'] = 0 ev['begin_timestamp'] = 0 ev['duration'] = 0 ev['duration_sec'] = 0 ev['end'] = 0 ev['title'] = "N/A" ev['shortdesc'] = "" ev['sname'] = "" ev['longdesc'] = "" ev['tleft'] = 0 ev['progress'] = 0 ev['now_timestamp'] = 0 ret.append(ev) return {"events": ret, "result": True}
def editTimer(session, serviceref, begin, end, name, description, disabled, justplay, afterEvent, dirname, tags, repeated, channelOld, beginOld, endOld, vpsinfo, always_zap): # TODO: exception handling channelOld_str = ':'.join(str(channelOld).split(':')[:11]) rt = session.nav.RecordTimer for timer in rt.timer_list + rt.processed_timers: needed_ref = ':'.join( timer.service_ref.ref.toString().split(':')[:11]) == channelOld_str if needed_ref and int(timer.begin) == beginOld and int( timer.end) == endOld: timer.service_ref = ServiceReference(serviceref) # TODO: start end time check timer.begin = int(float(begin)) timer.end = int(float(end)) timer.name = name timer.description = description # TODO : EIT # timer.eit = eit timer.disabled = disabled timer.justplay = justplay timer.afterEvent = afterEvent timer.dirname = dirname timer.tags = tags timer.repeated = repeated timer.processRepeated() if vpsinfo is not None: timer.vpsplugin_enabled = vpsinfo["vpsplugin_enabled"] timer.vpsplugin_overwrite = vpsinfo["vpsplugin_overwrite"] timer.vpsplugin_time = vpsinfo["vpsplugin_time"] if always_zap != -1: if hasattr(timer, "always_zap"): timer.always_zap = always_zap == 1 # TODO: multi tuner test sanity = TimerSanityCheck(rt.timer_list, timer) conflicts = None if not sanity.check(): conflicts = sanity.getSimulTimerList() if conflicts is not None: for conflict in conflicts: if conflict.setAutoincreaseEnd(entry): rt.timeChanged(conflict) if not sanity.check(): conflicts = sanity.getSimulTimerList() if conflicts is None: rt.timeChanged(timer) return { "result": True, "message": _("Timer '%s' changed") % name } else: errors = [] conflictinfo = [] for conflict in conflicts: errors.append(conflict.name) conflictinfo.append({ "serviceref": str(conflict.service_ref), "servicename": mangle_epg_text(conflict.service_ref.getServiceName()), "name": conflict.name, "begin": conflict.begin, "end": conflict.end, "realbegin": strftime("%d.%m.%Y %H:%M", (localtime(float(conflict.begin)))), "realend": strftime("%d.%m.%Y %H:%M", (localtime(float(conflict.end)))) }) return { "result": False, "message": _("Timer '%s' not saved while Conflict") % name, "conflicts": conflictinfo } msg = _("Could not find timer '%s' with given start and end time!") % name return {"result": False, "message": msg}
def addTimer(session, serviceref, begin, end, name, description, disabled, justplay, afterevent, dirname, tags, repeated, vpsinfo=None, logentries=None, eit=0, always_zap=-1): rt = session.nav.RecordTimer if not dirname: dirname = preferredTimerPath() try: timer = RecordTimerEntry(ServiceReference(serviceref), begin, end, name, description, eit, disabled, justplay, afterevent, dirname=dirname, tags=tags) timer.repeated = repeated if logentries: timer.log_entries = logentries conflicts = rt.record(timer) if conflicts: errors = [] conflictinfo = [] for conflict in conflicts: errors.append(conflict.name) conflictinfo.append({ "serviceref": str(conflict.service_ref), "servicename": mangle_epg_text(conflict.service_ref.getServiceName()), "name": conflict.name, "begin": conflict.begin, "end": conflict.end, "realbegin": strftime("%d.%m.%Y %H:%M", (localtime(float(conflict.begin)))), "realend": strftime("%d.%m.%Y %H:%M", (localtime(float(conflict.end)))) }) return { "result": False, "message": _("Conflicting Timer(s) detected! %s") % " / ".join(errors), "conflicts": conflictinfo } # VPS if vpsinfo is not None: timer.vpsplugin_enabled = vpsinfo["vpsplugin_enabled"] timer.vpsplugin_overwrite = vpsinfo["vpsplugin_overwrite"] timer.vpsplugin_time = vpsinfo["vpsplugin_time"] if always_zap != -1: if hasattr(timer, "always_zap"): timer.always_zap = always_zap == 1 except Exception as e: print e return { "result": False, "message": _("Could not add timer '%s'!") % name } return {"result": True, "message": _("Timer '%s' added") % name}
def getTimers(session): rt = session.nav.RecordTimer timers = [] for timer in rt.timer_list + rt.processed_timers: descriptionextended = "N/A" filename = None nextactivation = None if timer.eit and timer.service_ref: event = eEPGCache.getInstance().lookupEvent( ['EX', (str(timer.service_ref), 2, timer.eit)]) if event and event[0][0]: descriptionextended = event[0][0] try: filename = timer.Filename except Exception: pass try: nextactivation = timer.next_activation except Exception: pass disabled = 0 if timer.disabled: disabled = 1 justplay = 0 if timer.justplay: justplay = 1 if timer.dirname: dirname = timer.dirname else: dirname = "None" dontSave = 0 if timer.dontSave: dontSave = 1 toggledisabled = 1 if timer.disabled: toggledisabled = 0 toggledisabledimg = "off" if timer.disabled: toggledisabledimg = "on" asrefs = "" achannels = GetWithAlternative(str(timer.service_ref), False) if achannels: asrefs = achannels vpsplugin_enabled = False vpsplugin_overwrite = False vpsplugin_time = -1 if hasattr(timer, "vpsplugin_enabled"): vpsplugin_enabled = True if timer.vpsplugin_enabled else False if hasattr(timer, "vpsplugin_overwrite"): vpsplugin_overwrite = True if timer.vpsplugin_overwrite else False if hasattr(timer, "vpsplugin_time"): vpsplugin_time = timer.vpsplugin_time if not vpsplugin_time: vpsplugin_time = -1 always_zap = -1 if hasattr(timer, "always_zap"): if timer.always_zap: always_zap = 1 else: always_zap = 0 timers.append({ "serviceref": str(timer.service_ref), "servicename": mangle_epg_text(timer.service_ref.getServiceName()), "eit": timer.eit, "name": timer.name, "description": timer.description, "descriptionextended": unicode(descriptionextended, 'utf_8', errors='ignore').encode('utf_8', 'ignore'), "disabled": disabled, "begin": timer.begin, "end": timer.end, "duration": timer.end - timer.begin, "startprepare": timer.start_prepare, "justplay": justplay, "afterevent": timer.afterEvent, "dirname": dirname, "tags": " ".join(timer.tags), "logentries": timer.log_entries, "backoff": timer.backoff, "firsttryprepare": timer.first_try_prepare, "state": timer.state, "repeated": timer.repeated, "dontsave": dontSave, "cancelled": timer.cancelled, "toggledisabled": toggledisabled, "toggledisabledimg": toggledisabledimg, "filename": filename, "nextactivation": nextactivation, "realbegin": strftime("%d.%m.%Y %H:%M", (localtime(float(timer.begin)))), "realend": strftime("%d.%m.%Y %H:%M", (localtime(float(timer.end)))), "asrefs": asrefs, "vpsplugin_enabled": vpsplugin_enabled, "vpsplugin_overwrite": vpsplugin_overwrite, "vpsplugin_time": vpsplugin_time, "always_zap": always_zap }) return {"result": True, "timers": timers}
def getStatusInfo(self): # Get Current Volume and Mute Status vcontrol = eDVBVolumecontrol.getInstance() statusinfo = { 'volume': vcontrol.getVolume(), 'muted': vcontrol.isMuted(), 'transcoding': getTranscodingSupport(), 'currservice_filename': "", 'currservice_id': -1, 'state': { 'standby': False, 'recording': False } } # Get currently running Service event = None serviceref = self.session.nav.getCurrentlyPlayingServiceReference() serviceref_string = None currservice_station = None if serviceref is not None: serviceHandler = eServiceCenter.getInstance() serviceHandlerInfo = serviceHandler.info(serviceref) service = self.session.nav.getCurrentService() serviceinfo = service and service.info() event = serviceinfo and serviceinfo.getEvent(0) serviceref_string = serviceref.toString() currservice_station = mangle_epg_text( serviceHandlerInfo.getName(serviceref)) else: event = None serviceHandlerInfo = None if event is not None: # (begin, end, name, description, eit) curEvent = parseEvent(event) margin_before = config.recording.margin_before.value margin_after = config.recording.margin_after.value begin_timestamp = int(curEvent[0]) + (margin_before * 60) end_timestamp = int(curEvent[1]) - (margin_after * 60) statusinfo['currservice_name'] = mangle_epg_text(curEvent[2]) statusinfo['currservice_serviceref'] = serviceref_string statusinfo['currservice_begin'] = time.strftime( "%H:%M", (time.localtime(begin_timestamp))) statusinfo['currservice_begin_timestamp'] = begin_timestamp statusinfo['currservice_end'] = time.strftime( "%H:%M", (time.localtime(end_timestamp))) statusinfo['currservice_end_timestamp'] = end_timestamp statusinfo['currservice_description'] = curEvent[3] statusinfo['currservice_station'] = currservice_station if statusinfo['currservice_serviceref'].startswith('1:0:0'): fn = '/' + '/'.join(serviceref_string.split("/")[1:]) statusinfo['currservice_filename'] = fn statusinfo['currservice_fulldescription'] = mangle_epg_text( event.getExtendedDescription()) statusinfo['currservice_id'] = curEvent[4] else: statusinfo['currservice_name'] = "N/A" statusinfo['currservice_begin'] = "" statusinfo['currservice_end'] = "" statusinfo['currservice_description'] = "" statusinfo['currservice_fulldescription'] = "N/A" if serviceref: statusinfo['currservice_serviceref'] = serviceref_string if serviceHandlerInfo: statusinfo['currservice_station'] = currservice_station elif serviceref_string.find("http") != -1: statusinfo['currservice_station'] = serviceref_string.replace( '%3a', ':')[serviceref_string.find("http"):] else: statusinfo['currservice_station'] = "N/A" # Get Standby State from Screens.Standby import inStandby statusinfo['state']['standby'] = inStandby is not None if statusinfo['state']['standby'] is False: statusinfo['inStandby'] = "false" else: statusinfo['inStandby'] = "true" # Get recording state recs = NavigationInstance.instance.getRecordings() statusinfo['state']['recording'] = len(recs) > 0 if recs: statusinfo['Recording_list'] = "\n" for timer in NavigationInstance.instance.RecordTimer.timer_list: if timer.state == TimerEntry.StateRunning: if not timer.justplay: s_name = timer.service_ref.getServiceName() label = mangle_epg_text(s_name) + ": " + timer.name + "\n" statusinfo['Recording_list'] += label if statusinfo['state']['recording']: statusinfo['isRecording'] = "true" else: statusinfo['isRecording'] = "false" return statusinfo
def getInfo(session=None, need_fullinfo=False): global STATICBOXINFO if not (STATICBOXINFO is None or need_fullinfo): return STATICBOXINFO info = { 'brand': getMachineBrand(), 'model': getMachineName(), 'boxtype': getBoxType(), 'machinebuild': getMachineBuild(), 'tag_data': TAG_DATA, } chipset = "unknown" if os.path.isfile("/etc/.box"): f = open("/etc/.box", 'r') model = f.readline().strip().lower() f.close() if model.startswith("ufs") or model.startswith("ufc"): if model in ("ufs910", "ufs922", "ufc960"): chipset = "SH4 @266MHz" else: chipset = "SH4 @450MHz" elif model in ("topf", "tf7700hdpvr"): chipset = "SH4 @266MHz" elif model.startswith("azbox"): f = open("/proc/stb/info/model", 'r') model = f.readline().strip().lower() f.close() if model == "me": chipset = "SIGMA 8655" elif model == "minime": chipset = "SIGMA 8653" else: chipset = "SIGMA 8634" elif model.startswith("spark"): if model == "spark7162": chipset = "SH4 @540MHz" else: chipset = "SH4 @450MHz" elif os.path.isfile("/proc/stb/info/azmodel"): f = open("/proc/stb/info/model", 'r') model = f.readline().strip().lower() f.close() if model == "me": chipset = "SIGMA 8655" elif model == "minime": chipset = "SIGMA 8653" else: chipset = "SIGMA 8634" elif os.path.isfile("/proc/stb/info/model"): f = open("/proc/stb/info/model", 'r') model = f.readline().strip().lower() f.close() if model == "tf7700hdpvr": chipset = "SH4 @266MHz" elif model == "nbox": chipset = "STi7100 @266MHz" elif model == "arivalink200": chipset = "STi7109 @266MHz" elif model in ("adb2850", "adb2849", "dsi87"): chipset = "STi7111 @450MHz" elif model in ("sagemcom88", "esi88"): chipset = "STi7105 @450MHz" elif model.startswith("spark"): if model == "spark7162": chipset = "STi7162 @540MHz" else: chipset = "STi7111 @450MHz" if os.path.isfile("/proc/stb/info/chipset"): f = open("/proc/stb/info/chipset", 'r') chipset = f.readline().strip() f.close() info['chipset'] = chipset memFree = 0 for line in open("/proc/meminfo", 'r'): parts = line.split(':') key = parts[0].strip() if key == "MemTotal": info['mem1'] = parts[1].strip().replace("kB", _("kB")) elif key in ("MemFree", "Buffers", "Cached"): memFree += int(parts[1].strip().split(' ', 1)[0]) info['mem2'] = "%s %s" % (memFree, _("kB")) info['mem3'] = _("%s free / %s total") % (info['mem2'], info['mem1']) try: f = open("/proc/uptime", "rb") uptime = int(float(f.readline().split(' ', 2)[0].strip())) f.close() uptimetext = '' if uptime > 86400: d = uptime / 86400 uptime = uptime % 86400 uptimetext += '%dd ' % d uptimetext += "%d:%.2d" % (uptime / 3600, (uptime % 3600) / 60) except BaseException: uptimetext = "?" info['uptime'] = uptimetext info["webifver"] = TAG_DATA['owif_version'] info['imagedistro'] = getImageDistro() info['friendlyimagedistro'] = getFriendlyImageDistro() info['oever'] = getOEVersion() info['imagever'] = getImageVersion() ib = getImageBuild() if ib: info['imagever'] = info['imagever'] + "." + ib info['enigmaver'] = getEnigmaVersionString() info['driverdate'] = getDriverDate() info['kernelver'] = about.getKernelVersionString() try: info['fp_version'] = getFPVersion() except BaseException: info['fp_version'] = None friendlychipsetdescription = _("Chipset") friendlychipsettext = info['chipset'].replace("bcm", "Broadcom ") if friendlychipsettext in ("7335", "7356", "7362", "73625", "7424", "7425", "7429"): friendlychipsettext = "Broadcom " + friendlychipsettext if not (info['fp_version'] is None or info['fp_version'] == 0): friendlychipsetdescription += " (" + _("Frontprocessor Version") + ")" friendlychipsettext += " (" + str(info['fp_version']) + ")" info['friendlychipsetdescription'] = friendlychipsetdescription info['friendlychipsettext'] = friendlychipsettext info['tuners'] = [] for i in range(0, nimmanager.getSlotCount()): ILOG.debug("tuner {!r} {!r} {!r}".format( i, nimmanager.getNimName(i), nimmanager.getNim(i).getSlotName())) info['tuners'].append({ "name": nimmanager.getNim(i).getSlotName(), "type": nimmanager.getNimName(i) + " (" + nimmanager.getNim(i).getFriendlyType() + ")", "rec": "", "live": "" }) info['ifaces'] = [] ifaces = iNetwork.getConfiguredAdapters() for iface in ifaces: info['ifaces'].append({ "name": iNetwork.getAdapterName(iface), "friendlynic": getFriendlyNICChipSet(iface), "linkspeed": getLinkSpeed(iface), "mac": iNetwork.getAdapterAttribute(iface, "mac"), "dhcp": iNetwork.getAdapterAttribute(iface, "dhcp"), "ipv4method": getIPv4Method(iface), "ip": formatIp(iNetwork.getAdapterAttribute(iface, "ip")), "mask": formatIp(iNetwork.getAdapterAttribute(iface, "netmask")), "v4prefix": sum([ bin(int(x)).count('1') for x in formatIp( iNetwork.getAdapterAttribute(iface, "netmask")).split('.') ]), "gw": formatIp(iNetwork.getAdapterAttribute(iface, "gateway")), "ipv6": getAdapterIPv6(iface)['addr'], "ipmethod": getIPMethod(iface), "firstpublic": getAdapterIPv6(iface)['firstpublic'] }) info['hdd'] = [] for hdd in harddiskmanager.hdd: dev = hdd.findMount() if dev: stat = os.statvfs(dev) free = int((stat.f_bfree / 1024) * (stat.f_bsize / 1024)) else: stat = (-1, -1, -1, -1, -1, -1, -1, -1, -1, -1) free = -1 if free <= 1024: free = "%i %s" % (free, _("MB")) else: free = free / 1024. free = "%.1f %s" % (free, _("GB")) size = hdd.diskSize() * 1000000 / 1048576. if size > 1048576: size = "%.1f %s" % ((size / 1048576.), _("TB")) elif size > 1024: size = "%.1f %s" % ((size / 1024.), _("GB")) else: size = "%d %s" % (size, _("MB")) iecsize = hdd.diskSize() # Harddisks > 1000 decimal Gigabytes are labelled in TB if iecsize > 1000000: iecsize = (iecsize + 50000) // float(100000) / 10 # Omit decimal fraction if it is 0 if (iecsize % 1 > 0): iecsize = "%.1f %s" % (iecsize, _("TB")) else: iecsize = "%d %s" % (iecsize, _("TB")) # Round harddisk sizes beyond ~300GB to full tens: 320, 500, 640, 750GB elif iecsize > 300000: iecsize = "%d %s" % (((iecsize + 5000) // 10000 * 10), _("GB")) # ... be more precise for media < ~300GB (Sticks, SSDs, CF, MMC, ...): # 1, 2, 4, 8, 16 ... 256GB elif iecsize > 1000: iecsize = "%d %s" % (((iecsize + 500) // 1000), _("GB")) else: iecsize = "%d %s" % (iecsize, _("MB")) info['hdd'].append({ "model": hdd.model(), "capacity": size, "labelled_capacity": iecsize, "free": free, "mount": dev, "friendlycapacity": _("%s free / %s total") % (free, size + ' ("' + iecsize + '")'), "_statvfs_result": tuple(stat), }) info['shares'] = [] autofiles = ('/etc/auto.network', '/etc/auto.network_vti') for autofs in autofiles: if os.path.isfile(autofs): method = "autofs" for line in file(autofs).readlines(): if not line.startswith('#'): # Replace escaped spaces that can appear inside # credentials with underscores # Not elegant but we wouldn't want to expose credentials # on the OWIF anyways tmpline = line.replace("\ ", "_") tmp = tmpline.split() if not len(tmp) == 3: continue name = tmp[0].strip() kind = "unknown" if "cifs" in tmp[1]: # Linux still defaults to SMBv1 kind = "SMBv1.0" settings = tmp[1].split(",") for setting in settings: if setting.startswith("vers="): kind = setting.replace("vers=", "SMBv") elif "nfs" in tmp[1]: kind = "NFS" # Default is r/w mode = _("r/w") settings = tmp[1].split(",") for setting in settings: if setting == "ro": mode = _("r/o") uri = tmp[2] parts = tmp[2].split(':') if parts[0] is "": server = uri.split('/')[2] uri = uri.strip()[1:] else: server = parts[0] ipaddress = None if server: # Will fail on literal IPs try: # Try IPv6 first, as will Linux if has_ipv6: tmpaddress = None tmpaddress = getaddrinfo(server, 0, AF_INET6) if tmpaddress: ipaddress = "[" + \ list(tmpaddress)[0][4][0] + "]" # Use IPv4 if IPv6 fails or is not present if ipaddress is None: tmpaddress = None tmpaddress = getaddrinfo(server, 0, AF_INET) if tmpaddress: ipaddress = list(tmpaddress)[0][4][0] except BaseException: pass friendlyaddress = server if ipaddress is not None and not ipaddress == server: friendlyaddress = server + " (" + ipaddress + ")" info['shares'].append({ "name": name, "method": method, "type": kind, "mode": mode, "path": uri, "host": server, "ipaddress": ipaddress, "friendlyaddress": friendlyaddress }) # TODO: fstab info['transcoding'] = False #: models transcoding feature TC_MODELS = ("Uno4K", "Ultimo4K", "Solo4K", "Solo²", "Duo²", "Solo SE", "Quad", "Quad Plus") #: machinebuilds transcoding feature TC_MACHINEBUILD = ('inihdp', 'hd2400', 'et10000', 'et13000', 'sf5008', 'xpeedlx3', 'ew7356', 'dags7356', 'dags7252', 'formuler1tc', 'gb7356', 'gb7252', 'tiviaraplus', '8100s') if info['model'] in TC_MODELS or info['machinebuild'] in TC_MACHINEBUILD: prefixes = ( 'enigma2/python/Plugins/SystemPlugins/TransCodingSetup', 'enigma2/python/Plugins/SystemPlugins/TranscodingSetup', 'enigma2/python/Plugins/SystemPlugins/MultiTransCodingSetup') for pfx in prefixes: path = '/'.join(('${libdir}', pfx, 'plugin.pyo')) if os.path.exists(eEnv.resolve(path)): info['transcoding'] = True break info['kinopoisk'] = False lang = ['ru', 'uk', 'lv', 'lt', 'et'] current_language = language.getLanguage() for l in lang: if l in current_language: info['kinopoisk'] = True break info['EX'] = '' if session: try: recs = NavigationInstance.instance.getRecordings() if recs: # only one stream and only TV from ..stream import streamList s_name = '' ILOG.debug("streamList count {!r}".format(len(streamList))) if len(streamList) == 1: from Screens.ChannelSelection import service_types_tv service_handler = eServiceCenter.getInstance() services = service_handler.list( eServiceReference('%s ORDER BY name' % service_types_tv)) channels = services and services.getContent("SN", True) s = streamList[0] srefs = s.ref.toString() for channel in channels: if srefs == channel[0]: s_name = channel[1] + ' (' + s.clientIP + ')' break ILOG.debug("s_name {!r}".format(s_name)) for stream in streamList: srefs = stream.ref.toString() ILOG.debug("srefs {!r}".format(srefs)) sname = '' timers = [] r_timers = NavigationInstance.instance.RecordTimer.timer_list for timer in r_timers: if timer.isRunning() and not timer.justplay: sname = timer.service_ref.getServiceName() timers.append( mangle_epg_text( timer.service_ref.getServiceName())) ILOG.debug("timer {!r}".format(s_name)) # only one recording if len(timers) == 1: sname = timers[0] if sname == '' and s_name != '': sname = s_name ILOG.debug("recs count {!r}".format(len(recs))) for rec in recs: feinfo = rec.frontendInfo() frontend_data = feinfo and feinfo.getAll(True) if frontend_data is not None: cur_info = feinfo.getTransponderData(True) if cur_info: tno = info['tuners'][frontend_data['tuner_number']] label = getOrbitalText(cur_info) + ' / ' + sname tno['rec'] = mangle_epg_text(label) service = session.nav.getCurrentService() if service is not None: s_reference = session.nav.getCurrentlyPlayingServiceReference() service_information = service.info() sname = service_information.getName() feinfo = service.frontendInfo() frontend_data = feinfo and feinfo.getAll(True) if frontend_data is not None: cur_info = feinfo.getTransponderData(True) if cur_info: tno = info['tuners'][frontend_data['tuner_number']] label = getOrbitalText(cur_info) + ' / ' + sname tno['live'] = mangle_epg_text(label) tno['live_meta'] = { 'service_name': mangle_epg_text(sname), KEY_SERVICE_REFERENCE: s_reference.toString() } except Exception as error: info['EX'] = error STATICBOXINFO = info return info
def getMovieList(rargs=None, locations=None): """ Generate a `dict` containing movie items information. .. deprecated:: 0.86 Args: rargs (dict): request object's args locations(list): paths where recordings might be stored Returns: dict: movie items """ 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) 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': mangle_epg_text( ServiceReference(serviceref).getServiceName()), 'servicename': mangle_epg_text(sourceRef.getServiceName()), '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 BaseException: 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 "" # NOQA 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 BaseException: 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 _mangle(self): text_keys = ("shortinfo", "longinfo", "title", KEY_SERVICE_NAME, "shortservice_name") for tkey in text_keys: if tkey in self: self[tkey] = mangle_epg_text(self[tkey])