예제 #1
0
 def __init__(self, *args, **kwargs):
     self.log = logging.getLogger(__name__)
     self.service_center_instance = enigma.eServiceCenter.getInstance()
     self.encoding = kwargs.get("encoding", "utf-8")
     self.rt = kwargs.get("rt")
     # OR MAYBE: ["timer_list", "processed_timers"] ?
     self.sources = kwargs.get("sources", ["timer_list"])
     self.egon = EventsController()
class EventLookupApiController(RESTControllerSkeleton):
    """
    RESTful Controller for ``/api/eventlookup`` endpoint
    """
    def __init__(self, *args, **kwargs):
        RESTControllerSkeleton.__init__(self, *args, **kwargs)
        self.ec_instance = EventsController()

    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 __init__(self, *args, **kwargs):
     RESTControllerSkeleton.__init__(self, *args, **kwargs)
     self.ec_instance = EventsController()
class EventSearchApiController(RESTControllerSkeleton):
    """
    RESTful Controller for ``/api/eventsearch`` endpoint
    """
    def __init__(self, *args, **kwargs):
        RESTControllerSkeleton.__init__(self, *args, **kwargs)
        self.ec_instance = EventsController()

    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 __init__(self, *args, **kwargs):
     TwoFaceApiController.__init__(self, *args, **kwargs)
     self.log = logging.getLogger(__name__)
     self.session = kwargs.get("session")
     self.ec = EventsController()
     self.mc = RecordingsController()
class RESTCurrentEventController(TwoFaceApiController):
    """
    RESTful Controller for ``/current_event`` endpoint.

    .. http:get:: /current_event

        :statuscode 200: no error
        :statuscode 503: no currently playing service

    .. http:get:: /current_event/{basestring:service_reference}/

        :statuscode 200: no error
        :statuscode 503: no data
    """
    def __init__(self, *args, **kwargs):
        TwoFaceApiController.__init__(self, *args, **kwargs)
        self.log = logging.getLogger(__name__)
        self.session = kwargs.get("session")
        self.ec = EventsController()
        self.mc = RecordingsController()

    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_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)

    def render_list_item(self, request, service_reference, item_id):
        """
        Currently not supported.

        Args:
            request (twisted.web.server.Request): HTTP request object
        Returns:
            HTTP response with headers
        """
        return self.error_response(request, response_code=http.NOT_FOUND)
예제 #7
0
class TimersController(object):
    """
    Timers controller
    """
    def __init__(self, *args, **kwargs):
        self.log = logging.getLogger(__name__)
        self.service_center_instance = enigma.eServiceCenter.getInstance()
        self.encoding = kwargs.get("encoding", "utf-8")
        self.rt = kwargs.get("rt")
        # OR MAYBE: ["timer_list", "processed_timers"] ?
        self.sources = kwargs.get("sources", ["timer_list"])
        self.egon = EventsController()

    def _valid_service_reference_or_bust(self, service_reference):
        if not service_reference:
            raise ValueError(
                "invalid service reference: {!r}".format(service_reference))
        sr_obj = eServiceReference(service_reference)
        if sr_obj.valid() != 1:
            raise ValueError(
                "invalid service reference: {!r}".format(service_reference))
        return sr_obj

    def remove(self, service_reference, item_id):
        # sr_obj = self._valid_service_reference_or_bust(service_reference)
        raise NotImplementedError

    def list_items(self, service_reference=None, item_id=None):
        """
        Generate a list of timers, either **all**,
        **timers for service** or **specific timer of service**.

        Args:
            service_reference (basestring): Service reference string
            item_id (int): Timer ID
        Returns:
            generator: matching :py:obj:`TimerDict` items
        """
        self.log.debug('%s',
                       "Trying to list timer in {!r}".format(self.sources))

        if service_reference:
            sr_obj = self._valid_service_reference_or_bust(service_reference)
            service_reference = sr_obj.toCompareString()

        current_sources = []
        for source in self.sources:
            current_sources += getattr(self.rt, source)

        do_all = service_reference is None and item_id is None
        do_single = service_reference is not None and item_id is not None

        self.log.debug("Listing items ... {!r} / {!r}".format(
            service_reference, item_id))
        self.log.debug("do all={!r} do_single={!r}".format(do_all, do_single))

        for timer_item in current_sources:
            timer_sref, timer_id = str(timer_item.service_ref), timer_item.eit
            e_data = None
            data = TimerDict(timer_item)

            if timer_sref and timer_id:
                e_data = self.egon.lookup_event(timer_sref, timer_id)

            if e_data:
                data['event'] = e_data

            if do_all:
                yield data
            elif do_single:
                if timer_sref == service_reference and timer_id == item_id:
                    self.log.debug("service_reference + item_id")
                    yield data
                    break
            elif service_reference and timer_sref == service_reference:
                self.log.debug("service_reference")
                yield data