Ejemplo n.º 1
0
def enabled_plugins(started_deluge_client):
    started_deluge_client.core.set_config({"pre_allocate_storage": True})
    pytest_twisted.blockon(started_deluge_client.core.enable_plugin("Label"))
    pytest_twisted.blockon(
        started_deluge_client.core.enable_plugin("Waterwheel"))
    setup_translation()

    yield

    label_plugin = component.get("CorePlugin.Label")
    for label in label_plugin.get_labels():
        label_plugin.remove(label)
Ejemplo 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 separate 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_translation()

        # 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
        # Initialize the plugins
        self.plugins = PluginManager()
Ejemplo n.º 3
0
def start_ui():
    """Entry point for ui script"""
    setup_translation()

    # 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(ArgParserBase())

    # 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(ArgParserBase(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:
        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()
Ejemplo n.º 4
0
try:
    # pylint: disable=ungrouped-imports
    from gi.repository.GObject import TYPE_UINT64

    from deluge.ui.gtk3.gtkui import DEFAULT_PREFS
    from deluge.ui.gtk3.mainwindow import MainWindow
    from deluge.ui.gtk3.menubar import MenuBar
    from deluge.ui.gtk3.torrentdetails import TorrentDetails
    from deluge.ui.gtk3.torrentview import TorrentView
except (ImportError, ValueError):
    libs_available = False
    TYPE_UINT64 = 'Whatever'
else:
    libs_available = True

setup_translation()


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

    default_column_index = [
        'filter',
        'torrent_id',
        'dirty',
        '#',
        'Name',
        'Size',
        'Downloaded',
        'Uploaded',
        'Remaining',
Ejemplo n.º 5
0
 def setUp(self):  # NOQA
     self.config_dir = set_tmp_config_dir()
     setup_translation()
Ejemplo n.º 6
0
Archivo: ui.py Proyecto: zluca/deluge
 def __init__(self, name, **kwargs):
     self.__name = name
     self.ui_args = kwargs.pop('ui_args', None)
     setup_translation()
     self.__parser = ArgParserBase(**kwargs)
Ejemplo n.º 7
0
    def __init__(self, args):
        # Setup gtkbuilder/glade translation
        setup_translation()
        Builder().set_translation_domain(I18N_DOMAIN)

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

        self.osxapp = None
        if windows_check():
            from win32api import SetConsoleCtrlHandler

            SetConsoleCtrlHandler(on_die, True)
            log.debug('Win32 "die" handler registered')
        elif osx_check() and windowing('quartz'):
            try:
                import gtkosx_application
            except ImportError:
                pass
            else:
                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 gtk3ui.conf has at least the defaults set
        self.config = ConfigManager('gtk3ui.conf', DEFAULT_PREFS)

        # Make sure the gtkui state folder has been created
        if not os.path.exists(os.path.join(get_config_dir(), 'gtk3ui_state')):
            os.makedirs(os.path.join(get_config_dir(), 'gtk3ui_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)

        # 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 self.osxapp:

            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 .menubar_osx import menubar_osx

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

        # Initialize 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)