Example #1
0
    def process_child(self, ch, name, request):
        self.debug(f'process_child: {name} [child: {ch}, request: {request}]')
        if ch is not None:
            self.info(f'Child found {ch}')
            if request.method == b'GET' or request.method == b'HEAD':
                headers = request.getAllHeaders()
                if b'content-length' in headers:
                    self.warning(
                        f'{request.method} request with content-length ' +
                        f'{headers[b"content-length"]} header - sanitizing')
                    # Fix missing headers for some Samsung TVs (see issue #20)
                    try:
                        del request.received_headers[b'content-length']
                    except AttributeError:
                        request.received_headers = headers
                        del request.received_headers[b'content-length']
                self.debug('data')
                if len(request.content.getvalue()) > 0:
                    # shall we remove that?
                    # can we remove that?
                    self.warning(f'{request.method} request with ' +
                                 f'{len(request.content.getvalue())} ' +
                                 f'bytes of message-body - sanitizing')
                    request.content = StringIO()

            if hasattr(ch, 'location'):
                self.debug(f'we have a location ' +
                           f'{isinstance(ch.location, resource.Resource)}')
                if isinstance(ch.location, ReverseProxyResource) or isinstance(
                        ch.location, resource.Resource):
                    # self.info(f'getChild proxy {name} to {ch.location.uri}')
                    self.prepare_connection(request)
                    self.prepare_headers(ch, request)
                    return ch.location
            try:
                p = ch.get_path()
            except TypeError:
                return self.list_content(name, ch, request)
            except Exception as msg:
                self.debug(f'error accessing items path {msg}')
                self.debug(traceback.format_exc())
                return self.list_content(name, ch, request)
            if p is not None and os.path.exists(p):
                self.info(f'accessing path {p}')
                self.prepare_connection(request)
                self.prepare_headers(ch, request)
                ch = StaticFile(p)
            else:
                self.debug(f'accessing path {p} failed')
                return self.list_content(name, ch, request)

        if ch is None:
            p = util.sibpath(__file__.encode('ascii'), name)
            self.debug(f'checking if msroot is file: {p}')
            if os.path.exists(p):
                ch = StaticFile(p)
        self.info(f'MSRoot ch {ch}')
        return ch
Example #2
0
    def process_child(self, ch, name, request):
        if ch is not None:
            self.info('Child found %s', ch)
            if (request.method == 'GET' or request.method == 'HEAD'):
                headers = request.getAllHeaders()
                if 'content-length' in headers:
                    self.warning(
                        '%s request with content-length %s header - sanitizing',
                        request.method, headers['content-length'])
                    del request.received_headers['content-length']
                self.debug('data', )
                if len(request.content.getvalue()) > 0:
                    """ shall we remove that?
                        can we remove that?
                    """
                    self.warning(
                        '%s request with %d bytes of message-body - sanitizing',
                        request.method, len(request.content.getvalue()))
                    request.content = StringIO()

            if hasattr(ch, "location"):
                self.debug("we have a location %s",
                           isinstance(ch.location, resource.Resource))
                if (isinstance(ch.location, ReverseProxyResource)
                        or isinstance(ch.location, resource.Resource)):
                    #self.info('getChild proxy %s to %s' % (name, ch.location.uri))
                    self.prepare_connection(request)
                    self.prepare_headers(ch, request)
                    return ch.location
            try:
                p = ch.get_path()
            except TypeError:
                return self.list_content(name, ch, request)
            except Exception as msg:
                self.debug("error accessing items path %r", msg)
                self.debug(traceback.format_exc())
                return self.list_content(name, ch, request)
            if p != None and os.path.exists(p):
                self.info("accessing path %r", p)
                self.prepare_connection(request)
                self.prepare_headers(ch, request)
                ch = StaticFile(p)
            else:
                self.debug("accessing path %r failed", p)
                return self.list_content(name, ch, request)

        if ch is None:
            p = util.sibpath(__file__, name)
            if os.path.exists(p):
                ch = StaticFile(p)
        self.info('MSRoot ch %s', ch)
        return ch
Example #3
0
 def got_item(ch):
     if ch is not None:
         request.setResponseCode(200)
         file = ch.get_cover()
         if file and os.path.exists(file):
             self.info("got cover %s", file)
             return StaticFile(file)
     request.setResponseCode(404)
     return static.Data(
         '<html><p>cover requested not found</p></html>',
         'text/html')
Example #4
0
    def init_complete(self, backend):
        if self.backend != backend:
            return
        self._services = []
        self._devices = []

        try:
            self.connection_manager_server = ConnectionManagerServer(self)
            self._services.append(self.connection_manager_server)
        except LookupError as msg:
            self.warning('ConnectionManagerServer %s', msg)
            raise LookupError(msg)

        try:
            self.rendering_control_server = RenderingControlServer(self)
            self._services.append(self.rendering_control_server)
        except LookupError as msg:
            self.warning('RenderingControlServer %s', msg)
            raise LookupError(msg)

        try:
            self.av_transport_server = AVTransportServer(self)
            self._services.append(self.av_transport_server)
        except LookupError as msg:
            self.warning('AVTransportServer %s', msg)
            raise LookupError(msg)

        upnp_init = getattr(self.backend, "upnp_init", None)
        if upnp_init:
            upnp_init()

        self.web_resource = HttpRoot(self)
        self.coherence.add_web_resource(str(self.uuid)[5:], self.web_resource)

        try:
            dlna_caps = self.backend.dlna_caps
        except AttributeError:
            dlna_caps = []

        version = self.version
        while version > 0:
            self.web_resource.putChild(
                'description-%d.xml' % version,
                RootDeviceXML(
                    self.coherence.hostname,
                    str(self.uuid),
                    self.coherence.urlbase,
                    device_type=self.device_type,
                    version=version,
                    #presentation_url='/'+str(self.uuid)[5:],
                    friendly_name=self.backend.name,
                    model_description='Coherence UPnP A/V %s' %
                    self.device_type,
                    model_name='Coherence UPnP A/V %s' % self.device_type,
                    services=self._services,
                    devices=self._devices,
                    icons=self.icons,
                    dlna_caps=dlna_caps))
            version -= 1

        self.web_resource.putChild('ConnectionManager',
                                   self.connection_manager_server)
        self.web_resource.putChild('RenderingControl',
                                   self.rendering_control_server)
        self.web_resource.putChild('AVTransport', self.av_transport_server)

        for icon in self.icons:
            if 'url' in icon:
                if icon['url'].startswith('file://'):
                    if os.path.exists(icon['url'][7:]):
                        self.web_resource.putChild(
                            os.path.basename(icon['url']),
                            StaticFile(icon['url'][7:],
                                       defaultType=icon['mimetype']))
                elif icon['url'] == '.face':
                    face_path = os.path.abspath(
                        os.path.join(os.path.expanduser('~'), ".face"))
                    if os.path.exists(face_path):
                        self.web_resource.putChild(
                            'face-icon.png',
                            StaticFile(face_path,
                                       defaultType=icon['mimetype']))
                else:
                    from pkg_resources import resource_filename
                    icon_path = os.path.abspath(
                        resource_filename(
                            __name__,
                            os.path.join('..', '..', '..', 'misc',
                                         'device-icons', icon['url'])))
                    if os.path.exists(icon_path):
                        self.web_resource.putChild(
                            icon['url'],
                            StaticFile(icon_path,
                                       defaultType=icon['mimetype']))

        self.register()
        self.warning("%s %s (%s) activated with %s", self.backend.name,
                     self.device_type, self.backend,
                     str(self.uuid)[5:])
Example #5
0
    def init_complete(self, backend):
        if self.backend != backend:
            return
        self._services = []
        self._devices = []

        try:
            self.connection_manager_server = ConnectionManagerServer(self)
            self._services.append(self.connection_manager_server)
        except LookupError as msg:
            self.warning(f'ConnectionManagerServer {msg}')
            raise LookupError(msg)

        try:
            transcoding = False
            if self.coherence.config.get('transcoding', 'no') == 'yes':
                transcoding = True
            self.content_directory_server = ContentDirectoryServer(
                self, transcoding=transcoding
            )
            self._services.append(self.content_directory_server)
        except LookupError as msg:
            self.warning(f'ContentDirectoryServer {msg}')
            raise LookupError(msg)

        try:
            self.media_receiver_registrar_server = MediaReceiverRegistrarServer(  # noqa: E501
                self, backend=FakeMediaReceiverRegistrarBackend()
            )
            self._services.append(self.media_receiver_registrar_server)
        except LookupError as msg:
            self.warning(f'MediaReceiverRegistrarServer (optional) {msg}')

        try:
            self.scheduled_recording_server = ScheduledRecordingServer(self)
            self._services.append(self.scheduled_recording_server)
        except LookupError as msg:
            self.info(f'ScheduledRecordingServer {msg}')

        upnp_init = getattr(self.backend, 'upnp_init', None)
        if upnp_init:
            upnp_init()

        self.web_resource = MSRoot(self, backend)
        self.coherence.add_web_resource(str(self.uuid)[5:], self.web_resource)

        version = int(self.version)
        while version > 0:
            self.web_resource.putChild(
                f'description-{version}.xml'.encode('ascii'),
                RootDeviceXML(
                    self.coherence.hostname,
                    str(self.uuid),
                    self.coherence.urlbase,
                    self.device_type,
                    version,
                    friendly_name=self.backend.name,
                    services=self._services,
                    devices=self._devices,
                    icons=self.icons,
                    presentation_url=self.presentationURL,
                ),
            )
            self.web_resource.putChild(
                f'xbox-description-{version}.xml'.encode('ascii'),
                RootDeviceXML(
                    self.coherence.hostname,
                    str(self.uuid),
                    self.coherence.urlbase,
                    self.device_type,
                    version,
                    friendly_name=self.backend.name,
                    xbox_hack=True,
                    services=self._services,
                    devices=self._devices,
                    icons=self.icons,
                    presentation_url=self.presentationURL,
                ),
            )
            version -= 1

        self.web_resource.putChild(
            b'ConnectionManager', self.connection_manager_server
        )
        self.web_resource.putChild(
            b'ContentDirectory', self.content_directory_server
        )
        if hasattr(self, 'scheduled_recording_server'):
            self.web_resource.putChild(
                b'ScheduledRecording', self.scheduled_recording_server
            )
        if hasattr(self, 'media_receiver_registrar_server'):
            self.web_resource.putChild(
                b'X_MS_MediaReceiverRegistrar',
                self.media_receiver_registrar_server,
            )

        for icon in self.icons:
            if 'url' in icon:
                if icon['url'].startswith('file://'):
                    if os.path.exists(icon['url'][7:]):
                        self.web_resource.putChild(
                            os.path.basename(icon['url']).encode('ascii'),
                            StaticFile(
                                icon['url'][7:], defaultType=icon['mimetype']
                            ),
                        )
                elif icon['url'] == '.face':
                    face_path = os.path.abspath(
                        os.path.join(os.path.expanduser('~'), '.face')
                    )
                    if os.path.exists(face_path):
                        self.web_resource.putChild(
                            b'face-icon.png',
                            StaticFile(
                                face_path, defaultType=icon['mimetype']
                            ),
                        )
                else:
                    from pkg_resources import resource_filename

                    icon_path = os.path.abspath(
                        resource_filename(
                            __name__,
                            os.path.join(
                                '..',
                                '..',
                                '..',
                                'misc',
                                'device-icons',
                                icon['url'],
                            ),
                        )
                    )
                    if os.path.exists(icon_path):
                        self.web_resource.putChild(
                            icon['url'].encode('ascii'),
                            StaticFile(
                                icon_path, defaultType=icon['mimetype']
                            ),
                        )

        self.register()
        self.warning(
            f'{self.device_type} {self.backend.name} ({self.backend})'
            f' activated with id {str(self.uuid)[5:]}'
        )
Example #6
0
	def renderFile(self,request,filepath):
		self.info('Cache file available %r %r ' %(request, filepath))
		downloadedFile = StaticFile(filepath, self.mimetype)
		downloadedFile.type = QUICKTIME_MIMETYPE
		downloadedFile.encoding = None
		return downloadedFile.render(request)