Beispiel #1
0
def addTimerByEventId(session, eventid, serviceref, justplay, dirname, tags,
                      vpsinfo, always_zap, afterevent, pipzap, allow_duplicate,
                      autoadjust, recordingtype):
    event = eEPGCache.getInstance().lookupEventId(
        eServiceReference(serviceref), eventid)
    if event is None:
        return {"result": False, "message": _("EventId not found")}

    (begin, end, name, description, eit) = parseEvent(event)

    if justplay:
        begin += config.recording.margin_before.value * 60
        end = begin + 1

    return addTimer(session, serviceref, begin, end, name, description, False,
                    justplay, afterevent, dirname, tags, 0, recordingtype,
                    vpsinfo, None, eit, always_zap, pipzap, allow_duplicate,
                    autoadjust)
 def addProviderToBouquetlist(self, param):
     print(
         "[WebComponents.BouquetEditor] addProviderToBouquet with param = ",
         param)
     refstr = param["sProviderRef"]
     if refstr is None:
         return (False, _("No provider given!"))
     mode = MODE_TV  # init
     if "mode" in param:
         if param["mode"] is not None:
             mode = int(param["mode"])
     ref = eServiceReference(refstr)
     provider = ServiceReference(ref)
     providerName = provider.getServiceName()
     serviceHandler = eServiceCenter.getInstance()
     services = serviceHandler.list(provider.ref)
     return self.addBouquet(providerName, mode, services
                            and services.getContent('R', True))
Beispiel #3
0
def sendMessage(session, message, ttype, timeout):
    global lastreply
    if ttype not in [
            MessageBox.TYPE_YESNO, MessageBox.TYPE_INFO,
            MessageBox.TYPE_WARNING, MessageBox.TYPE_ERROR
    ]:
        ttype = MessageBox.TYPE_INFO

    if ttype == MessageBox.TYPE_YESNO:
        lastreply = None
        session.openWithCallback(messageReply,
                                 MessageBox,
                                 message,
                                 type=ttype,
                                 timeout=timeout)
    else:
        session.open(MessageBox, message, type=ttype, timeout=timeout)

    return {"result": True, "message": _('Message sent successfully!')}
Beispiel #4
0
def getSleepTimer(session):
    if hasattr(session.nav, "SleepTimer"):
        try:
            return {
                "enabled":
                session.nav.SleepTimer.isActive(),
                "minutes":
                session.nav.SleepTimer.getCurrentSleepTime(),
                "action":
                config.SleepTimer.action.value,
                "message":
                _("Sleeptimer is enabled")
                if session.nav.SleepTimer.isActive() else
                _("Sleeptimer is disabled")
            }
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
    else:
        # use powertimer , this works only if there is one of the standby OR deepstandby entries
        # todo : do not use repeated entries
        try:
            timer_list = session.nav.PowerTimer.timer_list
            for timer in timer_list:
                timertype = str(timer.timerType)
                if timertype in ["2", "3"]:
                    action = "standby"
                    if timertype == "3":
                        action = "shutdown"
                    minutes = str(timer.autosleepdelay)
                    enabled = True
                    if int(timer.disabled) == 1:
                        enabled = False
                    return {
                        "enabled":
                        enabled,
                        "minutes":
                        minutes,
                        "action":
                        action,
                        "message":
                        _("Sleeptimer is enabled")
                        if enabled else _("Sleeptimer is disabled")
                    }
                    break
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
def getSleepTimer(session):
    if hasattr(session.nav, "SleepTimer"):
        try:
            return {
                "enabled":
                session.nav.SleepTimer.isActive(),
                "minutes":
                session.nav.SleepTimer.getCurrentSleepTime(),
                "action":
                config.SleepTimer.action.value,
                "message":
                _("Sleeptimer is enabled")
                if session.nav.SleepTimer.isActive() else
                _("Sleeptimer is disabled")
            }
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
    elif InfoBar.instance is not None and hasattr(InfoBar.instance,
                                                  'sleepTimer'):
        try:
            # TODO test OpenPLI and similar
            active = InfoBar.instance.sleepTimer.isActive()
            if hasattr(config.usage, 'sleepTimer'):
                time = config.usage.sleepTimer.value
            if hasattr(config.usage, 'sleep_timer'):
                time = config.usage.sleep_timer.value
            action = "shutdown"
            if hasattr(config.usage, 'sleepTimerAction'):
                action = config.usage.sleepTimerAction.value
            if hasattr(config.usage, 'sleep_timer_action'):
                action = config.usage.sleep_timer_action.value
            if action == "deepstandby":
                action = "shutdown"

            if time != None and int(time) > 0:
                try:
                    time = int(int(time) / 60)
                except:
                    time = 60
            remaining = 0
            if active:
                remaining = int(InfoBar.instance.sleepTimerState())
            return {
                "enabled":
                active,
                "minutes":
                time,
                "action":
                action,
                "remaining":
                remaining,
                "message":
                _("Sleeptimer is enabled")
                if active else _("Sleeptimer is disabled")
            }
        except Exception as e:
            print(e)
            return {"result": False, "message": _("SleepTimer error")}
    else:
        # use powertimer , this works only if there is one of the standby OR deepstandby entries
        # todo : do not use repeated entries
        try:
            timer_list = session.nav.PowerTimer.timer_list
            for timer in timer_list:
                timertype = str(timer.timerType)
                if timertype in ["2", "3"]:
                    action = "standby"
                    if timertype == "3":
                        action = "shutdown"
                    minutes = str(timer.autosleepdelay)
                    enabled = True
                    if int(timer.disabled) == 1:
                        enabled = False
                    return {
                        "enabled":
                        enabled,
                        "minutes":
                        minutes,
                        "action":
                        action,
                        "message":
                        _("Sleeptimer is enabled")
                        if enabled else _("Sleeptimer is disabled")
                    }
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
def tvbrowser(session, request):
    if "name" in request.args:
        name = request.args['name'][0]
    else:
        name = "Unknown"

    if "description" in request.args:
        description = "".join(request.args['description'][0])
        description = description.replace("\n", " ")
    else:
        description = ""

    disabled = False
    if "disabled" in request.args:
        if (request.args['disabled'][0] == "1"):
            disabled = True

    justplay = False
    if 'justplay' in request.args:
        if (request.args['justplay'][0] == "1"):
            justplay = True

    afterevent = 3
    if 'afterevent' in request.args:
        if (request.args['afterevent'][0]
                == "0") or (request.args['afterevent'][0]
                            == "1") or (request.args['afterevent'][0] == "2"):
            afterevent = int(request.args['afterevent'][0])

    location = preferredTimerPath()
    if "dirname" in request.args:
        location = request.args['dirname'][0]

    if not location:
        location = "/hdd/movie/"

    begin = int(
        mktime((int(request.args['syear'][0]), int(request.args['smonth'][0]),
                int(request.args['sday'][0]), int(request.args['shour'][0]),
                int(request.args['smin'][0]), 0, 0, 0, -1)))
    end = int(
        mktime((int(request.args['syear'][0]), int(request.args['smonth'][0]),
                int(request.args['sday'][0]), int(request.args['ehour'][0]),
                int(request.args['emin'][0]), 0, 0, 0, -1)))

    if end < begin:
        end += 86400

    repeated = int(request.args['repeated'][0])
    if repeated == 0:
        for element in ("mo", "tu", "we", "th", "fr", "sa", "su", "ms", "mf"):
            if element in request.args:
                number = request.args[element][0] or 0
                del request.args[element][0]
                repeated = repeated + int(number)
        if repeated > 127:
            repeated = 127
    repeated = repeated

    if request.args['sRef'][0] is None:
        return {"result": False, "message": _("Missing requesteter: sRef")}
    else:
        takeApart = unquote(request.args['sRef'][0]).decode(
            'utf-8', 'ignore').encode('utf-8').split('|')
        sRef = takeApart[1]

    tags = []
    if 'tags' in request.args and request.args['tags'][0]:
        tags = unquote(request.args['tags'][0]).split(' ')

    if request.args['command'][0] == "add":
        del request.args['command'][0]
        return addTimer(session, sRef, begin, end, name, description, disabled,
                        justplay, afterevent, location, tags, repeated)
    elif request.args['command'][0] == "del":
        del request.args['command'][0]
        return removeTimer(session, sRef, begin, end, eit=None)
    elif request.args['command'][0] == "change":
        del request.args['command'][0]
        return editTimer(session, sRef, begin, end, name, description,
                         disabled, justplay, afterevent, location, tags,
                         repeated, begin, end, serviceref)
    else:
        return {
            "result": False,
            "message": _("Unknown command: '%s'") % request.args['command'][0]
        }
def writeTimerList(session):
    session.nav.RecordTimer.saveTimer()
    return {"result": True, "message": _("TimerList has been saved")}
def editTimer(session, serviceref, begin, end, name, description, disabled,
              justplay, afterEvent, dirname, tags, repeated, channelOld,
              beginOld, endOld, recordingtype, vpsinfo, always_zap, pipzap,
              allow_duplicate, autoadjust):
    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
                if hasattr(timer, "zapbeforerecord"):
                    timer.zapbeforerecord = always_zap == 1

            if pipzap != -1:
                if hasattr(timer, "pipzap"):
                    timer.pipzap = pipzap == 1

            if hasattr(timer, "allow_duplicate"):
                timer.allow_duplicate = allow_duplicate

            if hasattr(timer, "autoadjust"):
                if autoadjust == -1:
                    autoadjust = config.recording.adjust_time_to_event.value and 1 or 0
                timer.autoadjust = autoadjust

            if recordingtype:
                timer.descramble = {
                    "normal": True,
                    "descrambled": True,
                    "scrambled": False,
                }[recordingtype]
                timer.record_ecm = {
                    "normal": False,
                    "descrambled": True,
                    "scrambled": True,
                }[recordingtype]

            # 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(timer):
                            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":
                        removeBad(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
                }

    return {
        "result":
        False,
        "message":
        _("Could not find timer '%s' with given start and end time!") % name
    }
def addTimer(session,
             serviceref,
             begin,
             end,
             name,
             description,
             disabled,
             justplay,
             afterevent,
             dirname,
             tags,
             repeated,
             recordingtype,
             vpsinfo=None,
             logentries=None,
             eit=0,
             always_zap=-1,
             pipzap=-1,
             allow_duplicate=1,
             autoadjust=-1):
    rt = session.nav.RecordTimer

    if not dirname:
        dirname = preferredTimerPath()

    #  IPTV Fix
    serviceref = serviceref.replace('%253a', '%3a')

    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":
                    conflict.service_ref.getServiceName().replace(
                        '\xc2\x86', '').replace('\xc2\x87', ''),
                    "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
            if hasattr(timer, "zapbeforerecord"):
                timer.zapbeforerecord = always_zap == 1

        if hasattr(timer, "autoadjust"):
            if autoadjust == -1:
                autoadjust = config.recording.adjust_time_to_event.value and 1 or 0
            autoadjust = autoadjust

        if hasattr(timer, "allow_duplicate"):
            allow_duplicate = allow_duplicate

        if pipzap != -1:
            if hasattr(timer, "pipzap"):
                timer.pipzap = pipzap == 1

        if recordingtype:
            timer.descramble = {
                "normal": True,
                "descrambled": True,
                "scrambled": False,
            }[recordingtype]
            timer.record_ecm = {
                "normal": False,
                "descrambled": True,
                "scrambled": True,
            }[recordingtype]

    except Exception as e:
        print(str(e))
        return {
            "result": False,
            "message": _("Could not add timer '%s'!") % name
        }

    return {"result": True, "message": _("Timer '%s' added") % name}
    def prepareMainTemplate(self, request):
        # here will be generated the dictionary for the main template
        ret = getCollapsedMenus()
        ret['configsections'] = getConfigsSections()['sections']
        ret['showname'] = getShowName()['showname']
        ret['customname'] = getCustomName()['customname']
        ret['boxname'] = getBoxName()['boxname']
        if not ret['boxname'] or not ret['customname']:
            ret['boxname'] = getInfo()['brand'] + " " + getInfo()['model']
        ret['box'] = getBoxType()
        ret["remote"] = REMOTE
        if hasattr(eEPGCache, 'FULL_DESCRIPTION_SEARCH'):
            ret['epgsearchcaps'] = True
        else:
            ret['epgsearchcaps'] = False
        extras = [{'key': 'ajax/settings', 'description': _("Settings")}]

        ip = getIP()
        if ip != None:
            if fileExists(
                    resolveFilename(
                        SCOPE_PLUGINS,
                        "Extensions/LCD4linux/WebSite.pyo")) or fileExists(
                            resolveFilename(
                                SCOPE_PLUGINS,
                                "Extensions/LCD4linux/WebSite.py")):
                lcd4linux_key = "lcd4linux/config"
                if fileExists(
                        resolveFilename(SCOPE_PLUGINS,
                                        "Extensions/WebInterface/plugin.pyo")
                ) or fileExists(
                        resolveFilename(SCOPE_PLUGINS,
                                        "Extensions/WebInterface/plugin.py")):
                    try:
                        lcd4linux_port = "http://" + ip + ":" + str(
                            config.plugins.Webinterface.http.port.value) + "/"
                        lcd4linux_key = lcd4linux_port + 'lcd4linux/config'
                    except:  # nosec # noqa: E722
                        lcd4linux_key = None
                if lcd4linux_key:
                    extras.append({
                        'key': lcd4linux_key,
                        'description': _("LCD4Linux Setup"),
                        'nw': '1'
                    })

        oscamwebif, port, oscamconf, variant = self.oscamconfPath()

        # Assume http until we know better ...
        proto = "http"

        # config file exists
        if oscamwebif and oscamconf is not None:
            # oscam defaults to NOT to start the web interface unless a section for it exists, so reset port to None until we find one
            port = None
            data = open(oscamconf, "r").readlines()
            for i in data:
                if "httpport" in i.lower():
                    port = i.split("=")[1].strip()
                    if port[0] == '+':
                        proto = "https"
                        port = port[1:]

        if oscamwebif and port is not None:
            url = "%s://%s:%s" % (proto, request.getRequestHostname(), port)
            if variant == "oscam":
                extras.append({
                    'key': url,
                    'description': _("OSCam Webinterface"),
                    'nw': '1'
                })
            elif variant == "ncam":
                extras.append({
                    'key': url,
                    'description': _("NCam Webinterface"),
                    'nw': '1'
                })

        url1 = "http://%s:8000" % request.getRequestHostname()
        extras.append({'key': url1, 'description': _("FileLoad"), 'nw': '1'})

        if HASAUTOTIMER:
            extras.append({'key': 'ajax/at', 'description': _('AutoTimers')})

        if fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/bqe.tmpl")
        ) or fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/bqe.pyo")):
            extras.append({
                'key': 'ajax/bqe',
                'description': _('BouquetEditor')
            })

        try:
            from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh  # noqa: F401
            extras.append({'key': 'ajax/epgr', 'description': _('EPGRefresh')})
        except ImportError:
            pass

        try:
            # this will currenly only works if NO Webiterface plugin installed
            # TODO: test if webinterface AND openwebif installed

            # 'nw'='1' -> target _blank
            # 'nw'='2' -> target popup
            # 'nw'=None -> target _self

            # syntax
            # addExternalChild( (Link, Resource, Name, Version, HasGUI, WebTarget) )
            # example addExternalChild( ("webadmin", root, "WebAdmin", 1, True, "_self") )

            from Plugins.Extensions.WebInterface.WebChilds.Toplevel import loaded_plugins
            for plugins in loaded_plugins:
                if plugins[0] in ["fancontrol", "iptvplayer"]:
                    try:
                        extras.append({
                            'key': plugins[0],
                            'description': plugins[2],
                            'nw': '2'
                        })
                    except KeyError:
                        pass
                elif len(plugins) > 4:
                    if plugins[4] == True:
                        try:
                            if len(plugins) > 5 and plugins[5] == "_self":
                                extras.append({
                                    'key': plugins[0],
                                    'description': plugins[2]
                                })
                            else:
                                extras.append({
                                    'key': plugins[0],
                                    'description': plugins[2],
                                    'nw': '1'
                                })
                        except KeyError:
                            pass

        except ImportError:
            pass

        if os.path.exists('/usr/bin/shellinaboxd') and (fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.tmpl"
                )
        ) or fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.pyo")
        )):
            extras.append({
                'key': 'ajax/terminal',
                'description': _('Terminal')
            })

        ret['extras'] = extras
        theme = 'original'
        if config.OpenWebif.webcache.theme.value:
            theme = config.OpenWebif.webcache.theme.value
        if not os.path.exists(getPublicPath('themes')):
            if not (theme == 'original' or theme == 'clear'):
                theme = 'original'
                config.OpenWebif.webcache.theme.value = theme
                config.OpenWebif.webcache.theme.save()
        ret['theme'] = theme
        moviedb = config.OpenWebif.webcache.moviedb.value if config.OpenWebif.webcache.moviedb.value else EXT_EVENT_INFO_SOURCE
        config.OpenWebif.webcache.moviedb.value = moviedb
        config.OpenWebif.webcache.moviedb.save()
        ret['moviedb'] = moviedb
        imagedistro = getInfo()['imagedistro']
        ret['vti'] = "1" if imagedistro in ("VTi-Team Image") else "0"
        ret['webtv'] = os.path.exists(getPublicPath('webtv'))
        ret['stbLang'] = STB_LANG
        return ret
Beispiel #11
0
def removeMovie(session, sRef, Force=False):
    service = ServiceReference(sRef)
    result = False
    deleted = False
    message = "service error"

    if service is not None:
        serviceHandler = eServiceCenter.getInstance()
        offline = serviceHandler.offlineOperations(service.ref)
        info = serviceHandler.info(service.ref)
        name = info and info.getName(service.ref) or "this recording"

    if offline is not None:
        if Force is True:
            message = "force delete"
        elif hasattr(config.usage, 'movielist_trashcan'):
            fullpath = service.ref.getPath()
            srcpath = '/'.join(fullpath.split('/')[:-1]) + '/'
            # TODO: check trash
            # TODO: check enable trash default value
            if '.Trash' not in fullpath and config.usage.movielist_trashcan.value:
                result = False
                message = "trashcan"
                try:
                    import Tools.Trashcan
                    from Screens.MovieSelection import moveServiceFiles
                    trash = Tools.Trashcan.createTrashFolder(srcpath)
                    moveServiceFiles(service.ref, trash)
                    result = True
                    message = "The recording '%s' has been successfully moved to trashcan" % name
                except ImportError:
                    message = "trashcan exception"
                    pass
                except Exception as e:
                    message = "Failed to move to .Trash folder: %s" + str(e)
                    print(message)
                deleted = True
        elif hasattr(config.usage, 'movielist_use_trash_dir'):
            fullpath = service.ref.getPath()
            if TRASHDIRNAME not in fullpath and config.usage.movielist_use_trash_dir.value:
                message = "trashdir"
                try:
                    from Screens.MovieSelection import getTrashDir
                    from Components.FileTransfer import FileTransferJob
                    from Components.Task import job_manager
                    trash_dir = getTrashDir(fullpath)
                    if trash_dir:
                        src_file = str(fullpath)
                        dst_file = trash_dir
                        if dst_file.endswith("/"):
                            dst_file = trash_dir[:-1]
                        text = _("remove")
                        job_manager.AddJob(
                            FileTransferJob(src_file, dst_file, False, False,
                                            "%s : %s" % (text, src_file)))
                        # No Result because of async job
                        message = "The recording '%s' has been successfully moved to trashcan" % name
                        result = True
                    else:
                        message = _(
                            "Delete failed, because there is no movie trash !\nDisable movie trash in configuration to delete this item"
                        )
                except ImportError:
                    message = "trashdir exception"
                    pass
                except Exception as e:
                    message = "Failed to move to trashdir: %s" + str(e)
                    print(message)
                deleted = True
        if not deleted:
            if not offline.deleteFromDisk(0):
                result = True
    else:
        message = "no offline object"

    if result is False:
        return {
            "result": False,
            "message": "Could not delete Movie '%s' / %s" % (name, message)
        }
    else:
        # EMC reload
        try:
            config.EMC.needsreload.value = True
        except (AttributeError, KeyError):
            pass
        return {
            "result": True,
            "message": "The movie '%s' has been deleted successfully" % name
        }
Beispiel #12
0
def getMovieSearchList(rargs=None, locations=None):
    movieliste = []
    tag = None
    directory = None
    fields = None
    short = None
    extended = None
    searchstr = None

    if rargs:
        searchstr = getUrlArg2(rargs, "find")
        short = getUrlArg2(rargs, "short")
        extended = getUrlArg2(rargs, "extended")

    s = {'title': str(searchstr)}
    if short is not None:
        s['shortDesc'] = str(searchstr)
    if extended is not None:
        s['extDesc'] = str(searchstr)

    movielist = MovieList(None)
    vdir_list = []
    for x in moviedb.searchContent(s, 'ref', query_type="OR",
                                   exactmatch=False):
        vdir_list.append(eServiceReference(x[0]))
    root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + "/")
    movielist.load(root, None)
    movielist.reload(root=None, vdir=5, vdir_list=vdir_list)

    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:
            movie['begintime'] = FuzzyTime2(rtime)

        try:
            length_minutes = info.getLength(serviceref)
        except:  # noqa: E722
            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 = six.ensure_str(b''.join(handle.readlines()))

            event = info.getEvent(serviceref)
            extended_description = event and event.getExtendedDescription(
            ) or ""
            if extended_description == '' and txtdesc != '':
                extended_description = txtdesc
            movie['descriptionExtended'] = ConvertDesc(extended_description)
            desc = info.getInfoString(serviceref,
                                      iServiceInformation.sDescription)
            movie['description'] = ConvertDesc(desc)

        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:  # noqa: E722
                pass

            movie['filesize'] = size
            movie['filesize_readable'] = sz

        movieliste.append(movie)

    return {"movies": movieliste, "locations": []}
Beispiel #13
0
def getMovieList(rargs=None, locations=None):
    movieliste = []
    tag = None
    directory = None
    fields = None
    bookmarklist = []

    if rargs:
        tag = getUrlArg2(rargs, "tag")
        directory = getUrlArg2(rargs, "dirname")
        fields = getUrlArg2(rargs, "fields")

    if directory is None:
        directory = defaultMoviePath()
    else:
        if not PY3:
            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]
    brecursive = False
    if rargs and b"recursive" in list(rargs.keys()):
        brecursive = True
        dirs = []
        locations = []
        if PY3:
            from glob import glob
            for subdirpath in glob(directory + "**/", recursive=True):
                locations.append(subdirpath)
                subdirpath = subdirpath[len(directory):]
                dirs.append(subdirpath)
        else:
            # FIXME SLOW!!!
            for subdirpath in [x[0] for x in os.walk(directory)]:
                locations.append(subdirpath)
                subdirpath = subdirpath[len(directory):]
                dirs.append(subdirpath)

        for f in sorted(dirs):
            if f != '':
                if f[-1] != "/":
                    f += "/"
                ff = eServiceReference(MOVIE_LIST_SREF_ROOT + directory + f)
                folders.append(ff)
    else:
        # 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:
        movielist = MovieList(None)
        for root in folders:
            if tag is not None:
                movielist.load(root=root, filter_tags=[tag])
            else:
                movielist.load(root=root, filter_tags=None)

            for (serviceref, info, begin, unknown) in movielist.list:
                if serviceref.flags & eServiceReference.mustDescent:
                    continue

                # BAD fix
                _serviceref = serviceref.toString().replace('%25', '%')
                length_minutes = 0
                txtdesc = ""
                filename = '/'.join(_serviceref.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,
                    '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,
                }

                if rtime > 0:
                    movie['begintime'] = FuzzyTime2(rtime)

                try:
                    length_minutes = info.getLength(serviceref)
                except:  # noqa: E722
                    pass

                if length_minutes:
                    movie['length'] = "%d:%02d" % (length_minutes / 60,
                                                   length_minutes % 60)
                    if fields is None or 'pos' in fields:
                        movie['lastseen'] = _moviePlayState(
                            filename + '.cuts', serviceref,
                            length_minutes) or 0

                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 = six.ensure_str(b''.join(
                                handle.readlines()))

                    event = info.getEvent(serviceref)
                    extended_description = event and event.getExtendedDescription(
                    ) or ""
                    if extended_description == '' and txtdesc != '':
                        extended_description = txtdesc
                    movie['descriptionExtended'] = ConvertDesc(
                        extended_description)

                    desc = info.getInfoString(serviceref,
                                              iServiceInformation.sDescription)
                    movie['description'] = ConvertDesc(desc)

                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:  # noqa: E722
                        pass

                    movie['filesize'] = size
                    movie['filesize_readable'] = sz

                movieliste.append(movie)


#		del movielist

    if locations is None:
        return {
            "movies": movieliste,
            "bookmarks": bookmarklist,
            "directory": directory,
            "recursive": brecursive
        }

    if brecursive:
        return {
            "movies": movieliste,
            "locations": locations,
            "directory": directory,
            "bookmarks": bookmarklist,
            "recursive": brecursive
        }
    else:
        return {
            "movies": movieliste,
            "locations": locations,
            "recursive": brecursive
        }
	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
Beispiel #15
0
def setSleepTimer(session, time, action, enabled):
    if action not in ["shutdown", "standby"]:
        action = "standby"

    if hasattr(session.nav, "SleepTimer"):
        try:
            ret = getSleepTimer(session)
            from Screens.Standby import inStandby
            if inStandby is not None:
                ret["message"] = _(
                    "ERROR: Cannot set SleepTimer while device is in Standby-Mode"
                )
                return ret
            if enabled is False:
                session.nav.SleepTimer.clear()
                ret = getSleepTimer(session)
                ret["message"] = _("Sleeptimer has been disabled")
                return ret
            config.SleepTimer.action.value = action
            config.SleepTimer.action.save()
            session.nav.SleepTimer.setSleepTime(time)
            ret = getSleepTimer(session)
            ret["message"] = _("Sleeptimer set to %d minutes") % time
            return ret
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
    else:
        # use powertimer
        # todo activate powertimer
        try:
            done = False
            timer_list = session.nav.PowerTimer.timer_list
            begin = int(time() + 60)
            end = int(time() + 120)
            for timer in timer_list:
                timertype = str(timer.timerType)
                if timertype == "2" and action == "standby":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break
                if timertype == "3" and action == "shutdown":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break
                if timertype == "3" and action == "standby":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.timerType = 2
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break
                if timertype == "2" and action == "shutdown":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.timerType = 3
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break

            if done:
                return {
                    "result":
                    True,
                    "message":
                    _("Sleeptimer set to %d minutes") %
                    time if enabled else _("Sleeptimer has been disabled")
                }
            if enabled:
                begin = int(time() + 60)
                end = int(time() + 120)
                timertype = 2
                if action == "shutdown":
                    timertype = 3
                from PowerTimer import PowerTimerEntry
                entry = PowerTimerEntry(begin, end, False, 0, timertype)
                entry.repeated = 0
                entry.autosleepdelay = time
                return {
                    "result": True,
                    "message": _("Sleeptimer set to %d minutes") % time
                }
            else:
                return {
                    "result": True,
                    "message": _("Sleeptimer has been disabled")
                }
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
Beispiel #16
0
	def runSetup(self):
		self.list = []
		self.list.append(getConfigListEntry(_("OpenWebInterface Enabled"), config.OpenWebif.enabled))
		if config.OpenWebif.enabled.value:
			self.list.append(getConfigListEntry(_("Use new design"), config.OpenWebif.responsive_enabled))
			self.list.append(getConfigListEntry(_("Show box name in header"), config.OpenWebif.identifier))
			if config.OpenWebif.identifier.value:
				self.list.append(getConfigListEntry(_("Use custom box name"), config.OpenWebif.identifier_custom))
				if config.OpenWebif.identifier_custom.value:
					self.list.append(getConfigListEntry(_("Custom box name"), config.OpenWebif.identifier_text))
			self.list.append(getConfigListEntry(_("HTTP port"), config.OpenWebif.port))
			self.list.append(getConfigListEntry(_("Enable HTTP Authentication"), config.OpenWebif.auth))
			self.list.append(getConfigListEntry(_("Enable HTTPS"), config.OpenWebif.https_enabled))
			if config.OpenWebif.https_enabled.value:
				self.list.append(getConfigListEntry(_("HTTPS port"), config.OpenWebif.https_port))
				self.list.append(getConfigListEntry(_("Enable HTTPS Authentication"), config.OpenWebif.https_auth))
				self.list.append(getConfigListEntry(_("Require client cert for HTTPS"), config.OpenWebif.https_clientcert))
			if config.OpenWebif.auth.value:
				self.list.append(getConfigListEntry(_("Enable Authentication for streaming"), config.OpenWebif.auth_for_streaming))
				self.list.append(getConfigListEntry(_("Disable remote access for user root"), config.OpenWebif.no_root_access))
			if not config.OpenWebif.auth.value or (config.OpenWebif.https_enabled.value and not config.OpenWebif.https_auth.value):
				self.list.append(getConfigListEntry(_("Without auth only local access is allowed!"), config.OpenWebif.local_access_only))
				self.list.append(getConfigListEntry(_("Enable access from VPNs"), config.OpenWebif.vpn_access))
			self.list.append(getConfigListEntry(_("Enable Parental Control"), config.OpenWebif.parentalenabled))
			self.list.append(getConfigListEntry(_("Add service name to stream information"), config.OpenWebif.service_name_for_stream))
			self.list.append(getConfigListEntry(_("Allow IPK Upload"), config.OpenWebif.allow_upload_ipk))
			# FIXME Submenu			
			# self.list.append(getConfigListEntry(_("Webinterface jQuery UI Theme"), config.OpenWebif.webcache.theme))
			# self.list.append(getConfigListEntry(_("Movie List Sort"), config.OpenWebif.webcache.moviesort))

		self["config"].list = self.list
		self["config"].l.setList(self.list)
Beispiel #17
0
	def setWindowTitle(self):
		self.setTitle(_("OpenWebif Configuration"))
Beispiel #18
0
def FuzzyTime2(t):
    d = localtime(t)
    n = localtime()
    dayOfWeek = (_("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"),
                 _("Sun"))

    if d[:3] == n[:3]:
        day = _("Today")
    elif d[0] == n[0] and d[7] == n[7] - 1:
        day = _("Yesterday")
    else:
        day = dayOfWeek[d[6]]

    if d[0] == n[0]:
        # same year
        date = _("%s %02d.%02d.") % (day, d[2], d[1])
    else:
        date = _("%s %02d.%02d.%d") % (day, d[2], d[1], d[0])

    timeres = _("%02d:%02d") % (d[3], d[4])
    return date + ", " + timeres
def setSleepTimer(session, time, action, enabled):
    if action not in ["shutdown", "standby"]:
        action = "standby"

    if hasattr(session.nav, "SleepTimer"):
        try:
            ret = getSleepTimer(session)
            from Screens.Standby import inStandby
            if inStandby is not None:
                ret["message"] = _(
                    "ERROR: Cannot set SleepTimer while device is in Standby-Mode"
                )
                return ret
            if enabled is False:
                session.nav.SleepTimer.clear()
                ret = getSleepTimer(session)
                ret["message"] = _("Sleeptimer has been disabled")
                return ret
            config.SleepTimer.action.value = action
            config.SleepTimer.action.save()
            session.nav.SleepTimer.setSleepTime(time)
            ret = getSleepTimer(session)
            ret["message"] = _("Sleeptimer set to %d minutes") % time
            return ret
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
    elif InfoBar.instance is not None and hasattr(InfoBar.instance,
                                                  'sleepTimer'):
        try:
            if time == None:
                time = 60
            # TODO test OpenPLI and similar
            info = getInfo()
            cfgaction = None
            if hasattr(config.usage, 'sleepTimerAction'):
                cfgaction = config.usage.sleepTimerAction
            if hasattr(config.usage, 'sleep_timer_action'):
                cfgaction = config.usage.sleep_timer_action
            if cfgaction:
                if action == "shutdown":
                    cfgaction.value = "deepstandby"
                else:
                    cfgaction.value = action
                cfgaction.save()
            active = enabled
            time = int(time)
            cfgtimer = None
            if hasattr(config.usage, 'sleepTimer'):
                cfgtimer = config.usage.sleepTimer
                if cfgtimer.value == '0':
                    if info["imagedistro"] in ('openatv'):
                        for val in range(15, 241, 15):
                            if time == val:
                                break
                            if time < val:
                                time = int(abs(val / 60))
                                break
            elif hasattr(config.usage, 'sleep_timer'):
                cfgtimer = config.usage.sleep_timer
                if cfgtimer.value == '0':
                    # find the closest value
                    if info["imagedistro"] in ('openatv'):
                        times = time * 60
                        for val in list(range(900, 14401, 900)):
                            if times == val:
                                break
                            if times < val:
                                time = int(abs(val / 60))
                                break
            if cfgtimer:
                if active:
                    cfgtimer.value = str(time * 60)
                else:
                    cfgtimer.value = '0'
                cfgtimer.save()
                if enabled:
                    InfoBar.instance.setSleepTimer(time * 60, False)
                else:
                    InfoBar.instance.setSleepTimer(0, False)
            return {
                "enabled":
                active,
                "minutes":
                time,
                "action":
                action,
                "message":
                _("Sleeptimer is enabled")
                if active else _("Sleeptimer is disabled")
            }
        except Exception as e:
            print(e)
            return {"result": False, "message": _("SleepTimer error")}
    else:
        # use powertimer
        # todo activate powertimer
        try:
            done = False
            timer_list = session.nav.PowerTimer.timer_list
            begin = int(time() + 60)
            end = int(time() + 120)
            for timer in timer_list:
                timertype = str(timer.timerType)
                if timertype == "2" and action == "standby":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break
                if timertype == "3" and action == "shutdown":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break
                if timertype == "3" and action == "standby":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.timerType = 2
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break
                if timertype == "2" and action == "shutdown":
                    if enabled:
                        timer.disabled = False
                        timer.autosleepdelay = int(time)
                        timer.timerType = 3
                        timer.begin = begin
                        timer.end = end
                    else:
                        timer.disabled = True
                    done = True
                    break

            if done:
                return {
                    "result":
                    True,
                    "message":
                    _("Sleeptimer set to %d minutes") %
                    time if enabled else _("Sleeptimer has been disabled")
                }
            if enabled:
                begin = int(time() + 60)
                end = int(time() + 120)
                timertype = 2
                if action == "shutdown":
                    timertype = 3
                from PowerTimer import PowerTimerEntry
                entry = PowerTimerEntry(begin, end, False, 0, timertype)
                entry.repeated = 0
                entry.autosleepdelay = time
                return {
                    "result": True,
                    "message": _("Sleeptimer set to %d minutes") % time
                }
            else:
                return {
                    "result": True,
                    "message": _("Sleeptimer has been disabled")
                }
        except Exception:
            return {"result": False, "message": _("SleepTimer error")}
Beispiel #20
0
def getMovieDetails(sRef=None):

    service = ServiceReference(sRef)
    if service is not None:

        serviceref = service.ref
        length_minutes = 0
        txtdesc = ""
        fullpath = serviceref.getPath()
        filename = '/'.join(fullpath.split("/")[1:])
        filename = '/' + filename
        name, ext = os.path.splitext(filename)

        serviceHandler = eServiceCenter.getInstance()
        info = serviceHandler.info(serviceref)

        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':
            service.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:
            movie['begintime'] = FuzzyTime2(rtime)

        try:
            length_minutes = info.getLength(serviceref)
        except:  # noqa: E722
            pass

        if length_minutes:
            movie['length'] = "%d:%02d" % (length_minutes / 60,
                                           length_minutes % 60)
            movie['lastseen'] = _moviePlayState(filename + '.cuts', serviceref,
                                                length_minutes) or 0

        txtfile = name + '.txt'
        if ext.lower() != '.ts' and os.path.isfile(txtfile):
            with open(txtfile, "rb") as handle:
                txtdesc = six.ensure_str(b''.join(handle.readlines()))

        event = info.getEvent(serviceref)
        extended_description = event and event.getExtendedDescription() or ""
        if extended_description == '' and txtdesc != '':
            extended_description = txtdesc
        movie['descriptionExtended'] = ConvertDesc(extended_description)
        desc = info.getInfoString(serviceref, iServiceInformation.sDescription)
        movie['description'] = ConvertDesc(desc)

        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:  # noqa: E722
            pass

        movie['filesize'] = size
        movie['filesize_readable'] = sz

        return {"result": True, "movie": movie}
    else:
        return {
            "result": False,
        }
def FuzzyTime(t, inPast=False):
    d = localtime(t)
    nt = time()
    n = localtime()
    dayOfWeek = (_("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"),
                 _("Sun"))

    if d[:3] == n[:3]:
        # same day
        date = _("Today")
    elif d[0] == n[0] and d[7] == n[7] - 1 and inPast:
        # won't work on New Year's day
        date = _("Yesterday")
    elif ((t - nt) < 7 * 86400) and (nt < t) and not inPast:
        # same week (must be future)
        date = dayOfWeek[d[6]]
    elif d[0] == n[0]:
        # same year
        if inPast:
            # I want the day in the movielist
            date = _("%s %02d.%02d.") % (dayOfWeek[d[6]], d[2], d[1])
        else:
            date = _("%02d.%02d.") % (d[2], d[1])
    else:
        date = _("%02d.%02d.%d") % (d[2], d[1], d[0])

    timeres = _("%02d:%02d") % (d[3], d[4])

    return date, timeres
Beispiel #22
0
def getInfo(session=None, need_fullinfo=False):
    # TODO: get webif versione somewhere!
    info = {}
    global STATICBOXINFO

    if not (STATICBOXINFO is None or need_fullinfo):
        return STATICBOXINFO

    info['brand'] = getBoxBrand()
    info['model'] = getBoxType()
    info['platform'] = boxbranding.getMachineBuild()

    try:
        info['procmodel'] = getBoxProc()
    except:  # noqa: E722
        info['procmodel'] = boxbranding.getMachineProcModel()

    try:
        info['procmodeltype'] = getBoxProcType()
    except:  # noqa: E722
        info['procmodeltype'] = None

    try:
        info['lcd'] = getLcd()
    except:  # noqa: E722
        info['lcd'] = 0

    try:
        info['grabpip'] = getGrabPip()
    except:  # noqa: E722
        info['grabpip'] = 0

    cpu = about.getCPUInfoString()
    info['chipset'] = cpu
    info['cpubrand'] = about.getCPUBrand()
    info['socfamily'] = boxbranding.getSoCFamily()
    info['cpuarch'] = about.getCPUArch()
    if config.OpenWebif.about_benchmark.value is True:
        info['cpubenchmark'] = about.getCPUBenchmark()
    else:
        info['cpubenchmark'] = _("Disabled in configuration")
    info['flashtype'] = about.getFlashType()

    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'])

    info['uptime'] = about.getBoxUptime()

    info["webifver"] = OPENWEBIFVER
    info['imagedistro'] = boxbranding.getImageDistro()
    info['oever'] = boxbranding.getImageBuild()
    info['visionversion'] = boxbranding.getVisionVersion()
    info['visionrevision'] = boxbranding.getVisionRevision()
    info['visionmodule'] = about.getVisionModule()

    if fileExists("/etc/openvision/multiboot"):
        multibootflag = open("/etc/openvision/multiboot", "r").read().strip()
        if multibootflag == "1":
            info['multiboot'] = _("Yes")
        else:
            info['multiboot'] = _("No")
    else:
        info['multiboot'] = _("Yes")

    info['enigmaver'] = getEnigmaVersionString()
    info['driverdate'] = about.getDriverInstalledDate()
    info['kernelver'] = boxbranding.getKernelVersion()
    info['dvbapitype'] = about.getDVBAPI()
    info['gstreamerversion'] = about.getGStreamerVersionString(cpu)
    info['ffmpegversion'] = about.getFFmpegVersionString()
    info['pythonversion'] = about.getPythonVersionString()

    try:
        info['hwserial'] = getHWSerial()
    except:  # noqa: E722
        info['hwserial'] = None

    if (info['hwserial'] is None or info['hwserial'] == "unknown"):
        info['hwserial'] = about.getCPUSerial()

    try:
        info['boxrctype'] = getBoxRCType()
    except:  # noqa: E722
        info['boxrctype'] = None

    if (info['boxrctype'] is None or info['boxrctype'] == "unknown"):
        if fileExists("/usr/bin/remotecfg"):
            info['boxrctype'] = _("Amlogic remote")
        elif fileExists("/usr/sbin/lircd"):
            info['boxrctype'] = _("LIRC remote")

    info['ovrctype'] = boxbranding.getRCType()
    info['ovrcname'] = boxbranding.getRCName()
    info['ovrcidnum'] = boxbranding.getRCIDNum()

    info['transcoding'] = boxbranding.getHaveTranscoding()
    info['multitranscoding'] = boxbranding.getHaveMultiTranscoding()

    info['displaytype'] = boxbranding.getDisplayType()

    info['updatedatestring'] = about.getUpdateDateString()
    info['enigmadebuglvl'] = eGetEnigmaDebugLvl()

    info['imagearch'] = boxbranding.getImageArch()
    info['imagefolder'] = boxbranding.getImageFolder()
    info['imagefilesystem'] = boxbranding.getImageFileSystem()
    info['feedsurl'] = boxbranding.getFeedsUrl()
    info['developername'] = boxbranding.getDeveloperName()
    info['builddatestring'] = about.getBuildDateString()
    info['imagefpu'] = boxbranding.getImageFPU()
    info['havemultilib'] = boxbranding.getHaveMultiLib()

    try:
        info['fp_version'] = getFPVersion()
    except:  # noqa: E722
        info['fp_version'] = None

    info['tuners'] = []
    for i in list(range(0, nimmanager.getSlotCount())):
        print(
            "[OpenWebif] -D- tuner '%d' '%s' '%s'" %
            (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 = stat.f_bavail * stat.f_frsize / 1048576.
        else:
            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 + '")')
        })

    info['shares'] = []
    autofiles = ('/etc/auto.network', '/etc/auto.network_vti')
    for autofs in autofiles:
        if fileExists(autofs):
            method = "autofs"
            for line in open(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()
                    type = "unknown"
                    if "cifs" in tmp[1]:
                        # Linux still defaults to SMBv1
                        type = "SMBv1.0"
                        settings = tmp[1].split(",")
                        for setting in settings:
                            if setting.startswith("vers="):
                                type = setting.replace("vers=", "SMBv")
                    elif "nfs" in tmp[1]:
                        type = "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 = []
                    parts = tmp[2].split(':')
                    if parts[0] == "":
                        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:  # noqa: E722
                            pass

                    friendlyaddress = server
                    if ipaddress is not None and not ipaddress == server:
                        friendlyaddress = server + " (" + ipaddress + ")"
                    info['shares'].append({
                        "name": name,
                        "method": method,
                        "type": type,
                        "mode": mode,
                        "path": uri,
                        "host": server,
                        "ipaddress": ipaddress,
                        "friendlyaddress": friendlyaddress
                    })
    # TODO: fstab

    info['EX'] = ''

    if session:
        try:
            #  gets all current stream clients for images using eStreamServer
            #  TODO: merge eStreamServer and streamList
            #  TODO: get tuner info for streams
            #  TODO: get recoding/timer info if more than one
            info['streams'] = []
            try:
                from enigma import eStreamServer
                streamServer = eStreamServer.getInstance()
                if streamServer is not None:
                    for x in streamServer.getConnectedClients():
                        servicename = ServiceReference(
                            x[1]).getServiceName() or "(unknown service)"
                        if int(x[2]) == 0:
                            strtype = "S"
                        else:
                            strtype = "T"
                        info['streams'].append({
                            "ref": x[1],
                            "name": servicename,
                            "ip": x[0],
                            "type": strtype
                        })
            except Exception as error:
                print("[OpenWebif] -D- no eStreamServer %s" % error)
            recs = NavigationInstance.instance.getRecordings()
            if recs:
                #  only one stream and only TV
                from Plugins.Extensions.OpenWebif.controllers.stream import streamList
                s_name = ''
                # s_cip = ''

                print("[OpenWebif] -D- streamList count '%d'" %
                      len(streamList))
                if len(streamList) == 1:
                    from Screens.ChannelSelection import service_types_tv
                    # from enigma import eEPGCache
                    # epgcache = eEPGCache.getInstance()
                    serviceHandler = eServiceCenter.getInstance()
                    services = serviceHandler.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
                print("[OpenWebif] -D- s_name '%s'" % s_name)

                # only for debug
                for stream in streamList:
                    srefs = stream.ref.toString()
                    print("[OpenWebif] -D- srefs '%s'" % srefs)

                sname = ''
                timers = []
                for timer in NavigationInstance.instance.RecordTimer.timer_list:
                    if timer.isRunning() and not timer.justplay:
                        timers.append(
                            removeBad(timer.service_ref.getServiceName()))
                        print("[OpenWebif] -D- timer '%s'" %
                              timer.service_ref.getServiceName())


# TODO: more than one recording
                if len(timers) == 1:
                    sname = timers[0]

                if sname == '' and s_name != '':
                    sname = s_name

                print("[OpenWebif] -D- recs count '%d'" % len(recs))

                for rec in recs:
                    feinfo = rec.frontendInfo()
                    frontendData = feinfo and feinfo.getAll(True)
                    if frontendData is not None:
                        cur_info = feinfo.getTransponderData(True)
                        if cur_info:
                            nr = frontendData['tuner_number']
                            info['tuners'][nr]['rec'] = getOrbitalText(
                                cur_info) + ' / ' + sname

            service = session.nav.getCurrentService()
            if service is not None:
                sname = service.info().getName()
                feinfo = service.frontendInfo()
                frontendData = feinfo and feinfo.getAll(True)
                if frontendData is not None:
                    cur_info = feinfo.getTransponderData(True)
                    if cur_info:
                        nr = frontendData['tuner_number']
                        info['tuners'][nr]['live'] = getOrbitalText(
                            cur_info) + ' / ' + sname
        except Exception as error:
            info['EX'] = error

    info['timerpipzap'] = False
    info['timerautoadjust'] = False

    try:
        timer = RecordTimerEntry('', 0, 0, '', '', 0)
        if hasattr(timer, "pipzap"):
            info['timerpipzap'] = True
        if hasattr(timer, "autoadjust"):
            info['timerautoadjust'] = True
    except Exception as error:
        print("[OpenWebif] -D- RecordTimerEntry check %s" % error)

    STATICBOXINFO = info
    return info
def cleanupTimer(session):
    session.nav.RecordTimer.cleanup()
    return {"result": True, "message": _("List of Timers has been cleaned")}
Beispiel #24
0
def getInfo(session=None, need_fullinfo=False):
    # TODO: get webif versione somewhere!
    info = {}
    global STATICBOXINFO

    if not (STATICBOXINFO is None or need_fullinfo):
        return STATICBOXINFO

    info['brand'] = getMachineBrand()
    info['model'] = getMachineName()
    info['boxtype'] = getBoxType()
    info['machinebuild'] = getMachineBuild()
    try:  # temporary due OE-A
        info['lcd'] = getLcd()
    except:  # noqa: E722
        info['lcd'] = 0
    try:  # temporary due OE-A
        info['grabpip'] = getGrabPip()
    except:  # noqa: E722
        info['grabpip'] = 0

    chipset = "unknown"
    if fileExists("/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 fileExists("/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 fileExists("/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"
        elif model == "dm800":
            chipset = "bcm7401"
        elif model in ("dm800se", "dm500hd", "dm7020hd", "dm800sev2",
                       "dm500hdv2", "dm7020hdv2"):
            chipset = "bcm7405"
        elif model == "dm8000":
            chipset = "bcm7400"
        elif model in ("dm820", "dm7080"):
            chipset = "bcm7435"
        elif model in ("dm520", "dm525"):
            chipset = "bcm73625"
        elif model in ("dm900", "dm920"):
            chipset = "bcm7252S"

    if fileExists("/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", "r")
        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:  # noqa: E722
        uptimetext = "?"
    info['uptime'] = uptimetext

    info["webifver"] = OPENWEBIFVER
    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:
        from Tools.StbHardware import getFPVersion
    except ImportError:
        from Tools.DreamboxHardware import getFPVersion

    try:
        info['fp_version'] = getFPVersion()
    except:  # noqa: E722
        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 = friendlychipsetdescription + " (" + _(
            "Front processor version") + ")"
        friendlychipsettext = friendlychipsettext + " (" + str(
            info['fp_version']) + ")"

    info['friendlychipsetdescription'] = friendlychipsetdescription
    info['friendlychipsettext'] = friendlychipsettext
    info['tuners'] = []
    for i in list(range(0, nimmanager.getSlotCount())):
        print(
            "[OpenWebif] -D- tuner '%d' '%s' '%s'" %
            (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 = stat.f_bavail * stat.f_frsize / 1048576.
        else:
            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 + '")')
        })

    info['shares'] = []
    autofiles = ('/etc/auto.network', '/etc/auto.network_vti')
    for autofs in autofiles:
        if fileExists(autofs):
            method = "autofs"
            for line in open(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()
                    type = "unknown"
                    if "cifs" in tmp[1]:
                        # Linux still defaults to SMBv1
                        type = "SMBv1.0"
                        settings = tmp[1].split(",")
                        for setting in settings:
                            if setting.startswith("vers="):
                                type = setting.replace("vers=", "SMBv")
                    elif "nfs" in tmp[1]:
                        type = "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 = []
                    parts = tmp[2].split(':')
                    if parts[0] == "":
                        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:  # noqa: E722
                            pass

                    friendlyaddress = server
                    if ipaddress is not None and not ipaddress == server:
                        friendlyaddress = server + " (" + ipaddress + ")"
                    info['shares'].append({
                        "name": name,
                        "method": method,
                        "type": type,
                        "mode": mode,
                        "path": uri,
                        "host": server,
                        "ipaddress": ipaddress,
                        "friendlyaddress": friendlyaddress
                    })
    # TODO: fstab

    info['transcoding'] = TRANSCODING

    info['EX'] = ''

    if session:
        try:
            #  gets all current stream clients for images using eStreamServer
            #  TODO: merge eStreamServer and streamList
            #  TODO: get tuner info for streams
            #  TODO: get recoding/timer info if more than one
            info['streams'] = []
            try:
                from enigma import eStreamServer
                streamServer = eStreamServer.getInstance()
                if streamServer is not None:
                    for x in streamServer.getConnectedClients():
                        servicename = ServiceReference(
                            x[1]).getServiceName() or "(unknown service)"
                        if int(x[2]) == 0:
                            strtype = "S"
                        else:
                            strtype = "T"
                        info['streams'].append({
                            "ref": x[1],
                            "name": servicename,
                            "ip": x[0],
                            "type": strtype
                        })
            except Exception as error:
                print("[OpenWebif] -D- no eStreamServer %s" % error)

            recs = NavigationInstance.instance.getRecordings()
            if recs:
                #  only one stream and only TV
                from Plugins.Extensions.OpenWebif.controllers.stream import streamList
                s_name = ''
                #  s_cip = ''

                print("[OpenWebif] -D- streamList count '%d'" %
                      len(streamList))
                if len(streamList) == 1:
                    from Screens.ChannelSelection import service_types_tv
                    # from enigma import eEPGCache
                    # epgcache = eEPGCache.getInstance()
                    serviceHandler = eServiceCenter.getInstance()
                    services = serviceHandler.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
                print("[OpenWebif] -D- s_name '%s'" % s_name)

                # only for debug
                for stream in streamList:
                    srefs = stream.ref.toString()
                    print("[OpenWebif] -D- srefs '%s'" % srefs)

                sname = ''
                timers = []
                for timer in NavigationInstance.instance.RecordTimer.timer_list:
                    if timer.isRunning() and not timer.justplay:
                        timers.append(
                            removeBad(timer.service_ref.getServiceName()))
                        print("[OpenWebif] -D- timer '%s'" %
                              timer.service_ref.getServiceName())


# TODO: more than one recording
                if len(timers) == 1:
                    sname = timers[0]

                if sname == '' and s_name != '':
                    sname = s_name

                print("[OpenWebif] -D- recs count '%d'" % len(recs))

                for rec in recs:
                    feinfo = rec.frontendInfo()
                    frontendData = feinfo and feinfo.getAll(True)
                    if frontendData is not None:
                        cur_info = feinfo.getTransponderData(True)
                        if cur_info:
                            nr = frontendData['tuner_number']
                            info['tuners'][nr]['rec'] = getOrbitalText(
                                cur_info) + ' / ' + sname

            service = session.nav.getCurrentService()
            if service is not None:
                sname = service.info().getName()
                feinfo = service.frontendInfo()
                frontendData = feinfo and feinfo.getAll(True)
                if frontendData is not None:
                    cur_info = feinfo.getTransponderData(True)
                    if cur_info:
                        nr = frontendData['tuner_number']
                        info['tuners'][nr]['live'] = getOrbitalText(
                            cur_info) + ' / ' + sname
        except Exception as error:
            info['EX'] = error

    info['timerpipzap'] = False
    info['timerautoadjust'] = False

    try:
        timer = RecordTimerEntry(ServiceReference("1:0:1:0:0:0:0:0:0:0"), 0, 0,
                                 '', '', 0)
        if hasattr(timer, "pipzap"):
            info['timerpipzap'] = True
        if hasattr(timer, "autoadjust"):
            info['timerautoadjust'] = True
    except Exception as error:
        print("[OpenWebif] -D- RecordTimerEntry check %s" % error)

    STATICBOXINFO = info
    return info
def getTimers(session):
    rt = session.nav.RecordTimer
    epg = Epg()
    timers = []
    for timer in rt.timer_list + rt.processed_timers:
        if hasattr(timer, "wakeup_t"):
            energytimer = timer.wakeup_t or timer.standby_t or timer.shutdown_t or timer.fnc_t != "off" or 0
            if energytimer:
                continue

        descriptionextended = "N/A"
        filename = None
        nextactivation = None
        if timer.eit and timer.service_ref:
            descriptionextended = epg.getEventDescription(
                timer.service_ref, timer.eit)

        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 hasattr(timer, "allow_duplicate"):
            allow_duplicate = timer.allow_duplicate and 1 or 0
        else:
            allow_duplicate = 1

        autoadjust = -1
        if hasattr(timer, "autoadjust"):
            autoadjust = timer.autoadjust and 1 or 0
        elif hasattr(config.recording, "adjust_time_to_event"):
            autoadjust = config.recording.adjust_time_to_event.value and 1 or 0

        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
        if hasattr(timer, "zapbeforerecord"):
            if timer.zapbeforerecord:
                always_zap = 1
            else:
                always_zap = 0

        pipzap = -1
        if hasattr(timer, "pipzap"):
            if timer.pipzap:
                pipzap = 1
            else:
                pipzap = 0

        isAutoTimer = -1
        if hasattr(timer, "isAutoTimer"):
            if timer.isAutoTimer:
                isAutoTimer = 1
            else:
                isAutoTimer = 0

        if six.PY2:
            descriptionextended = six.text_type(descriptionextended,
                                                'utf_8',
                                                errors='ignore').encode(
                                                    'utf_8', 'ignore')

        recordingtype = "normal"

        if timer.record_ecm:
            recordingtype = "scrambled"
            if timer.descramble:
                recordingtype = "descrambled"

        ice_timer_id = -1
        if hasattr(timer, "ice_timer_id"):
            ice_timer_id = timer.ice_timer_id or -1

        # switch back to old way.
        #fuzzyBegin = ' '.join(str(i) for i in FuzzyTime(timer.begin, inPast = True)[1:])
        #fuzzyEnd = ""
        #if strftime("%Y%m%d", localtime(timer.begin)) == strftime("%Y%m%d", localtime(timer.end)):
        #	fuzzyEnd = FuzzyTime(timer.end)[1]
        #else:
        #	fuzzyEnd = ' '.join(str(i) for i in FuzzyTime(timer.end, inPast = True))

        fuzzyBegin = strftime(_("%d.%m.%Y %H:%M"),
                              (localtime(float(timer.begin))))
        fuzzyEnd = strftime(_("%d.%m.%Y %H:%M"), (localtime(float(timer.end))))

        timers.append({
            "serviceref":
            str(timer.service_ref),
            "servicename":
            removeBad(timer.service_ref.getServiceName()),
            "eit":
            timer.eit,
            "name":
            timer.name,
            "description":
            timer.description,
            "descriptionextended":
            descriptionextended,
            "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":
            fuzzyBegin,
            "realend":
            fuzzyEnd,
            "asrefs":
            asrefs,
            "vpsplugin_enabled":
            vpsplugin_enabled,
            "vpsplugin_overwrite":
            vpsplugin_overwrite,
            "vpsplugin_time":
            vpsplugin_time,
            "always_zap":
            always_zap,
            "pipzap":
            pipzap,
            "isAutoTimer":
            isAutoTimer,
            "allow_duplicate":
            allow_duplicate,
            "autoadjust":
            autoadjust,
            "recordingtype":
            recordingtype,
            "ice_timer_id":
            ice_timer_id
        })

    return {"result": True, "timers": timers}
Beispiel #26
0
def getOrb(pos):
    direction = _("E")
    if pos > 1800:
        pos = 3600 - pos
        direction = _("W")
    return "%d.%d° %s" % (pos / 10, pos % 10, direction)
def getPowerTimer(session, request):

    try:
        from PowerTimer import TIMERTYPE, AFTEREVENT
        logs = False
        if "logs" in list(request.args.keys()):
            logs = True

        timers = []
        timer_list = session.nav.PowerTimer.timer_list
        processed_timers = session.nav.PowerTimer.processed_timers

        pos = 0
        for timer in timer_list + processed_timers:
            list = []
            pos += 1
            if logs:
                for _time, code, msg in timer.log_entries:
                    list.append({
                        "code": str(code),
                        "time": str(_time),
                        "msg": str(msg)
                    })
            timers.append({
                "id":
                str(pos),
                "timertype":
                str(timer.timerType),
                "timertypename":
                str({
                    TIMERTYPE.NONE: "nothing",
                    TIMERTYPE.WAKEUP: "wakeup",
                    TIMERTYPE.WAKEUPTOSTANDBY: "wakeuptostandby",
                    TIMERTYPE.AUTOSTANDBY: "autostandby",
                    TIMERTYPE.AUTODEEPSTANDBY: "autodeepstandby",
                    TIMERTYPE.STANDBY: "standby",
                    TIMERTYPE.DEEPSTANDBY: "deepstandby",
                    TIMERTYPE.REBOOT: "reboot",
                    TIMERTYPE.RESTART: "restart"
                }[timer.timerType]),
                "begin":
                str(int(timer.begin)),
                "end":
                str(int(timer.end)),
                "repeated":
                str(int(timer.repeated)),
                "afterevent":
                str(timer.afterEvent),
                "aftereventname":
                str({
                    AFTEREVENT.NONE: "nothing",
                    AFTEREVENT.WAKEUP: "wakeup",
                    AFTEREVENT.WAKEUPTOSTANDBY: "wakeuptostandby",
                    AFTEREVENT.STANDBY: "standby",
                    AFTEREVENT.DEEPSTANDBY: "deepstandby"
                }[timer.afterEvent]),
                "disabled":
                str(int(timer.disabled)),
                "autosleepinstandbyonly":
                str(timer.autosleepinstandbyonly),
                "autosleepdelay":
                str(timer.autosleepdelay),
                "autosleeprepeat":
                str(timer.autosleeprepeat),
                "logentries":
                list
            })

        return {"result": True, "timers": timers}
    except Exception as e:
        print(str(e))
        return {
            "result": False,
            "message": _("PowerTimer feature not available")
        }
Beispiel #28
0
    def runSetup(self):
        self.list = []
        self.list.append(
            getConfigListEntry(_("OpenWebInterface Enabled"),
                               config.OpenWebif.enabled))
        if config.OpenWebif.enabled.value:
            self.list.append(
                getConfigListEntry(_("Use modern interface"),
                                   config.OpenWebif.responsive_enabled))
            if config.OpenWebif.responsive_enabled.value:
                self.list.append(
                    getConfigListEntry(_("Theme mode"),
                                       config.OpenWebif.responsive_themeMode))
                self.list.append(
                    getConfigListEntry(_("Use custom Color"),
                                       config.OpenWebif.responsive_skinColor))
            self.list.append(
                getConfigListEntry(_("Show box name in header"),
                                   config.OpenWebif.identifier))
            if config.OpenWebif.identifier.value:
                self.list.append(
                    getConfigListEntry(_("Use custom box name"),
                                       config.OpenWebif.identifier_custom))
                if config.OpenWebif.identifier_custom.value:
                    self.list.append(
                        getConfigListEntry(_("Custom box name"),
                                           config.OpenWebif.identifier_text))
            self.list.append(
                getConfigListEntry(_("HTTP port"), config.OpenWebif.port))
            self.list.append(
                getConfigListEntry(_("Enable HTTP Authentication"),
                                   config.OpenWebif.auth))
            self.list.append(
                getConfigListEntry(_("Enable HTTPS"),
                                   config.OpenWebif.https_enabled))
            if config.OpenWebif.https_enabled.value:
                self.list.append(
                    getConfigListEntry(_("HTTPS port"),
                                       config.OpenWebif.https_port))
                self.list.append(
                    getConfigListEntry(_("Enable HTTPS Authentication"),
                                       config.OpenWebif.https_auth))
                self.list.append(
                    getConfigListEntry(_("Require client cert for HTTPS"),
                                       config.OpenWebif.https_clientcert))
            if config.OpenWebif.auth.value:
                self.list.append(
                    getConfigListEntry(
                        _("Enable Authentication for streaming"),
                        config.OpenWebif.auth_for_streaming))
                self.list.append(
                    getConfigListEntry(
                        _("Disable remote access for user root"),
                        config.OpenWebif.no_root_access))
            if not config.OpenWebif.auth.value or (
                    config.OpenWebif.https_enabled.value
                    and not config.OpenWebif.https_auth.value):
                self.list.append(
                    getConfigListEntry(
                        _("Without auth only local access is allowed!"),
                        config.OpenWebif.local_access_only))
                self.list.append(
                    getConfigListEntry(_("Enable access from VPNs"),
                                       config.OpenWebif.vpn_access))
            self.list.append(
                getConfigListEntry(_("Enable Parental Control"),
                                   config.OpenWebif.parentalenabled))
            self.list.append(
                getConfigListEntry(_("Streaming port"),
                                   config.OpenWebif.streamport))
            self.list.append(
                getConfigListEntry(_("Add service name to stream information"),
                                   config.OpenWebif.service_name_for_stream))
            if imagedistro in ("VTi-Team Image"):
                self.list.append(
                    getConfigListEntry(_("Character encoding for EPG data"),
                                       config.OpenWebif.epg_encoding))
            self.list.append(
                getConfigListEntry(_("Allow IPK Upload"),
                                   config.OpenWebif.allow_upload_ipk))
            self.list.append(
                getConfigListEntry(_("Playback IPTV Streams in browser"),
                                   config.OpenWebif.playiptvdirect))
            self.list.append(
                getConfigListEntry(_("Debug - Display Tracebacks in browser"),
                                   config.OpenWebif.displayTracebacks))
            # FIXME Submenu
            # self.list.append(getConfigListEntry(_("Webinterface jQuery UI Theme"), config.OpenWebif.webcache.theme))
            # self.list.append(getConfigListEntry(_("Movie List Sort"), config.OpenWebif.webcache.moviesort))

        self["config"].list = self.list
        self["config"].l.setList(self.list)
Beispiel #29
0
def getCurrentFullInfo(session):
    now = next = {}
    inf = getCurrentService(session)
    inf['tuners'] = list(map(chr, range(65, 65 + nimmanager.getSlotCount())))

    try:
        info = session.nav.getCurrentService().info()
    except:  # noqa: E722
        info = None

    try:
        subservices = session.nav.getCurrentService().subServices()
    except:  # noqa: E722
        subservices = None

    try:
        audio = session.nav.getCurrentService().audioTracks()
    except:  # noqa: E722
        audio = None

    try:
        ref = session.nav.getCurrentlyPlayingServiceReference().toString()
    except:  # noqa: E722
        ref = None

    if ref is not None:
        inf['sref'] = '_'.join(ref.split(':', 10)[:10])
        inf['srefv2'] = ref
        inf['picon'] = getPicon(ref)
        inf['wide'] = inf['aspect'] in (3, 4, 7, 8, 0xB, 0xC, 0xF, 0x10)
        inf['ttext'] = getServiceInfoString(info, iServiceInformation.sTXTPID)
        inf['crypt'] = getServiceInfoString(info,
                                            iServiceInformation.sIsCrypted)
        inf['subs'] = str(subservices
                          and subservices.getNumberOfSubservices() > 0)
    else:
        inf['sref'] = None
        inf['picon'] = None
        inf['wide'] = None
        inf['ttext'] = None
        inf['crypt'] = None
        inf['subs'] = None

    inf['date'] = strftime("%d.%m.%Y", (localtime()))
    inf['dolby'] = False

    if audio:
        n = audio.getNumberOfTracks()
        idx = 0
        while idx < n:
            i = audio.getTrackInfo(idx)
            description = i.getDescription()
            if "AC3" in description or "DTS" in description or "Dolby Digital" in description:
                inf['dolby'] = True
            idx += 1
    try:
        feinfo = session.nav.getCurrentService().frontendInfo()
    except:  # noqa: E722
        feinfo = None

    frontendData = feinfo and feinfo.getAll(True)

    if frontendData is not None:
        cur_info = feinfo.getTransponderData(True)
        inf['tunertype'] = frontendData.get("tuner_type", "UNKNOWN")
        if frontendData.get("system", -1) == 1:
            inf['tunertype'] += "2"
        inf['tunernumber'] = frontendData.get("tuner_number")
        orb = getOrbitalText(cur_info)
        inf['orbital_position'] = orb
        if cur_info:
            if cur_info.get('tuner_type') == "DVB-S":
                inf['orbital_position'] = _("Orbital Position") + ': ' + orb
    else:
        inf['tunernumber'] = "N/A"
        inf['tunertype'] = "N/A"

    try:
        frontendStatus = feinfo and feinfo.getFrontendStatus()
    except:  # noqa: E722
        frontendStatus = None

    if frontendStatus is not None:
        percent = frontendStatus.get("tuner_signal_quality")
        if percent is not None:
            inf['snr'] = int(percent * 100 / 65535)
            inf['snr_db'] = inf['snr']
        percent = frontendStatus.get("tuner_signal_quality_db")
        if percent is not None:
            inf['snr_db'] = "%3.02f dB" % (percent / 100.0)
        percent = frontendStatus.get("tuner_signal_power")
        if percent is not None:
            inf['agc'] = int(percent * 100 / 65535)
        percent = frontendStatus.get("tuner_bit_error_rate")
        if percent is not None:
            inf['ber'] = int(percent * 100 / 65535)
    else:
        inf['snr'] = 0
        inf['snr_db'] = inf['snr']
        inf['agc'] = 0
        inf['ber'] = 0

    try:
        recordings = session.nav.getRecordings()
    except:  # noqa: E722
        recordings = None

    inf['rec_state'] = False
    if recordings:
        inf['rec_state'] = True

    ev = getChannelEpg(ref)
    if len(ev['events']) > 1:
        now = ev['events'][0]
        next = ev['events'][1]
        if len(now['title']) > 50:
            now['title'] = now['title'][0:48] + "..."
        if len(next['title']) > 50:
            next['title'] = next['title'][0:48] + "..."

    return {"info": inf, "now": now, "next": next}
Beispiel #30
0
	def prepareMainTemplate(self, request):
		# here will be generated the dictionary for the main template
		ret = getCollapsedMenus()
		ret['configsections'] = getConfigsSections()['sections']
		ret['showname'] = getShowName()['showname']
		ret['customname'] = getCustomName()['customname']
		ret['boxname'] = getBoxName()['boxname']
		if not ret['boxname'] or not ret['customname']:
			ret['boxname'] = getInfo()['brand'] + " " + getInfo()['model']
		ret['box'] = getBoxType()
		ret["remote"] = REMOTE
		if hasattr(eEPGCache, 'FULL_DESCRIPTION_SEARCH'):
			ret['epgsearchcaps'] = True
		else:
			ret['epgsearchcaps'] = False
		extras = [{'key': 'ajax/settings', 'description': _("Settings")}]
		ifaces = iNetwork.getConfiguredAdapters()
		if len(ifaces):
			ip_list = iNetwork.getAdapterAttribute(ifaces[0], "ip")  # use only the first configured interface
			if ip_list:
				ip = "%d.%d.%d.%d" % (ip_list[0], ip_list[1], ip_list[2], ip_list[3])

				if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/LCD4linux/WebSite.pyo")):
					lcd4linux_key = "lcd4linux/config"
					if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/WebInterface/plugin.pyo")):
						try:
							lcd4linux_port = "http://" + ip + ":" + str(config.plugins.Webinterface.http.port.value) + "/"
							lcd4linux_key = lcd4linux_port + 'lcd4linux/config'
						except:  # noqa: E722
							lcd4linux_key = None
					if lcd4linux_key:
						extras.append({'key': lcd4linux_key, 'description': _("LCD4Linux Setup"), 'nw': '1'})

		oscamwebif, port, oscamconf, variant = self.oscamconfPath()

		# Assume http until we know better ...
		proto = "http"

		# config file exists
		if oscamwebif and oscamconf is not None:
			# oscam defaults to NOT to start the web interface unless a section for it exists, so reset port to None until we find one
			port = None
			data = open(oscamconf, "r").readlines()
			for i in data:
				if "httpport" in i.lower():
					port = i.split("=")[1].strip()
					if port[0] == '+':
						proto = "https"
						port = port[1:]

		if oscamwebif and port is not None:
			url = "%s://%s:%s" % (proto, request.getRequestHostname(), port)
			if variant == "oscam":
				extras.append({'key': url, 'description': _("OSCam Webinterface"), 'nw': '1'})
			elif variant == "ncam":
				extras.append({'key': url, 'description': _("NCam Webinterface"), 'nw': '1'})

		try:
			from Plugins.Extensions.AutoTimer.AutoTimer import AutoTimer  # noqa: F401
			extras.append({'key': 'ajax/at', 'description': _('AutoTimer')})
		except ImportError:
			pass

		if fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/OpenWebif/controllers/views/ajax/bqe.tmpl")) or fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/OpenWebif/controllers/views/ajax/bqe.pyo")):
			extras.append({'key': 'ajax/bqe', 'description': _('BouquetEditor')})

		try:
			from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh  # noqa: F401
			extras.append({'key': 'ajax/epgr', 'description': _('EPGRefresh')})
		except ImportError:
			pass

		try:
			# this will currenly only works if NO Webiterface plugin installed
			# TODO: test if webinterface AND openwebif installed
			from Plugins.Extensions.WebInterface.WebChilds.Toplevel import loaded_plugins
			for plugins in loaded_plugins:
				if plugins[0] in ["fancontrol", "iptvplayer", "serienrecorderui"]:
					try:
						extras.append({'key': plugins[0], 'description': plugins[2], 'nw': '2'})
					except KeyError:
						pass
		except ImportError:
			pass

		if os.path.exists('/usr/bin/shellinaboxd') and (fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/OpenWebif/controllers/views/ajax/terminal.tmpl")) or fileExists(resolveFilename(SCOPE_PLUGINS, "Extensions/OpenWebif/controllers/views/ajax/terminal.pyo"))):
			extras.append({'key': 'ajax/terminal', 'description': _('Terminal')})

		ret['extras'] = extras
		theme = 'original'
		if config.OpenWebif.webcache.theme.value:
			theme = config.OpenWebif.webcache.theme.value
		if not os.path.exists(getPublicPath('themes')):
			if not (theme == 'original' or theme == 'clear'):
				theme = 'original'
				config.OpenWebif.webcache.theme.value = theme
				config.OpenWebif.webcache.theme.save()
		ret['theme'] = theme

		moviedb = config.OpenWebif.webcache.moviedb.value if config.OpenWebif.webcache.moviedb.value else 'IMDb'
		config.OpenWebif.webcache.moviedb.value = moviedb
		config.OpenWebif.webcache.moviedb.save()
		ret['moviedb'] = moviedb
		imagedistro = getInfo()['imagedistro']
		ret['vti'] = imagedistro in ("vti") and 1 or 0
		ret['webtv'] = os.path.exists(getPublicPath('webtv'))
		return ret