Esempio n. 1
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())
Esempio n. 2
0
    def start(self):
        print "Upnp backend starting"
        # clear device list
        self._removeXML()

        # config Coherence
        conf = Config(self._configfile)
        c = Coherence({'logmode': 'warning'})
        c.setup(conf)
        #add share folders
        con = ""
        for f in config.share_folders:
            if len(con) > 0:
                con += ","
            con += f
        c.add_plugin('FSStore', name=config.device_name, content=con)

        # start a ControlPoint to start detecting upnp activity
        cp = ControlPoint(c, auto_client=['MediaServer'])
        cp.connect(self.mediaserver_detected,
                   'Coherence.UPnP.ControlPoint.MediaServer.detected')
        cp.connect(self.mediaserver_removed,
                   'Coherence.UPnP.ControlPoint.MediaServer.removed')

        #self._localdevice = cp.get_device_by_name(self._localdevicename)
        #print "SPRURPDDSOPF            ",self._localdevice.client.get_friendly_name()

        print "Upnp loop succesfully started"
        self._handler.start()
        print "DBus loop succesfully started"
Esempio n. 3
0
def start():
    control_point = ControlPoint(Coherence({'logmode': 'warning'}),
                                 auto_client=['MediaServer'])
    control_point.connect(media_server_found,
                          'Coherence.UPnP.ControlPoint.MediaServer.detected')
    control_point.connect(media_server_removed,
                          'Coherence.UPnP.ControlPoint.MediaServer.removed')
Esempio n. 4
0
def start():
  control_point = ControlPoint(Coherence({'logmode': 'warning'}),
                               auto_client=['MediaServer'])
  control_point.connect(media_server_found, 'Coherence.UPnP.ControlPoint.MediaServer.detected')
  control_point.connect(media_server_removed, 'Coherence.UPnP.ControlPoint.MediaServer.removed')

  # now we should also try to discover the ones that are already there:
  for device in control_point.coherence.devices:
    print device
Esempio n. 5
0
    def __init__(self,command,config):
        #print "command %r %r %r" %(command,config,config.subOptions)
        self.config = config
        self.locked = False
        if command == None:
            self.command = 'show-devices'
        else:
            self.command = command

        if self.command == 'show-devices':
            self.locked = None

        if self.command == 'add-mapping':
            if self.config.subOptions['internal-host'] == None:
                raise Exception("internal-host parameter missing")
            if self.config.subOptions['internal-port'] == None:
                raise Exception("internal-port parameter missing")
            if self.config.subOptions['protocol'].lower() not in ['tcp','udp']:
                raise Exception("protocol value invalid")
            if self.config.subOptions['active'].lower() in ['y','true','1','yes']:
                self.config.subOptions['active'] = True
            else:
                self.config.subOptions['active'] = False
            if self.config.subOptions['remote-host'].lower() in ['""','any']:
                self.config.subOptions['remote-host'] = ''
            if self.config.subOptions['external-port'] == None:
                self.config.subOptions['external-port'] = self.config.subOptions['internal-port']

        if self.command == 'delete-mapping':
            if self.config.subOptions['remote-host'] == None:
                raise Exception("remote-host parameter missing")
            if self.config.subOptions['external-port'] == None:
                raise Exception("external-port parameter missing")
            if self.config.subOptions['protocol'].lower() not in ['tcp','udp']:
                raise Exception("protocol value invalid")

        coherence_config = {}
        coherence_config['logmode'] = 'none'

        self.control_point = ControlPoint(Coherence(coherence_config),auto_client=['InternetGatewayDevice'])
        self.control_point.connect(self.igd_found, 'Coherence.UPnP.ControlPoint.InternetGatewayDevice.detected')
        self.control_point.connect(self.igd_removed, 'Coherence.UPnP.ControlPoint.InternetGatewayDevice.removed')

        self.timeout = reactor.callLater(int(self.config['timeout']),self.stop)
        self.devices = {}

        self.reports = {'show-devices': self.show_devices,
                        'show-mappings': self.show_mappings,
                        'info': self.show_info}
Esempio n. 6
0
 def doStart(*args, **kwargs):
     if self._controlPoint:
         Log.w("already running!")
         return
     Log.i("starting now!")
     self._startPending = False
     self.coherence = Coherence({
         'logging': {
             'level':
             'warning',
             'subsystem': [{
                 'name': 'msearch',
                 'level': 'warning'
             }, {
                 'name': 'ssdp',
                 'level': 'warning'
             }]
         }
     })
     self._controlPoint = ControlPoint(
         self.coherence, auto_client=['MediaServer', 'MediaRenderer'])
     self.coherence.ctrl = self._controlPoint
     self.__mediaServerClients = {}
     self.__mediaRendererClients = {}
     self.__mediaDevices = {}
     self.__devices = []
     self._controlPoint.connect(
         self._onMediaServerDetected,
         'Coherence.UPnP.ControlPoint.MediaServer.detected')
     self._controlPoint.connect(
         self._onMediaServerRemoved,
         'Coherence.UPnP.ControlPoint.MediaServer.removed')
     self._controlPoint.connect(
         self._onMediaRendererDetected,
         'Coherence.UPnP.ControlPoint.MediaRenderer.detected')
     self._controlPoint.connect(
         self._onMediaRendererRemoved,
         'Coherence.UPnP.ControlPoint.MediaRenderer.removed')
     self._controlPoint.connect(
         self._onMediaDeviceDectected,
         'Coherence.UPnP.Device.detection_completed')
     self._controlPoint.connect(self._onMediaDeviceRemoved,
                                'Coherence.UPnP.RootDevice.removed')
     self.__deferredShutDown = None
     if self._session:
         self._callPlugins(reason=0)
Esempio n. 7
0
from twisted.internet import stdio
from twisted.internet import defer
from twisted.protocols import basic

from lxml import etree

import time, json, shutil, os

from coherence.base import Coherence
from coherence.upnp.devices.control_point import ControlPoint

logfile = None
config = {'logmode': 'none', 'logfile': logfile}
coherence = Coherence(config)

controlpoint = ControlPoint(coherence, auto_client=[])

BOOKMARKPATH = os.path.expanduser('~/.grace-bookmarks')

devices = []
unknown_devices = []

CONFPATH = os.path.join(os.path.expanduser('~'), '.graceradiorc')
DEFAULT_CONFIG = {
    # Number of lines to output from the buffer every time enter is pressed
    "buffer_rate": 20,
}

CONFIG = load_config(DEFAULT_CONFIG, CONFPATH)

Esempio n. 8
0
    def __init__(self, logfile=None):
        config = {'logmode': 'none', 'logfile': logfile}
        self.coherence = Coherence(config)
        self.controlpoint = ControlPoint(self.coherence, auto_client=[])
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.connect("delete_event", lambda x, y: reactor.stop())
        window.set_default_size(350, 700)
        window.set_title('UPnP Inspector')
        icon = resource_filename(__name__,
                                 os.path.join('icons', 'inspector-icon.png'))
        gtk.window_set_default_icon_from_file(icon)

        vbox = gtk.VBox(homogeneous=False, spacing=0)
        menu_bar = gtk.MenuBar()
        menu = gtk.Menu()
        refresh_item = gtk.MenuItem("Rediscover Devices")
        refresh_item.connect("activate", self.refresh_devices)
        menu.append(refresh_item)
        menu.append(gtk.SeparatorMenuItem())
        quit_item = gtk.MenuItem("Quit")
        menu.append(quit_item)
        quit_item.connect("activate", lambda x: reactor.stop())

        file_menu = gtk.MenuItem("File")
        file_menu.set_submenu(menu)
        menu_bar.append(file_menu)

        menu = gtk.Menu()
        self.show_details_item = gtk.CheckMenuItem("show details")
        menu.append(self.show_details_item)
        self.show_details_item.connect("activate", self.show_details_widget,
                                       "view.details")
        self.show_events_item = gtk.CheckMenuItem("show events")
        menu.append(self.show_events_item)
        self.show_events_item.connect("activate", self.show_events_widget,
                                      "view.events")
        self.show_log_item = gtk.CheckMenuItem("show global log")
        menu.append(self.show_log_item)
        self.show_log_item.connect("activate", self.show_log_widget,
                                   "view.log")
        #self.show_log_item.set_sensitive(False)
        view_menu = gtk.MenuItem("View")
        view_menu.set_submenu(menu)
        menu_bar.append(view_menu)

        test_menu = gtk.MenuItem("Test")
        test_menu.set_sensitive(False)
        #test_menu.set_submenu(menu)
        menu_bar.append(test_menu)

        menu = gtk.Menu()
        item = gtk.MenuItem("Info")
        menu.append(item)
        item.connect("activate", self.show_about_widget, "help.info")
        help_menu = gtk.MenuItem("Help")
        help_menu.set_submenu(menu)
        menu_bar.append(help_menu)

        vbox.pack_start(menu_bar, False, False, 2)

        self.device_tree = DevicesWidget(self.coherence)
        self.device_tree.cb_item_left_click = self.show_details
        vbox.pack_start(self.device_tree.window, True, True, 0)
        window.add(vbox)
        window.show_all()

        self.events_widget = EventsWidget(self.coherence)
        self.events_widget.window.connect('delete_event',
                                          self.hide_events_widget)
        self.details_widget = DetailsWidget(self.coherence)
        self.details_widget.window.connect('delete_event',
                                           self.hide_details_widget)
        self.log_widget = LogWidget(self.coherence)
        self.log_widget.window.connect('delete_event', self.hide_log_widget)
Esempio n. 9
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())
Esempio n. 10
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())