Exemple #1
0
    def render_path_listing(self, request, root_path):
        """
        Generate a list of movie items available on current device.

        Args:
            request (twisted.web.server.Request): HTTP request object
            root_path (basestring): Movie item to remove
        Returns:
            HTTP response with headers
        """
        data = dict(result=True, items=[])
        removed_keys = (KEY_SERVICE_REFERENCE, 'flags', 'kind',)
        r_path = request.path

        if r_path.endswith('/'):
            r_path = r_path[:-1]

        for item in self.movie_controller.list_movies(root_path):
            for rkey in removed_keys:
                try:
                    del item[rkey]
                except KeyError:
                    pass

            data["items"].append(item)
            if item["path"].startswith(self.root):
                item["path"] = '/'.join(
                    (r_path, item["path"][len(self.root):]))

        add_expires_header(request, expires=60*30)
        return json_response(request, data)
Exemple #2
0
    def remove(self, request, target_path):
        """
        Remove movie file including meta data files.

        Args:
            request (twisted.web.server.Request): HTTP request object
            target_path (basestring): Movie item to remove
        Returns:
            HTTP response with headers
        """
        data = dict(files=[])
        e_ext_level1 = ('ts', 'eit',)
        e_ext_level2 = ('ap', 'cuts', 'meta', 'sc',)
        (trunk, _) = os.path.splitext(target_path)
        files_to_remove = []

        for ext1 in e_ext_level1:
            current = '.'.join((trunk, ext1))
            if os.path.isfile(current):
                files_to_remove.append(current)

        ext1 = e_ext_level1[0]
        for ext2 in e_ext_level2:
            current = '.'.join((trunk, ext1, ext2))
            if os.path.isfile(current):
                files_to_remove.append(current)

        for path in files_to_remove:
            try:
                os.unlink(path)
                data["files"].append(path)
            except Exception as exc:
                self.log.error(exc)

        return json_response(request, data)
    def render_list_subset(self, request, service_reference):
        """
        Return event data for specific service (if available).

        Args:
            request (twisted.web.server.Request): HTTP request object
            service_reference (basestring): Service reference string
        Returns:
            HTTP response with headers
        """
        items = self.ec.lookup(service_reference,
                               querytype=QUERYTYPE_LOOKUP__WHILE,
                               begin=QUERY_TIMESTAMP_CURRENT_TIME,
                               minutes=0)

        self._cache(request, expires=False)

        try:
            data = items[0]
            data['path'] = None
        except IndexError:
            data = dict(service_reference=service_reference)
            request.setResponseCode(http.SERVICE_UNAVAILABLE)

        return json_response(request, data)
Exemple #4
0
    def render_POST(self, request):
        """
        Execute python code defined by request parameter *uma*.

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

        .. http:post:: /api/evil

            :query string uma: python code snippet to be executed

        """
        request.setHeader('Access-Control-Allow-Origin',
                          CORS_DEFAULT_ALLOW_ORIGIN)

        uma = request.args['uma'][0]
        data = {"_controller": self.__class__.__name__, "uma": False}

        with stdout_ctx() as s:
            try:
                exec(uma)
                data['uma'] = True
            except Exception as exc:
                data['exception'] = repr(exc)
                request.setResponseCode(http.INTERNAL_SERVER_ERROR)
        data['stdout'] = s.getvalue()

        return json_response(request, data)
Exemple #5
0
    def render_GET(self, request):
        """
        HTTP GET implementation.

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

        .. http:get:: /services/

            :statuscode 200: no error
            :statuscode 500: error(s)

        .. http:get:: /services/tv

            :statuscode 200: no error
            :statuscode 500: error(s)

        .. http:get:: /services/radio

            :statuscode 200: no error
            :statuscode 500: error(s)

        .. http:get:: /services/(int:service_type)

            :statuscode 200: no error
            :statuscode 500: error(s)

        """
        request.setHeader('Access-Control-Allow-Origin',
                          CORS_DEFAULT_ALLOW_ORIGIN)

        data = {
            "errors": [],
            "len": 0,
            # "postpath": request.postpath
        }

        service_types = None

        if len(request.postpath) == 0 or request.postpath[0] == '':
            service_types = None
        elif len(request.postpath) == 1:
            service_types = request.postpath[0]

        try:
            data['items'] = list(
                self.sc_instance.get_services_set(service_types))
            data['result'] = True
            data['len'] = len(data['items'])
        except Exception as exc:
            data['errors'].append(repr(exc))
            request.setResponseCode(http.INTERNAL_SERVER_ERROR)

        add_expires_header(request, expires=14 * 24 * 3600)

        return json_response(request, data)
    def _index(self, request):
        """
        Return a swagger/JSON based description of the implemented interface.

        Args:
                request (twisted.web.server.Request): HTTP request object
        Returns:
                HTTP response with headers
        """
        with open(SWAGGER_TEMPLATE, "rb") as src:
            data = json.load(src)

        return json_response(request, data)
    def render_list_all(self, request):
        """
        List all timers

        Args:
            request (twisted.web.server.Request): HTTP request object
        Returns:
            HTTP response with headers
        """
        data = dict(result=True, items=[])

        for item in self.tc.list_items():
            data['items'].append(item)

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

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

        .. http:get:: /api/saveconfig
        """
        request.setHeader('Access-Control-Allow-Origin',
                          CORS_DEFAULT_ALLOW_ORIGIN)

        return json_response(request, {"result": False})
Exemple #9
0
    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,
            "request_header_host": request.getHeader("host"),
            "request_hostname": request.getRequestHostname(),
            "same_same": False,
        }
        fallback_port = "8010"
        try:
            data['whoami_result'] = whoami(request,
                                           fallback_port=fallback_port)
        except Exception as exc:
            data['whoami_result'] = 'FAIL: {!r}'.format(exc)

        try:
            data['mangle_host_header_port'] = mangle_host_header_port(
                request.getHeader("host"), fallback_port=fallback_port)
        except Exception as exc:
            data['mangle_host_header_port'] = 'FAIL: {!r}'.format(exc)

        data['monkey_host'] = new_getRequestHostname(request)

        try:
            a = data['whoami_result']
            b = data['mangle_host_header_port']
            keys = ('port', 'proto')
            data['same_same'] = True
            for key in keys:
                if a[key] != b[key]:
                    data['same_same'] = False
                    break
        except Exception:
            pass
        return json_response(request, data)
    def render_list_subset(self, request, service_reference):
        """
        List timers for specific service.

        Args:
            request (twisted.web.server.Request): HTTP request object
            service_reference (basestring): Service reference string
        Returns:
            HTTP response with headers
        """
        data = dict(result=True, items=[],
                    service_reference=service_reference)

        for item in self.tc.list_items(service_reference=service_reference):
            data['items'].append(item)

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

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

        .. http:post:: /api/saveconfig

            :query string key: configuration key
            :query string value: configuration value
        """
        request.setHeader('Access-Control-Allow-Origin',
                          CORS_DEFAULT_ALLOW_ORIGIN)

        return json_response(request, self.web_instance.P_saveconfig(request))
    def render_DELETE(self, request):
        """
        HTTP DELETE implementation for removing a timer.

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

        .. http:delete:: /timers/{basestring:service_reference}/{int:timer_id}/

            :statuscode 200: no error
            :statuscode 400: invalid
            :statuscode 404: not found
        """
        request.setHeader(
            'Access-Control-Allow-Origin', CORS_DEFAULT_ALLOW_ORIGIN)

        try:
            service_reference, item_id = self._mangle_args(request)
        except ValueError as vexc:
            item_id = None
            service_reference = None
            request.setResponseCode(http.BAD_REQUEST)
            self.log.error(vexc.message)

        try:
            self.tc.remove(service_reference, item_id)
        except ValueError as vexc:
            request.setResponseCode(http.BAD_REQUEST)
            self.log.error(vexc.message)

        data = {
            "result": False,
            "_controller": self.__class__.__name__,
            "request": {
                "postpath": request.postpath,
                "path": request.path,
                "args": request.args,
            }
        }

        return json_response(request, data)
    def render_list_all(self, request):
        """
        Return event data for currently playing service.

        Args:
            request (twisted.web.server.Request): HTTP request object
        Returns:
            HTTP response with headers
        """
        try:
            sr_obj = self.session.nav.getCurrentlyPlayingServiceReference()
            servicereference = sr_obj.toString()
            item = mangle_servicereference(servicereference)
            # self.log.debug("sr item: {!r}".format(item))
            # self.log.debug("sr obj: {!r}".format(sr_obj.toString()))

            if item.get("path"):
                raw_data = self.mc.mangle_servicereference_information(sr_obj)
                data = raw_data  # do something if no event data is available?

                if raw_data.get("event"):
                    data = raw_data.get("event")
                    data[KEY_SERVICE_REFERENCE] = raw_data['meta'].get(
                        "Serviceref")
                    data[KEY_SERVICE_NAME] = get_servicereference_name(
                        data[KEY_SERVICE_REFERENCE])
                else:
                    data = NoneEventDict(item.get("path").split('/')[-1])

                item.update(data)
                for key in ('kind', 'flags'):
                    try:
                        del item[key]
                    except KeyError:
                        pass

                return json_response(request, item)
            return self.render_list_subset(request, sr_obj.toString())
        except Exception as exc:
            self.log.error(exc)
            self._cache(request, expires=False)
            return self.error_response(request,
                                       response_code=http.SERVICE_UNAVAILABLE)
    def render_list_item(self, request, service_reference, item_id):
        """
        List timer data for specific timer of service.

        Args:
            request (twisted.web.server.Request): HTTP request object
            service_reference (basestring): Service reference string
            item_id (int): Timer ID
        Returns:
            HTTP response with headers
        """
        data = dict(result=True, items=[],
                    service_reference=service_reference,
                    item_id=item_id)

        for item in self.tc.list_items(service_reference=service_reference,
                                       item_id=item_id):
            data['items'].append(item)

        if not data['items']:
            request.setResponseCode(http.NOT_FOUND)

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

        .. seealso::

            * *querytype* Parameter – :ref:`event_search_parameters-label`
            * *flags* Parameter – :ref:`event_format-label`

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

        .. http:get:: /api/eventsearch

            :query basestring what: search term
            :query int querytype: (optional) query type
            :query basestring flags: (optional) fields to be returned
            :query int max_rows: (optional) maximum number of result rows

            :statuscode 200: no error
        """
        request.setHeader('Access-Control-Allow-Origin',
                          CORS_DEFAULT_ALLOW_ORIGIN)

        mangled_parameters = dict(case_sensitive=False, flags=None, what=None)

        if "flags" in request.args:
            mangled_parameters["flags"] = request.args["flags"][0]

        for key in ("querytype", "max_rows"):
            try:
                value = int(request.args[key][0])
            except Exception:
                value = None
            mangled_parameters[key] = value

        if request.args.get("case_sensitive", [False])[0]:
            mangled_parameters["case_sensitive"] = True

        data = {
            "errors": [],
            "result": False,
            "mangled_parameters": mangled_parameters,
            "len": 0
        }

        try:
            mangled_parameters["what"] = request.args["what"][0]
        except KeyError:
            data['errors'].append("Nothing to search for?!")
        except Exception as exc1:
            data['errors'].append(repr(exc1))

        if mangled_parameters["what"]:
            try:
                data['events'] = self.ec_instance.search(**mangled_parameters)
                data['result'] = True
                data['len'] = len(data['events'])
            except Exception as exc:
                data['errors'].append(repr(exc))

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

        .. seealso::

            * *querytype* Parameter – :ref:`event_lookup_parameters-label`
            * *flags* Parameter – :ref:`event_format-label`

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

        .. http:get:: /api/eventlookup

            :query basestring service_reference: service_reference
            :query int begin: (optional) timestamp
            :query int minutes: (optional) time range in minutes or event ID
            :query int querytype: (optional) query type
            :query basestring flags: (optional) fields to be returned
            :query int max_rows: (optional) maximum number of result rows

            :statuscode 200: no error

        """
        request.setHeader('Access-Control-Allow-Origin',
                          CORS_DEFAULT_ALLOW_ORIGIN)

        mangled_parameters = dict(
            flags=None,
            service_reference=None  # '1:0:19:7C:6:85:FFFF0000:0:0:0:'
        )

        for key in ("flags", "service_reference"):
            if key in request.args:
                mangled_parameters[key] = request.args[key][0]

        for key in ("querytype", "max_rows", "begin", "minutes"):
            try:
                value = int(request.args[key][0])
            except (KeyError, TypeError, ValueError):
                value = None
            mangled_parameters[key] = value

        data = {
            "errors": [],
            "result": False,
            "mangled_parameters": mangled_parameters,
            "len": 0
        }

        if mangled_parameters["service_reference"]:
            try:
                data['events'] = self.ec_instance.lookup(**mangled_parameters)
                data['result'] = True
                data['len'] = len(data['events'])
            except Exception as exc:
                data['errors'].append(repr(exc))

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

        Args:
                request (twisted.web.server.Request): HTTP request object
        Returns:
                HTTP response with headers
        """
        rq_path = urlparse.unquote(request.path)

        if not rq_path.startswith(self._resource_prefix):
            raise ValueError("Invalid Request Path {!r}".format(request.path))

        request.setHeader(
            'Access-Control-Allow-Origin', CORS_DEFAULT_ALLOW_ORIGIN)

        # as implemented in BaseController -----------------v
        func_path = rq_path[len(self._resource_prefix) + 1:].replace(".", "")

        if func_path in ("", "index"):
            return self._index(request)

        if func_path == 'reverse_proxy_conf':
            return self._reverse_proxy_configuration(request)

        #: name of OpenWebif method to be called
        owif_func = "{:s}{:s}".format(OWIF_PREFIX, func_path)

        #: callable methods
        funcs = [
            # TODO: add method of *self*
            ('web', getattr(self.web_instance, owif_func, None)),
        ]

        if self.ajax_instance is not None:
            funcs.append(
                ('ajax', getattr(self.ajax_instance, owif_func, None)))

        #: method to be called
        func = None
        #: nickname for controller instance
        source_controller = None

        # query controller instances for given method - first match wins
        for candidate_controller, candidate in funcs:
            if callable(candidate):
                func = candidate
                source_controller = candidate_controller
                break

        if func is None:
            request.setResponseCode(http.NOT_FOUND)
            data = {
                "method": repr(func_path),
                "result": False,
            }

            if self.verbose:
                data["request"] = {
                    "path": request.path,
                    "postpath": request.postpath,
                    "mangled_host_header": mangle_host_header_port(
                        request.getHeader('host')),
                    "host_header": request.getHeader('host')
                }

            return json_response(request, data)

        try:
            request.setResponseCode(http.OK)
            data = func(request)
            data['_controller'] = source_controller
            try:
                if "result" not in data:
                    data["result"] = True
            except Exception:
                # ignoring exceptions is bad.
                pass

            return json_response(data=data, request=request)
        except Exception as exc:
            request.setResponseCode(http.INTERNAL_SERVER_ERROR)
            data = {
                "exception": repr(exc),
                "result": False,
                "path": request.path,
            }

            return json_response(request, data)