예제 #1
0
파일: core.py 프로젝트: muzena/autoshutdown
    def enable(self):
        log.debug("[AutoShutDown] Enabling plugin...")
        if osx_check():
            log.error("[AutoShutDown] OSX not currently supported")
            #Using subprocess could call osascript
            #subprocess.call(['osascript', '-e', 'tell app "System Events" to shut down'])
            self.disable()

        if not windows_check():
            self.bus_name = UPOWER
            bus_path = UPOWER_PATH
            try:
                bus = dbus.SystemBus()
                self.bus_obj = bus.get_object(self.bus_name, bus_path)
            except:
                log.debug("[AutoShutDown] Fallback to older dbus PowerManagement")
                self.bus_name = POWERMAN
                bus_path = POWERMAN_PATH
                bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
                self.bus_obj = bus.get_object(self.bus_name, bus_path)

            self.bus_iface = dbus.Interface(self.bus_obj, self.bus_name)
            self.bus_iface_props = dbus.Interface(self.bus_obj, 'org.freedesktop.DBus.Properties')

        self.config = deluge.configmanager.ConfigManager("autoshutdown.conf", DEFAULT_PREFS)
        self.check_suspend_hibernate_flags()

        component.get("EventManager").register_event_handler("TorrentFinishedEvent", self.on_event_torrent_finished)
예제 #2
0
    def enable(self):
        log.debug("[AutoShutDown] Enabling plugin...")
        if osx_check():
            log.error("[AutoShutDown] OSX not currently supported")
            #Using subprocess could call osascript
            #subprocess.call(['osascript', '-e', 'tell app "System Events" to shut down'])
            self.disable()

        if not windows_check():
            try:
                bus = dbus.SystemBus()
                try:
                    self.bus_name = LOGIN1
                    self.bus_obj = bus.get_object(self.bus_name, LOGIN1_PATH)
                    self.bus_iface = dbus.Interface(self.bus_obj,
                                                    self.bus_name + '.Manager')
                except DBusException:
                    self.bus_name = UPOWER
                    self.bus_obj = bus.get_object(self.bus_name, UPOWER_PATH)
                    self.bus_iface = dbus.Interface(self.bus_obj,
                                                    self.bus_name)
            except:
                log.debug(
                    "[AutoShutDown] Fallback to older dbus PowerManagement")
                bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
                self.bus_name = POWERMAN
                self.bus_obj = bus.get_object(self.bus_name, POWERMAN_PATH)
                self.bus_iface = dbus.Interface(self.bus_obj, self.bus_name)

        self.config = deluge.configmanager.ConfigManager(
            "autoshutdown.conf", DEFAULT_PREFS)
        self.check_suspend_hibernate_flags()

        component.get("EventManager").register_event_handler(
            "TorrentFinishedEvent", self.on_event_torrent_finished)
예제 #3
0
    def on_tray_popup(self, status_icon, button, activate_time):
        """Called when the tray icon is right clicked."""
        self.blink(False)

        if self.mainwindow.visible():
            self.builder.get_object('menuitem_show_deluge').set_active(True)
        else:
            self.builder.get_object('menuitem_show_deluge').set_active(False)

        popup_function = status_icon_position_menu
        if windows_check() or osx_check():
            popup_function = None
            button = 0
        self.tray_menu.popup(None, None, popup_function, button, activate_time, status_icon)
예제 #4
0
파일: systemtray.py 프로젝트: zluca/deluge
    def on_tray_popup(self, status_icon, button, activate_time):
        """Called when the tray icon is right clicked."""
        self.blink(False)

        if self.mainwindow.visible():
            self.builder.get_object('menuitem_show_deluge').set_active(True)
        else:
            self.builder.get_object('menuitem_show_deluge').set_active(False)

        popup_function = StatusIcon.position_menu
        if windows_check() or osx_check():
            popup_function = None
            button = 0
        self.tray_menu.popup(None, None, popup_function, status_icon, button,
                             activate_time)
예제 #5
0
파일: common.py 프로젝트: newfyle/deluge
def associate_magnet_links(overwrite=False):
    """
    Associates magnet links to Deluge.

    Params:
        overwrite (bool): if this is True, the current setting will be overwritten

    Returns:
        bool: True if association was set
    """

    if windows_check():
        try:
            import winreg
        except ImportError:
            import _winreg as winreg  # For Python 2.

        try:
            hkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, 'Magnet')
        except WindowsError:
            overwrite = True
        else:
            winreg.CloseKey(hkey)

        if overwrite:
            deluge_exe = os.path.join(os.path.dirname(sys.executable),
                                      'deluge.exe')
            try:
                magnet_key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT,
                                              'Magnet')
            except WindowsError:
                # Could not create for all users, falling back to current user
                magnet_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER,
                                              'Software\\Classes\\Magnet')

            winreg.SetValue(magnet_key, '', winreg.REG_SZ,
                            'URL:Magnet Protocol')
            winreg.SetValueEx(magnet_key, 'URL Protocol', 0, winreg.REG_SZ, '')
            winreg.SetValueEx(magnet_key, 'BrowserFlags', 0, winreg.REG_DWORD,
                              0x8)
            winreg.SetValue(magnet_key, 'DefaultIcon', winreg.REG_SZ,
                            '{},0'.format(deluge_exe))
            winreg.SetValue(
                magnet_key,
                r'shell\open\command',
                winreg.REG_SZ,
                '"{}" "%1"'.format(deluge_exe),
            )
            winreg.CloseKey(magnet_key)

    # Don't try associate magnet on OSX see: #2420
    elif not osx_check():
        # gconf method is only available in a GNOME environment
        try:
            import gconf
        except ImportError:
            log.debug(
                'gconf not available, so will not attempt to register magnet uri handler'
            )
            return False
        else:
            key = '/desktop/gnome/url-handlers/magnet/command'
            gconf_client = gconf.client_get_default()
            if (gconf_client.get(key)
                    and overwrite) or not gconf_client.get(key):
                # We are either going to overwrite the key, or do it if it hasn't been set yet
                if gconf_client.set_string(key, 'deluge "%s"'):
                    gconf_client.set_bool(
                        '/desktop/gnome/url-handlers/magnet/needs_terminal',
                        False)
                    gconf_client.set_bool(
                        '/desktop/gnome/url-handlers/magnet/enabled', True)
                    log.info(
                        'Deluge registered as default magnet uri handler!')
                    return True
                else:
                    log.error(
                        'Unable to register Deluge as default magnet uri handler.'
                    )
                    return False
    return False
예제 #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)
예제 #7
0
파일: systemtray.py 프로젝트: zluca/deluge
    def enable(self):
        """Enables the system tray icon."""
        self.builder = Builder()
        self.builder.add_from_file(
            resource_filename(__package__,
                              os.path.join('glade', 'tray_menu.ui')))

        self.builder.connect_signals(self)

        self.tray_menu = self.builder.get_object('tray_menu')

        if AppIndicator3 and self.config['enable_appindicator']:
            log.debug('Enabling the Application Indicator...')
            self.indicator = AppIndicator3.Indicator.new(
                'deluge',
                'deluge-panel',
                AppIndicator3.IndicatorCategory.APPLICATION_STATUS,
            )
            self.indicator.set_property('title', _('Deluge'))

            # Pass the menu to the Application Indicator
            self.indicator.set_menu(self.tray_menu)

            # Make sure the status of the Show Window MenuItem is correct
            self._sig_win_hide = self.mainwindow.window.connect(
                'hide', self._on_window_hide)
            self._sig_win_show = self.mainwindow.window.connect(
                'show', self._on_window_show)
            if self.mainwindow.visible():
                self.builder.get_object('menuitem_show_deluge').set_active(
                    True)
            else:
                self.builder.get_object('menuitem_show_deluge').set_active(
                    False)

            # Show the Application Indicator
            self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)

        else:
            log.debug('Enabling the system tray icon..')
            if windows_check() or osx_check():
                self.tray = StatusIcon.new_from_pixbuf(get_logo(32))
            else:
                self.tray = StatusIcon.new_from_icon_name('deluge-panel')

            self.tray.connect('activate', self.on_tray_clicked)
            self.tray.connect('popup-menu', self.on_tray_popup)

        self.builder.get_object('download-limit-image').set_from_file(
            get_pixmap('downloading16.png'))
        self.builder.get_object('upload-limit-image').set_from_file(
            get_pixmap('seeding16.png'))

        client.register_event_handler('ConfigValueChangedEvent',
                                      self.config_value_changed)
        if client.connected():
            # We're connected so we need to get some values from the core
            self.__start()
        else:
            # Hide menu widgets because we're not connected to a host.
            for widget in self.hide_widget_list:
                self.builder.get_object(widget).hide()
예제 #8
0
파일: gtkui.py 프로젝트: newfyle/deluge
    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)
예제 #9
0
파일: core.py 프로젝트: muzena/autoshutdown
#

from deluge.log import LOG as log
from deluge.plugins.pluginbase import CorePluginBase
import deluge.component as component
import deluge.configmanager
from deluge.core.rpcserver import export
from deluge.common import windows_check, osx_check

if windows_check():
    import thread
    import ctypes
    from win32security import OpenProcessToken, LookupPrivilegeValue, AdjustTokenPrivileges
    from win32api import InitiateSystemShutdown, GetCurrentProcess, GetPwrCapabilities
    from ntsecuritycon import TOKEN_ADJUST_PRIVILEGES, TOKEN_QUERY, SE_SHUTDOWN_NAME, SE_PRIVILEGE_ENABLED
elif osx_check():
    #import subprocess
    pass
else:
    import dbus
    # Freedesktop Constants
    UPOWER = "org.freedesktop.UPower"
    UPOWER_PATH = "/org/freedesktop/UPower"
    POWERMAN = 'org.freedesktop.PowerManagement'
    POWERMAN_PATH = '/org/freedesktop/PowerManagement'

DEFAULT_PREFS = {
    "enabled"           : True,
    "system_state"      : None,
    "can_hibernate"     : False,
    "can_suspend"       : False
예제 #10
0
import deluge.component as component
import deluge.configmanager
from deluge.core.rpcserver import export
from deluge.common import windows_check, osx_check

if windows_check():
    import thread
    import ctypes
    from win32security import OpenProcessToken, LookupPrivilegeValue, AdjustTokenPrivileges
    from win32api import InitiateSystemShutdown, GetCurrentProcess, GetPwrCapabilities
    # Negate need for ntsecuritycon import
    TOKEN_QUERY = 8
    TOKEN_ADJUST_PRIVILEGES = 32
    SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
    SE_PRIVILEGE_ENABLED = 2
elif osx_check():
    #import subprocess
    pass
else:
    import dbus
    # Freedesktop Constants
    UPOWER = "org.freedesktop.UPower"
    UPOWER_PATH = "/org/freedesktop/UPower"
    POWERMAN = 'org.freedesktop.PowerManagement'
    POWERMAN_PATH = '/org/freedesktop/PowerManagement'
    LOGIN1 = "org.freedesktop.login1"
    LOGIN1_PATH = "/org/freedesktop/login1"

DEFAULT_PREFS = {
    "enabled": True,
    "system_state": None,
예제 #11
0
def associate_magnet_links(overwrite=False):
    """
    Associates magnet links to Deluge.

    Params:
        overwrite (bool): if this is True, the current setting will be overwritten

    Returns:
        bool: True if association was set
    """

    if windows_check():
        try:
            import winreg
        except ImportError:
            import _winreg as winreg  # For Python 2.

        try:
            hkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, 'Magnet')
        except WindowsError:
            overwrite = True
        else:
            winreg.CloseKey(hkey)

        if overwrite:
            deluge_exe = os.path.join(os.path.dirname(sys.executable), 'deluge.exe')
            try:
                magnet_key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, 'Magnet')
            except WindowsError:
                # Could not create for all users, falling back to current user
                magnet_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, 'Software\\Classes\\Magnet')

            winreg.SetValue(magnet_key, '', winreg.REG_SZ, 'URL:Magnet Protocol')
            winreg.SetValueEx(magnet_key, 'URL Protocol', 0, winreg.REG_SZ, '')
            winreg.SetValueEx(magnet_key, 'BrowserFlags', 0, winreg.REG_DWORD, 0x8)
            winreg.SetValue(magnet_key, 'DefaultIcon', winreg.REG_SZ, '{},0'.format(deluge_exe))
            winreg.SetValue(magnet_key, r'shell\open\command', winreg.REG_SZ, '"{}" "%1"'.format(deluge_exe))
            winreg.CloseKey(magnet_key)

    # Don't try associate magnet on OSX see: #2420
    elif not osx_check():
        # gconf method is only available in a GNOME environment
        try:
            import gconf
        except ImportError:
            log.debug('gconf not available, so will not attempt to register magnet uri handler')
            return False
        else:
            key = '/desktop/gnome/url-handlers/magnet/command'
            gconf_client = gconf.client_get_default()
            if (gconf_client.get(key) and overwrite) or not gconf_client.get(key):
                # We are either going to overwrite the key, or do it if it hasn't been set yet
                if gconf_client.set_string(key, 'deluge "%s"'):
                    gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/needs_terminal', False)
                    gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/enabled', True)
                    log.info('Deluge registered as default magnet uri handler!')
                    return True
                else:
                    log.error('Unable to register Deluge as default magnet uri handler.')
                    return False
    return False