From 53228f9d15ff5fdb2e1146bc757ef7105ad44e60 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 |  269 ++++++++++++++++++++++++++++++++++
 1 files changed, 269 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..1f0debd
--- /dev/null
+++ b/deluge/ui/console/commands/manage.py
@@ -0,0 +1,269 @@
+#
+# 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 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, "Makes torrent obey deluge's queue settings.  (see FAQ for details)."],
+    #'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 allow this torrent to use for uploading.'],
+    '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.\nNOTE: Only has effect if the torrent contains a single file.'], # Only has effect if torrent contains a single file.  Can only be set, not cleared.
+
+    # 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
+
+
+def layout_option_help(opt, text):
+    base_indent = 7
+    hanging_indent = 15
+    offset_indent = 20 - len(opt)
+    split_text = ('\n' + ' ' * hanging_indent).join(text.split('\n'))
+    if offset_indent > 0:
+        split_text = ' ' * offset_indent + split_text
+    else:
+        split_text = '\n' + ' ' * hanging_indent + split_text
+    return ' ' * base_indent + opt + ': ' + split_text
+
+class Command(BaseCommand):
+    """Show and set per-torrent options"""
+
+    option_help = [ layout_option_help(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>
+
+       The torrent-id * (a single asterisk) means "all loaded torrents".
+       The value -1 means unlimited (for max_connections, max_download_speed, max_upload_slots and max_upload_speed).
+
+Available keys:
+''' + '\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_prioritize_first_last_pieces(self, torrent_ids, val):
+
+        def on_option_set(status):
+            self.console.write('{!success!}Torrent option successfully updated.')
+
+        def on_set_option_failed(reason):
+            self.console.write("{!error!}Error setting torrent option: %s" % reason)
+
+        def on_got_info(status):
+            single_ids = []
+            multi_ids = []
+            error_ids = []
+            for tid in torrent_ids:
+                if tid not in status:
+                    error_ids.append(tid)
+                elif len(status[tid]['files']) > 1:
+                    multi_ids.append(tid)
+                else:
+                    single_ids.append(tid)
+            if multi_ids:
+                torrent_names = [ self.console.get_torrent_name(tid) for tid in multi_ids ]
+                self.console.write('{!error!}Not setting prioritize_first_last_pieces to ' + str(val) +
+                                   ' (multiple files in torrent) for torrents: ' + ', '.join(torrent_names))
+            if error_ids:
+                torrent_names = [ self.console.get_torrent_name(tid) for tid in error_ids ]
+                self.console.write('{!error!}Will try to set prioritize_first_last_pieces to  ' + str(val) +
+                                   ', but may fail silently for torrents: ' + ', '.join(torrent_names))
+
+            use_ids = single_ids + error_ids
+            if use_ids:
+                torrent_names = [ self.console.get_torrent_name(tid) for tid in single_ids ]
+                self.console.write('{!info!}Setting prioritize_first_last_pieces to %s for torrent(s): %s' % (val, ', '.join(torrent_names)))
+                d = client.core.set_torrent_options(use_ids, {'prioritize_first_last_pieces': val})
+                d.addCallback(on_option_set)
+                d.addErrback(on_set_option_failed)
+            else:
+                self.console.write('{!error!}No valid torrents to set prioritize_first_last_pieces on')
+
+        def on_info_failed(reason):
+            self.console.write("{!error!}Error getting torrent info (for setting prioritize_last_first_pieces): %s" % reason)
+
+        d = client.core.get_torrents_status({"id": torrent_ids}, [ "files" ])
+        d.addCallback(on_got_info)
+        d.addErrback(on_info_failed)
+
+    def _set_option(self, *args, **options):
+        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)
+
+        if key == 'prioritize_first_last_pieces':
+            self._set_prioritize_first_last_pieces(torrent_ids, val)
+            return
+
+        def on_option_set(result):
+            self.console.write('{!success!}Torrent option successfully updated.')
+
+        def on_set_option_failed(reason):
+            self.console.write("{!error!}Error setting torrent option: %s" % reason)
+
+        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)))
+        d = client.core.set_torrent_options(torrent_ids, {key: val})
+        d.addCallback(on_option_set)
+        d.addErrback(on_set_option_failed)
+
+    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

