Coverage for coherence/base.py : 55%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Licensed under the MIT license # http://opensource.org/licenses/mit-license.php
# Copyright 2006,2007,2008 Frank Scholz <coherence@beebits.net>
except ImportError: pkg_resources = None
""" we have an out-of-band request """ return static.File( self.coherence.dbus.pinboard[request.args['key'][0]])
self.warning('\t modified wrong name from {} to {}'.format( name, name[:-1])) name = name[:-1]
# at this stage, name should be a device UUID except KeyError: self.warning("Cannot find device for requested name: %r", name) request.setResponseCode(404) return \ static.Data( b'<html><p>No device for requested UUID: %s</p></html>' % name.encode('ascii'), 'text/html')
if isinstance(uri, bytes): uri = uri.decode('utf-8') self.info('listchilds %s', uri) if uri[-1] != '/': uri += '/' cl = [] for child in self.coherence.children: device = self.coherence.get_device_with_id(child) if device is not None: cl.append('<li><a href=%s%s>%s:%s %s</a></li>' % ( uri, child, device.get_friendly_device_type(), device.get_device_type_version(), device.get_friendly_name()))
for child in self.children: cl.append('<li><a href=%s%s>%s</a></li>' % (uri, child, child)) return "".join(cl)
result = """<html> <head><title>Coherence</title></head> <body><a href="http://coherence.beebits.net">Coherence</a> - a Python DLNA/UPnP framework for the Digital Living <p>Hosting:<ul>%r</ul></p> </body> </html>""" % self.listchilds(request.uri.encode('utf-8')) return result
"coherence.plugins.backend.media_renderer", "coherence.plugins.backend.binary_light", "coherence.plugins.backend.dimmable_light")
# initialize only once
ids = (ids,) # set a placeholder for lazy loading self._plugins[entrypoint.name] = entrypoint else: self.info("no pkg_resources, fallback to simple plugin handling")
return str(self._plugins)
try: plugin = plugin.load(require=False) except (ImportError, AttributeError, pkg_resources.ResolutionError) as msg: self.warning( "Can't load plugin %s (%s), maybe missing dependencies...", plugin.name, msg) self.info(traceback.format_exc()) del self._plugins[key] raise KeyError else: self._plugins[key] = plugin
except KeyError: return default
self._plugins.__setitem__(key, value)
return self.__setitem__(key, value)
return list(self._plugins.keys())
os.path.join(os.path.dirname(__file__), 'backends'), log=self.warning)
# initialize only once
# supers
""" Services """
""" initializes logsystem a COHEN_DEBUG environment variable overwrites all level settings here """
if isinstance(subsystems, dict): subsystems = [subsystems] for subsystem in subsystems: try: if subsystem['active'] == 'no': continue except (KeyError, TypeError): pass self.info("setting log-level for subsystem %s to %s", subsystem['name'], subsystem['level']) logging.getLogger(subsystem['name'].lower()).setLevel( subsystem['level'].upper()) logging.getLogger(subsystem.lower()).setLevel(level.upper()) if logfile is not None: logfile = str(logfile)
__version__)
self.hostname = get_ip_address('%s' % network_if) else: except socket.gaierror: self.warning("hostname can't be resolved, " "maybe a system misconfiguration?") self.hostname = '127.0.0.1'
""" use interface detection via routing table as last resort """
else: self.setup_part2()
""" we do need this to survive multiple calls to Coherence during trial tests """
self.warning('detection of own ip failed, using %s as own address,' ' functionality will be limited', self.hostname)
""" SSDP Server Initialization """ # TODO: add ip/interface bind 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.Any) louie.Any) 'Coherence.UPnP.RootDevice.detection_completed', louie.Any) # louie.connect(self.receiver, # 'Coherence.UPnP.Service.detection_completed', # louie.Any)
force=True)
""" Web Server Initialization """ # TODO: add ip/interface bind self.web_server_port, self) except CannotListenError: self.warning('port %r already in use, aborting!', self.web_server_port) reactor.stop() return
# self.renew_service_subscription_loop = \ # task.LoopingCall(self.check_devices) # self.renew_service_subscription_loop.start(20.0, now=False)
if isinstance(plugins, dict): plugins = [plugins]
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.hostname, str(self.web_server_port)))
""" Control Point Initialization """ 'json', 'no') == 'yes':
""" Json Interface Initialization """ from coherence.json_service import JsonInterface self.json = JsonInterface(self.ctrl)
""" Transcoder Initialization """ from coherence.transcoder import TranscoderManager self.transcoder_manager = TranscoderManager(self)
""" DBus Initialization """ 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())
# TODO clean up this exception concept raise KeyError raise KeyError except KeyError: self.warning( "Can't enable %s plugin, sub-system %s not found!", plugin, device) except Exception as e1: self.exception( "Can't enable %s plugin for sub-system %s " "[exception: %r]", plugin, device, e1) self.debug(traceback.format_exc()) except KeyError: self.warning("Can't enable %s plugin, not found!", plugin) except Exception as e2: self.warning("Can't enable %s plugin, %s!", plugin, e2) self.debug(traceback.format_exc())
""" Removes a backend from Coherence
@:param plugin: is the object return by add_plugin or an UUID string """ if isinstance(plugin, str): try: plugin = self.active_backends[plugin] except KeyError: self.warning("no backend with the uuid %r found", plugin) return ""
try: del self.active_backends[str(plugin.uuid)] self.info("removing plugin %r", plugin) plugin.unregister() return plugin.uuid except KeyError: self.warning("no backend with the uuid %r found", plugin.uuid) return ""
def writeable_config(): """ do we have a new-style config file """ return False
""" find the backend with uuid and store in its the config the key and value pair(s) """ plugins = self.config.get('plugin') if plugins is None: self.warning("storing a plugin config option is only possible" " with the new config file format") return if isinstance(plugins, dict): plugins = [plugins] uuid = str(uuid) if uuid.startswith('uuid:'): uuid = uuid[5:] for plugin in plugins: try: if plugin['uuid'] == uuid: for k, v in list(items.items()): plugin[k] = v self.config.save() except Exception as e: self.warning('Coherence.store_plugin_config: %r' % e) else: self.info( "storing plugin config option for %s failed, plugin not found", uuid)
pass
self.dbus.shutdown() self.dbus = None
""" send service unsubscribe messages """ self.msearch.double_discover_loop.stop() self.msearch.port.stopListening() self.ssdp_server.resend_notify_loop.stop() self.ssdp_server.port.stopListening() # self.renew_service_subscription_loop.stop() except Exception: pass
dd = device.unsubscribe_service_subscriptions() dd.addCallback(device.remove) dev_l.append(dd)
"""anything left over""" 'Coherence.UPnP.SSDP.new_device', louie.Any) 'Coherence.UPnP.SSDP.removed_device', louie.Any) 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
""" iterate over devices and their embedded ones and renew subscriptions """ for root_device in self.get_devices(): root_device.renew_service_subscriptions() for device in root_device.get_devices(): device.renew_service_subscriptions()
self._callbacks.setdefault(name, []).append(callback)
callbacks = self._callbacks.get(name, []) if callback in callbacks: callbacks.remove(callback) self._callbacks[name] = callbacks
for callback in self._callbacks.get(name, []): callback(*args)
found = [] for device in self.devices: if device.get_host() == host: found.append(device) return found
found = None for device in self.devices: if device.get_usn() == usn: found = device break return found
# print('get_device_with_id [{}]: {}'.format( # type(device_id), device_id)) found = None for device in self.devices: id = device.get_id() if device_id[:5] != 'uuid:': id = id[5:] if id == device_id: found = device break return found
# print('get_devices: {}'.format(self.devices))
# print('get_local_devices: {}'.format( # [d for d in self.devices if d.manifestation == 'local'])) return [d for d in self.devices if d.manifestation == 'local']
# print('get_nonlocal_devices: {}'.format( # [d for d in self.devices if d.manifestation == 'remote'])) return [d for d in self.devices if d.manifestation == 'remote']
else: self.info('creating device/service {}'.format(infos['USN'])) root_id = infos['USN'][:-len(infos['ST']) - 2] root = self.get_device_with_id(root_id) # TODO: must check that this is working as expected device = Device(root, udn=infos['UDN'])
device.get_id(), device.get_usn(), device.friendly_device_type))
self.info('removed device {} %s{}'.format(infos['ST'], infos['USN'])) 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']) self.callback("removed_device", infos['ST'], infos['USN'])
except KeyError: """ probably the backend init failed """ pass
weak=True): """ wrapper method around louie.connect """ louie.connect(receiver, signal=signal, sender=sender, weak=weak)
weak=True): """ wrapper method around louie.disconnect """ louie.disconnect(receiver, signal=signal, sender=sender, weak=weak) |