Example #1
0
 def __init__(self):
     self.ssdp = SSDPServer()  # listen for things destined to port 1900
     self.ssdpalt = SSDPServerAlt()
     self.msearch = MSearch(self.ssdpalt,
                            test=False)  # use correct source port
     self.devices = []
     self.orphans = {}
     self.listeners = {'added': [], 'deleted': []}
     louie.connect(self.ssdp_detected, 'Coherence.UPnP.SSDP.new_device',
                   louie.Any)
     louie.connect(self.ssdp_deleted, 'Coherence.UPnP.SSDP.removed_device',
                   louie.Any)
     louie.connect(self.device_found,
                   'Coherence.UPnP.RootDevice.detection_completed',
                   louie.Any)
     self.msearch.double_discover()
Example #2
0
	def __init__(self):
		self.ssdp = SSDPServer()
		self.msearch = MSearch(self.ssdp, test=False)
		self.devices = []
		louie.connect(self.ssdp_detected, 'Coherence.UPnP.SSDP.new_device', louie.Any)
		louie.connect(self.ssdp_deleted, 'Coherence.UPnP.SSDP.removed_device', louie.Any)
		louie.connect(self.device_found, 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
		self.msearch.double_discover()
Example #3
0
	def __init__(self):
		self.ssdp = SSDPServer()		# listen for things destined to port 1900
		self.ssdpalt = SSDPServerAlt()
		self.msearch = MSearch(self.ssdpalt, test=False)	# use correct source port
		self.devices = []
		self.orphans = {}
		self.listeners = {'added':[], 'deleted':[]}
		louie.connect(self.ssdp_detected, 'Coherence.UPnP.SSDP.new_device', louie.Any)
		louie.connect(self.ssdp_deleted, 'Coherence.UPnP.SSDP.removed_device', louie.Any)
		louie.connect(self.device_found, 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
		self.msearch.double_discover()
Example #4
0
    def setup_part2(self):
        '''Initializes the basic and optional services/devices and the enabled
        plugins (backends).'''
        self.setup_ssdp_server()
        if not self.ssdp_server:
            raise Exception('Unable to initialize an ssdp server')

        self.msearch = MSearch(self.ssdp_server, test=self.is_unittest)

        reactor.addSystemEventTrigger(
            'before',
            'shutdown',
            self.shutdown,
            force=True,
        )

        self.setup_web_server()
        if not self.urlbase:
            raise Exception('Unable to initialize an web server')

        self.setup_plugins()

        # Control Point Initialization
        if (self.config.get('controlpoint', 'no') == 'yes'
                or self.config.get('json', 'no') == 'yes'):
            self.ctrl = ControlPoint(self)

        # Json Interface Initialization
        if self.config.get('json', 'no') == 'yes':
            from coherence.json_service import JsonInterface

            self.json = JsonInterface(self.ctrl)

        # Transcoder Initialization
        if self.config.get('transcoding', 'no') == 'yes':
            from coherence.transcoder import TranscoderManager

            self.transcoder_manager = TranscoderManager(self)

        # DBus Initialization
        if self.config.get('use_dbus', 'no') == 'yes':
            try:
                from coherence import dbus_service

                if self.ctrl is None:
                    self.ctrl = ControlPoint(self)
                self.ctrl.auto_client_append('InternetGatewayDevice')
                self.dbus = dbus_service.DBusPontoon(self.ctrl)
            except Exception as msg:
                self.warning(f'Unable to activate dbus sub-system: {msg}')
                self.debug(traceback.format_exc())
Example #5
0
class DeviceManager(object):
    def __init__(self):
        self.ssdp = SSDPServer()  # listen for things destined to port 1900
        self.ssdpalt = SSDPServerAlt()
        self.msearch = MSearch(self.ssdpalt,
                               test=False)  # use correct source port
        self.devices = []
        self.orphans = {}
        self.listeners = {'added': [], 'deleted': []}
        louie.connect(self.ssdp_detected, 'Coherence.UPnP.SSDP.new_device',
                      louie.Any)
        louie.connect(self.ssdp_deleted, 'Coherence.UPnP.SSDP.removed_device',
                      louie.Any)
        louie.connect(self.device_found,
                      'Coherence.UPnP.RootDevice.detection_completed',
                      louie.Any)
        self.msearch.double_discover()

    def register(self, event, callback):
        self.listeners[event].append(callback)

    def unregister(self, event, callback):
        if callback in self.listeners[event]:
            self.listeners[event].remove(callback)

    def _send_event(self, event, args=(), kwargs={}):
        for callback in self.listeners[event]:
            callback(*args, **kwargs)

    def _get_device_by_id(self, id):
        found = None
        for device in self.devices:
            this_id = device.get_id()
            if this_id[:5] != 'uuid:':
                this_id = this_id[5:]
            if this_id == id:
                found = device
                break
        return found

    def _get_device_by_usn(self, usn):
        found = None
        for device in self.devices:
            if device.get_usn() == usn:
                found = device
                break
        return found

    def ssdp_detected(self, device_type, infos, *args, **kwargs):
        logger.debug("SSDP announced: %s" % (infos, ))
        if infos['ST'] == 'upnp:rootdevice':
            root = RootDevice(infos)  # kicks off loading of the device info
            # which will call device_found callback
            root_id = infos['USN']
            for orphan in self.orphans.get(root_id, []):
                orphan.parent = root
        else:
            logger.debug("Find subdevice %s" % (infos, ))
            root_id = infos['USN'][:-len(infos['ST']) - 2]
            root = self._get_device_by_id(root_id)
            if root:
                device = Device(infos, root)
                root.add_device(device)
                self.device_found(device)
            else:
                device = Device(infos)
                wants_parent = self.orphans.get(root_id, [])
                wants_parent.append(device)
                self.orphans[root_id] = wants_parent

    def ssdp_deleted(self, device_type, infos, *args, **kwargs):
        device = self._get_device_by_usn(infos['USN'])
        if device:
            louie.send('Coherence.UPnP.Device.removed', None, usn=infos['USN'])
            self._send_event('deleted', args=(device, ))
            self.devices.remove(device)
            device.remove()
            if infos['ST'] == 'upnp:rootdevice':
                louie.send('Coherence.UPnP.RootDevice.removed',
                           None,
                           usn=infos['USN'])

    def device_found(self, device):
        logger.debug("UPNP Device discovered: %s" % (device, ))
        self.devices.append(device)
        self._send_event('added', args=(device, ))

    def browse_callback(self, result):
        results = DIDLLite.DIDLElement.fromString(result['Result']).getItems()
        print([result.title for result in results])

    def browse_error(self, error):
        print(error.getTraceback())
Example #6
0
  def setup_part2(self):
    self.info('running on host: %s', self.hostname)
    if self.hostname.startswith('127.'):
      self.warning('detection of own ip failed, using %s as own address, functionality will be limited', self.hostname)

    unittest = self.config.get('unittest', 'no')
    unittest = False if unittest == 'no' else True

    """ SSDP Server Initialization
    """
    try:
      # TODO: add ip/interface bind
      self.ssdp_server = SSDPServer(test=unittest)
    except CannotListenError as err:
      self.error("Error starting the SSDP-server: %s", err)
      self.debug("Error starting the SSDP-server", exc_info=True)
      reactor.stop()
      return

    louie.connect(self.create_device, 'Coherence.UPnP.SSDP.new_device', louie.Any)
    louie.connect(self.remove_device, 'Coherence.UPnP.SSDP.removed_device', louie.Any)
    louie.connect(self.add_device, 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
    # louie.connect( self.receiver, 'Coherence.UPnP.Service.detection_completed', louie.Any)

    self.ssdp_server.subscribe("new_device", self.add_device)
    self.ssdp_server.subscribe("removed_device", self.remove_device)

    self.msearch = MSearch(self.ssdp_server, test=unittest)

    reactor.addSystemEventTrigger('before', 'shutdown', self.shutdown, force=True)

    """ Web Server Initialization
    """
    try:
      # TODO: add ip/interface bind
      self.web_server = WebServer(self.config.get('web-ui', None), self.web_server_port, self)
    except CannotListenError:
      self.warning('port %r already in use, aborting!', self.web_server_port)
      reactor.stop()
      return

    self.urlbase = 'http://%s:%d/' % (self.hostname, self.web_server_port)
    # self.renew_service_subscription_loop = task.LoopingCall(self.check_devices)
    # self.renew_service_subscription_loop.start(20.0, now=False)

    try:
      plugins = self.config['plugin']
      if isinstance(plugins, dict):
        plugins = [plugins]
    except:
      plugins = None

    if plugins is None:
      plugins = self.config.get('plugins', None)

    if plugins is None:
      self.info("No plugin defined!")
    else:
      if isinstance(plugins, dict):
        for plugin, arguments in list(plugins.items()):
          try:
            if not isinstance(arguments, dict):
              arguments = {}
            self.add_plugin(plugin, **arguments)
          except Exception as msg:
            self.warning("Can't enable plugin, %s: %s!", plugin, msg)
            self.info(traceback.format_exc())
      else:
        for plugin in plugins:
          try:
            if plugin['active'] == 'no':
              continue
          except (KeyError, TypeError):
            pass
          try:
            backend = plugin['backend']
            arguments = copy.copy(plugin)
            del arguments['backend']
            backend = self.add_plugin(backend, **arguments)
            if self.writeable_config():
              if 'uuid' not in plugin:
                plugin['uuid'] = str(backend.uuid)[5:]
                self.config.save()
          except Exception as msg:
            self.warning("Can't enable plugin, %s: %s!", plugin, msg)
            self.info(traceback.format_exc())

    self.external_address = ':'.join((self.hostname, str(self.web_server_port)))

    """ Control Point Initialization
    """
    if self.config.get('controlpoint', 'no') == 'yes' or self.config.get('json', 'no') == 'yes':
      self.ctrl = ControlPoint(self)

    """ Json Interface Initialization
    """
    if self.config.get('json', 'no') == 'yes':
      from coherence.json_service import JsonInterface
      self.json = JsonInterface(self.ctrl)

    """ Transcoder Initialization
    """
    if self.config.get('transcoding', 'no') == 'yes':
      from coherence.transcoder import TranscoderManager
      self.transcoder_manager = TranscoderManager(self)

    """ DBus Initialization
    """
    if self.config.get('use_dbus', 'no') == 'yes':
      try:
        from coherence import dbus_service
        if self.ctrl is None:
          self.ctrl = ControlPoint(self)
        self.ctrl.auto_client_append('InternetGatewayDevice')
        self.dbus = dbus_service.DBusPontoon(self.ctrl)
      except Exception as msg:
        self.warning("Unable to activate dbus sub-system: %r", msg)
        self.debug(traceback.format_exc())
Example #7
0
class DeviceManager(object):
	def __init__(self):
		self.ssdp = SSDPServer()		# listen for things destined to port 1900
		self.ssdpalt = SSDPServerAlt()
		self.msearch = MSearch(self.ssdpalt, test=False)	# use correct source port
		self.devices = []
		self.orphans = {}
		self.listeners = {'added':[], 'deleted':[]}
		louie.connect(self.ssdp_detected, 'Coherence.UPnP.SSDP.new_device', louie.Any)
		louie.connect(self.ssdp_deleted, 'Coherence.UPnP.SSDP.removed_device', louie.Any)
		louie.connect(self.device_found, 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
		self.msearch.double_discover()

	def register(self, event, callback):
		self.listeners[event].append(callback)

	def unregister(self, event, callback):
		if callback in self.listeners[event]:
			self.listeners[event].remove(callback)

	def _send_event(self, event, args=(), kwargs={}):
		for callback in self.listeners[event]:
			callback(*args, **kwargs)

	def _get_device_by_id(self, id):
		found = None
		for device in self.devices:
			this_id = device.get_id()
			if this_id[:5] != 'uuid:':
				this_id = this_id[5:]
			if this_id == id:
				found = device
				break
		return found

	def _get_device_by_usn(self, usn):
		found = None
		for device in self.devices:
			if device.get_usn() == usn:
				found = device
				break
		return found

	def ssdp_detected(self, device_type, infos, *args, **kwargs):
		logger.debug("SSDP announced: %s"%(infos,))
		if infos['ST'] == 'upnp:rootdevice':
			root = RootDevice(infos)	# kicks off loading of the device info
			                        	# which will call device_found callback
			root_id = infos['USN']
			for orphan in self.orphans.get(root_id, []):
				orphan.parent = root
		else:
			logger.debug("Find subdevice %s"%(infos,))
			root_id = infos['USN'][:-len(infos['ST']) - 2]
			root = self._get_device_by_id(root_id)
			if root:
				device = Device(infos, root)
				root.add_device(device)
				self.device_found(device)
			else:
				device = Device(infos)
				wants_parent = self.orphans.get(root_id, [])
				wants_parent.append(device)
				self.orphans[root_id] = wants_parent
	def ssdp_deleted(self, device_type, infos, *args, **kwargs):
		device = self._get_device_by_usn(infos['USN'])
		if device:
			louie.send('Coherence.UPnP.Device.removed', None, usn=infos['USN'])
			self._send_event('deleted', args=(device,))
			self.devices.remove(device)
			device.remove()
			if infos['ST'] == 'upnp:rootdevice':
				louie.send('Coherence.UPnP.RootDevice.removed', None, usn=infos['USN'])

	def device_found(self, device):
		logger.debug("UPNP Device discovered: %s"%(device,))
		self.devices.append(device)
		self._send_event('added', args=(device,))
	
	def browse_callback(self, result):
		results = DIDLLite.DIDLElement.fromString(result['Result']).getItems()
		print([result.title for result in results])
	def browse_error(self, error):
		print(error.getTraceback())
Example #8
0
class DevicesListener(object):
	def __init__(self):
		self.ssdp = SSDPServer()
		self.msearch = MSearch(self.ssdp, test=False)
		self.devices = []
		louie.connect(self.ssdp_detected, 'Coherence.UPnP.SSDP.new_device', louie.Any)
		louie.connect(self.ssdp_deleted, 'Coherence.UPnP.SSDP.removed_device', louie.Any)
		louie.connect(self.device_found, 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
		self.msearch.double_discover()

	def _get_device_by_id(self, id):
		found = None
		for device in self.devices:
			this_id = device.get_id()
			if this_id[:5] != 'uid:':
				this_id = this_id[5:]
			if this_id == id:
				found = device
				break
		return found

	def _get_device_by_usn(self, usn):
		found = None
		for device in self.devices:
			if device.get_usn() == usn:
				found = device
				break
		return found

	def ssdp_detected(self, device_type, infos, *args, **kwargs):
		print("Found ssdp %s"%(infos,))
		if infos['ST'] == 'upnp:rootdevice':
			root = RootDevice(infos)
		else:
			root_id = infos['USN'][:-len(infos['ST']) - 2]
			root = self._get_device_by_id(root_id)
			device = Device(infos, root)	# kicks off loading of the device info
			                            	# which will call device_found callback
	def ssdp_deleted(self, device_type, infos, *args, **kwargs):
		device = self._get_device_with_usn(infos['USN'])
		if device:
			louie.send('Coherence.UPnP.Device.removed', None, usn=infos['USN'])
			self.devices.remove(device)
			device.remove()
			if infos['ST'] == 'upnp:rootdevice':
				louie.send('Coherence.UPnP.RootDevice.removed', None, usn=infos['USN'])

	def device_found(self, device):
		print("Found device %s"%(device,))
		self.devices.append(device)
		for service in device.get_services():
			print("  %s @ %s"%(service.get_type(), service.get_control_url()))
			if 'ContentDirectory' in service.get_type():
				for actionname,action in service.get_actions().items():
					if action.get_name() == 'Browse':
						d = action.call(
						    ObjectID='0',
						    BrowseFlag='BrowseDirectChildren',
						    Filter='*', SortCriteria='',
						    StartingIndex='0',
						    RequestedCount='0'
						)
						d.addCallback(self.browse_callback)
	
	def browse_callback(self, result):
		results = DIDLLite.DIDLElement.fromString(result['Result']).getItems()
		print([result.title for result in results])
	def browse_error(self, error):
		print(error.getTraceback())
Example #9
0
    def setup_part2(self):
        '''Initializes the basic and optional services/devices and the enabled
        plugins (backends).'''
        self.info(f'running on host: {self.hostname}')
        if self.hostname.startswith('127.'):
            self.warning(f'detection of own ip failed, using {self.hostname} '
                         f'as own address, functionality will be limited')

        unittest = self.config.get('unittest', 'no')
        unittest = False if unittest == 'no' else True

        try:
            # TODO: add ip/interface bind
            self.ssdp_server = SSDPServer(test=unittest)
        except CannotListenError as err:
            self.error(f'Error starting the SSDP-server: {err}')
            self.debug('Error starting the SSDP-server', exc_info=True)
            reactor.stop()
            return

        # maybe some devices are already notified, so we enforce
        # to create the device, if it is not already added...and
        # then we connect the signals for new detections.
        for st, usn in self.ssdp_server.root_devices:
            self.create_device(st, usn)
        self.ssdp_server.bind(new_device=self.create_device)
        self.ssdp_server.bind(removed_device=self.remove_device)

        self.ssdp_server.subscribe('new_device', self.add_device)
        self.ssdp_server.subscribe('removed_device', self.remove_device)

        self.msearch = MSearch(self.ssdp_server, test=unittest)

        reactor.addSystemEventTrigger('before',
                                      'shutdown',
                                      self.shutdown,
                                      force=True)

        # Web Server Initialization
        try:
            # TODO: add ip/interface bind
            if self.config.get('web-ui', 'no') != 'yes':
                self.web_server = WebServer(None, self.web_server_port, self)
            else:
                self.web_server = WebServerUi(self.web_server_port,
                                              self,
                                              unittests=unittest)
        except CannotListenError:
            self.error(
                f'port {self.web_server_port} already in use, aborting!')
            reactor.stop()
            return

        self.urlbase = f'http://{self.hostname}:{self.web_server_port:d}/'
        # self.renew_service_subscription_loop = \
        #     task.LoopingCall(self.check_devices)
        # self.renew_service_subscription_loop.start(20.0, now=False)

        # Plugins Initialization
        try:
            plugins = self.config['plugin']
            if isinstance(plugins, dict):
                plugins = [plugins]
        except Exception:
            plugins = None

        if plugins is None:
            plugins = self.config.get('plugins', None)

        if plugins is None:
            self.info('No plugin defined!')
        else:
            if isinstance(plugins, dict):
                for plugin, arguments in list(plugins.items()):
                    try:
                        if not isinstance(arguments, dict):
                            arguments = {}
                        self.add_plugin(plugin, **arguments)
                    except Exception as msg:
                        self.warning(f'Can\'t enable plugin, {plugin}: {msg}!')
                        self.info(traceback.format_exc())
            else:
                for plugin in plugins:
                    try:
                        if plugin['active'] == 'no':
                            continue
                    except (KeyError, TypeError):
                        pass
                    try:
                        backend = plugin['backend']
                        arguments = copy.copy(plugin)
                        del arguments['backend']
                        backend = self.add_plugin(backend, **arguments)
                        if self.writeable_config():
                            if 'uuid' not in plugin:
                                plugin['uuid'] = str(backend.uuid)[5:]
                                self.config.save()
                    except Exception as msg:
                        self.warning(f'Can\'t enable plugin, {plugin}: {msg}!')
                        self.info(traceback.format_exc())

        self.external_address = ':'.join(
            (self.hostname, str(self.web_server_port)))

        # Control Point Initialization
        if self.config.get('controlpoint', 'no') == 'yes' or self.config.get(
                'json', 'no') == 'yes':
            self.ctrl = ControlPoint(self)

        # Json Interface Initialization
        if self.config.get('json', 'no') == 'yes':
            from coherence.json_service import JsonInterface
            self.json = JsonInterface(self.ctrl)

        # Transcoder Initialization
        if self.config.get('transcoding', 'no') == 'yes':
            from coherence.transcoder import TranscoderManager
            self.transcoder_manager = TranscoderManager(self)

        # DBus Initialization
        if self.config.get('use_dbus', 'no') == 'yes':
            try:
                from coherence import dbus_service
                if self.ctrl is None:
                    self.ctrl = ControlPoint(self)
                self.ctrl.auto_client_append('InternetGatewayDevice')
                self.dbus = dbus_service.DBusPontoon(self.ctrl)
            except Exception as msg:
                self.warning(f'Unable to activate dbus sub-system: {msg}')
                self.debug(traceback.format_exc())