Esempio n. 1
0
    def __init__(self, options=None, daemon=True):
        """
        Setup the DelugeWeb server.

        Args:
            options (argparse.Namespace): The web server options.
            daemon (bool): If True run web server as a seperate daemon process (starts a twisted
                reactor). If False shares the process and twisted reactor from WebUI plugin or tests.

        """
        component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
        self.config = configmanager.ConfigManager('web.conf',
                                                  defaults=CONFIG_DEFAULTS,
                                                  file_version=2)
        self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
        self.config.register_set_function('language',
                                          self._on_language_changed)
        self.socket = None
        self.top_level = TopLevel()

        self.interface = self.config['interface']
        self.port = self.config['port']
        self.https = self.config['https']
        self.pkey = self.config['pkey']
        self.cert = self.config['cert']
        self.base = self.config['base']

        if options:
            self.interface = (options.interface if options.interface
                              is not None else self.interface)
            self.port = options.port if options.port else self.port
            self.base = options.base if options.base else self.base
            if options.ssl:
                self.https = True
            elif options.no_ssl:
                self.https = False

        if self.base != '/':
            # Strip away slashes and serve on the base path as well as root path
            self.top_level.putChild(self.base.strip('/'), self.top_level)

        setup_translations(setup_gettext=True, setup_pygtk=False)

        # Remove twisted version number from 'server' http-header for security reasons
        server.version = 'TwistedWeb'
        self.site = server.Site(self.top_level)
        self.web_api = WebApi()
        self.web_utils = WebUtils()

        self.auth = Auth(self.config)
        self.daemon = daemon
        # Initalize the plugins
        self.plugins = PluginManager()
Esempio n. 2
0
    def __init__(self, options=None, daemon=True):
        """
        Setup the DelugeWeb server.

        Args:
            options (argparse.Namespace): The web server options.
            daemon (bool): If True run web server as a seperate daemon process (starts a twisted
                reactor). If False shares the process and twisted reactor from WebUI plugin or tests.

        """
        component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
        self.config = configmanager.ConfigManager('web.conf', defaults=CONFIG_DEFAULTS, file_version=2)
        self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
        self.config.register_set_function('language', self._on_language_changed)
        self.socket = None
        self.top_level = TopLevel()

        self.interface = self.config['interface']
        self.port = self.config['port']
        self.https = self.config['https']
        self.pkey = self.config['pkey']
        self.cert = self.config['cert']
        self.base = self.config['base']

        if options:
            self.interface = options.interface if options.interface is not None else self.interface
            self.port = options.port if options.port else self.port
            self.base = options.base if options.base else self.base
            if options.ssl:
                self.https = True
            elif options.no_ssl:
                self.https = False

        if self.base != '/':
            # Strip away slashes and serve on the base path as well as root path
            self.top_level.putChild(self.base.strip('/'), self.top_level)

        setup_translations(setup_gettext=True, setup_pygtk=False)

        self.site = server.Site(self.top_level)
        self.web_api = WebApi()
        self.web_utils = WebUtils()

        self.auth = Auth(self.config)
        self.daemon = daemon
        # Initalize the plugins
        self.plugins = PluginManager()
Esempio n. 3
0
    def callback(value):
        if not watchdog.called and not watchdog.cancelled:
            watchdog.cancel()
        if not deferred.called:
            if message:
                print(message)
            deferred.cancel()
        return value

    deferred.addBoth(callback)
    watchdog = reactor.callLater(timeout, defer.timeout, deferred)
    return watchdog


# Initialize gettext
setup_translations()


class ReactorOverride(object):
    """Class used to patch reactor while running unit tests
    to avoid starting and stopping the twisted reactor
    """
    def __getattr__(self, attr):
        if attr == 'run':
            return self._run
        if attr == 'stop':
            return self._stop
        return getattr(reactor, attr)

    def _run(self):
        pass
Esempio n. 4
0
try:
    from gobject import TYPE_UINT64
except ImportError as err:
    libs_available = False
    TYPE_UINT64 = 'Whatever'
    import traceback
    traceback.print_exc()
else:
    libs_available = True
    from deluge.ui.gtkui.mainwindow import MainWindow  # pylint: disable=ungrouped-imports
    from deluge.ui.gtkui.menubar import MenuBar
    from deluge.ui.gtkui.torrentdetails import TorrentDetails
    from deluge.ui.gtkui.torrentview import TorrentView
    from deluge.ui.gtkui.gtkui import DEFAULT_PREFS

setup_translations()


@pytest.mark.gtkui
class TorrentviewTestCase(BaseTestCase):

    default_column_index = ['filter', 'torrent_id', 'dirty', '#',
                            'Name',
                            'Size', 'Downloaded', 'Uploaded', 'Remaining',
                            'Progress',
                            'Seeds', 'Peers', 'Seeds:Peers',
                            'Down Speed', 'Up Speed', 'Down Limit', 'Up Limit',
                            'ETA', 'Ratio', 'Avail',
                            'Added', 'Completed', 'Complete Seen',
                            'Tracker', 'Download Folder', 'Owner', 'Shared']
    default_liststore_columns = [bool, str, bool, int,
Esempio n. 5
0
File: ui.py Progetto: th841/deluge
 def __init__(self, name, **kwargs):
     self.__name = name
     self.ui_args = kwargs.pop('ui_args', None)
     setup_translations()
     self.__parser = BaseArgParser(**kwargs)
Esempio n. 6
0
    def __init__(self, args):
        # Setup gtkbuilder/glade translation
        setup_translations(setup_gettext=False, setup_pygtk=True)

        # Setup signals
        def on_die(*args):
            log.debug('OS signal "die" caught with args: %s', args)
            reactor.stop()

        if windows_check():
            from win32api import SetConsoleCtrlHandler
            SetConsoleCtrlHandler(on_die, True)
            log.debug('Win32 "die" handler registered')
        elif osx_check() and WINDOWING == 'quartz':
            import gtkosx_application
            self.osxapp = gtkosx_application.gtkosx_application_get()
            self.osxapp.connect('NSApplicationWillTerminate', on_die)
            log.debug('OSX quartz "die" handler registered')

        # Set process name again to fix gtk issue
        setproctitle(getproctitle())

        # Attempt to register a magnet URI handler with gconf, but do not overwrite
        # if already set by another program.
        associate_magnet_links(False)

        # Make sure gtkui.conf has at least the defaults set
        self.config = ConfigManager('gtkui.conf', DEFAULT_PREFS)

        # Make sure the gtkui state folder has been created
        if not os.path.exists(os.path.join(get_config_dir(), 'gtkui_state')):
            os.makedirs(os.path.join(get_config_dir(), 'gtkui_state'))

        # Set language
        if self.config['language'] is not None:
            set_language(self.config['language'])

        # Start the IPC Interface before anything else.. Just in case we are
        # already running.
        self.queuedtorrents = QueuedTorrents()
        self.ipcinterface = IPCInterface(args.torrents)

        # Initialize gdk threading
        threads_init()

        # We make sure that the UI components start once we get a core URI
        client.set_disconnect_callback(self.__on_disconnect)

        self.trackericons = TrackerIcons()
        self.sessionproxy = SessionProxy()
        # Initialize various components of the gtkui
        self.mainwindow = MainWindow()
        self.menubar = MenuBar()
        self.toolbar = ToolBar()
        self.torrentview = TorrentView()
        self.torrentdetails = TorrentDetails()
        self.sidebar = SideBar()
        self.filtertreeview = FilterTreeView()
        self.preferences = Preferences()
        self.systemtray = SystemTray()
        self.statusbar = StatusBar()
        self.addtorrentdialog = AddTorrentDialog()

        if osx_check() and WINDOWING == 'quartz':
            def nsapp_open_file(osxapp, filename):
                # Ignore command name which is raised at app launch (python opening main script).
                if filename == sys.argv[0]:
                    return True
                process_args([filename])
            self.osxapp.connect('NSApplicationOpenFile', nsapp_open_file)
            from deluge.ui.gtkui.menubar_osx import menubar_osx
            menubar_osx(self, self.osxapp)
            self.osxapp.ready()

        # Initalize the plugins
        self.plugins = PluginManager()

        # Show the connection manager
        self.connectionmanager = ConnectionManager()

        # Setup RPC stats logging
        # daemon_bps: time, bytes_sent, bytes_recv
        self.daemon_bps = (0, 0, 0)
        self.rpc_stats = LoopingCall(self.log_rpc_stats)
        self.closing = False

        # Twisted catches signals to terminate, so have it call a pre_shutdown method.
        reactor.addSystemEventTrigger('before', 'gtkui_close', self.close)

        def gtkui_sigint_handler(num, frame):
            log.debug('SIGINT signal caught, firing event: gtkui_close')
            reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close')

        signal.signal(signal.SIGINT, gtkui_sigint_handler)
Esempio n. 7
0
def start_ui():
    """Entry point for ui script"""
    setup_translations()

    # Get the registered UI entry points
    ui_entrypoints = {}
    for entrypoint in pkg_resources.iter_entry_points('deluge.ui'):
        try:
            ui_entrypoints[entrypoint.name] = entrypoint.load()
        except ImportError:
            # Unable to load entrypoint so skip adding it.
            pass

    ui_titles = sorted(ui_entrypoints)

    def add_ui_options_group(_parser):
        """Function to enable reuse of UI Options group"""
        group = _parser.add_argument_group(_('UI Options'))
        group.add_argument(
            '-s',
            '--set-default-ui',
            dest='default_ui',
            choices=ui_titles,
            help=_('Set the default UI to be run, when no UI is specified'),
        )
        return _parser

    # Setup parser with Common Options and add UI Options group.
    parser = add_ui_options_group(BaseArgParser())

    # Parse and handle common/process group options
    options = parser.parse_known_ui_args(sys.argv, withhold=AMBIGUOUS_CMD_ARGS)

    config = deluge.configmanager.ConfigManager('ui.conf', DEFAULT_PREFS)
    log = logging.getLogger(__name__)
    log.info('Deluge ui %s', deluge.common.get_version())

    if options.default_ui:
        config['default_ui'] = options.default_ui
        config.save()
        log.info('The default UI has been changed to %s', options.default_ui)
        sys.exit(0)

    default_ui = config['default_ui']
    config.save()  # Save in case config didn't already exist.
    del config

    # We have parsed and got the config dir needed to get the default UI
    # Now create a parser for choosing the UI. We reuse the ui option group for
    # parsing to succeed and the text displayed to user, but result is not used.
    parser = add_ui_options_group(BaseArgParser(common_help=True))

    # Create subparser for each registered UI. Empty title is used to remove unwanted positional text.
    subparsers = parser.add_subparsers(
        dest='selected_ui',
        metavar='{%s} [UI args]' % ','.join(ui_titles),
        title=None,
        help=
        _('Alternative UI to launch, with optional ui args \n  (default UI: *)'
          ),
    )
    for ui in ui_titles:
        parser_ui = subparsers.add_parser(
            ui,
            common_help=False,
            help=getattr(ui_entrypoints[ui], 'cmd_description', ''),
        )
        parser_ui.add_argument('ui_args', nargs=argparse.REMAINDER)
        # If the UI is set as default, indicate this in help by prefixing with a star.
        subactions = subparsers._get_subactions()
        prefix = '*' if ui == default_ui else ' '
        subactions[-1].metavar = '%s %s' % (prefix, ui)

    # Insert a default UI subcommand unless one of the ambiguous_args are specified
    parser.set_default_subparser(default_ui, abort_opts=AMBIGUOUS_CMD_ARGS)

    # Only parse known arguments to leave the UIs to show a help message if parsing fails.
    options, remaining = parser.parse_known_args()
    selected_ui = options.selected_ui
    ui_args = remaining + options.ui_args

    # Remove the UI argument before launching the UI.
    sys.argv.remove(selected_ui)

    try:
        ui = ui_entrypoints[selected_ui](
            prog='%s %s' % (os.path.basename(sys.argv[0]), selected_ui),
            ui_args=ui_args)
    except KeyError as ex:
        log.error(
            'Unable to find chosen UI: "%s". Please choose a different UI '
            'or use "--set-default-ui" to change default UI.',
            selected_ui,
        )
    except ImportError as ex:
        import traceback

        error_type, error_value, tb = sys.exc_info()
        stack = traceback.extract_tb(tb)
        last_frame = stack[-1]
        if last_frame[0] == __file__:
            log.error(
                'Unable to find chosen UI: "%s". Please choose a different UI '
                'or use "--set-default-ui" to change default UI.',
                selected_ui,
            )
        else:
            log.exception(ex)
            log.error('Encountered an error launching the request UI: %s',
                      selected_ui)
        sys.exit(1)
    else:
        ui.start()
Esempio n. 8
0
def start_ui():
    """Entry point for ui script"""
    setup_translations()

    # Get the registered UI entry points
    ui_entrypoints = {}
    for entrypoint in pkg_resources.iter_entry_points('deluge.ui'):
        try:
            ui_entrypoints[entrypoint.name] = entrypoint.load()
        except ImportError:
            # Unable to load entrypoint so skip adding it.
            pass

    ui_titles = sorted(ui_entrypoints)

    def add_ui_options_group(_parser):
        """Function to enable reuse of UI Options group"""
        group = _parser.add_argument_group(_('UI Options'))
        group.add_argument('-s', '--set-default-ui', dest='default_ui', choices=ui_titles,
                           help=_('Set the default UI to be run, when no UI is specified'))
        return _parser

    # Setup parser with Common Options and add UI Options group.
    parser = add_ui_options_group(BaseArgParser())

    # Parse and handle common/process group options
    options = parser.parse_known_ui_args(sys.argv, withhold=AMBIGUOUS_CMD_ARGS)

    config = deluge.configmanager.ConfigManager('ui.conf', DEFAULT_PREFS)
    log = logging.getLogger(__name__)
    log.info('Deluge ui %s', deluge.common.get_version())

    if options.default_ui:
        config['default_ui'] = options.default_ui
        config.save()
        log.info('The default UI has been changed to %s', options.default_ui)
        sys.exit(0)

    default_ui = config['default_ui']
    config.save()  # Save in case config didn't already exist.
    del config

    # We have parsed and got the config dir needed to get the default UI
    # Now create a parser for choosing the UI. We reuse the ui option group for
    # parsing to succeed and the text displayed to user, but result is not used.
    parser = add_ui_options_group(BaseArgParser(common_help=True))

    # Create subparser for each registered UI. Empty title is used to remove unwanted positional text.
    subparsers = parser.add_subparsers(dest='selected_ui', metavar='{%s} [UI args]' % ','.join(ui_titles), title=None,
                                       help=_('Alternative UI to launch, with optional ui args \n  (default UI: *)'))
    for ui in ui_titles:
        parser_ui = subparsers.add_parser(ui, common_help=False,
                                          help=getattr(ui_entrypoints[ui], 'cmd_description', ''))
        parser_ui.add_argument('ui_args', nargs=argparse.REMAINDER)
        # If the UI is set as default, indicate this in help by prefixing with a star.
        subactions = subparsers._get_subactions()
        prefix = '*' if ui == default_ui else ' '
        subactions[-1].dest = '%s %s' % (prefix, ui)

    # Insert a default UI subcommand unless one of the ambiguous_args are specified
    parser.set_default_subparser(default_ui, abort_opts=AMBIGUOUS_CMD_ARGS)

    # Only parse known arguments to leave the UIs to show a help message if parsing fails.
    options, remaining = parser.parse_known_args()
    selected_ui = options.selected_ui
    ui_args = remaining + options.ui_args

    # Remove the UI argument before launching the UI.
    sys.argv.remove(selected_ui)

    try:
        ui = ui_entrypoints[selected_ui](prog='%s %s' % (os.path.basename(sys.argv[0]), selected_ui), ui_args=ui_args)
    except KeyError as ex:
        log.error('Unable to find chosen UI: "%s". Please choose a different UI '
                  'or use "--set-default-ui" to change default UI.', selected_ui)
    except ImportError as ex:
        import traceback
        error_type, error_value, tb = sys.exc_info()
        stack = traceback.extract_tb(tb)
        last_frame = stack[-1]
        if last_frame[0] == __file__:
            log.error('Unable to find chosen UI: "%s". Please choose a different UI '
                      'or use "--set-default-ui" to change default UI.', selected_ui)
        else:
            log.exception(ex)
            log.error('Encountered an error launching the request UI: %s', selected_ui)
        sys.exit(1)
    else:
        ui.start()
Esempio n. 9
0
    def __init__(self, args):
        # Setup gtkbuilder/glade translation
        setup_translations(setup_gettext=False, setup_pygtk=True)

        # Setup signals
        def on_die(*args):
            log.debug('OS signal "die" caught with args: %s', args)
            reactor.stop()

        if windows_check():
            from win32api import SetConsoleCtrlHandler

            SetConsoleCtrlHandler(on_die, True)
            log.debug('Win32 "die" handler registered')
        elif osx_check() and WINDOWING == 'quartz':
            import gtkosx_application

            self.osxapp = gtkosx_application.gtkosx_application_get()
            self.osxapp.connect('NSApplicationWillTerminate', on_die)
            log.debug('OSX quartz "die" handler registered')

        # Set process name again to fix gtk issue
        setproctitle(getproctitle())

        # Attempt to register a magnet URI handler with gconf, but do not overwrite
        # if already set by another program.
        associate_magnet_links(False)

        # Make sure gtkui.conf has at least the defaults set
        self.config = ConfigManager('gtkui.conf', DEFAULT_PREFS)

        # Make sure the gtkui state folder has been created
        if not os.path.exists(os.path.join(get_config_dir(), 'gtkui_state')):
            os.makedirs(os.path.join(get_config_dir(), 'gtkui_state'))

        # Set language
        if self.config['language'] is not None:
            set_language(self.config['language'])

        # Start the IPC Interface before anything else.. Just in case we are
        # already running.
        self.queuedtorrents = QueuedTorrents()
        self.ipcinterface = IPCInterface(args.torrents)

        # Initialize gdk threading
        threads_init()

        # We make sure that the UI components start once we get a core URI
        client.set_disconnect_callback(self.__on_disconnect)

        self.trackericons = TrackerIcons()
        self.sessionproxy = SessionProxy()
        # Initialize various components of the gtkui
        self.mainwindow = MainWindow()
        self.menubar = MenuBar()
        self.toolbar = ToolBar()
        self.torrentview = TorrentView()
        self.torrentdetails = TorrentDetails()
        self.sidebar = SideBar()
        self.filtertreeview = FilterTreeView()
        self.preferences = Preferences()
        self.systemtray = SystemTray()
        self.statusbar = StatusBar()
        self.addtorrentdialog = AddTorrentDialog()

        if osx_check() and WINDOWING == 'quartz':

            def nsapp_open_file(osxapp, filename):
                # Ignore command name which is raised at app launch (python opening main script).
                if filename == sys.argv[0]:
                    return True
                process_args([filename])

            self.osxapp.connect('NSApplicationOpenFile', nsapp_open_file)
            from deluge.ui.gtkui.menubar_osx import menubar_osx

            menubar_osx(self, self.osxapp)
            self.osxapp.ready()

        # Initalize the plugins
        self.plugins = PluginManager()

        # Show the connection manager
        self.connectionmanager = ConnectionManager()

        # Setup RPC stats logging
        # daemon_bps: time, bytes_sent, bytes_recv
        self.daemon_bps = (0, 0, 0)
        self.rpc_stats = LoopingCall(self.log_rpc_stats)
        self.closing = False

        # Twisted catches signals to terminate, so have it call a pre_shutdown method.
        reactor.addSystemEventTrigger('before', 'gtkui_close', self.close)

        def gtkui_sigint_handler(num, frame):
            log.debug('SIGINT signal caught, firing event: gtkui_close')
            reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close')

        signal.signal(signal.SIGINT, gtkui_sigint_handler)
Esempio n. 10
0
 def setUp(self):  # NOQA
     self.config_dir = set_tmp_config_dir()
     setup_translations()
Esempio n. 11
0
 def setUp(self):  # NOQA
     self.config_dir = set_tmp_config_dir()
     setup_translations()