From e071382a7024e170fd4996f8e7ca6fa278d86176 Mon Sep 17 00:00:00 2001
From: Eirik Byrkjeflot Anonsen <eirik@eirikba.org>
Date: Thu, 19 May 2011 21:19:13 +0200
Subject: [PATCH] Implement console command for displaying and setting per-torrent options.

---
 deluge/ui/console/commands/manage.py |  208 ++++++++++++++++++++++++++++++++++
 1 files changed, 208 insertions(+), 0 deletions(-)
 create mode 100644 deluge/ui/console/commands/manage.py

diff --git a/deluge/ui/console/commands/manage.py b/deluge/ui/console/commands/manage.py
new file mode 100644
index 0000000..6e7bbfc
--- /dev/null
+++ b/deluge/ui/console/commands/manage.py
@@ -0,0 +1,208 @@
+#
+# manage.py
+#
+# Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com>
+# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
+#
+# Deluge is free software.
+#
+# You may redistribute it and/or modify it under the terms of the
+# GNU General Public License, as published by the Free Software
+# Foundation; either version 3 of the License, or (at your option)
+# any later version.
+#
+# deluge is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with deluge.    If not, write to:
+# 	The Free Software Foundation, Inc.,
+# 	51 Franklin Street, Fifth Floor
+# 	Boston, MA  02110-1301, USA.
+#
+#    In addition, as a special exception, the copyright holders give
+#    permission to link the code of portions of this program with the OpenSSL
+#    library.
+#    You must obey the GNU General Public License in all respects for all of
+#    the code used other than OpenSSL. If you modify file(s) with this
+#    exception, you may extend this exception to your version of the file(s),
+#    but you are not obligated to do so. If you do not wish to do so, delete
+#    this exception statement from your version. If you delete this exception
+#    statement from all source files in the program, then also delete it here.
+#
+#
+
+from twisted.internet import defer
+
+from deluge.ui.console.main import BaseCommand
+import deluge.ui.console.colors as colors
+from deluge.ui.client import client
+import deluge.component as component
+from deluge.log import LOG as log
+
+from optparse import make_option
+
+
+# torrent.py's Torrent.get_status() renames some of the options.
+# This maps the getter names to the setter names
+get_torrent_options = {
+    'max_download_speed': 'max_download_speed',
+    'max_upload_speed': 'max_upload_speed',
+    'max_connections': 'max_connections',
+    'max_upload_slots': 'max_upload_slots',
+    'prioritize_first_last': 'prioritize_first_last_pieces',
+    'is_auto_managed': 'auto_managed',
+    'stop_at_ratio': 'stop_at_ratio',
+    'stop_ratio': 'stop_ratio',
+    'remove_at_ratio': 'remove_at_ratio',
+    'move_on_completed': 'move_completed',
+    'move_on_completed_path': 'move_completed_path',
+    #'file_priorities': 'file_priorities',
+    #'compact': 'compact_allocation',
+    #'save_path': 'download_location'
+    }
+
+# These are the things that can be set, as far as I can tell.  The
+# ones that aren't commented out are the ones that look like they
+# probably will behave as expected if set.
+#
+# Each value is [ type, getter name, help text ]
+set_torrent_options = {
+    # These are handled by torrent.py's Torrent.set_options()
+    'auto_managed': [bool, None, '(Actually, I do not know what this does)'],
+    #'download_location': str, # Probably not useful to set
+    #'file_priorities': ???, # Not a simple value to set, probably needs its own command
+    'max_connections': [int, None, 'Maximum number of connections to use for this torrent'],
+    'max_download_speed': [float, None, 'Maximum total download speed to allow this torrent to use (KiB/s)'],
+    'max_upload_slots': [int, None, 'Maximum number of connections to use for uploading for this torrent'],
+    'max_upload_speed': [float, None, 'Maximum total upload speed to allow this torrent to use (KiB/s)'],
+    'prioritize_first_last_pieces': [bool, None, 'Whether to download the first and last piece of the torrent first.  NOTE: Only has effect if the torrent contains a single file'], # Only has effect if torrent contains a single file
+
+    # These are "handled" by being set directly on the options dict
+    'stop_at_ratio': [bool, None, 'Whether to stop seeding when share ratio reaches "stop_ratio".'],
+    'stop_ratio': [float, None, 'The ratio at which to stop seeding (if "stop_at_ratio" is True)'],
+    'remove_at_ratio': [bool, None, 'Whether to remove torrent when share ratio reaches "stop_ratio".'],
+    'move_completed': [bool, None, 'Whether to move the downloaded data when downloading is complete.'],
+    'move_completed_path': [str, None, 'Where to move completed data to (if "move_completed" is True)'],
+
+    #'compact_allocation': bool, # Unclear what setting this would do
+    #'add_paused': ???, # Not returned by get_status, unclear what setting it would do
+    #'mapped_files': ??? # Not returned by get_status, unclear what setting it would do
+    }
+for k,v in get_torrent_options.items():
+    set_torrent_options[v][1] = k
+
+
+class Command(BaseCommand):
+    """Show and set per-torrent options"""
+
+    option_help = [ ' ' * 7 + k + ':  ' + v[2] for k,v in set_torrent_options.items() ]
+    option_help.sort()
+
+    option_list = BaseCommand.option_list + (
+            make_option('-s', '--set', action='store', nargs=2, dest='set',
+                        help='set value for key'),
+    )
+    usage = '''Usage: manage <torrent-id> [<torrent-id> ...] [<key1> [<key2> ...]]
+       manage <torrent-id> [<torrent-id> ...] --set <key> <value>
+
+       torrent-id can be "*" to signify "all torrents"
+
+Possible options that this command can display or show:
+''' + '\n'.join(option_help)
+
+
+    def handle(self, *args, **options):
+        self.console = component.get('ConsoleUI')
+        if options['set']:
+            return self._set_option(*args, **options)
+        else:
+            return self._get_option(*args, **options)
+
+
+    def _get_option(self, *args, **options):
+
+        def on_torrents_status(status):
+            for torrentid, data in status.items():
+                self.console.write('\n')
+                if 'name' in data:
+                    self.console.write('{!info!}Name: {!input!}%s' % data.get('name'))
+                self.console.write('{!info!}ID: {!input!}%s' % torrentid)
+                for k, v in data.items():
+                    if k != 'name':
+                        displayname = get_torrent_options.get(k, '???' + k)
+                        self.console.write('{!info!}%s: {!input!}%s' % (displayname, v))
+
+        def on_torrents_status_fail(reason):
+            self.console.write('{!error!}Failed to get torrent data.')
+
+        torrent_ids = []
+        request_options = []
+
+        for arg in args:
+            if arg in set_torrent_options:
+                request_options.append(set_torrent_options[arg][1])
+            else:
+                if arg == '*':
+                    ids = self.console.match_torrent('')
+                else:
+                    ids = self.console.match_torrent(arg)
+                if not ids:
+                    self.console.write("{!error!}The argument '" + arg + "' is not a recognized option nor did it match any torrents")
+                    return
+                torrent_ids.extend(ids)
+
+        if not torrent_ids:
+            self.console.write('{!error!}No torrents mentioned.  To request info on all torrents use "manage * [<key>...]".')
+            return
+
+        if not request_options:
+            request_options = [ opt for opt in get_torrent_options ]
+        request_options.append('name')
+
+        d = client.core.get_torrents_status({'id': torrent_ids}, request_options)
+        d.addCallback(on_torrents_status)
+        d.addErrback(on_torrents_status_fail)
+        return d
+
+
+    def _set_option(self, *args, **options):
+        deferred = defer.Deferred()
+        torrent_ids = []
+        for arg in args:
+            if arg == '*':
+                ids = self.console.match_torrent('')
+            else:
+                ids = self.console.match_torrent(arg)
+            if not ids:
+                self.console.write("{!error!}The argument '" + arg + "' did not match any torrents")
+                return
+            torrent_ids.extend(ids)
+        if not torrent_ids:
+            self.console.write('{!error!}No torrents mentioned.')
+            return
+        key = options['set'][0]
+        val = options['set'][1]
+
+        if key not in set_torrent_options:
+            self.console.write("{!error!}The key '%s' is invalid!" % key)
+            return
+
+        val = set_torrent_options[key][0](val)
+
+        def on_set_config(result):
+            self.console.write('{!success!}Torrent option successfully updated.')
+            deferred.callback(True)
+
+        torrent_names = [ self.console.get_torrent_name(tid) for tid in torrent_ids ]
+        self.console.write('{!info!}Setting %s to %s for torrent(s): %s' % (key, val, ', '.join(torrent_names)))
+        client.core.set_torrent_options(torrent_ids, {key: val}).addCallback(on_set_config)
+        return deferred
+
+    def complete(self, text):
+        torrents = component.get('ConsoleUI').tab_complete_torrent(text)
+        options = [ x for x in set_torrent_options if x.startswith(text) ]
+        # This should probably only return options immediately after --set.
+        return torrents + options
-- 
1.7.2.5

