Exemplo n.º 1
0
	def P_at(self, request):
		ret = {}
		ret['hasVPS'] = 0
		ret['hasSeriesPlugin'] = 0
		ret['test'] = 0
		ret['autoadjust'] = getInfo()['timerautoadjust']
		ret['searchTypes'] = {}

		try:
			from Plugins.Extensions.AutoTimer.AutoTimer import typeMap
			ret['searchTypes'] = typeMap
		except ImportError as e:
			pass
		if config.OpenWebif.autotimer_regex_searchtype.value:
			ret['searchTypes']['regex'] = 0

		loc = getLocations()
		ret['locations'] = loc['locations']

		try:
			from Plugins.SystemPlugins.vps import Vps  # noqa: F401
			ret['hasVPS'] = 1
		except ImportError as e:
			pass
		try:
			from Plugins.Extensions.SeriesPlugin.plugin import Plugins  # noqa: F401
			ret['hasSeriesPlugin'] = 1
		except ImportError as e:
			pass
		try:
			from Plugins.Extensions.AutoTimer.AutoTimerResource import AutoTimerTestResource  # noqa: F401
			ret['test'] = 1
		except ImportError as e:
			pass
		return ret
Exemplo n.º 2
0
    def P_at(self, request):
        ret = {}
        ret['hasVPS'] = 0
        ret['hasSeriesPlugin'] = 0
        ret['test'] = 0
        ret['autoadjust'] = getInfo()['timerautoadjust']

        try:
            from Plugins.Extensions.AutoTimer.AutoTimer import typeMap
            ret['types'] = typeMap
        except ImportError:
            pass
        loc = getLocations()
        ret['locations'] = loc['locations']

        try:
            from Plugins.SystemPlugins.vps import Vps  # noqa: F401
            ret['hasVPS'] = 1
        except ImportError:
            pass
        try:
            from Plugins.Extensions.SeriesPlugin.plugin import Plugins  # noqa: F401
            ret['hasSeriesPlugin'] = 1
        except ImportError:
            pass
        try:
            from Plugins.Extensions.AutoTimer.AutoTimerResource import AutoTimerTestResource  # noqa: F401
            ret['test'] = 1
        except ImportError:
            pass
        return ret
Exemplo n.º 3
0
	def P_boxinfo(self, request):
		info = getInfo(self.session, need_fullinfo=True)

		if fileExists(getPublicPath("/images/boxes/" + type + ".png")):
			info["boximage"] = type + ".png"
		elif fileExists(getPublicPath("/images/boxes/" + type + ".jpg")):
			info["boximage"] = type + ".jpg"
		else:
			info["boximage"] = "unknown.png"
		return info
Exemplo n.º 4
0
    def P_at(self, request):
        ret = {}
        ret['hasVPS'] = 1 if HASVPS else 0
        ret['hasSeriesPlugin'] = 1 if HASSERIES else 0
        ret['test'] = 1 if HASAUTOTIMERTEST else 0
        ret['hasChange'] = 1 if HASAUTOTIMERCHANGE else 0
        ret['autoadjust'] = getInfo()['timerautoadjust']
        ret['searchTypes'] = ATSEARCHTYPES

        if config.OpenWebif.autotimer_regex_searchtype.value:
            ret['searchTypes']['regex'] = 0

        loc = getLocations()
        ret['locations'] = loc['locations']
        ret['showiptvchannelsinselection'] = config.OpenWebif.webcache.showiptvchannelsinselection.value
        return ret
Exemplo n.º 5
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")}
    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")}
Exemplo n.º 6
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")}]

        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
Exemplo n.º 7
0
 def P_edittimer(self, request):
     pipzap = getInfo()['timerpipzap']
     autoadjust = getInfo()['timerautoadjust']
     return {"autoadjust": autoadjust, "pipzap": pipzap}
Exemplo n.º 8
0
										'iso-8859-1',
										'iso-8859-2',
										'iso-8859-3',
										'iso-8859-4',
										'iso-8859-5',
										'iso-8859-6',
										'iso-8859-7',
										'iso-8859-8',
										'iso-8859-9',
										'iso-8859-10',
										'iso-8859-16'])

from Plugins.Extensions.OpenWebif import vtiaddon
vtiaddon.expandConfig()

imagedistro = getInfo()['imagedistro']

class OpenWebifConfig(Screen, ConfigListScreen):
	skin = """
	<screen position="center,center" size="700,340" title="OpenWebif Configuration">
		<widget name="lab1" position="10,30" halign="center" size="680,60" zPosition="1" font="Regular;24" valign="top" transparent="1" />
		<widget name="config" position="10,100" size="680,180" scrollbarMode="showOnDemand" />
		<ePixmap position="140,290" size="140,40" pixmap="skin_default/buttons/red.png" alphatest="on" />
		<widget name="key_red" position="140,290" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" />
		<ePixmap position="420,290" size="140,40" pixmap="skin_default/buttons/green.png" alphatest="on" zPosition="1" />
		<widget name="key_green" position="420,290" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="green" transparent="1" />
	</screen>"""

	def __init__(self, session):
		self.skin = OpenWebifConfig.skin
		Screen.__init__(self, session)
Exemplo n.º 9
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
Exemplo n.º 10
0
def getStream(session, request, m3ufile):
	sRef = getUrlArg(request, "ref")
	if sRef != None:
		if PY3:
			sRef = unquote(unquote(sRef))
		else:
			sRef = unquote(unquote(request.args["ref"][0]).decode('utf-8', 'ignore')).encode('utf-8')
	else:
		sRef = ""

	currentServiceRef = None
	if m3ufile == "streamcurrent.m3u":
		currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		sRef = currentServiceRef.toString()

	if sRef.startswith("1:134:"):
		if currentServiceRef is None:
			currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		if currentServiceRef is None:
			currentServiceRef = eServiceReference()
		ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef)
		if ref is None:
			sRef = ""
		else:
			sRef = ref.toString()

	# #EXTINF:-1,%s\n adding back to show service name in programs like VLC
	progopt = ''
	name = getUrlArg(request, "name")
	if name != None:
		if config.OpenWebif.service_name_for_stream.value:
			progopt = "#EXTINF:-1,%s\n" % name

	name = "stream"
	portNumber = config.OpenWebif.streamport.value
	info = getInfo()
	model = info["model"]
	machinebuild = info["machinebuild"]
	urlparam = '?'
	if info["imagedistro"] in ('openpli', 'satdreamgr', 'openvision'):
		urlparam = '&'
	transcoder_port = None
	args = ""

	device = getUrlArg(request, "device")

	if fileExists("/dev/bcm_enc0"):
		try:
			transcoder_port = int(config.plugins.transcodingsetup.port.value)
		except Exception:
			# Transcoding Plugin is not installed or your STB does not support transcoding
			transcoder_port = None
		if device == "phone":
			portNumber = transcoder_port
		_port = getUrlArg(request, "port")
		if _port != None:
			portNumber = _port
	elif fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
		transcoder_port = portNumber

	if fileExists("/dev/bcm_enc0") or fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
		if device == "phone":
			try:
				bitrate = config.plugins.transcodingsetup.bitrate.value
				resolution = config.plugins.transcodingsetup.resolution.value
				(width, height) = tuple(resolution.split('x'))
				# framerate = config.plugins.transcodingsetup.framerate.value
				aspectratio = config.plugins.transcodingsetup.aspectratio.value
				interlaced = config.plugins.transcodingsetup.interlaced.value
				if fileExists("/proc/stb/encoder/0/vcodec"):
					vcodec = config.plugins.transcodingsetup.vcodec.value
					args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, vcodec, aspectratio, interlaced)
				else:
					args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, aspectratio, interlaced)
				args = args.replace('__', urlparam)
			except Exception:
				pass

	# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
	if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
		progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3], 16))

	if config.OpenWebif.auth_for_streaming.value:
		asession = GetSession()
		if asession.GetAuth(request) is not None:
			auth = ':'.join(asession.GetAuth(request)) + "@"
		else:
			auth = '-sid:' + str(asession.GetSID(request)) + "@"
	else:
		auth = ''

	response = "#EXTM3U \n#EXTVLCOPT:http-reconnect=true \n%shttp://%s%s:%s/%s%s\n" % (progopt, auth, request.getRequestHostname(), portNumber, sRef, args)
	if config.OpenWebif.playiptvdirect.value:
		if "http://" in sRef or "https://" in sRef:
			l = sRef.split(":http")[1]
			response = "#EXTM3U \n#EXTVLCOPT:http-reconnect=true\n%shttp%s\n" % (progopt, l)
	request.setHeader('Content-Type', 'application/x-mpegurl')
	# Note: do not rename the m3u file all the time
	fname = getUrlArg(request, "fname")
	if fname != None:
		request.setHeader('Content-Disposition', 'inline; filename=%s.%s;' % (fname, 'm3u8'))
	return response
Exemplo n.º 11
0
def getTS(self, request):
	file = getUrlArg(request, "file")
	if file != None:
		if PY3:
			filename = unquote(file)
		else:
			filename = unquote(file).decode('utf-8', 'ignore').encode('utf-8')
		if not os.path.exists(filename):
			return "File '%s' not found" % (filename)

# ServiceReference is not part of filename so look in the '.ts.meta' file
		sRef = ""
		progopt = ''

		if os.path.exists(filename + '.meta'):
			metafile = open(filename + '.meta', "r")
			name = ''
			seconds = -1  # unknown duration default
			line = metafile.readline()  # service ref
			if line:
				sRef = eServiceReference(line.strip()).toString()
			line2 = metafile.readline()  # name
			if line2:
				name = line2.strip()
			line6 = metafile.readline()  # description
			line6 = metafile.readline()  # recording time
			line6 = metafile.readline()  # tags
			line6 = metafile.readline()  # length

			if line6:
				seconds = float(line6.strip()) / 90000  # In seconds

			if config.OpenWebif.service_name_for_stream.value:
				progopt = "%s#EXTINF:%d,%s\n" % (progopt, seconds, name)

			metafile.close()

		portNumber = None
		proto = 'http'
		info = getInfo()
		model = info["model"]
		machinebuild = info["machinebuild"]
		transcoder_port = None
		args = ""
		urlparam = '?'
		if info["imagedistro"] in ('openpli', 'satdreamgr', 'openvision'):
			urlparam = '&'

		device = getUrlArg(request, "device")

		if fileExists("/dev/bcm_enc0") or fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
			try:
				transcoder_port = int(config.plugins.transcodingsetup.port.value)
			except Exception:
				# Transcoding Plugin is not installed or your STB does not support transcoding
				transcoder_port = None
			if device == "phone":
				portNumber = transcoder_port
			_port = getUrlArg(request, "port")
			if _port != None:
				portNumber = _port

		if fileExists("/dev/bcm_enc0") or fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
			if device == "phone":
				try:
					bitrate = config.plugins.transcodingsetup.bitrate.value
					resolution = config.plugins.transcodingsetup.resolution.value
					(width, height) = tuple(resolution.split('x'))
					# framerate = config.plugins.transcodingsetup.framerate.value
					aspectratio = config.plugins.transcodingsetup.aspectratio.value
					interlaced = config.plugins.transcodingsetup.interlaced.value
					if fileExists("/proc/stb/encoder/0/vcodec"):
						vcodec = config.plugins.transcodingsetup.vcodec.value
						args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, vcodec, aspectratio, interlaced)
					else:
						args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, aspectratio, interlaced)
					args = args.replace('__', urlparam)
				except Exception:
					pass
			# Add position parameter to m3u link
			position = getUrlArg(request, "position")
			if position != None:
				args = args + "&position=" + position

		# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
		if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
			progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3], 16))

		if portNumber is None:
			portNumber = config.OpenWebif.port.value
			if request.isSecure():
				portNumber = config.OpenWebif.https_port.value
				proto = 'https'
			ourhost = request.getHeader('host')
			m = re.match('.+\:(\d+)$', ourhost)
			if m is not None:
				portNumber = m.group(1)

		if config.OpenWebif.auth_for_streaming.value:
			asession = GetSession()
			if asession.GetAuth(request) is not None:
				auth = ':'.join(asession.GetAuth(request)) + "@"
			else:
				auth = '-sid:' + str(asession.GetSID(request)) + "@"
		else:
			auth = ''

		response = "#EXTM3U \n#EXTVLCOPT:http-reconnect=true \n%s%s://%s%s:%s/file?file=%s%s\n" % ((progopt, proto, auth, request.getRequestHostname(), portNumber, quote(filename), args))
		request.setHeader('Content-Type', 'application/x-mpegurl')
		return response
	else:
		return "Missing file parameter"
Exemplo n.º 12
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")}
    elif InfoBar.instance is not None and hasattr(InfoBar.instance,
                                                  'sleepTimer'):
        try:
            # TODO test OpenPLI and similar
            active = InfoBar.instance.sleepTimer.isActive()
            time = config.usage.sleep_timer.value
            info = getInfo()
            if info["imagedistro"] not in ('openpli', 'satdreamgr',
                                           'openvision'):
                action = config.usage.sleep_timer_action.value
                if action == "deepstandby":
                    action = "shutdown"
            else:
                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")}
Exemplo n.º 13
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")
			}
	elif InfoBar.instance is not None and hasattr(InfoBar.instance, 'sleepTimer'):
		try:
			# TODO test OpenPLI and similar
			info = getInfo()
			if info["imagedistro"] not in ('openpli', 'satdreamgr', 'openvision'):
				if action == "shutdown":
					config.usage.sleep_timer_action.value = "deepstandby"
				else:
					config.usage.sleep_timer_action.value = action
				config.usage.sleep_timer_action.save()
			active = enabled
			if enabled:
				InfoBar.instance.setSleepTimer(time * 60)
			else:
				InfoBar.instance.setSleepTimer(0)
				config.usage.sleep_timer.value = str(time * 60)
				config.usage.sleep_timer.save()
			return {
				"enabled": active,
				"minutes": time,
				"action": action,
				"message": _("Sleeptimer is enabled") if active else _("Sleeptimer is disabled")
			}
		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")
			}