def HttpdStart(session):
	"""
	Helper class to start web server

	Args:
		session: (?) session object
	"""
	if config.OpenWebif.enabled.value is True:
		global listener, site, sslsite
		port = config.OpenWebif.port.value
		if listener != None and len(listener) > 0:
			print("[OpenWebif] httpserver already started")
			return

		temproot = buildRootTree(session)
		root = AuthResource(session, temproot)
		site = server.Site(root)
		site.displayTracebacks = config.OpenWebif.displayTracebacks.value

		# start http webserver on configured port
		try:
			if has_ipv6 and fileExists('/proc/net/if_inet6') and version.major >= 12:
				# use ipv6
				listener.append(reactor.listenTCP(port, site, interface='::'))
			else:
				# ipv4 only
				listener.append(reactor.listenTCP(port, site))
			print("[OpenWebif] started on %i" % (port))
			BJregisterService('http', port)
		except CannotListenError:
			print("[OpenWebif] failed to listen on Port %i" % (port))

		if config.OpenWebif.https_clientcert.value is True and not os.path.exists(CA_FILE):
			# Disable https
			config.OpenWebif.https_enabled.value = False
			config.OpenWebif.https_enabled.save()
			# Inform the user
			session.open(MessageBox, "Cannot read CA certs for HTTPS access\nHTTPS access is disabled!", MessageBox.TYPE_ERROR)

		if config.OpenWebif.https_enabled.value is True:
			httpsPort = config.OpenWebif.https_port.value
			installCertificates(session)
			# start https webserver on port configured port
			try:
				try:
					key = crypto.load_privatekey(crypto.FILETYPE_PEM, open(KEY_FILE, 'rt').read())
					cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(CERT_FILE, 'rt').read())
					print("[OpenWebif] CHAIN_FILE = %s" % CHAIN_FILE)
					chain = None
					if os.path.exists(CHAIN_FILE):
						chain = [crypto.load_certificate(crypto.FILETYPE_PEM, open(CHAIN_FILE, 'rt').read())]
						print("[OpenWebif] ssl chain file found - loading")
					context = ssl.CertificateOptions(privateKey=key, certificate=cert, extraCertChain=chain)
				except:  # nosec # noqa: E722
					# THIS EXCEPTION IS ONLY CATCHED WHEN CERT FILES ARE BAD (look below for error)
					print("[OpenWebif] failed to get valid cert files. (It could occure bad file save or format, removing...)")
					# removing bad files
					if os.path.exists(KEY_FILE):
						os.remove(KEY_FILE)
					if os.path.exists(CERT_FILE):
						os.remove(CERT_FILE)
					# regenerate new ones
					installCertificates(session)
					context = ssl.DefaultOpenSSLContextFactory(KEY_FILE, CERT_FILE)

				if config.OpenWebif.https_clientcert.value is True:
					ctx = context.getContext()
					ctx.set_verify(
						SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
						verifyCallback
						)
					ctx.load_verify_locations(CA_FILE)

				sslroot = AuthResource(session, temproot)
				sslsite = server.Site(sslroot)

				if has_ipv6 and fileExists('/proc/net/if_inet6') and version.major >= 12:
					# use ipv6
					listener.append(reactor.listenSSL(httpsPort, sslsite, context, interface='::'))
				else:
					# ipv4 only
					listener.append(reactor.listenSSL(httpsPort, sslsite, context))
				print("[OpenWebif] started on", httpsPort)
				BJregisterService('https', httpsPort)
			except CannotListenError:
				print("[OpenWebif] failed to listen on Port", httpsPort)
			except:  # nosec # noqa: E722
				print("[OpenWebif] failed to start https, disabling...")
				# Disable https
				config.OpenWebif.https_enabled.value = False
				config.OpenWebif.https_enabled.save()

		# Streaming requires listening on 127.0.0.1:80
		if port != 80:
			try:
				if has_ipv6 and fileExists('/proc/net/if_inet6') and version.major >= 12:
					# use ipv6
					# Dear Twisted devs: Learning English, lesson 1 - interface != address
					listener.append(reactor.listenTCP(80, site, interface='::1'))
					listener.append(reactor.listenTCP(80, site, interface='::ffff:127.0.0.1'))
				else:
					# ipv4 only
					listener.append(reactor.listenTCP(80, site, interface='127.0.0.1'))
				print("[OpenWebif] started stream listening on port 80")
			except CannotListenError:
				print("[OpenWebif] port 80 busy")


Initialize an ordered dictionary . Signature is the same as for regular dictionaries but keyword arguments are not recommended because their insertion order is arbitrary .

def __init__(self, *args, **kwds):
		'''Initialize an ordered dictionary.  Signature is the same as for
		regular dictionaries, but keyword arguments are not recommended
		because their insertion order is arbitrary.
		'''
		if len(args) > 1:
			raise TypeError('expected at most 1 arguments, got %d' % len(args))
		try:
			self.__root
		except AttributeError:
			self.__root = root = []					 # sentinel node
			root[:] = [root, root, None]
			self.__map = {}
		self.__update(*args, **kwds)

def
__init__
(
self
,
*
args
,
*
*
kwds
)
:
if
len
(
args
)
>
1
:
raise
TypeError
(
'expected at most 1 arguments, got %d'
%
len
(
args
)
)
try
:
self
.
__root
except
AttributeError
:
self
.
__root
=
root
=
[
]
# sentinel node
root
[
:
]
=
[
root
,
root
,
]
self
.
__map
=
{
}
self
.
__update
(
*
args
,
*
*
kwds
)


od . __setitem__ ( i y ) < == > od [ i ] = y

def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
		'od.__setitem__(i, y) <==> od[i]=y'
		# Setting a new item creates a new link which goes at the end of the linked
		# list, and the inherited dictionary is updated with the new key/value pair.
		if key not in self:
			root = self.__root
			last = root[0]
			last[1] = root[0] = self.__map[key] = [last, root, key]
		dict_setitem(self, key, value)


od . __delitem__ ( y ) < == > del od [ y ]

def __delitem__(self, key, dict_delitem=dict.__delitem__):
		'od.__delitem__(y) <==> del od[y]'
		# Deleting an existing item uses self.__map to find the link which is
		# then removed by updating the links in the predecessor and successor nodes.
		dict_delitem(self, key)
		link_prev, link_next, key = self.__map.pop(key)
		link_prev[1] = link_next
		link_next[0] = link_prev


def __iter__(self):
		'od.__iter__() <==> iter(od)'
		root = self.__root
		curr = root[1]
		while curr is not root:
			yield curr[2]
			curr = curr[1]

def __iter__ ( self ) : root = self . __root curr = root [ 1 ] while curr is not root : yield curr [ 2 ] curr = curr [ 1 ]


od . __reversed__ () < == > reversed ( od )

def __reversed__(self):
		'od.__reversed__() <==> reversed(od)'
		root = self.__root
		curr = root[0]
		while curr is not root:
			yield curr[2]
			curr = curr[0]

def __reversed__ ( self ) : root = self . __root curr = root [ 0 ] while curr is not root : yield curr [ 2 ] curr = curr [ 0 ]


od . clear () - > None . Remove all items from od .

def clear(self):
		'od.clear() -> None.  Remove all items from od.'
		try:
			for node in self.__map.itervalues():
				del node[:]
			root = self.__root
			root[:] = [root, root, None]
			self.__map.clear()
		except AttributeError:
			pass
		dict.clear(self)

def clear ( self ) : try : for node in self . __map . itervalues ( ) : del node [ : ] root = self . __root root [ : ] = [ root , root , None ] self . __map . clear ( ) except AttributeError : pass dict . clear ( self )


od . popitem () - > ( k v ) return and remove a ( key value ) pair . Pairs are returned in LIFO order if last is true or FIFO order if false .

def popitem(self, last=True):
		'''od.popitem() -> (k, v), return and remove a (key, value) pair.
		Pairs are returned in LIFO order if last is true or FIFO order if false.
		'''
		if not self:
			raise KeyError('dictionary is empty')
		root = self.__root
		if last:
			link = root[0]
			link_prev = link[0]
			link_prev[1] = root
			root[0] = link_prev
		else:
			link = root[1]
			link_next = link[1]
			root[1] = link_next
			link_next[0] = root
		key = link[2]
		del self.__map[key]
		value = dict.pop(self, key)
		return key, value

def
popitem
(
self
,
last
=
True
)
:
if
not
self
:
raise
KeyError
(
'dictionary is empty'
)
root
=
self
.
__root
if
last
:
link
=
root
[
0
]
link_prev
=
link
[
0
]
link_prev
[
1
]
=
root
root
[
0
]
=
link_prev
else
:
link
=
root
[
1
]
link_next
=
link
[
1
]
root
[
1
]
=
link_next
link_next
[
0
]
=
root
key
=
link
[
2
]
del
self
.
__map
[
key
]
value
=
dict
.
pop
(
self
,
key
)
return
key
,
value


def keys(self):
		'od.keys() -> list of keys in od'
		return list(self)

def keys ( self ) : return list ( self )


def values(self):
		'od.values() -> list of values in od'
		return [self[key] for key in self]

def values ( self ) : return [ self [ key ] for key in self ]


od . items () - > list of ( key value ) pairs in od

def items(self):
		'od.items() -> list of (key, value) pairs in od'
		return [(key, self[key]) for key in self]

def items ( self ) : return [ ( key , self [ key ] ) for key in self ]


od . iterkeys () - > an iterator over the keys in od

def iterkeys(self):
		'od.iterkeys() -> an iterator over the keys in od'
		return iter(self)

def iterkeys ( self ) : return iter ( self )


od . itervalues - > an iterator over the values in od

def itervalues(self):
		'od.itervalues -> an iterator over the values in od'
		for k in self:
			yield self[k]

def itervalues ( self ) : for k in self : yield self [ k ]


od . iteritems - > an iterator over the ( key value ) items in od

def iteritems(self):
		'od.iteritems -> an iterator over the (key, value) items in od'
		for k in self:
			yield (k, self[k])

def iteritems ( self ) : for k in self : yield ( k , self [ k ] )


od . update ( E ** F ) - > None . Update od from dict / iterable E and F . If E is a dict instance does : for k in E : od [ k ] = E [ k ] If E has a . keys () method does : for k in E . keys () : od [ k ] = E [ k ] Or if E is an iterable of items does : for k v in E : od [ k ] = v In either case this is followed by : for k v in F . items () : od [ k ] = v

def update(*args, **kwds):
		'''od.update(E, **F) -> None.  Update od from dict/iterable E and F.
		If E is a dict instance, does:		   for k in E: od[k] = E[k]
		If E has a .keys() method, does:		 for k in E.keys(): od[k] = E[k]
		Or if E is an iterable of items, does:   for k, v in E: od[k] = v
		In either case, this is followed by:	 for k, v in F.items(): od[k] = v
		'''
		if len(args) > 2:
			raise TypeError('update() takes at most 2 positional '
							'arguments (%d given)' % (len(args),))
		elif not args:
			raise TypeError('update() takes at least 1 argument (0 given)')
		self = args[0]
		# Make progressively weaker assumptions about "other"
		other = ()
		if len(args) == 2:
			other = args[1]
		if isinstance(other, dict):
			for key in other:
				self[key] = other[key]
		elif hasattr(other, 'keys'):
			for key in other.keys():
				self[key] = other[key]
		else:
			for key, value in other:
				self[key] = value
		for key, value in kwds.items():
			self[key] = value


od . pop ( k [ d ] ) - > v remove specified key and return the corresponding value . If key is not found d is returned if given otherwise KeyError is raised .

def pop(self, key, default=__marker):
		'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
		If key is not found, d is returned if given, otherwise KeyError is raised.
		'''
		if key in self:
			result = self[key]
			del self[key]
			return result
		if default is self.__marker:
			raise KeyError(key)
		return default

def pop ( self , key , default = __marker ) : if key in self : result = self [ key ] del self [ key ] return result if default is self . __marker : raise KeyError ( key ) return default


od . setdefault ( k [ d ] ) - > od . get ( k d ) also set od [ k ] = d if k not in od

def setdefault(self, key, default=None):
		'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
		if key in self:
			return self[key]
		self[key] = default
		return default

def setdefault ( self , key , default = None ) : if key in self : return self [ key ] self [ key ] = default return default


def __repr__(self, _repr_running={}):
		'od.__repr__() <==> repr(od)'
		call_key = id(self), _get_ident()
		if call_key in _repr_running:
			return '...'
		_repr_running[call_key] = 1
		try:
			if not self:
				return '%s()' % (self.__class__.__name__,)
			return '%s(%r)' % (self.__class__.__name__, self.items())
		finally:
			del _repr_running[call_key]

def __repr__ ( self , _repr_running = { } ) : call_key = id ( self ) , _get_ident ( ) if call_key in _repr_running : return '...' _repr_running [ call_key ] = 1 try : if not self : return '%s()' % ( self . __class__ . __name__ , ) return '%s(%r)' % ( self . __class__ . __name__ , self . items ( ) ) finally : del _repr_running [ call_key ]


def __reduce__(self):
		'Return state information for pickling'
		items = [[k, self[k]] for k in self]
		inst_dict = vars(self).copy()
		for k in vars(OrderedDict()):
			inst_dict.pop(k, None)
		if inst_dict:
			return (self.__class__, (items,), inst_dict)
		return self.__class__, (items,)

def __reduce__ ( self ) : items = [ [ k , self [ k ] ] for k in self ] inst_dict = vars ( self ) . copy ( ) for k in vars ( OrderedDict ( ) ) : inst_dict . pop ( k , None ) if inst_dict : return ( self . __class__ , ( items , ) , inst_dict ) return self . __class__ , ( items , )


def copy(self):
		'od.copy() -> a shallow copy of od'
		return self.__class__(self)

def copy ( self ) : return self . __class__ ( self )


OD . fromkeys ( S [ v ] ) - > New ordered dictionary with keys from S and values equal to v ( which defaults to None ) .

def fromkeys(cls, iterable, value=None):
		'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
		and values equal to v (which defaults to None).
		'''
		d = cls()
		for key in iterable:
			d[key] = value
		return d

def fromkeys ( cls , iterable , value = None ) : d = cls ( ) for key in iterable : d [ key ] = value return d


od . __eq__ ( y ) < == > od == y . Comparison to another OD is order - sensitive while comparison to a regular mapping is order - insensitive .

def __eq__(self, other):
		'''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
		while comparison to a regular mapping is order-insensitive.
		'''
		if isinstance(other, OrderedDict):
			return len(self) == len(other) and self.items() == other.items()
		return dict.__eq__(self, other)

def __eq__ ( self , other ) : if isinstance ( other , OrderedDict ) : return len ( self ) == len ( other ) and self . items ( ) == other . items ( ) return dict . __eq__ ( self , other )


od . viewkeys () - > a set - like object providing a view on od s keys

def viewkeys(self):
		"od.viewkeys() -> a set-like object providing a view on od's keys"
		return KeysView(self)

def viewkeys ( self ) : return KeysView ( self )


od . viewvalues () - > an object providing a view on od s values

def viewvalues(self):
		"od.viewvalues() -> an object providing a view on od's values"
		return ValuesView(self)

def viewvalues ( self ) : return ValuesView ( self )


od . viewitems () - > a set - like object providing a view on od s items

def viewitems(self):
		"od.viewitems() -> a set-like object providing a view on od's items"
		return ItemsView(self)

def viewitems ( self ) : return ItemsView ( self )


Create a JSON representation for * data * and set HTTP headers indicating that JSON encoded data is returned .

def json_response(request, data, indent=1):
    """
    Create a JSON representation for *data* and set HTTP headers indicating
    that JSON encoded data is returned.

    Args:
        request (twisted.web.server.Request): HTTP request object
        data: response content
        indent: indentation level or None
    Returns:
        JSON representation of *data* with appropriate HTTP headers
    """
    request.setHeader("content-type", "application/json; charset=utf-8")
    return json.dumps(data, indent=indent)

def
json_response
(
request
,
data
,
indent
=
1
)
:
request
.
setHeader
(
"content-type"
,
"application/json; charset=utf-8"
)
return
json
.
dumps
(
data
,
indent
=
indent
)


Render response for an HTTP OPTIONS request .

def render_OPTIONS(self, request):
        """
        Render response for an HTTP OPTIONS request.

        Args:
            request (twisted.web.server.Request): HTTP request object
        Returns:
            HTTP response with headers
        """
        for key in self._cors_header:
            request.setHeader(key, self._cors_header[key])

        return ''

def render_OPTIONS ( self , request ) : for key in self . _cors_header : request . setHeader ( key , self . _cors_header [ key ] ) return ''


def render_GET(self, request):
        """
        HTTP GET implementation.

        Args:
            request (twisted.web.server.Request): HTTP request object
        Returns:
            HTTP response with headers
        """
        request.setHeader(
            'Access-Control-Allow-Origin', CORS_DEFAULT_ALLOW_ORIGIN)

        data = {
            "_controller": self.__class__.__name__,
            "request_postpath": request.postpath,
            "method": request.method,
            "request_path": request.path,
        }

        return json_response(request, data)

def render_GET ( self , request ) : request . setHeader ( 'Access-Control-Allow-Origin' , CORS_DEFAULT_ALLOW_ORIGIN ) data = { "_controller" : self . __class__ . __name__ , "request_postpath" : request . postpath , "method" : request . method , "request_path" : request . path , } return json_response ( request , data )


def render_POST(self, request):
        """
        HTTP POST implementation.

        Args:
            request (twisted.web.server.Request): HTTP request object
        Returns:
            HTTP response with headers
        """
        request.setHeader(
            'Access-Control-Allow-Origin', CORS_DEFAULT_ALLOW_ORIGIN)

        data = {
            "_controller": self.__class__.__name__,
            "request_postpath": request.postpath,
            "method": request.method,
            "request_path": request.path,
        }

        return json_response(request, data)

def render_POST ( self , request ) : request . setHeader ( 'Access-Control-Allow-Origin' , CORS_DEFAULT_ALLOW_ORIGIN ) data = { "_controller" : self . __class__ . __name__ , "request_postpath" : request . postpath , "method" : request . method , "request_path" : request . path , } return json_response ( request , data )


Request handler for the tsstart endpoint . Start timeshift ( ? ) .

def P_tsstart(self, request):
		"""
		Request handler for the `tsstart` endpoint.
		Start timeshift (?).

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		success = True
		try:
			InfoBar.instance.startTimeshift()
		except Exception:  # nosec # noqa: E722
			success = False
		return self.P_tstate(request, success)

def
P_tsstart
(
self
,
request
)
:
success
=
True
try
:
InfoBar
.
instance
.
startTimeshift
(
)
except
Exception
:
# nosec # noqa: E722
success
=
False
return
self
.
P_tstate
(
request
,
success
)


Request handler for the tsstop endpoint . Stop timeshift ( ? ) .

def P_tsstop(self, request):
		"""
		Request handler for the `tsstop` endpoint.
		Stop timeshift (?).

		.. note::

			Not available in *Enigma2 WebInterface API*.

		*TODO: improve after action / save , save+record , nothing
		config.timeshift.favoriteSaveAction ....*

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		success = True
		oldcheck = False
		try:
			if comp_config.usage.check_timeshift.value:
				oldcheck = comp_config.usage.check_timeshift.value
				# don't ask but also don't save
				comp_config.usage.check_timeshift.value = False
				comp_config.usage.check_timeshift.save()
			InfoBar.instance.stopTimeshift()
		except Exception:  # nosec # noqa: E722
			success = False
		if comp_config.usage.check_timeshift.value:
			comp_config.usage.check_timeshift.value = oldcheck
			comp_config.usage.check_timeshift.save()
		return self.P_tstate(request, success)

def
P_tsstop
(
self
,
request
)
:
success
=
True
oldcheck
=
False
try
:
if
comp_config
.
usage
.
check_timeshift
.
value
:
oldcheck
=
comp_config
.
usage
.
check_timeshift
.
value
# don't ask but also don't save
comp_config
.
usage
.
check_timeshift
.
value
=
False
comp_config
.
usage
.
check_timeshift
.
save
(
)
InfoBar
.
instance
.
stopTimeshift
(
)
except
Exception
:
# nosec # noqa: E722
success
=
False
if
comp_config
.
usage
.
check_timeshift
.
value
:
comp_config
.
usage
.
check_timeshift
.
value
=
oldcheck
comp_config
.
usage
.
check_timeshift
.
save
(
)
return
self
.
P_tstate
(
request
,
success
)


Request handler for the tsstate endpoint . Retrieve timeshift status ( ? ) .

def P_tsstate(self, request, success=True):
		"""
		Request handler for the `tsstate` endpoint.
		Retrieve timeshift status(?).

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return {
			"state": success,
			"timeshiftEnabled": InfoBar.instance.timeshiftEnabled()
		}

def P_tsstate ( self , request , success = True ) : return { "state" : success , "timeshiftEnabled" : InfoBar . instance . timeshiftEnabled ( ) }


Request handler for the about endpoint .

def P_about(self, request):
		"""
		Request handler for the `about` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#about

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return {
			"info": getInfo(self.session, need_fullinfo=True),
			"service": getCurrentService(self.session)
		}

def P_about ( self , request ) : return { "info" : getInfo ( self . session , need_fullinfo = True ) , "service" : getCurrentService ( self . session ) }


Request handler for the tunersignal endpoint . Get tuner signal status ( ? )

def P_tunersignal(self, request):
		"""
		Request handler for the `tunersignal` endpoint.
		Get tuner signal status(?)

		.. seealso::

			Probably https://dream.reichholf.net/e2web/#signal

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/signal
		"""
		return getFrontendStatus(self.session)

def P_tunersignal ( self , request ) : return getFrontendStatus ( self . session )


Request handler for the vol endpoint . Get / Set current volume setting .

def P_vol(self, request):
		"""
		Request handler for the `vol` endpoint.
		Get/Set current volume setting.

		.. seealso::

			https://dream.reichholf.net/e2web/#vol

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		set = getUrlArg(request, "set")
		if set == None or set == "state":
			return getVolumeStatus()
		elif set == "up":
			return setVolumeUp()
		elif set == "down":
			return setVolumeDown()
		elif set == "mute":
			return setVolumeMute()
		elif set[:3] == "set":
			try:
				return setVolume(int(set[3:]))
			except Exception:  # nosec # noqa: E722
				res = getVolumeStatus()
				res["result"] = False
				res["message"] = _("Wrong parameter format 'set=%s'. Use set=set15 ") % set
				return res

		res = getVolumeStatus()
		res["result"] = False
		res["message"] = _("Unknown Volume command %s") % set
		return res


Request handler for the / getaudiotracks endpoint .

def P_getaudiotracks(self, request):
		"""
		Request handler for the `/getaudiotracks` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#getaudiotracks

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getAudioTracks(self.session)

def P_getaudiotracks ( self , request ) : return getAudioTracks ( self . session )


Request handler for the / selectaudiotrack endpoint .

def P_selectaudiotrack(self, request):
		"""
		Request handler for the `/selectaudiotrack` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#selectaudiotrack

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/signal

			:query int id: audio track ID
		"""
		try:
			id = int(request.args[b"id"][0])
		except Exception:  # nosec # noqa: E722
			id = -1

		return setAudioTrack(self.session, id)

def
P_selectaudiotrack
(
self
,
request
)
:
try
:
id
=
int
(
request
.
args
[
b"id"
]
[
0
]
)
except
Exception
:
# nosec # noqa: E722
id
=
1
return
setAudioTrack
(
self
.
session
,
id
)


Request handler for the / zap endpoint . Zap to requested service_reference .

def P_zap(self, request):
		"""
		Request handler for the `/zap` endpoint.
		Zap to requested service_reference.

		.. seealso::

			https://dream.reichholf.net/e2web/#zap

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/zap

			:query string sRef: service reference
			:query string title: service title
		"""
		res = self.testMandatoryArguments(request, ["sRef"])
		if res:
			return res

		title = getUrlArg(request, "title", "")
		sRef = getUrlArg(request, "sRef")
		return zapService(self.session, sRef, title)

def P_zap ( self , request ) : res = self . testMandatoryArguments ( request , [ "sRef" ] ) if res : return res title = getUrlArg ( request , "title" , "" ) sRef = getUrlArg ( request , "sRef" ) return zapService ( self . session , sRef , title )


Request handler for the remotecontrol endpoint . Send remote control codes .

def P_remotecontrol(self, request):
		"""
		Request handler for the `remotecontrol` endpoint.
		Send remote control codes.

		.. seealso::

			https://dream.reichholf.net/e2web/#remotecontrol

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""

		text = getUrlArg(request, "text", "")
		if text:
			return remoteControl(0, "text", text)  # text input do not need type and command

		res = self.testMandatoryArguments(request, ["command"])
		if res:
			return res

		id = -1
		try:
			id = int(request.args[b"command"][0])
		except Exception:  # nosec # noqa: E722
			return {
				"result": False,
				"message": _("The parameter 'command' must be a number")
			}

		type = getUrlArg(request, "type", "")
		rcu = getUrlArg(request, "rcu", "")

		return remoteControl(id, type, rcu)


Request handler for the powerstate endpoint . Get / set power state of enigma2 device .

def P_powerstate(self, request):
		"""
		Request handler for the `powerstate` endpoint.
		Get/set power state of enigma2 device.

		.. seealso::

			https://dream.reichholf.net/e2web/#powerstate

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		if b"shift" in list(request.args.keys()):
			self.P_set_powerup_without_waking_tv(request)
		newstate = getUrlArg(request, "newstate")
		if newstate != None:
			return setPowerState(self.session, newstate)
		return getStandbyState(self.session)

def P_powerstate ( self , request ) : if b"shift" in list ( request . args . keys ( ) ) : self . P_set_powerup_without_waking_tv ( request ) newstate = getUrlArg ( request , "newstate" ) if newstate != None : return setPowerState ( self . session , newstate ) return getStandbyState ( self . session )


Request handler for the supports_powerup_without_waking_tv endpoint . Check if powerup without waking TV is available .

def P_supports_powerup_without_waking_tv(self, request):
		"""
		Request handler for the `supports_powerup_without_waking_tv` endpoint.
		Check if 'powerup without waking TV' is available.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		try:
			# returns 'True' if the image supports the function "Power on without TV":
			f = open("/tmp/powerup_without_waking_tv.txt", "r")  # nosec
			powerupWithoutWakingTv = f.read()
			f.close()
			if ((powerupWithoutWakingTv == 'True') or (powerupWithoutWakingTv == 'False')):
				return True
			else:
				return False
		except:  # nosec # noqa: E722
			return False


Request handler for the set_powerup_without_waking_tv endpoint . Mark powerup without waking TV being available .

def P_set_powerup_without_waking_tv(self, request):
		"""
		Request handler for the `set_powerup_without_waking_tv` endpoint.
		Mark 'powerup without waking TV' being available.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		if self.P_supports_powerup_without_waking_tv(request):
			try:
				# write "True" to file so that the box will power on ONCE skipping the HDMI-CEC communication:
				f = open("/tmp/powerup_without_waking_tv.txt", "w")  # nosec
				f.write('True')
				f.close()
				return True
			except:  # nosec # noqa: E722
				return False
		else:
			return False


Request handler for the getlocations endpoint . Retrieve paths where video files are stored .

def P_getlocations(self, request):
		"""
		Request handler for the `getlocations` endpoint.
		Retrieve paths where video files are stored.

		.. seealso::

			https://dream.reichholf.net/e2web/#getlocations

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getLocations()

def P_getlocations ( self , request ) : return getLocations ( )


Request handler for the getcurrlocation endpoint . Get currently selected path where video files are to be stored .

def P_getcurrlocation(self, request):
		"""
		Request handler for the `getcurrlocation` endpoint.
		Get currently selected path where video files are to be stored.

		.. seealso::

			https://dream.reichholf.net/e2web/#getcurrlocation

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getCurrentLocation()

def P_getcurrlocation ( self , request ) : return getCurrentLocation ( )


Request handler for the getallservices endpoint . Retrieve list of services in bouquets .

def P_getallservices(self, request):
		"""
		Request handler for the `getallservices` endpoint.
		Retrieve list of services in bouquets.

		.. seealso::

			https://dream.reichholf.net/e2web/#getallservices

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		type = "tv"
		if b"type" in list(request.args.keys()):
			type = "radio"
		noiptv = False
		if b"noiptv" in list(request.args.keys()):
			noiptv = True
		nolastscanned = False
		if b"nolastscanned" in list(request.args.keys()):
			nolastscanned = True
		bouquets = getAllServices(type, noiptv, nolastscanned)
		if b"renameserviceforxmbc" in list(request.args.keys()):
			for bouquet in bouquets["services"]:
				for service in bouquet["subservices"]:
					if not int(service["servicereference"].split(":")[1]) & 64:
						service["servicename"] = "%d - %s" % (service["pos"], service["servicename"])
			return bouquets
		return bouquets

def
P_getallservices
(
self
,
request
)
:
type
=
"tv"
if
b"type"
in
list
(
request
.
args
.
keys
(
)
)
:
type
=
"radio"
noiptv
=
False
if
b"noiptv"
in
list
(
request
.
args
.
keys
(
)
)
:
noiptv
=
True
nolastscanned
=
False
if
b"nolastscanned"
in
list
(
request
.
args
.
keys
(
)
)
:
nolastscanned
=
True
bouquets
=
getAllServices
(
type
,
noiptv
,
nolastscanned
)
if
b"renameserviceforxmbc"
in
list
(
request
.
args
.
keys
(
)
)
:
for
bouquet
in
bouquets
[
"services"
]
:
for
service
in
bouquet
[
"subservices"
]
:
if
not
int
(
service
[
"servicereference"
]
.
split
(
":"
)
[
1
]
)
&
64
:
service
[
"servicename"
]
=
"%d - %s"
%
(
service
[
"pos"
]
,
service
[
"servicename"
]
)
return
bouquets
return
bouquets


Request handler for the getservices endpoint . Retrieve list of bouquets .

def P_getservices(self, request):
		"""
		Request handler for the `getservices` endpoint.
		Retrieve list of bouquets.

		.. seealso::

			https://dream.reichholf.net/e2web/#getservices

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		sRef = getUrlArg(request, "sRef", "")
		hidden = getUrlArg(request, "hidden") == "1"
		provider = getUrlArg(request, "provider") == "1"
		picon = getUrlArg(request, "picon") == "1"
		return getServices(sRef=sRef, showAll=True, showHidden=hidden, provider=provider, picon=picon)

def P_getservices ( self , request ) : sRef = getUrlArg ( request , "sRef" , "" ) hidden = getUrlArg ( request , "hidden" ) == "1" provider = getUrlArg ( request , "provider" ) == "1" picon = getUrlArg ( request , "picon" ) == "1" return getServices ( sRef = sRef , showAll = True , showHidden = hidden , provider = provider , picon = picon )


Request handler for the servicesxspf endpoint . Retrieve list of bouquets ( ? ) in XSPF format .

def P_servicesxspf(self, request):
		"""
		Request handler for the `servicesxspf` endpoint.
		Retrieve list of bouquets(?) in XSPF format.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/services.xspf

			:query string bRef: bouquet reference
		"""
		bRef = getUrlArg(request, "bRef", "")
		request.setHeader('Content-Type', 'application/xspf+xml')
		bouquetName = getUrlArg(request, "bName")
		if bouquetName != None:
			bouquetName = bouquetName.replace(",", "_").replace(";", "_")
			request.setHeader('Content-Disposition', 'inline; filename=%s.%s;' % (bouquetName, 'xspf'))
		services = getServices(bRef, False)
		if comp_config.OpenWebif.auth_for_streaming.value:
			session = GetSession()
			if session.GetAuth(request) is not None:
				auth = ':'.join(session.GetAuth(request)) + "@"
			else:
				auth = '-sid:' + str(session.GetSID(request)) + "@"
		else:
			auth = ''
		portNumber = comp_config.OpenWebif.streamport.value
		services["host"] = "%s:%s" % (request.getRequestHostname(), portNumber)
		services["auth"] = auth
		services["bname"] = bouquetName
		return services

def
P_servicesxspf
(
self
,
request
)
:
bRef
=
getUrlArg
(
request
,
"bRef"
,
""
)
request
.
setHeader
(
'Content-Type'
,
'application/xspf+xml'
)
bouquetName
=
getUrlArg
(
request
,
"bName"
)
if
bouquetName
!=
:
bouquetName
=
bouquetName
.
replace
(
","
,
"_"
)
.
replace
(
";"
,
"_"
)
request
.
setHeader
(
'Content-Disposition'
,
'inline; filename=%s.%s;'
%
(
bouquetName
,
'xspf'
)
)
services
=
getServices
(
bRef
,
False
)
if
comp_config
.
OpenWebif
.
auth_for_streaming
.
value
:
session
=
GetSession
(
)
if
session
.
GetAuth
(
request
)
is
not
:
auth
=
':'
.
join
(
session
.
GetAuth
(
request
)
)
+
"@"
else
:
auth
=
'-sid:'
+
str
(
session
.
GetSID
(
request
)
)
+
"@"
else
:
auth
=
''
portNumber
=
comp_config
.
OpenWebif
.
streamport
.
value
services
[
"host"
]
=
"%s:%s"
%
(
request
.
getRequestHostname
(
)
,
portNumber
)
services
[
"auth"
]
=
auth
services
[
"bname"
]
=
bouquetName
return
services


Request handler for the servicesm3u endpoint . Retrieve list of bouquets ( ? ) in M3U format .

def P_servicesm3u(self, request):
		"""
		Request handler for the `servicesm3u` endpoint.
		Retrieve list of bouquets(?) in M3U format.

		.. seealso::

			https://dream.reichholf.net/e2web/#services.m3u

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/services.m3u

			:query string bRef: bouquet reference
		"""
		bRef = getUrlArg(request, "bRef", "")
		request.setHeader('Content-Type', 'application/x-mpegurl')
		bouquetName = getUrlArg(request, "bName")
		if bouquetName != None:
			bouquetName = bouquetName.replace(",", "_").replace(";", "_")
			request.setHeader('Content-Disposition', 'inline; filename=%s.%s;' % (bouquetName, 'm3u8'))
		services = getServices(bRef, False)
		if comp_config.OpenWebif.auth_for_streaming.value:
			session = GetSession()
			if session.GetAuth(request) is not None:
				auth = ':'.join(session.GetAuth(request)) + "@"
			else:
				auth = '-sid:' + str(session.GetSID(request)) + "@"
		else:
			auth = ''
		portNumber = comp_config.OpenWebif.streamport.value
		services["host"] = "%s:%s" % (request.getRequestHostname(), portNumber)
		services["auth"] = auth
		return services

def
P_servicesm3u
(
self
,
request
)
:
bRef
=
getUrlArg
(
request
,
"bRef"
,
""
)
request
.
setHeader
(
'Content-Type'
,
'application/x-mpegurl'
)
bouquetName
=
getUrlArg
(
request
,
"bName"
)
if
bouquetName
!=
:
bouquetName
=
bouquetName
.
replace
(
","
,
"_"
)
.
replace
(
";"
,
"_"
)
request
.
setHeader
(
'Content-Disposition'
,
'inline; filename=%s.%s;'
%
(
bouquetName
,
'm3u8'
)
)
services
=
getServices
(
bRef
,
False
)
if
comp_config
.
OpenWebif
.
auth_for_streaming
.
value
:
session
=
GetSession
(
)
if
session
.
GetAuth
(
request
)
is
not
:
auth
=
':'
.
join
(
session
.
GetAuth
(
request
)
)
+
"@"
else
:
auth
=
'-sid:'
+
str
(
session
.
GetSID
(
request
)
)
+
"@"
else
:
auth
=
''
portNumber
=
comp_config
.
OpenWebif
.
streamport
.
value
services
[
"host"
]
=
"%s:%s"
%
(
request
.
getRequestHostname
(
)
,
portNumber
)
services
[
"auth"
]
=
auth
return
services


Request handler for the subservices endpoint .

def P_subservices(self, request):
		"""
		Request handler for the `subservices` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#subservices

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getSubServices(self.session)

def P_subservices ( self , request ) : return getSubServices ( self . session )


Request handler for the parentcontrollist endpoint .

def P_parentcontrollist(self, request):
		"""
		Request handler for the `parentcontrollist` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#parentcontrollist

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getParentalControlList()

def P_parentcontrollist ( self , request ) : return getParentalControlList ( )


Request handler for the servicelistplayable endpoint . Retrieve list of playable bouquets .

def P_servicelistplayable(self, request):
		"""
		Request handler for the `servicelistplayable` endpoint.
		Retrieve list of 'playable' bouquets.

		.. seealso::

			https://dream.reichholf.net/e2web/#servicelistplayable

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		sRef = getUrlArg(request, "sRef", "")
		sRefPlaying = getUrlArg(request, "sRefPlaying", "")
		return getPlayableServices(sRef, sRefPlaying)

def P_servicelistplayable ( self , request ) : sRef = getUrlArg ( request , "sRef" , "" ) sRefPlaying = getUrlArg ( request , "sRefPlaying" , "" ) return getPlayableServices ( sRef , sRefPlaying )


Request handler for the serviceplayable endpoint . Check if referenced service is playable .

def P_serviceplayable(self, request):
		"""
		Request handler for the `serviceplayable` endpoint.
		Check if referenced service is 'playable'.

		.. seealso::

			https://dream.reichholf.net/e2web/#serviceplayable

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		sRef = getUrlArg(request, "sRef", "")
		sRefPlaying = getUrlArg(request, "sRefPlaying", "")
		return getPlayableService(sRef, sRefPlaying)

def P_serviceplayable ( self , request ) : sRef = getUrlArg ( request , "sRef" , "" ) sRefPlaying = getUrlArg ( request , "sRefPlaying" , "" ) return getPlayableService ( sRef , sRefPlaying )


Request handler for the addlocation endpoint . Add a path to the list of paths where video files are stored .

def P_addlocation(self, request):
		"""
		Request handler for the `addlocation` endpoint.
		Add a path to the list of paths where video files are stored.

		.. seealso::

			https://dream.reichholf.net/e2web/#addlocation

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["dirname"])
		if res:
			return res

		dirname = getUrlArg(request, "dirname")
		create = getUrlArg(request, "createFolder") == "1"
		return addLocation(dirname, create)

def P_addlocation ( self , request ) : res = self . testMandatoryArguments ( request , [ "dirname" ] ) if res : return res dirname = getUrlArg ( request , "dirname" ) create = getUrlArg ( request , "createFolder" ) == "1" return addLocation ( dirname , create )


Request handler for the removelocation endpoint . Remove a path from the list of paths where video files are stored .

def P_removelocation(self, request):
		"""
		Request handler for the `removelocation` endpoint.
		Remove a path from the list of paths where video files are stored.

		.. seealso::

			https://dream.reichholf.net/e2web/#removelocation

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["dirname"])
		if res:
			return res

		dirname = getUrlArg(request, "dirname")
		remove = getUrlArg(request, "removeFolder") == "1"
		return removeLocation(dirname, remove)

def P_removelocation ( self , request ) : res = self . testMandatoryArguments ( request , [ "dirname" ] ) if res : return res dirname = getUrlArg ( request , "dirname" ) remove = getUrlArg ( request , "removeFolder" ) == "1" return removeLocation ( dirname , remove )


Request handler for the message endpoint . Display a message on the screen attached to enigma2 device .

def P_message(self, request):
		"""
		Request handler for the `message` endpoint.
		Display a message on the screen attached to enigma2 device.

		.. seealso::

			https://dream.reichholf.net/e2web/#message

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["text", "type"])
		if res:
			return res

		try:
			ttype = int(request.args[b"type"][0])
		except ValueError:
			return {
				"result": False,
				"message": _("type %s is not a number") % request.args[b"type"][0]
			}

		timeout = -1
		if b"timeout" in list(request.args.keys()):
			try:
				timeout = int(request.args[b"timeout"][0])
			except ValueError:
				pass

		text = getUrlArg(request, "text")
		return sendMessage(self.session, text, ttype, timeout)

def
P_message
(
self
,
request
)
:
res
=
self
.
testMandatoryArguments
(
request
,
[
"text"
,
"type"
]
)
if
res
:
return
res
try
:
ttype
=
int
(
request
.
args
[
b"type"
]
[
0
]
)
except
ValueError
:
return
{
"result"
:
False
,
"message"
:
_
(
"type %s is not a number"
)
%
request
.
args
[
b"type"
]
[
0
]
}
timeout
=
1
if
b"timeout"
in
list
(
request
.
args
.
keys
(
)
)
:
try
:
timeout
=
int
(
request
.
args
[
b"timeout"
]
[
0
]
)
except
ValueError
:
pass
text
=
getUrlArg
(
request
,
"text"
)
return
sendMessage
(
self
.
session
,
text
,
ttype
,
timeout
)


Request handler for the messageanswer endpoint .

def P_messageanswer(self, request):
		"""
		Request handler for the `messageanswer` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#messageanswer

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getMessageAnswer()

def P_messageanswer ( self , request ) : return getMessageAnswer ( )


Request handler for the movielist endpoint . Retrieve list of movie items . ( alternative implementation )

def P_movielist(self, request):
		"""
		Request handler for the `movielist` endpoint.
		Retrieve list of movie items. (alternative implementation)

		.. seealso::

			https://dream.reichholf.net/e2web/#movielist

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getMovieList(request.args)

def P_movielist ( self , request ) : return getMovieList ( request . args )


Request handler for the movielisthtml endpoint . Retrieve list of movie items in HTML format .

def P_movielisthtml(self, request):
		"""
		Request handler for the `movielisthtml` endpoint.
		Retrieve list of movie items in HTML format.

		.. seealso::

			https://dream.reichholf.net/e2web/#movielist.html

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		request.setHeader("content-type", "text/html")
		return getMovieList(request.args)

def P_movielisthtml ( self , request ) : request . setHeader ( "content-type" , "text/html" ) return getMovieList ( request . args )


Request handler for the movielistm3u endpoint . Retrieve list of movie items in M3U format .

def P_movielistm3u(self, request):
		"""
		Request handler for the `movielistm3u` endpoint.
		Retrieve list of movie items in M3U format.

		.. seealso::

			https://dream.reichholf.net/e2web/#movielist.m3u

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		request.setHeader('Content-Type', 'application/x-mpegurl')
		movielist = getMovieList(request.args)
		movielist["host"] = "%s://%s:%s" % (whoami(request)['proto'], request.getRequestHostname(), whoami(request)['port'])
		return movielist

def P_movielistm3u ( self , request ) : request . setHeader ( 'Content-Type' , 'application/x-mpegurl' ) movielist = getMovieList ( request . args ) movielist [ "host" ] = "%s://%s:%s" % ( whoami ( request ) [ 'proto' ] , request . getRequestHostname ( ) , whoami ( request ) [ 'port' ] ) return movielist


Request handler for the movielistrss endpoint . Retrieve list of movie items in RSS format .

def P_movielistrss(self, request):
		"""
		Request handler for the `movielistrss` endpoint.
		Retrieve list of movie items in RSS format.

		.. seealso::
			https://dream.reichholf.net/e2web/#movielist.rss

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		movielist = getMovieList(request.args)
		movielist["host"] = "%s://%s:%s" % (whoami(request)['proto'], request.getRequestHostname(), whoami(request)['port'])
		return movielist

def P_movielistrss ( self , request ) : movielist = getMovieList ( request . args ) movielist [ "host" ] = "%s://%s:%s" % ( whoami ( request ) [ 'proto' ] , request . getRequestHostname ( ) , whoami ( request ) [ 'port' ] ) return movielist


Request handler for the moviedelete endpoint . Delete movie file .

def P_moviedelete(self, request):
		"""
		Request handler for the `moviedelete` endpoint.
		Delete movie file.

		.. seealso::
			https://dream.reichholf.net/e2web/#moviedelete

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["sRef"])
		if res:
			return res
		sRef = getUrlArg(request, "sRef")
		force = getUrlArg(request, "force") != None
		return removeMovie(self.session, sRef, force)

def P_moviedelete ( self , request ) : res = self . testMandatoryArguments ( request , [ "sRef" ] ) if res : return res sRef = getUrlArg ( request , "sRef" ) force = getUrlArg ( request , "force" ) != None return removeMovie ( self . session , sRef , force )


Request handler for the moviemove endpoint . Move movie file .

def P_moviemove(self, request):
		"""
		Request handler for the `moviemove` endpoint.
		Move movie file.

		.. seealso::
			https://dream.reichholf.net/e2web/#moviemove

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["sRef"])
		if res:
			return res
		res = self.testMandatoryArguments(request, ["dirname"])
		if res:
			return res

		sRef = getUrlArg(request, "sRef")
		dirname = getUrlArg(request, "dirname")
		return moveMovie(self.session, sRef, dirname)

def P_moviemove ( self , request ) : res = self . testMandatoryArguments ( request , [ "sRef" ] ) if res : return res res = self . testMandatoryArguments ( request , [ "dirname" ] ) if res : return res sRef = getUrlArg ( request , "sRef" ) dirname = getUrlArg ( request , "dirname" ) return moveMovie ( self . session , sRef , dirname )


Request handler for the movierename endpoint . Rename movie file .

def P_movierename(self, request):
		"""
		Request handler for the `movierename` endpoint.
		Rename movie file.

		.. seealso::
			https://dream.reichholf.net/e2web/#movierename

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["sRef"])
		if res:
			return res
		res = self.testMandatoryArguments(request, ["newname"])
		if res:
			return res
		sRef = getUrlArg(request, "sRef")
		newname = getUrlArg(request, "newname")
		return renameMovie(self.session, sRef, newname)

def P_movierename ( self , request ) : res = self . testMandatoryArguments ( request , [ "sRef" ] ) if res : return res res = self . testMandatoryArguments ( request , [ "newname" ] ) if res : return res sRef = getUrlArg ( request , "sRef" ) newname = getUrlArg ( request , "newname" ) return renameMovie ( self . session , sRef , newname )


Request handler for the movietags endpoint . Add / Remove tags to movie file .

def P_movietags(self, request):
		"""
		Request handler for the `movietags` endpoint.
		Add/Remove tags to movie file.

		.. seealso::
			https://dream.reichholf.net/e2web/#movietags

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		_add = getUrlArg(request, "add")
		_del = getUrlArg(request, "del")
		_sRef = getUrlArg(request, "sRef")
		if _sRef == None:
			_sRef = getUrlArg(request, "sref")
		return getMovieInfo(_sRef, _add, _del)

def P_movietags ( self , request ) : _add = getUrlArg ( request , "add" ) _del = getUrlArg ( request , "del" ) _sRef = getUrlArg ( request , "sRef" ) if _sRef == None : _sRef = getUrlArg ( request , "sref" ) return getMovieInfo ( _sRef , _add , _del )


Request handler for the movie endpoint . Add / Remove tags to movie file . Multiple tags needs to separate by Remame title of movie . Get / set movie cuts .

def P_movieinfo(self, request):
		"""
		Request handler for the `movie` endpoint.
		Add/Remove tags to movie file. Multiple tags needs to separate by ,
		Remame title of movie.
		Get/set movie cuts.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		_sRef = getUrlArg(request, "sRef")
		if _sRef == None:
			_sRef = getUrlArg(request, "sref")
		if _sRef != None:
			_addtag = getUrlArg(request, "addtag")
			_deltag = getUrlArg(request, "deltag")
			_title = getUrlArg(request, "title")
			_cuts = getUrlArg(request, "cuts")
			_desc = getUrlArg(request, "desc")
			return getMovieInfo(_sRef, _addtag, _deltag, _title, _cuts, _desc ,True)
		else:
			return getMovieInfo()

def P_movieinfo ( self , request ) : _sRef = getUrlArg ( request , "sRef" ) if _sRef == None : _sRef = getUrlArg ( request , "sref" ) if _sRef != None : _addtag = getUrlArg ( request , "addtag" ) _deltag = getUrlArg ( request , "deltag" ) _title = getUrlArg ( request , "title" ) _cuts = getUrlArg ( request , "cuts" ) _desc = getUrlArg ( request , "desc" ) return getMovieInfo ( _sRef , _addtag , _deltag , _title , _cuts , _desc , True ) else : return getMovieInfo ( )


Request handler for the movie endpoint .

def P_moviedetails(self, request):
		"""
		Request handler for the `movie` endpoint.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		_sRef = getUrlArg(request, "sRef")
		if _sRef == None:
			_sRef = getUrlArg(request, "sref")
		if _sRef != None:
			return getMovieDetails(_sRef)
		else:
			return {
				"result": False
			}

def P_moviedetails ( self , request ) : _sRef = getUrlArg ( request , "sRef" ) if _sRef == None : _sRef = getUrlArg ( request , "sref" ) if _sRef != None : return getMovieDetails ( _sRef ) else : return { "result" : False }


Request handler for the gettags endpoint . Get tags of movie file ( ? ) .

def P_gettags(self, request):
		"""
		Request handler for the `gettags` endpoint.
		Get tags of movie file (?).

		.. seealso::
			https://dream.reichholf.net/e2web/#gettags

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getMovieInfo()

def P_gettags ( self , request ) : return getMovieInfo ( )


def vpsparams(self, request):
		"""
		VPS related helper function(?)

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		vpsplugin_enabled = getUrlArg(request, "vpsplugin_enabled") == "1"
		vpsplugin_overwrite = getUrlArg(request, "vpsplugin_overwrite") == "1"
		vpsplugin_time = None
		if b"vpsplugin_time" in request.args:
			vpsplugin_time = int(float(request.args[b"vpsplugin_time"][0]))
			if vpsplugin_time == -1:
				vpsplugin_time = None
		# partnerbox:
		vps_pbox = getUrlArg(request, "vps_pbox")
		if vps_pbox != None:
			vpsplugin_enabled = None
			vpsplugin_overwrite = None
			if "yes_safe" in vps_pbox:
				vpsplugin_enabled = True
			elif "yes" in vps_pbox:
				vpsplugin_enabled = True
				vpsplugin_overwrite = True
		return {
			"vpsplugin_time": vpsplugin_time,
			"vpsplugin_overwrite": vpsplugin_overwrite,
			"vpsplugin_enabled": vpsplugin_enabled
		}

def
vpsparams
(
self
,
request
)
:
vpsplugin_enabled
=
getUrlArg
(
request
,
"vpsplugin_enabled"
)
==
"1"
vpsplugin_overwrite
=
getUrlArg
(
request
,
"vpsplugin_overwrite"
)
==
"1"
vpsplugin_time
=
if
b"vpsplugin_time"
in
request
.
args
:
vpsplugin_time
=
int
(
float
(
request
.
args
[
b"vpsplugin_time"
]
[
0
]
)
)
if
vpsplugin_time
==
1
:
vpsplugin_time
=
# partnerbox:
vps_pbox
=
getUrlArg
(
request
,
"vps_pbox"
)
if
vps_pbox
!=
:
vpsplugin_enabled
=
vpsplugin_overwrite
=
if
"yes_safe"
in
vps_pbox
:
vpsplugin_enabled
=
True
elif
"yes"
in
vps_pbox
:
vpsplugin_enabled
=
True
vpsplugin_overwrite
=
True
return
{
"vpsplugin_time"
:
vpsplugin_time
,
"vpsplugin_overwrite"
:
vpsplugin_overwrite
,
"vpsplugin_enabled"
:
vpsplugin_enabled
}


Request handler for the vpschannels endpoint .

def P_vpschannels(self, request):
		"""
		Request handler for the `vpschannels` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getVPSChannels(self.session)

def P_vpschannels ( self , request ) : return getVPSChannels ( self . session )


Request handler for the timerlist endpoint . Retrieve list of timers .

def P_timerlist(self, request):
		"""
		Request handler for the `timerlist` endpoint.
		Retrieve list of timers.

		.. seealso::

			https://dream.reichholf.net/e2web/#timerlist

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		ret = getTimers(self.session)
		ret["locations"] = comp_config.movielist.videodirs.value
		return ret

def P_timerlist ( self , request ) : ret = getTimers ( self . session ) ret [ "locations" ] = comp_config . movielist . videodirs . value return ret


Request handler for the timeradd endpoint . Add timer

def P_timeradd(self, request):
		"""
		Request handler for the `timeradd` endpoint.
		Add timer

		.. seealso::

			https://dream.reichholf.net/e2web/#timeradd

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["sRef", "begin", "end", "name"])
		if res:
			return res

		return self._AddEditTimer(request, 0)

def P_timeradd ( self , request ) : res = self . testMandatoryArguments ( request , [ "sRef" , "begin" , "end" , "name" ] ) if res : return res return self . _AddEditTimer ( request , 0 )


Request handler for the timeraddbyeventid endpoint . Add timer by event ID

def P_timeraddbyeventid(self, request):
		"""
		Request handler for the `timeraddbyeventid` endpoint.
		Add timer by event ID

		.. seealso::

			https://dream.reichholf.net/e2web/#timeraddbyeventid

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/timeraddbyeventid
			:query string sRef: service reference
			:query int eventid: Event ID
			:query int justplay: *Just Play* indicator
			:query string dirname: target path(?)
			:query string tags: tags to add(?)
			:query int always_zap: always zap first(?)
			:query int afterevent: afterevent state
		"""
		res = self.testMandatoryArguments(request, ["sRef", "eventid"])
		if res:
			return res

		return self._AddEditTimer(request, 1)

def P_timeraddbyeventid ( self , request ) : res = self . testMandatoryArguments ( request , [ "sRef" , "eventid" ] ) if res : return res return self . _AddEditTimer ( request , 1 )


Request handler for the timerchange endpoint . Change timer

def P_timerchange(self, request):
		"""
		Request handler for the `timerchange` endpoint.
		Change timer

		.. seealso::

			https://dream.reichholf.net/e2web/#timerchange

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/timerchange

			:query string sRef: service reference
			:query int begin: begin timestamp
			:query int end: end timestamp
			:query string name: name
			:query string description: description
			:query string channelOld: old channel(?)
			:query int beginOld: old begin timestamp(?)
			:query int endOld: old end timestamp(?)
			:query int justplay: *Just Play* indicator
			:query string dirname: target path(?)
			:query string tags: tags to add(?)
			:query int always_zap: always zap first(?)
			:query int disabled: disabled state
			:query int afterevent: afterevent state
		"""
		res = self.testMandatoryArguments(request, ["sRef", "begin", "end", "name", "channelOld", "beginOld", "endOld"])
		if res:
			return res

		return self._AddEditTimer(request, 2)

def P_timerchange ( self , request ) : res = self . testMandatoryArguments ( request , [ "sRef" , "begin" , "end" , "name" , "channelOld" , "beginOld" , "endOld" ] ) if res : return res return self . _AddEditTimer ( request , 2 )


Request handler for the timertogglestatus endpoint .

def P_timertogglestatus(self, request):
		"""
		Request handler for the `timertogglestatus` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["sRef", "begin", "end"])
		if res:
			return res
		try:
			begin = int(request.args[b"begin"][0])
		except Exception:  # nosec # noqa: E722
			return {
				"result": False,
				"message": "The parameter 'begin' must be a number"
			}

		try:
			end = int(request.args[b"end"][0])
		except Exception:  # nosec # noqa: E722
			return {
				"result": False,
				"message": "The parameter 'end' must be a number"
			}

		return toggleTimerStatus(self.session, getUrlArg(request, "sRef"), begin, end)


Request handler for the timerdelete endpoint . Delete timer

def P_timerdelete(self, request):
		"""
		Request handler for the `timerdelete` endpoint.
		Delete timer

		.. seealso::

			https://dream.reichholf.net/e2web/#timerdelete

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["sRef", "begin", "end"])
		if res:
			return res

		try:
			begin = int(request.args[b"begin"][0])
		except Exception:  # nosec # noqa: E722
			return {
				"result": False,
				"message": "The parameter 'begin' must be a number"
			}

		try:
			end = int(request.args[b"end"][0])
		except Exception:  # nosec # noqa: E722
			return {
				"result": False,
				"message": "The parameter 'end' must be a number"
			}

		try:
			eit = int(request.args[b"eit"][0])
		except Exception:  # nosec # noqa: E722
			eit = None

		return removeTimer(self.session, getUrlArg(request, "sRef"), begin, end, eit)


Request handler for the timercleanup endpoint .

def P_timercleanup(self, request):
		"""
		Request handler for the `timercleanup` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#timercleanup

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return cleanupTimer(self.session)

def P_timercleanup ( self , request ) : return cleanupTimer ( self . session )


Request handler for the timerlistwrite endpoint .

def P_timerlistwrite(self, request):
		"""
		Request handler for the `timerlistwrite` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#timerlistwrite

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return writeTimerList(self.session)

def P_timerlistwrite ( self , request ) : return writeTimerList ( self . session )


Request handler for the recordnow endpoint .

def P_recordnow(self, request):
		"""
		Request handler for the `recordnow` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#recordnow

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		infinite = False
		if b"undefinitely" in list(request.args.keys()) or b"infinite" in list(request.args.keys()):
			infinite = True
		return recordNow(self.session, infinite)

def P_recordnow ( self , request ) : infinite = False if b"undefinitely" in list ( request . args . keys ( ) ) or b"infinite" in list ( request . args . keys ( ) ) : infinite = True return recordNow ( self . session , infinite )


Request handler for the currenttime endpoint .

def P_currenttime(self, request):
		"""
		Request handler for the `currenttime` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#currenttime

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getCurrentTime()

def P_currenttime ( self , request ) : return getCurrentTime ( )


Request handler for the deviceinfo endpoint .

def P_deviceinfo(self, request):
		"""
		Request handler for the `deviceinfo` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#deviceinfo

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getInfo(session=self.session, need_fullinfo=True)

def P_deviceinfo ( self , request ) : return getInfo ( session = self . session , need_fullinfo = True )


Request handler for the epgmulti endpoint .

def P_epgmulti(self, request):
		"""
		Request handler for the `epgmulti` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["bRef"])
		if res:
			return res

		begintime = -1
		if b"time" in list(request.args.keys()):
			try:
				begintime = int(request.args[b"time"][0])
			except ValueError:
				pass

		endtime = None
		if b"endTime" in list(request.args.keys()):
			try:
				endtime = int(request.args[b"endTime"][0])
			except ValueError:
				pass
		return getBouquetEpg(getUrlArg(request, "bRef"), begintime, endtime, self.isJson)

def P_epgmulti ( self , request ) : res = self . testMandatoryArguments ( request , [ "bRef" ] ) if res : return res begintime = - 1 if b"time" in list ( request . args . keys ( ) ) : try : begintime = int ( request . args [ b"time" ] [ 0 ] ) except ValueError : pass endtime = None if b"endTime" in list ( request . args . keys ( ) ) : try : endtime = int ( request . args [ b"endTime" ] [ 0 ] ) except ValueError : pass return getBouquetEpg ( getUrlArg ( request , "bRef" ) , begintime , endtime , self . isJson )


Request handler for the epgxmltv endpoint .

def P_epgxmltv(self, request):
		"""
		Request handler for the `epgxmltv` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
			bRef: mandatory, method uses epgmulti
			lang: mandatory, needed for xmltv and Enigma2 has no parameter for epg language
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["bRef", "lang"])
		if res:
			return res
		ret = self.P_epgmulti(request)
		bRef = getUrlArg(request, "bRef")
		ret["services"] = getServices(bRef, True, False)["services"]
		ret["lang"] = getUrlArg(request, "lang")
		ret["offset"] = getUtcOffset()
		return ret

def P_epgxmltv ( self , request ) : res = self . testMandatoryArguments ( request , [ "bRef" , "lang" ] ) if res : return res ret = self . P_epgmulti ( request ) bRef = getUrlArg ( request , "bRef" ) ret [ "services" ] = getServices ( bRef , True , False ) [ "services" ] ret [ "lang" ] = getUrlArg ( request , "lang" ) ret [ "offset" ] = getUtcOffset ( ) return ret


def P_epgsearch(self, request):
		"""
		EPG event search and lookup handler.

		.. note::

			One may use
			:py:func:`controllers.events.EventsController.search` for
			searching events.

		.. seealso::

			https://dream.reichholf.net/e2web/#epgsearch

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		search = getUrlArg(request, "search")
		if search != None:
			endtime = None
			if b"endtime" in list(request.args.keys()):
				try:
					endtime = int(request.args[b"endtime"][0])
				except ValueError:
					pass
			fulldesc = False
			if b"full" in list(request.args.keys()):
				fulldesc = True
			return getSearchEpg(search, endtime, fulldesc, False, self.isJson)
		else:
			res = self.testMandatoryArguments(request, ["eventid"])
			if res:
				return res
			sRef = getUrlArg(request, "sRef")
			if sRef == None:
				sRef = getUrlArg(request, "sref")
			if sRef == None:
				return {
					"result": False,
					"message": _("The parameter '%s' can't be empty") % "sRef,sref"
				}
			item_id = 0
			try:
				item_id = int(request.args[b"eventid"][0])
			except ValueError:
				pass
			return getEvent(sRef, item_id, self.isJson)

def
P_epgsearch
(
self
,
request
)
:
search
=
getUrlArg
(
request
,
"search"
)
if
search
!=
:
endtime
=
if
b"endtime"
in
list
(
request
.
args
.
keys
(
)
)
:
try
:
endtime
=
int
(
request
.
args
[
b"endtime"
]
[
0
]
)
except
ValueError
:
pass
fulldesc
=
False
if
b"full"
in
list
(
request
.
args
.
keys
(
)
)
:
fulldesc
=
True
return
getSearchEpg
(
search
,
endtime
,
fulldesc
,
False
,
self
.
isJson
)
else
:
res
=
self
.
testMandatoryArguments
(
request
,
[
"eventid"
]
)
if
res
:
return
res
sRef
=
getUrlArg
(
request
,
"sRef"
)
if
sRef
==
:
sRef
=
getUrlArg
(
request
,
"sref"
)
if
sRef
==
:
return
{
"result"
:
False
,
"message"
:
_
(
"The parameter '%s' can't be empty"
)
%
"sRef,sref"
}
item_id
=
0
try
:
item_id
=
int
(
request
.
args
[
b"eventid"
]
[
0
]
)
except
ValueError
:
pass
return
getEvent
(
sRef
,
item_id
,
self
.
isJson
)


Request handler for the getcurrent endpoint .

def P_getcurrent(self, request):
		"""
		Request handler for the `getcurrent` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#getcurrent

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/getcurrent

		"""
		info = getCurrentService(self.session)
		now = getNowNextEpg(info["ref"], 0, self.isJson)
		if len(now["events"]) > 0:
			now = now["events"][0]
			now["provider"] = info["provider"]
		else:
			now = {
				"id": 0,
				"begin_timestamp": 0,
				"duration_sec": 0,
				"title": "",
				"shortdesc": "",
				"longdesc": "",
				"sref": "",
				"sname": "",
				"now_timestamp": 0,
				"remaining": 0,
				"provider": "",
				"genre": "",
				"genreid": 0
			}
		next = getNowNextEpg(info["ref"], 1, self.isJson)
		if len(next["events"]) > 0:
			next = next["events"][0]
			next["provider"] = info["provider"]
		else:
			next = {
				"id": 0,
				"begin_timestamp": 0,
				"duration_sec": 0,
				"title": "",
				"shortdesc": "",
				"longdesc": "",
				"sref": "",
				"sname": "",
				"now_timestamp": 0,
				"remaining": 0,
				"provider": "",
				"genre": "",
				"genreid": 0
			}
		# replace EPG NOW with Movie info
		mnow = now
		if mnow["sref"].startswith('1:0:0:0:0:0:0:0:0:0:/') or mnow["sref"].startswith('4097:0:0:0:0:0:0:0:0:0:/'):
			try:
				service = self.session.nav.getCurrentService()
				minfo = service and service.info()
				movie = minfo and minfo.getEvent(0)
				if movie and minfo:
					mnow["title"] = movie.getEventName()
					mnow["shortdesc"] = movie.getShortDescription()
					mnow["longdesc"] = movie.getExtendedDescription()
					mnow["begin_timestamp"] = movie.getBeginTime()
					mnow["duration_sec"] = movie.getDuration()
					mnow["remaining"] = movie.getDuration()
					mnow["id"] = movie.getEventId()
			except Exception:  # nosec # noqa: E722
				mnow = now
		elif mnow["sref"] == '':
			serviceref = self.session.nav.getCurrentlyPlayingServiceReference()
			if serviceref is not None:
				try:
					if serviceref.toString().startswith('4097:0:0:0:0:0:0:0:0:0:/'):
						from enigma import eServiceCenter
						serviceHandler = eServiceCenter.getInstance()
						sinfo = serviceHandler.info(serviceref)
						if sinfo:
							mnow["title"] = sinfo.getName(serviceref)
						servicepath = serviceref and serviceref.getPath()
						if servicepath and servicepath.startswith("/"):
							mnow["filename"] = servicepath
							mnow["sref"] = serviceref.toString()
				except Exception:  # nosec
					pass
		return {
			"info": info,
			"now": mnow,
			"next": next
		}

def
P_getcurrent
(
self
,
request
)
:
info
=
getCurrentService
(
self
.
session
)
now
=
getNowNextEpg
(
info
[
"ref"
]
,
0
,
self
.
isJson
)
if
len
(
now
[
"events"
]
)
>
0
:
now
=
now
[
"events"
]
[
0
]
now
[
"provider"
]
=
info
[
"provider"
]
else
:
now
=
{
"id"
:
0
,
"begin_timestamp"
:
0
,
"duration_sec"
:
0
,
"title"
:
""
,
"shortdesc"
:
""
,
"longdesc"
:
""
,
"sref"
:
""
,
"sname"
:
""
,
"now_timestamp"
:
0
,
"remaining"
:
0
,
"provider"
:
""
,
"genre"
:
""
,
"genreid"
:
0
}
next
=
getNowNextEpg
(
info
[
"ref"
]
,
1
,
self
.
isJson
)
if
len
(
next
[
"events"
]
)
>
0
:
next
=
next
[
"events"
]
[
0
]
next
[
"provider"
]
=
info
[
"provider"
]
else
:
next
=
{
"id"
:
0
,
"begin_timestamp"
:
0
,
"duration_sec"
:
0
,
"title"
:
""
,
"shortdesc"
:
""
,
"longdesc"
:
""
,
"sref"
:
""
,
"sname"
:
""
,
"now_timestamp"
:
0
,
"remaining"
:
0
,
"provider"
:
""
,
"genre"
:
""
,
"genreid"
:
0
}
# replace EPG NOW with Movie info
mnow
=
now
if
mnow
[
"sref"
]
.
startswith
(
'1:0:0:0:0:0:0:0:0:0:/'
)
or
mnow
[
"sref"
]
.
startswith
(
'4097:0:0:0:0:0:0:0:0:0:/'
)
:
try
:
service
=
self
.
session
.
nav
.
getCurrentService
(
)
minfo
=
service
and
service
.
info
(
)
movie
=
minfo
and
minfo
.
getEvent
(
0
)
if
movie
and
minfo
:
mnow
[
"title"
]
=
movie
.
getEventName
(
)
mnow
[
"shortdesc"
]
=
movie
.
getShortDescription
(
)
mnow
[
"longdesc"
]
=
movie
.
getExtendedDescription
(
)
mnow
[
"begin_timestamp"
]
=
movie
.
getBeginTime
(
)
mnow
[
"duration_sec"
]
=
movie
.
getDuration
(
)
mnow
[
"remaining"
]
=
movie
.
getDuration
(
)
mnow
[
"id"
]
=
movie
.
getEventId
(
)
except
Exception
:
# nosec # noqa: E722
mnow
=
now
elif
mnow
[
"sref"
]
==
''
:
serviceref
=
self
.
session
.
nav
.
getCurrentlyPlayingServiceReference
(
)
if
serviceref
is
not
:
try
:
if
serviceref
.
toString
(
)
.
startswith
(
'4097:0:0:0:0:0:0:0:0:0:/'
)
:
from
enigma
import
eServiceCenter
serviceHandler
=
eServiceCenter
.
getInstance
(
)
sinfo
=
serviceHandler
.
info
(
serviceref
)
if
sinfo
:
mnow
[
"title"
]
=
sinfo
.
getName
(
serviceref
)
servicepath
=
serviceref
and
serviceref
.
getPath
(
)
if
servicepath
and
servicepath
.
startswith
(
"/"
)
:
mnow
[
"filename"
]
=
servicepath
mnow
[
"sref"
]
=
serviceref
.
toString
(
)
except
Exception
:
# nosec
pass
return
{
"info"
:
info
,
"now"
:
mnow
,
"next"
:
next
}


Request handler for the getpid endpoint .

def P_getpid(self, request):
		"""
		Request handler for the `getpid` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#getpid

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		request.setHeader("content-type", "text/html")
		info = getCurrentService(self.session)
		return {
			"ppid": "%x" % info["pmtpid"],
			"vpid": "%x" % info["vpid"],
			"apid": "%x" % info["apid"],
			"host": request.getRequestHostname()
		}

def P_getpid ( self , request ) : request . setHeader ( "content-type" , "text/html" ) info = getCurrentService ( self . session ) return { "ppid" : "%x" % info [ "pmtpid" ] , "vpid" : "%x" % info [ "vpid" ] , "apid" : "%x" % info [ "apid" ] , "host" : request . getRequestHostname ( ) }


Request handler for the streamm3u endpoint .

def P_streamm3u(self, request):
		"""
		Request handler for the `streamm3u` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#stream.m3u

		.. note::

			Parameters Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/stream.m3u

			:query string ref: service reference
			:query string name: service name
		"""
		self.isCustom = True
		if comp_config.OpenWebif.webcache.zapstream.value:
			ref = getUrlArg(request, "ref")
			if ref != None:
				name = getUrlArg(request, "name", "")
				zapService(self.session, ref, name, stream=True)
		return getStream(self.session, request, "stream.m3u")

def P_streamm3u ( self , request ) : self . isCustom = True if comp_config . OpenWebif . webcache . zapstream . value : ref = getUrlArg ( request , "ref" ) if ref != None : name = getUrlArg ( request , "name" , "" ) zapService ( self . session , ref , name , stream = True ) return getStream ( self . session , request , "stream.m3u" )


Request handler for the tsm3u endpoint .

def P_tsm3u(self, request):
		"""
		Request handler for the `tsm3u` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#ts.m3u

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/ts.m3u

		"""
		self.isCustom = True
		return getTS(self.session, request)

def P_tsm3u ( self , request ) : self . isCustom = True return getTS ( self . session , request )


Request handler for the streamcurrentm3u endpoint .

def P_streamcurrentm3u(self, request):
		"""
		Request handler for the `streamcurrentm3u` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#streamcurrent.m3u

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/streamcurrent.m3u

		"""
		self.isCustom = True
		return getStream(self.session, request, "streamcurrent.m3u")

def P_streamcurrentm3u ( self , request ) : self . isCustom = True return getStream ( self . session , request , "streamcurrent.m3u" )


Request handler for the streamsubservices endpoint .

def P_streamsubservices(self, request):
		"""
		Request handler for the `streamsubservices` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#streamsubservices

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/streamsubservices

			:query string sRef: service reference
		"""
		return getStreamSubservices(self.session, request)

def P_streamsubservices ( self , request ) : return getStreamSubservices ( self . session , request )


Reload service lists transponders parental control black - / white lists or / and lamedb .

def P_servicelistreload(self, request):
		"""
		Reload service lists, transponders, parental control black-/white lists
		or/and lamedb.

		.. seealso::

			https://dream.reichholf.net/e2web/#servicelistreload

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		mode = getUrlArg(request, "mode")
		return reloadServicesLists(self.session, mode)

def P_servicelistreload ( self , request ) : mode = getUrlArg ( request , "mode" ) return reloadServicesLists ( self . session , mode )


Request handler for the tvbrowser endpoint .

def P_tvbrowser(self, request):
		"""
		Request handler for the `tvbrowser` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#tvbrowser

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return tvbrowser(self.session, request)

def P_tvbrowser ( self , request ) : return tvbrowser ( self . session , request )


Request handler for the saveconfig endpoint .

def P_saveconfig(self, request):
		"""
		Request handler for the `saveconfig` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:post:: /web/saveconfig

			:query string key: configuration key
			:query string value: configuration value
		"""
		if request.method == b'POST':
			res = self.testMandatoryArguments(request, ["key"])
			if res:
				return res
			value = getUrlArg(request, "value")
			if value != None:
				key = getUrlArg(request, "key")
				return saveConfig(key, value)
		return {"result": False}

def P_saveconfig ( self , request ) : if request . method == b'POST' : res = self . testMandatoryArguments ( request , [ "key" ] ) if res : return res value = getUrlArg ( request , "value" ) if value != None : key = getUrlArg ( request , "key" ) return saveConfig ( key , value ) return { "result" : False }


Request handler for the pluginlistread endpoint .

def P_pluginlistread(self, request):
		"""
		Request handler for the `pluginlistread` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#pluginlistread

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return reloadPlugins()

def P_pluginlistread ( self , request ) : return reloadPlugins ( )


Request handler for the restarttwisted endpoint .

def P_restarttwisted(self, request):
		"""
		Request handler for the `restarttwisted` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#restarttwisted

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		from Plugins.Extensions.OpenWebif.httpserver import HttpdRestart
		HttpdRestart(self.session)
		return ""

def P_restarttwisted ( self , request ) : from Plugins . Extensions . OpenWebif . httpserver import HttpdRestart HttpdRestart ( self . session ) return ""


Request handler for the sleeptimer endpoint .

def P_sleeptimer(self, request):
		"""
		Request handler for the `sleeptimer` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#sleeptimer

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers

		.. http:get:: /web/sleeptimer

			:query string cmd: command (*get* or *set*)
			:query int time: time in minutes (*0* -- *999*)
			:query string action: action (*standby* or *shutdown*)
			:query string enabled: enabled (*True* or *False*)
			:query string confirmed: confirmed (supported?)
		"""
		cmd = getUrlArg(request, "cmd", "get")
		if cmd == "get":
			return getSleepTimer(self.session)

		time = getUrlArg(request, "time")
		if time != None:
			try:
				time = int(time)
				if time > 999:
					time = 999
				elif time < 0:
					time = 0
			except ValueError:
				pass

		action = getUrlArg(request, "action", "standby")
		enabled = getUrlArg(request, "enabled")
		if enabled != None:
			if enabled == "True" or enabled == "true":
				enabled = True
			elif enabled == "False" or enabled == "false":
				enabled = False

		ret = getSleepTimer(self.session)

		if cmd != "set":
			ret["message"] = "ERROR: Obligatory parameter 'cmd' [get,set] has unspecified value '%s'" % cmd
			return ret

		if time is None and enabled is True:  # it's used only if the timer is enabled
			ret["message"] = "ERROR: Obligatory parameter 'time' [0-999] is missing"
			return ret

		if enabled is None:
			ret["message"] = "Obligatory parameter 'enabled' [True,False] is missing"
			return ret

		return setSleepTimer(self.session, time, action, enabled)


Request handler for the external endpoint .

def P_external(self, request):
		"""
		Request handler for the `external` endpoint.

		.. seealso::

			https://dream.reichholf.net/e2web/#external

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		try:
			from Plugins.Extensions.WebInterface.WebChilds.Toplevel import loaded_plugins
			result = []
			for p in loaded_plugins:
				result.append((p[0], '', p[2], p[3]))
			return {
				"plugins": result
			}
		except Exception:
			return {
				"plugins": []
			}

def P_external ( self , request ) : try : from Plugins . Extensions . WebInterface . WebChilds . Toplevel import loaded_plugins result = [ ] for p in loaded_plugins : result . append ( ( p [ 0 ] , '' , p [ 2 ] , p [ 3 ] ) ) return { "plugins" : result } except Exception : return { "plugins" : [ ] }


Request handler for the settings endpoint . Retrieve list of key / kalue pairs of device configuration .

def P_settings(self, request):
		"""
		Request handler for the `settings` endpoint.
		Retrieve list of key/kalue pairs of device configuration.

		.. seealso::

			https://dream.reichholf.net/e2web/#settings

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return getSettings()

def P_settings ( self , request ) : return getSettings ( )


Request handler for the boquets endpoint . Get list of tuples ( bouquet reference bouquet name ) for available bouquets .

def P_bouquets(self, request):
		"""
		Request handler for the `boquets` endpoint.
		Get list of tuples (bouquet reference, bouquet name) for available
		bouquets.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		stype = getUrlArg(request, "stype", "tv")
		return getBouquets(stype)

def P_bouquets ( self , request ) : stype = getUrlArg ( request , "stype" , "tv" ) return getBouquets ( stype )


Request handler for the saveepg endpoint .

def P_saveepg(self, request):
		"""
		Request handler for the `saveepg` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return saveEpg()

def P_saveepg ( self , request ) : return saveEpg ( )


Request handler for the loadepg endpoint .

def P_loadepg(self, request):
		"""
		Request handler for the `loadepg` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		return loadEpg()

def P_loadepg ( self , request ) : return loadEpg ( )


Request handler for the getsubtitles endpoint .

def P_getsubtitles(self, request):
		"""
		Request handler for the `getsubtitles` endpoint.

		.. note::

			Not available in *Enigma2 WebInterface API*.

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		service = self.session.nav.getCurrentService()
		ret = {"subtitlelist": [], "result": False}
		subtitle = service and service.subtitle()
		subtitlelist = subtitle and subtitle.getSubtitleList()
		if subtitlelist:
			for i in list(range(0, len(subtitlelist))):
				ret["result"] = True
				subt = subtitlelist[i]
				ret["subtitlelist"].append({
					"type": subt[0],
					"pid": subt[1],
					"page_nr": subt[2],
					"mag_nr": subt[3],
					"lang": subt[4]
				})
		return ret

def P_getsubtitles ( self , request ) : service = self . session . nav . getCurrentService ( ) ret = { "subtitlelist" : [ ] , "result" : False } subtitle = service and service . subtitle ( ) subtitlelist = subtitle and subtitle . getSubtitleList ( ) if subtitlelist : for i in list ( range ( 0 , len ( subtitlelist ) ) ) : ret [ "result" ] = True subt = subtitlelist [ i ] ret [ "subtitlelist" ] . append ( { "type" : subt [ 0 ] , "pid" : subt [ 1 ] , "page_nr" : subt [ 2 ] , "mag_nr" : subt [ 3 ] , "lang" : subt [ 4 ] } ) return ret


def P_getserviceref(self, request):
		"""
		Get the serviceref from name.

		.. http:get:: /api/getserviceref

			:query string name: service name to find
			:query string searchinBouquetsOnly: must be 'true'
			:query string bRef: define only one single bouquet where to find

		Args:
			request (twisted.web.server.Request): HTTP request object
		Returns:
			HTTP response with headers
		"""
		res = self.testMandatoryArguments(request, ["name"])
		if res:
			return res
		name = getUrlArg(request, "name")
		bRef = getUrlArg(request, "bRef")
		searchinBouquetsOnly = (getUrlArg(request, "searchinBouquetsOnly") == 'true')
		return getServiceRef(name, searchinBouquetsOnly, bRef)

def P_getserviceref ( self , request ) : res = self . testMandatoryArguments ( request , [ "name" ] ) if res : return res name = getUrlArg ( request , "name" ) bRef = getUrlArg ( request , "bRef" ) searchinBouquetsOnly = ( getUrlArg ( request , "searchinBouquetsOnly" ) == 'true' ) return getServiceRef ( name , searchinBouquetsOnly , bRef )


def NoDataRender(self):
		"""
		mobile requests with no extra data
		"""
		return ['index', 'control', 'screenshot', 'satfinder', 'about']

def NoDataRender ( self ) : return [ 'index' , 'control' , 'screenshot' , 'satfinder' , 'about' ]


def __init__(self, path="", **kwargs):
		"""

		Args:
			* path: Base path
			* session: (?) Session instance
			* withMainTemplate: (?)
			* isJson: responses shall be JSON encoded
			* isCustom: (?)
			* isGZ: responses shall be GZIP compressed
			* isMobile: (?) responses shall be optimised for mobile devices
			* isImage: (?) responses shall image
		"""
		resource.Resource.__init__(self)

		self.path = six.ensure_str(path)
		self.session = kwargs.get("session")
		self.withMainTemplate = kwargs.get("withMainTemplate", False)
		self.isJson = kwargs.get("isJson", False)
		self.isCustom = kwargs.get("isCustom", False)
		self.isGZ = kwargs.get("isGZ", False)
		self.isMobile = kwargs.get("isMobile", False)
		self.isImage = kwargs.get("isImage", False)

def __init__ ( self , path = "" , * * kwargs ) : resource . Resource . __init__ ( self ) self . path = six . ensure_str ( path ) self . session = kwargs . get ( "session" ) self . withMainTemplate = kwargs . get ( "withMainTemplate" , False ) self . isJson = kwargs . get ( "isJson" , False ) self . isCustom = kwargs . get ( "isCustom" , False ) self . isGZ = kwargs . get ( "isGZ" , False ) self . isMobile = kwargs . get ( "isMobile" , False ) self . isImage = kwargs . get ( "isImage" , False )


def error404(self, request):
		"""
		Perform HTTP Error 404

		Args:
			request (twisted.web.server.Request): HTTP request object

		"""
		request.setHeader("content-type", "text/html")
		request.setResponseCode(http.NOT_FOUND)
		request.write(b"<title>Open Webif</title>
Error 404: Page not found

The requested URL was not found on this server.")
		request.finish()


Decode an encoded string and convert it to an unicode string .

def lenient_decode(value, encoding=None):
	"""
	Decode an encoded string and convert it to an unicode string.

	Args:
		value: input value
		encoding: string encoding, defaults to utf-8
	Returns:
		(unicode) decoded value

	>>> lenient_decode("Hallo")
	u'Hallo'
	>>> lenient_decode(u"Hallo")
	u'Hallo'
	>>> lenient_decode("HällöÜ")
	u'H\\xe4ll\\xf6\\xdc'
	"""
	if isinstance(value, six.text_type):
		return value

	if encoding is None:
		encoding = 'utf_8'

	return value.decode(encoding, 'ignore')

def lenient_decode ( value , encoding = None ) : if isinstance ( value , six . text_type ) : return value if encoding is None : encoding = 'utf_8' return value . decode ( encoding , 'ignore' )


def lenient_force_utf_8(value):
	"""

	Args:
		value: input value
	Returns:
		(basestring) utf-8 encoded value

	>>> isinstance(lenient_force_utf_8(''), basestring)
	True
	>>> lenient_force_utf_8(u"Hallo")
	'Hallo'
	>>> lenient_force_utf_8("HällöÜ")
	'H\\xc3\\xa4ll\\xc3\\xb6\\xc3\\x9c'
	"""
	if isinstance(value, six.text_type):
		return value
	return lenient_decode(value).encode('utf_8')

def lenient_force_utf_8 ( value ) : if isinstance ( value , six . text_type ) : return value return lenient_decode ( value ) . encode ( 'utf_8' )


def sanitise_filename_slashes(value):
	"""

	Args:
		value: input value
	Returns:
		value w/o multiple slashes

	>>> in_value = "///tmp/x/y/z"
	>>> expected = re.sub("^/+", "/", "///tmp/x/y/z")
	>>> sanitise_filename_slashes(in_value) == expected
	True
	"""
	return re.sub(MANY_SLASHES_REGEX, '/', value)

def sanitise_filename_slashes ( value ) : return re . sub ( MANY_SLASHES_REGEX , '/' , value )


Determine attribute of * root_obj * to be accessed by * path * in a ( somewhat ) safe manner . This implementation will allow key and index based accessing too ( e . g . config . some_list [ 0 ] or config . some_dict [ some_key ] ) The * path * value needs to start with * head * ( default = config ) .

def get_config_attribute(path, root_obj, head=None):
	"""
	Determine attribute of *root_obj* to be accessed by *path* in a
	(somewhat) safe manner.
	This implementation will allow key and index based accessing too
	(e.g. ``config.some_list[0]`` or ``config.some_dict['some_key']``)
	The *path* value needs to start with *head* (default='config').

	Args:
		path: character string specifying which attribute is to be accessed
		root_obj: An object whose attributes are to be accessed.
		head: Value of the first portion of *path*

	Returns:
		Attribute of *root_obj*

	Raises:
		ValueError: If *path* is invalid.
		AttributeError: If attribute cannot be accessed
	"""
	if head is None:
		head = 'config'
	portions = path.split('.')

	if len(portions) < 2:
		raise ValueError('Invalid path length')

	if portions[0] != head:
		raise ValueError(
			'Head is {!r}, expected {!r}'.format(portions[0], head))

	current_obj = root_obj

	for attr_name in portions[1:]:
		if not attr_name:
			raise ValueError("empty attr_name")

		if attr_name.startswith('_'):
			raise ValueError('private member')

		matcher = REGEX_ITEM_OR_KEY_ACCESS.match(attr_name)

		if matcher:
			gdict = matcher.groupdict()
			attr_name = gdict.get('attr_name')
			next_obj = getattr(current_obj, attr_name)

			if gdict.get("index"):
				index = int(gdict.get("index"))
				current_obj = next_obj[index]
			else:
				key = gdict["key"]
				current_obj = next_obj[key]
		else:
			current_obj = getattr(current_obj, attr_name)

	return current_obj

def
get_config_attribute
(
path
,
root_obj
,
head
=
)
:
if
head
is
:
head
=
'config'
portions
=
path
.
split
(
'.'
)
if
len
(
portions
)
<
2
:
raise
ValueError
(
'Invalid path length'
)
if
portions
[
0
]
!=
head
:
raise
ValueError
(
'Head is {!r}, expected {!r}'
.
format
(
portions
[
0
]
,
head
)
)
current_obj
=
root_obj
for
attr_name
in
portions
[
1
:
]
:
if
not
attr_name
:
raise
ValueError
(
"empty attr_name"
)
if
attr_name
.
startswith
(
'_'
)
:
raise
ValueError
(
'private member'
)
matcher
=
REGEX_ITEM_OR_KEY_ACCESS
.
match
(
attr_name
)
if
matcher
:
gdict
=
matcher
.
groupdict
(
)
attr_name
=
gdict
.
get
(
'attr_name'
)
next_obj
=
getattr
(
current_obj
,
attr_name
)
if
gdict
.
get
(
"index"
)
:
index
=
int
(
gdict
.
get
(
"index"
)
)
current_obj
=
next_obj
[
index
]
else
:
key
=
gdict
[
"key"
]
current_obj
=
next_obj
[
key
]
else
:
current_obj
=
getattr
(
current_obj
,
attr_name
)
return
current_obj


Parse a Enigma2 style service reference string representation .

def parse_servicereference(serviceref):
	"""
	Parse a Enigma2 style service reference string representation.

	:param serviceref: Enigma2 style service reference
	:type serviceref: string

	>>> sref = '1:0:1:300:7:85:00c00000:0:0:0:'
	>>> result = parse_servicereference(sref)
	>>> result
	{'service_type': 1, 'oid': 133, 'tsid': 7, 'ns': 12582912, 'sid': 768}
	>>> sref_g = create_servicereference(**result)
	>>> sref_g
	'1:0:1:300:7:85:00c00000:0:0:0:'
	>>> sref_g2 = create_servicereference(result)
	>>> sref_g2
	'1:0:1:300:7:85:00c00000:0:0:0:'
	>>> sref == sref_g
	True
	>>> sref2 = '1:64:A:0:0:0:0:0:0:0::SKY Sport'
	>>> result2 = parse_servicereference(sref2)
	>>> result2
	{'service_type': 10, 'oid': 0, 'tsid': 0, 'ns': 0, 'sid': 0}
	>>> sref3 = '1:0:0:0:0:0:0:0:0:0:/media/hdd/movie/20170921 2055 - DASDING - DASDING Sprechstunde - .ts'
	>>> result3 = parse_servicereference(sref3)
	>>> result3
	{'service_type': 0, 'oid': 0, 'tsid': 0, 'ns': 0, 'sid': 0}
	"""
	parts = serviceref.split(":")
	sref_data = {
		'service_type': int(parts[2], 16),
		'sid': int(parts[3], 16),
		'tsid': int(parts[4], 16),
		'oid': int(parts[5], 16),
		'ns': int(parts[6], 16)
	}
	return sref_data

def parse_servicereference ( serviceref ) : parts = serviceref . split ( ":" ) sref_data = { 'service_type' : int ( parts [ 2 ] , 16 ) , 'sid' : int ( parts [ 3 ] , 16 ) , 'tsid' : int ( parts [ 4 ] , 16 ) , 'oid' : int ( parts [ 5 ] , 16 ) , 'ns' : int ( parts [ 6 ] , 16 ) } return sref_data


Generate a ( Enigma2 style ) service reference string representation .

def create_servicereference(*args, **kwargs):
	"""
	Generate a (Enigma2 style) service reference string representation.

	:param args[0]: Service Reference Parameter as dict
	:type args[0]: :class:`dict`

	:param service_type: Service Type
	:type service_type: int

	:param sid: SID
	:type sid: int

	:param tsid: TSID
	:type tsid: int

	:param oid: OID
	:type oid: int

	:param ns: Enigma2 Namespace
	:type ns: int
	"""
	if len(args) == 1 and isinstance(args[0], dict):
		kwargs = args[0]
	service_type = kwargs.get('service_type', 0)
	sid = kwargs.get('sid', 0)
	tsid = kwargs.get('tsid', 0)
	oid = kwargs.get('oid', 0)
	ns = kwargs.get('ns', 0)

	return '{:x}:0:{:x}:{:x}:{:x}:{:x}:{:08x}:0:0:0:'.format(
		1,
		service_type,
		sid,
		tsid,
		oid,
		ns)


def NoDataRender(self):
		"""
		ajax requests with no extra data
		"""
		return ['powerstate', 'message', 'myepg', 'radio', 'terminal', 'bqe', 'tv', 'satfinder']

def NoDataRender ( self ) : return [ 'powerstate' , 'message' , 'myepg' , 'radio' , 'terminal' , 'bqe' , 'tv' , 'satfinder' ]