diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2023-02-19 15:05:49 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2023-02-19 15:05:49 +0000 |
commit | d395bd510fa4f4376dc5237ab2f8d190a920d35d (patch) | |
tree | 3e3b16b44064938be801aede14381562bae14f6a /deluge/ui/console | |
parent | Adding upstream version 2.0.3. (diff) | |
download | deluge-a442edfa553d906131bfbb00a015adb3f52719d7.tar.xz deluge-a442edfa553d906131bfbb00a015adb3f52719d7.zip |
Adding upstream version 2.1.1.upstream/2.1.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'deluge/ui/console')
56 files changed, 263 insertions, 462 deletions
diff --git a/deluge/ui/console/__init__.py b/deluge/ui/console/__init__.py index 56e8d62..7da04a6 100644 --- a/deluge/ui/console/__init__.py +++ b/deluge/ui/console/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - from deluge.ui.console.console import Console UI_PATH = __path__[0] @@ -16,4 +13,4 @@ UI_PATH = __path__[0] def start(): - Console().start() + return Console().start() diff --git a/deluge/ui/console/cmdline/command.py b/deluge/ui/console/cmdline/command.py index 2ff32df..40edd78 100644 --- a/deluge/ui/console/cmdline/command.py +++ b/deluge/ui/console/cmdline/command.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -9,8 +8,6 @@ # See LICENSE for more details. # -from __future__ import print_function, unicode_literals - import logging import shlex @@ -23,7 +20,7 @@ from deluge.ui.console.utils.colors import strip_colors log = logging.getLogger(__name__) -class Commander(object): +class Commander: def __init__(self, cmds, interactive=False): self._commands = cmds self.interactive = interactive @@ -144,7 +141,7 @@ class Commander(object): return ret -class BaseCommand(object): +class BaseCommand: usage = None interactive_only = False diff --git a/deluge/ui/console/cmdline/commands/__init__.py b/deluge/ui/console/cmdline/commands/__init__.py index 628fae5..39dbefe 100644 --- a/deluge/ui/console/cmdline/commands/__init__.py +++ b/deluge/ui/console/cmdline/commands/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - from deluge.ui.console.cmdline.command import BaseCommand __all__ = ['BaseCommand'] diff --git a/deluge/ui/console/cmdline/commands/add.py b/deluge/ui/console/cmdline/commands/add.py index 34881d8..706ae16 100644 --- a/deluge/ui/console/cmdline/commands/add.py +++ b/deluge/ui/console/cmdline/commands/add.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,10 +7,10 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import os from base64 import b64encode +from urllib.parse import urlparse +from urllib.request import url2pathname from twisted.internet import defer @@ -21,14 +20,6 @@ from deluge.ui.client import client from . import BaseCommand -try: - from urllib.parse import urlparse - from urllib.request import url2pathname -except ImportError: - # PY2 fallback - from urlparse import urlparse # pylint: disable=ungrouped-imports - from urllib import url2pathname # pylint: disable=ungrouped-imports - class Command(BaseCommand): """Add torrents""" @@ -81,7 +72,7 @@ class Command(BaseCommand): continue if deluge.common.is_url(torrent): self.console.write( - '{!info!}Attempting to add torrent from url: %s' % torrent + '{!info!}Attempting to add torrent from URL: %s' % torrent ) deferreds.append( client.core.add_torrent_url(torrent, t_options) @@ -90,7 +81,7 @@ class Command(BaseCommand): ) elif deluge.common.is_magnet(torrent): self.console.write( - '{!info!}Attempting to add torrent from magnet uri: %s' % torrent + '{!info!}Attempting to add torrent from magnet URI: %s' % torrent ) deferreds.append( client.core.add_torrent_magnet(torrent, t_options) diff --git a/deluge/ui/console/cmdline/commands/cache.py b/deluge/ui/console/cmdline/commands/cache.py index e427f08..fe6cd58 100644 --- a/deluge/ui/console/cmdline/commands/cache.py +++ b/deluge/ui/console/cmdline/commands/cache.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component from deluge.ui.client import client from deluge.ui.common import DISK_CACHE_KEYS @@ -24,7 +21,7 @@ class Command(BaseCommand): def on_cache_status(status): for key, value in sorted(status.items()): - self.console.write('{!info!}%s: {!input!}%s' % (key, value)) + self.console.write(f'{{!info!}}{key}: {{!input!}}{value}') return client.core.get_session_status(DISK_CACHE_KEYS).addCallback( on_cache_status diff --git a/deluge/ui/console/cmdline/commands/config.py b/deluge/ui/console/cmdline/commands/config.py index bd0a1e1..8b31ca3 100644 --- a/deluge/ui/console/cmdline/commands/config.py +++ b/deluge/ui/console/cmdline/commands/config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,11 +7,9 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - +import json import logging -import tokenize -from io import StringIO +import re import deluge.component as component import deluge.ui.console.utils.colors as colors @@ -23,54 +20,25 @@ from . import BaseCommand log = logging.getLogger(__name__) -def atom(src, token): - """taken with slight modifications from http://effbot.org/zone/simple-iterator-parser.htm""" - if token[1] == '(': - out = [] - token = next(src) - while token[1] != ')': - out.append(atom(src, token)) - token = next(src) - if token[1] == ',': - token = next(src) - return tuple(out) - elif token[0] is tokenize.NUMBER or token[1] == '-': - try: - if token[1] == '-': - return int(token[-1], 0) - else: - if token[1].startswith('0x'): - # Hex number so return unconverted as string. - return token[1].decode('string-escape') - else: - return int(token[1], 0) - except ValueError: - try: - return float(token[-1]) - except ValueError: - return str(token[-1]) - elif token[1].lower() == 'true': - return True - elif token[1].lower() == 'false': - return False - elif token[0] is tokenize.STRING or token[1] == '/': - return token[-1].decode('string-escape') - elif token[1].isalpha(): - # Parse Windows paths e.g. 'C:\\xyz' or 'C:/xyz'. - if next()[1] == ':' and next()[1] in '\\/': - return token[-1].decode('string-escape') - - raise SyntaxError('malformed expression (%s)' % token[1]) - - -def simple_eval(source): - """ evaluates the 'source' string into a combination of primitive python objects - taken from http://effbot.org/zone/simple-iterator-parser.htm""" - src = StringIO(source).readline - src = tokenize.generate_tokens(src) - src = (token for token in src if token[0] is not tokenize.NL) - res = atom(src, next(src)) - return res +def json_eval(source): + """Evaluates string as json data and returns Python objects.""" + if source == '': + return source + + src = source.splitlines()[0] + + # Substitutions to enable usage of pythonic syntax. + if src.startswith('(') and src.endswith(')'): + src = re.sub(r'^\((.*)\)$', r'[\1]', src) + elif src.lower() in ('true', 'false'): + src = src.lower() + elif src.lower() == 'none': + src = 'null' + + try: + return json.loads(src) + except ValueError: + return src class Command(BaseCommand): @@ -126,10 +94,10 @@ class Command(BaseCommand): value = pprint.pformat(value, 2, 80) new_value = [] for line in value.splitlines(): - new_value.append('%s%s' % (color, line)) + new_value.append(f'{color}{line}') value = '\n'.join(new_value) - string += '%s: %s%s\n' % (key, color, value) + string += f'{key}: {color}{value}\n' self.console.write(string.strip()) return client.core.get_config().addCallback(_on_get_config) @@ -140,8 +108,8 @@ class Command(BaseCommand): val = ' '.join(options.values) try: - val = simple_eval(val) - except SyntaxError as ex: + val = json_eval(val) + except Exception as ex: self.console.write('{!error!}%s' % ex) return @@ -161,7 +129,7 @@ class Command(BaseCommand): def on_set_config(result): self.console.write('{!success!}Configuration value successfully updated.') - self.console.write('Setting "%s" to: %s' % (key, val)) + self.console.write(f'Setting "{key}" to: {val!r}') return client.core.set_config({key: val}).addCallback(on_set_config) def complete(self, text): diff --git a/deluge/ui/console/cmdline/commands/connect.py b/deluge/ui/console/cmdline/commands/connect.py index 6588f7a..4c76de3 100644 --- a/deluge/ui/console/cmdline/commands/connect.py +++ b/deluge/ui/console/cmdline/commands/connect.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import deluge.component as component @@ -57,17 +54,12 @@ class Command(BaseCommand): def on_connect(result): if self.console.interactive: - self.console.write('{!success!}Connected to %s:%s!' % (host, port)) + self.console.write(f'{{!success!}}Connected to {host}:{port}!') return component.start() def on_connect_fail(result): - try: - msg = result.value.exception_msg - except AttributeError: - msg = result.value.message self.console.write( - '{!error!}Failed to connect to %s:%s with reason: %s' - % (host, port, msg) + f'{{!error!}}Failed to connect to {host}:{port} with reason: {result.value.message}' ) return result diff --git a/deluge/ui/console/cmdline/commands/debug.py b/deluge/ui/console/cmdline/commands/debug.py index 3ca06ed..af48a8b 100644 --- a/deluge/ui/console/cmdline/commands/debug.py +++ b/deluge/ui/console/cmdline/commands/debug.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - from twisted.internet import defer import deluge.component as component diff --git a/deluge/ui/console/cmdline/commands/gui.py b/deluge/ui/console/cmdline/commands/gui.py index 10e4c49..575bc9b 100644 --- a/deluge/ui/console/cmdline/commands/gui.py +++ b/deluge/ui/console/cmdline/commands/gui.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import deluge.component as component diff --git a/deluge/ui/console/cmdline/commands/halt.py b/deluge/ui/console/cmdline/commands/halt.py index 6355958..608f2de 100644 --- a/deluge/ui/console/cmdline/commands/halt.py +++ b/deluge/ui/console/cmdline/commands/halt.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component from deluge.ui.client import client diff --git a/deluge/ui/console/cmdline/commands/help.py b/deluge/ui/console/cmdline/commands/help.py index 2711eea..754dadb 100644 --- a/deluge/ui/console/cmdline/commands/help.py +++ b/deluge/ui/console/cmdline/commands/help.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from twisted.internet import defer diff --git a/deluge/ui/console/cmdline/commands/info.py b/deluge/ui/console/cmdline/commands/info.py index 0d22f76..7ea9a67 100644 --- a/deluge/ui/console/cmdline/commands/info.py +++ b/deluge/ui/console/cmdline/commands/info.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import division, unicode_literals - from os.path import sep as dirsep import deluge.component as component @@ -70,6 +67,7 @@ STATUS_KEYS = [ 'total_payload_download', 'total_payload_upload', 'time_added', + 'label', ] # Add filter specific state to torrent states @@ -177,7 +175,7 @@ class Command(BaseCommand): sort_key = 'name' sort_reverse = False for key, value in sorted( - list(status.items()), + status.items(), key=lambda x: x[1].get(sort_key), reverse=sort_reverse, ): @@ -218,9 +216,9 @@ class Command(BaseCommand): for depth, subdir in enumerate(filepath): indent = ' ' * depth * spaces_per_level if depth >= len(prevpath): - self.console.write('%s{!cyan!}%s' % (indent, subdir)) + self.console.write(f'{indent}{{!cyan!}}{subdir}') elif subdir != prevpath[depth]: - self.console.write('%s{!cyan!}%s' % (indent, subdir)) + self.console.write(f'{indent}{{!cyan!}}{subdir}') depth = len(filepath) @@ -296,7 +294,7 @@ class Command(BaseCommand): s += peer['ip'] else: # IPv6 - s += '[%s]:%s' % ( + s += '[{}]:{}'.format( ':'.join(peer['ip'].split(':')[:-1]), peer['ip'].split(':')[-1], ) @@ -308,7 +306,7 @@ class Command(BaseCommand): s += '\t\t' else: s += '\t' - s += '%s%s\t%s%s' % ( + s += '{}{}\t{}{}'.format( colors.state_color['Seeding'], fspeed(peer['up_speed']), colors.state_color['Downloading'], @@ -336,7 +334,7 @@ class Command(BaseCommand): if verbose or detailed: self.console.write('{!info!}Name: {!input!}%s' % (status['name'])) self.console.write('{!info!}ID: {!input!}%s' % (torrent_id)) - s = '{!info!}State: %s%s' % ( + s = '{{!info!}}State: {}{}'.format( colors.state_color[status['state']], status['state'], ) @@ -354,12 +352,12 @@ class Command(BaseCommand): self.console.write(s) if status['state'] in ('Seeding', 'Downloading', 'Queued'): - s = '{!info!}Seeds: {!input!}%s (%s)' % ( + s = '{{!info!}}Seeds: {{!input!}}{} ({})'.format( status['num_seeds'], status['total_seeds'], ) s += sep - s += '{!info!}Peers: {!input!}%s (%s)' % ( + s += '{{!info!}}Peers: {{!input!}}{} ({})'.format( status['num_peers'], status['total_peers'], ) @@ -378,7 +376,7 @@ class Command(BaseCommand): if total_done == total_size: s = '{!info!}Size: {!input!}%s' % (total_size) else: - s = '{!info!}Size: {!input!}%s/%s' % (total_done, total_size) + s = f'{{!info!}}Size: {{!input!}}{total_done}/{total_size}' s += sep s += '{!info!}Downloaded: {!input!}%s' % fsize( status['all_time_download'], shortform=True @@ -418,14 +416,20 @@ class Command(BaseCommand): pbar = f_progressbar( status['progress'], cols - (13 + len('%.2f%%' % status['progress'])) ) - s = '{!info!}Progress: {!input!}%.2f%% %s' % (status['progress'], pbar) + s = '{{!info!}}Progress: {{!input!}}{:.2f}% {}'.format( + status['progress'], pbar + ) self.console.write(s) s = '{!info!}Download Folder: {!input!}%s' % status['download_location'] - self.console.write(s + '\n') + self.console.write(s) + + if 'label' in status: + s = '{!info!}Label: {!input!}%s' % status['label'] + self.console.write(s) if detailed: - self.console.write('{!info!}Files in torrent') + self.console.write('\n{!info!}Files in torrent') self.show_file_info(torrent_id, status) self.console.write('{!info!}Connected peers') self.show_peer_info(torrent_id, status) @@ -433,7 +437,7 @@ class Command(BaseCommand): up_color = colors.state_color['Seeding'] down_color = colors.state_color['Downloading'] - s = '%s%s' % ( + s = '{}{}'.format( colors.state_color[status['state']], '[' + status['state'][0] + ']', ) @@ -458,7 +462,7 @@ class Command(BaseCommand): ) if status['download_payload_rate'] > 0: - dl_info += ' @ %s%s' % ( + dl_info += ' @ {}{}'.format( down_color, fspeed(status['download_payload_rate'], shortform=True), ) @@ -468,7 +472,7 @@ class Command(BaseCommand): status['total_uploaded'], status['total_payload_upload'] ) if status['upload_payload_rate'] > 0: - ul_info += ' @ %s%s' % ( + ul_info += ' @ {}{}'.format( up_color, fspeed(status['upload_payload_rate'], shortform=True), ) diff --git a/deluge/ui/console/cmdline/commands/manage.py b/deluge/ui/console/cmdline/commands/manage.py index 6375a74..e5ea9b2 100644 --- a/deluge/ui/console/cmdline/commands/manage.py +++ b/deluge/ui/console/cmdline/commands/manage.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from twisted.internet import defer @@ -69,7 +66,7 @@ class Command(BaseCommand): self.console.write('{!info!}ID: {!input!}%s' % torrentid) for k, v in data.items(): if k != 'name': - self.console.write('{!info!}%s: {!input!}%s' % (k, v)) + self.console.write(f'{{!info!}}{k}: {{!input!}}{v}') def on_torrents_status_fail(reason): self.console.write('{!error!}Failed to get torrent data.') @@ -106,9 +103,7 @@ class Command(BaseCommand): self.console.write('{!success!}Torrent option successfully updated.') deferred.callback(True) - self.console.write( - 'Setting %s to %s for torrents %s..' % (key, val, torrent_ids) - ) + self.console.write(f'Setting {key} to {val} for torrents {torrent_ids}..') client.core.set_torrent_options(torrent_ids, {key: val}).addCallback( on_set_config ) diff --git a/deluge/ui/console/cmdline/commands/move.py b/deluge/ui/console/cmdline/commands/move.py index 13e475e..67ee0af 100644 --- a/deluge/ui/console/cmdline/commands/move.py +++ b/deluge/ui/console/cmdline/commands/move.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import os.path @@ -52,7 +49,7 @@ class Command(BaseCommand): names.append(self.console.get_torrent_name(tid)) def on_move(res): - msg = 'Moved "%s" to %s' % (', '.join(names), options.path) + msg = 'Moved "{}" to {}'.format(', '.join(names), options.path) self.console.write(msg) log.info(msg) diff --git a/deluge/ui/console/cmdline/commands/pause.py b/deluge/ui/console/cmdline/commands/pause.py index 1f7ef31..1334242 100644 --- a/deluge/ui/console/cmdline/commands/pause.py +++ b/deluge/ui/console/cmdline/commands/pause.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component from deluge.ui.client import client diff --git a/deluge/ui/console/cmdline/commands/plugin.py b/deluge/ui/console/cmdline/commands/plugin.py index fafc77a..c424cb2 100644 --- a/deluge/ui/console/cmdline/commands/plugin.py +++ b/deluge/ui/console/cmdline/commands/plugin.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component import deluge.configmanager from deluge.ui.client import client @@ -106,8 +103,8 @@ class Command(BaseCommand): elif options.install: import os.path - from base64 import b64encode import shutil + from base64 import b64encode filepath = options.install diff --git a/deluge/ui/console/cmdline/commands/quit.py b/deluge/ui/console/cmdline/commands/quit.py index 261a01a..4459dfc 100644 --- a/deluge/ui/console/cmdline/commands/quit.py +++ b/deluge/ui/console/cmdline/commands/quit.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component from . import BaseCommand diff --git a/deluge/ui/console/cmdline/commands/recheck.py b/deluge/ui/console/cmdline/commands/recheck.py index c9b6360..046cb0b 100644 --- a/deluge/ui/console/cmdline/commands/recheck.py +++ b/deluge/ui/console/cmdline/commands/recheck.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component from deluge.ui.client import client diff --git a/deluge/ui/console/cmdline/commands/resume.py b/deluge/ui/console/cmdline/commands/resume.py index 1f62c5f..27b8528 100644 --- a/deluge/ui/console/cmdline/commands/resume.py +++ b/deluge/ui/console/cmdline/commands/resume.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component from deluge.ui.client import client diff --git a/deluge/ui/console/cmdline/commands/rm.py b/deluge/ui/console/cmdline/commands/rm.py index ff3125d..4a3fd00 100644 --- a/deluge/ui/console/cmdline/commands/rm.py +++ b/deluge/ui/console/cmdline/commands/rm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import deluge.component as component @@ -70,9 +67,11 @@ class Command(BaseCommand): def on_removed_finished(errors): if errors: - self.console.write('Error(s) occured when trying to delete torrent(s).') + self.console.write( + 'Error(s) occurred when trying to delete torrent(s).' + ) for t_id, e_msg in errors: - self.console.write('Error removing torrent %s : %s' % (t_id, e_msg)) + self.console.write(f'Error removing torrent {t_id} : {e_msg}') log.info('Removing %d torrents', len(torrent_ids)) d = client.core.remove_torrents(torrent_ids, options.remove_data) diff --git a/deluge/ui/console/cmdline/commands/status.py b/deluge/ui/console/cmdline/commands/status.py index 948ad6b..05c9796 100644 --- a/deluge/ui/console/cmdline/commands/status.py +++ b/deluge/ui/console/cmdline/commands/status.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from twisted.internet import defer @@ -65,7 +62,12 @@ class Command(BaseCommand): deferreds = [] ds = client.core.get_session_status( - ['num_peers', 'payload_upload_rate', 'payload_download_rate', 'dht_nodes'] + [ + 'peer.num_peers_connected', + 'payload_upload_rate', + 'payload_download_rate', + 'dht.dht_nodes', + ] ) ds.addCallback(on_session_status) deferreds.append(ds) @@ -95,7 +97,7 @@ class Command(BaseCommand): '{!info!}Total download: %s' % fspeed(self.status['payload_download_rate']) ) - self.console.write('{!info!}DHT Nodes: %i' % self.status['dht_nodes']) + self.console.write('{!info!}DHT Nodes: %i' % self.status['dht.dht_nodes']) if isinstance(self.torrents, int): if self.torrents == -2: diff --git a/deluge/ui/console/cmdline/commands/update_tracker.py b/deluge/ui/console/cmdline/commands/update_tracker.py index 591b951..c05569d 100644 --- a/deluge/ui/console/cmdline/commands/update_tracker.py +++ b/deluge/ui/console/cmdline/commands/update_tracker.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.component as component from deluge.ui.client import client diff --git a/deluge/ui/console/console.py b/deluge/ui/console/console.py index 58d31d5..8ef87e8 100644 --- a/deluge/ui/console/console.py +++ b/deluge/ui/console/console.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -7,8 +6,6 @@ # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # -from __future__ import print_function, unicode_literals - import fnmatch import logging import os @@ -53,7 +50,7 @@ def load_commands(command_dir): return dict(commands) -class LogStream(object): +class LogStream: out = sys.stdout def write(self, data): @@ -68,9 +65,7 @@ class Console(UI): cmd_description = """Console or command-line user interface""" def __init__(self, *args, **kwargs): - super(Console, self).__init__( - 'console', *args, log_stream=LogStream(), **kwargs - ) + super().__init__('console', *args, log_stream=LogStream(), **kwargs) group = self.parser.add_argument_group( _('Console Options'), @@ -112,9 +107,9 @@ class Console(UI): ) # To properly print help message for the console commands ( e.g. deluge-console info -h), # we add a subparser for each command which will trigger the help/usage when given - from deluge.ui.console.parser import ( + from deluge.ui.console.parser import ( # import here because (see top) ConsoleCommandParser, - ) # import here because (see top) + ) self.console_parser = ConsoleCommandParser( parents=[self.parser], @@ -150,7 +145,7 @@ class Console(UI): self.console_parser.subcommand = False self.parser.subcommand = False if i == -1 else True - super(Console, self).start(self.console_parser) + super().start(self.console_parser) from deluge.ui.console.main import ConsoleUI # import here because (see top) def run(options): diff --git a/deluge/ui/console/main.py b/deluge/ui/console/main.py index 23965bb..31d1db1 100644 --- a/deluge/ui/console/main.py +++ b/deluge/ui/console/main.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import print_function, unicode_literals - import locale import logging import os @@ -67,6 +64,14 @@ DEFAULT_CONSOLE_PREFS = { } +class MockConsoleLog: + def write(self, data): + pass + + def flush(self): + pass + + class ConsoleUI(component.Component, TermResizeHandler): def __init__(self, options, cmds, log_stream): component.Component.__init__(self, 'ConsoleUI') @@ -114,6 +119,7 @@ class ConsoleUI(component.Component, TermResizeHandler): all commands are executed. Else None is returned. """ if self.options.parsed_cmds: + # Non-Interactive mode self.interactive = False if not self._commands: print('No valid console commands found') @@ -122,41 +128,37 @@ class ConsoleUI(component.Component, TermResizeHandler): deferred = self.exec_args(self.options) reactor.run() return deferred - else: - # Interactive - if deluge.common.windows_check(): - print( - """\nDeluge-console does not run in interactive mode on Windows. \n -Please use commands from the command line, e.g.:\n - deluge-console.exe help - deluge-console.exe info - deluge-console.exe "add --help" - deluge-console.exe "add -p c:\\mytorrents c:\\new.torrent" -""" - ) - else: - class ConsoleLog(object): - def write(self, data): - pass + # Interactive - def flush(self): - pass + # We use the curses.wrapper function to prevent the console from getting + # messed up if an uncaught exception is experienced. + try: + from curses import wrapper + except ImportError: + wrapper = None - # We don't ever want log output to terminal when running in - # interactive mode, so insert a dummy here - self.log_stream.out = ConsoleLog() + if deluge.common.windows_check() and not wrapper: + print( + """\nDeluge-console does not run in interactive mode on Windows. \n +Please use commands from the command line, e.g.:\n +deluge-console.exe help +deluge-console.exe info +deluge-console.exe "add --help" +deluge-console.exe "add -p c:\\mytorrents c:\\new.torrent" +""" + ) - # Set Esc key delay to 0 to avoid a very annoying delay - # due to curses waiting in case of other key are pressed - # after ESC is pressed - os.environ.setdefault('ESCDELAY', '0') + # We don't ever want log output to terminal when running in + # interactive mode, so insert a dummy here + self.log_stream.out = MockConsoleLog() - # We use the curses.wrapper function to prevent the console from getting - # messed up if an uncaught exception is experienced. - from curses import wrapper + # Set Esc key delay to 0 to avoid a very annoying delay + # due to curses waiting in case of other key are pressed + # after ESC is pressed + os.environ.setdefault('ESCDELAY', '0') - wrapper(self.run) + wrapper(self.run) def quit(self): if client.connected(): @@ -281,7 +283,7 @@ Please use commands from the command line, e.g.:\n @overrides(TermResizeHandler) def on_terminal_size(self, *args): - rows, cols = super(ConsoleUI, self).on_terminal_size(args) + rows, cols = super().on_terminal_size(args) for mode in self.modes: self.modes[mode].on_resize(rows, cols) @@ -706,7 +708,7 @@ class EventLog(component.Component): if not t_name: return - self.write('%s: {!info!}%s ({!cyan!}%s{!info!})' % (state, t_name, torrent_id)) + self.write(f'{state}: {{!info!}}{t_name} ({{!cyan!}}{torrent_id}{{!info!}})') def on_torrent_finished_event(self, torrent_id): if component.get('TorrentList').config['ring_bell']: @@ -734,7 +736,7 @@ class EventLog(component.Component): except KeyError: pass - self.write('ConfigValueChanged: {!input!}%s: %s%s' % (key, color, value)) + self.write(f'ConfigValueChanged: {{!input!}}{key}: {color}{value}') def write(self, s): current_time = time.localtime() @@ -748,8 +750,6 @@ class EventLog(component.Component): if date_different: string = time.strftime(self.date_change_format) - if deluge.common.PY2: - string = string.decode() self.console.write_event(' ') self.console.write_event(string) diff --git a/deluge/ui/console/modes/add_util.py b/deluge/ui/console/modes/add_util.py index 88a24d0..9d29a1f 100644 --- a/deluge/ui/console/modes/add_util.py +++ b/deluge/ui/console/modes/add_util.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -9,15 +8,11 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import glob import logging import os from base64 import b64encode -from six import unichr as chr - import deluge.common from deluge.ui.client import client from deluge.ui.common import TorrentInfo diff --git a/deluge/ui/console/modes/addtorrents.py b/deluge/ui/console/modes/addtorrents.py index 6b2c105..217b63d 100644 --- a/deluge/ui/console/modes/addtorrents.py +++ b/deluge/ui/console/modes/addtorrents.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2012 Arek Stefański <asmageddon@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import os from base64 import b64encode @@ -24,12 +21,6 @@ from deluge.ui.console.utils import format_utils from deluge.ui.console.widgets.popup import InputPopup, MessagePopup try: - from future_builtins import zip -except ImportError: - # Ignore on Py3. - pass - -try: import curses except ImportError: pass @@ -377,7 +368,7 @@ class AddTorrents(BaseMode): def fail_cb(msg, t_file, ress): log.debug('failed to add torrent: %s: %s', t_file, msg) ress['fail'] += 1 - ress['fmsg'].append('{!input!} * %s: {!error!}%s' % (t_file, msg)) + ress['fmsg'].append(f'{{!input!}} * {t_file}: {{!error!}}{msg}') if (ress['succ'] + ress['fail']) >= ress['total']: report_add_status( component.get('TorrentList'), @@ -526,9 +517,9 @@ class AddTorrents(BaseMode): self.last_mark = self.cursel elif chr(c) == 'j': - self.scroll_list_up(1) - elif chr(c) == 'k': self.scroll_list_down(1) + elif chr(c) == 'k': + self.scroll_list_up(1) elif chr(c) == 'M': if self.last_mark != -1: if self.last_mark > self.cursel: diff --git a/deluge/ui/console/modes/basemode.py b/deluge/ui/console/modes/basemode.py index dd3681f..5ebaf86 100644 --- a/deluge/ui/console/modes/basemode.py +++ b/deluge/ui/console/modes/basemode.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,8 +7,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import sys @@ -26,9 +23,9 @@ except ImportError: try: import signal - from fcntl import ioctl - import termios import struct + import termios + from fcntl import ioctl except ImportError: pass @@ -36,7 +33,7 @@ except ImportError: log = logging.getLogger(__name__) -class InputKeyHandler(object): +class InputKeyHandler: def __init__(self): self._input_result = None @@ -62,12 +59,14 @@ class InputKeyHandler(object): return util.ReadState.IGNORED -class TermResizeHandler(object): +class TermResizeHandler: def __init__(self): try: signal.signal(signal.SIGWINCH, self.on_terminal_size) except ValueError as ex: - log.debug('Unable to catch SIGWINCH signal: %s', ex) + log.debug('TermResize unavailable, unable to catch SIGWINCH signal: %s', ex) + except AttributeError as ex: + log.debug('TermResize unavailable, no SIGWINCH signal on Windows: %s', ex) def on_terminal_size(self, *args): # Get the new rows and cols value @@ -78,14 +77,14 @@ class TermResizeHandler(object): return rows, cols -class CursesStdIO(object): +class CursesStdIO: """ fake fd to be registered as a reader with the twisted reactor. Curses classes needing input should extend this """ def fileno(self): - """ We want to select on FD 0 """ + """We want to select on FD 0""" return 0 def doRead(self): # NOQA: N802 diff --git a/deluge/ui/console/modes/cmdline.py b/deluge/ui/console/modes/cmdline.py index 2735168..7b0ff2d 100644 --- a/deluge/ui/console/modes/cmdline.py +++ b/deluge/ui/console/modes/cmdline.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> @@ -8,16 +7,12 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import os import re -from io import open import deluge.component as component import deluge.configmanager -from deluge.common import PY2 from deluge.decorators import overrides from deluge.ui.console.cmdline.command import Commander from deluge.ui.console.modes.basemode import BaseMode, move_cursor @@ -139,18 +134,18 @@ class CmdLine(BaseMode, Commander): self._hf_lines = [0, 0] if self.console_config['cmdline']['save_command_history']: try: - with open(self.history_file[0], 'r', encoding='utf8') as _file: + with open(self.history_file[0], encoding='utf8') as _file: lines1 = _file.read().splitlines() self._hf_lines[0] = len(lines1) - except IOError: + except OSError: lines1 = [] self._hf_lines[0] = 0 try: - with open(self.history_file[1], 'r', encoding='utf8') as _file: + with open(self.history_file[1], encoding='utf8') as _file: lines2 = _file.read().splitlines() self._hf_lines[1] = len(lines2) - except IOError: + except OSError: lines2 = [] self._hf_lines[1] = 0 @@ -332,10 +327,10 @@ class CmdLine(BaseMode, Commander): # A key to add to the input string else: - if c > 31 and c < 256: + if 31 < c < 256: # Emulate getwch stroke = chr(c) - uchar = '' if PY2 else stroke + uchar = stroke while not uchar: try: uchar = stroke.decode(self.encoding) @@ -826,21 +821,21 @@ class CmdLine(BaseMode, Commander): # Let's avoid listing all torrents twice if there's no pattern if not empty and torrent_id.startswith(line): # Highlight the matching part - text = '{!info!}%s{!input!}%s - "%s"' % ( + text = '{{!info!}}{}{{!input!}}{} - "{}"'.format( torrent_id[:line_len], torrent_id[line_len:], torrent_name, ) possible_matches.append(text) if torrent_name.startswith(line): - text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % ( + text = '{{!info!}}{}{{!input!}}{} ({{!cyan!}}{}{{!input!}})'.format( escaped_name[:line_len], escaped_name[line_len:], torrent_id, ) possible_matches.append(text) elif torrent_name.lower().startswith(line.lower()): - text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % ( + text = '{{!info!}}{}{{!input!}}{} ({{!cyan!}}{}{{!input!}})'.format( escaped_name[:line_len], escaped_name[line_len:], torrent_id, diff --git a/deluge/ui/console/modes/connectionmanager.py b/deluge/ui/console/modes/connectionmanager.py index 84a3fbc..0ccdd93 100644 --- a/deluge/ui/console/modes/connectionmanager.py +++ b/deluge/ui/console/modes/connectionmanager.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import deluge.component as component @@ -32,11 +29,13 @@ class ConnectionManager(BaseMode, PopupsHandler): self.statuses = {} self.all_torrents = None self.hostlist = HostList() - self.update_hosts_status() BaseMode.__init__(self, stdscr, encoding=encoding) - self.update_select_host_popup() def update_select_host_popup(self): + if self.popup and not isinstance(self.popup, SelectablePopup): + # Ignore MessagePopup on popup stack upon connect fail + return + selected_index = self.popup.current_selection() if self.popup else None popup = SelectablePopup( @@ -51,32 +50,33 @@ class ConnectionManager(BaseMode, PopupsHandler): % (_('Quit'), _('Add Host'), _('Delete Host')), space_below=True, ) - self.push_popup(popup, clear=True) for host_entry in self.hostlist.get_hosts_info(): host_id, hostname, port, user = host_entry - args = {'data': host_id, 'foreground': 'red'} - state = 'Offline' - if host_id in self.statuses: - state = 'Online' - args.update({'data': self.statuses[host_id], 'foreground': 'green'}) - host_str = '%s:%d [%s]' % (hostname, port, state) - self.popup.add_line( + host_status = self.statuses.get(host_id) + + state = host_status[1] if host_status else 'Offline' + state_color = 'green' if state in ('Online', 'Connected') else 'red' + host_str = f'{hostname}:{port} [{state}]' + + args = {'data': host_id, 'foreground': state_color} + popup.add_line( host_id, host_str, selectable=True, use_underline=True, **args ) if selected_index: - self.popup.set_selection(selected_index) + popup.set_selection(selected_index) + + self.push_popup(popup, clear=True) self.inlist = True self.refresh() def update_hosts_status(self): - for host_entry in self.hostlist.get_hosts_info(): - - def on_host_status(status_info): - self.statuses[status_info[0]] = status_info - self.update_select_host_popup() + def on_host_status(status_info): + self.statuses[status_info[0]] = status_info + self.update_select_host_popup() + for host_entry in self.hostlist.get_hosts_info(): self.hostlist.get_host_status(host_entry[0]).addCallback(on_host_status) def _on_connected(self, result): @@ -87,7 +87,7 @@ class ConnectionManager(BaseMode, PopupsHandler): d.addCallback(on_console_start) def _on_connect_fail(self, result): - self.report_message('Failed to connect!', result) + self.report_message('Failed to connect!', result.getErrorMessage()) self.refresh() if hasattr(result, 'getTraceback'): log.exception(result) @@ -130,7 +130,7 @@ class ConnectionManager(BaseMode, PopupsHandler): try: self.hostlist.add_host(hostname, port, username, password) except ValueError as ex: - self.report_message(_('Error adding host'), '%s: %s' % (hostname, ex)) + self.report_message(_('Error adding host'), f'{hostname}: {ex}') else: self.update_select_host_popup() @@ -169,7 +169,9 @@ class ConnectionManager(BaseMode, PopupsHandler): if not self.popup: self.update_select_host_popup() - self.popup.refresh() + if self.popup: + self.popup.refresh() + curses.doupdate() @overrides(BaseMode) diff --git a/deluge/ui/console/modes/eventview.py b/deluge/ui/console/modes/eventview.py index cd3308c..b6e63b0 100644 --- a/deluge/ui/console/modes/eventview.py +++ b/deluge/ui/console/modes/eventview.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import deluge.component as component @@ -100,9 +97,9 @@ class EventView(BaseMode): elif c == curses.KEY_END: self.offset += num_events elif c == ord('j'): - self.offset -= 1 - elif c == ord('k'): self.offset += 1 + elif c == ord('k'): + self.offset -= 1 if self.offset <= 0: self.offset = 0 diff --git a/deluge/ui/console/modes/preferences/__init__.py b/deluge/ui/console/modes/preferences/__init__.py index 15d77c4..e827d91 100644 --- a/deluge/ui/console/modes/preferences/__init__.py +++ b/deluge/ui/console/modes/preferences/__init__.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - from deluge.ui.console.modes.preferences.preferences import Preferences __all__ = ['Preferences'] diff --git a/deluge/ui/console/modes/preferences/preference_panes.py b/deluge/ui/console/modes/preferences/preference_panes.py index 62029a6..b47bc4b 100644 --- a/deluge/ui/console/modes/preferences/preference_panes.py +++ b/deluge/ui/console/modes/preferences/preference_panes.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,11 +6,9 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging -from deluge.common import is_ip +from deluge.common import is_interface from deluge.decorators import overrides from deluge.i18n import get_languages from deluge.ui.client import client @@ -94,11 +91,12 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler): ) elif ipt.name == 'listen_interface': listen_interface = ipt.get_value().strip() - if is_ip(listen_interface) or not listen_interface: + if is_interface(listen_interface) or not listen_interface: conf_dict['listen_interface'] = listen_interface elif ipt.name == 'outgoing_interface': outgoing_interface = ipt.get_value().strip() - conf_dict['outgoing_interface'] = outgoing_interface + if is_interface(outgoing_interface) or not outgoing_interface: + conf_dict['outgoing_interface'] = outgoing_interface elif ipt.name.startswith('proxy_'): if ipt.name == 'proxy_type': conf_dict.setdefault('proxy', {})['type'] = ipt.get_value() @@ -724,11 +722,6 @@ class CachePane(BasePreferencePane): self.add_info_field( 'blocks_read', ' %s:' % _('Blocks Read'), status['disk.num_blocks_read'] ) - self.add_info_field( - 'blocks_read_hit', - ' %s:' % _('Blocks Read hit'), - status['disk.num_blocks_cache_hits'], - ) self.add_info_field('reads', ' %s:' % _('Reads'), status['disk.num_read_ops']) self.add_info_field( 'read_hit_ratio', diff --git a/deluge/ui/console/modes/preferences/preferences.py b/deluge/ui/console/modes/preferences/preferences.py index 45a39a6..2c95323 100644 --- a/deluge/ui/console/modes/preferences/preferences.py +++ b/deluge/ui/console/modes/preferences/preferences.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from collections import deque @@ -74,7 +71,7 @@ arrow to edit the other value, and escape to get back to the check box. """ -class ZONE(object): +class ZONE: length = 3 CATEGORIES, PREFRENCES, ACTIONS = list(range(length)) diff --git a/deluge/ui/console/modes/torrentdetail.py b/deluge/ui/console/modes/torrentdetail.py index d02a0d3..16bd08a 100644 --- a/deluge/ui/console/modes/torrentdetail.py +++ b/deluge/ui/console/modes/torrentdetail.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import division, unicode_literals - import logging import deluge.component as component @@ -220,7 +217,7 @@ class TorrentDetail(BaseMode, PopupsHandler): self.refresh() def build_file_list(self, torrent_files, progress, priority): - """ Split file list from torrent state into a directory tree. + """Split file list from torrent state into a directory tree. Returns: @@ -425,9 +422,9 @@ class TorrentDetail(BaseMode, PopupsHandler): attr = 'bold' if attr: - color_string = '{!%s,%s,%s!}' % (fg, bg, attr) + color_string = f'{{!{fg},{bg},{attr}!}}' else: - color_string = '{!%s,%s!}' % (fg, bg) + color_string = f'{{!{fg},{bg}!}}' # actually draw the dir/file string if fl[3] and fl[4]: # this is an expanded directory @@ -439,7 +436,7 @@ class TorrentDetail(BaseMode, PopupsHandler): r = format_row( [ - '%s%s %s' % (' ' * depth, xchar, fl[0]), + '{}{} {}'.format(' ' * depth, xchar, fl[0]), fsize(fl[2]), fl[5], format_priority(fl[6]), @@ -447,7 +444,7 @@ class TorrentDetail(BaseMode, PopupsHandler): self.column_widths, ) - self.add_string(off, '%s%s' % (color_string, r), trim=False) + self.add_string(off, f'{color_string}{r}', trim=False) off += 1 if fl[3] and fl[4]: @@ -502,7 +499,7 @@ class TorrentDetail(BaseMode, PopupsHandler): download_color = colors.state_color['Downloading'] def add_field(name, row, pre_color='{!info!}', post_color='{!input!}'): - s = '%s%s: %s%s' % ( + s = '{}{}: {}{}'.format( pre_color, torrent_data_fields[name]['name'], post_color, @@ -523,7 +520,7 @@ class TorrentDetail(BaseMode, PopupsHandler): if status['progress'] != 100.0: s += '/%s' % fsize(status['total_wanted']) if status['download_payload_rate'] > 0: - s += ' {!yellow!}@ %s%s' % ( + s += ' {{!yellow!}}@ {}{}'.format( download_color, fsize(status['download_payload_rate']), ) @@ -534,7 +531,7 @@ class TorrentDetail(BaseMode, PopupsHandler): # Print UL info and ratio s = add_field('uploaded', 0, download_color) if status['upload_payload_rate'] > 0: - s += ' {!yellow!}@ %s%s' % ( + s += ' {{!yellow!}}@ {}{}'.format( colors.state_color['Seeding'], fsize(status['upload_payload_rate']), ) @@ -542,13 +539,13 @@ class TorrentDetail(BaseMode, PopupsHandler): row = self.add_string(row, s) # Seed/peer info - s = '{!info!}%s:{!green!} %s {!input!}(%s)' % ( + s = '{{!info!}}{}:{{!green!}} {} {{!input!}}({})'.format( torrent_data_fields['seeds']['name'], status['num_seeds'], status['total_seeds'], ) row = self.add_string(row, s) - s = '{!info!}%s:{!red!} %s {!input!}(%s)' % ( + s = '{{!info!}}{}:{{!red!}} {} {{!input!}}({})'.format( torrent_data_fields['peers']['name'], status['num_peers'], status['total_peers'], @@ -557,7 +554,7 @@ class TorrentDetail(BaseMode, PopupsHandler): # Tracker tracker_color = '{!green!}' if status['message'] == 'OK' else '{!red!}' - s = '{!info!}%s: {!magenta!}%s{!input!} says "%s%s{!input!}"' % ( + s = '{{!info!}}{}: {{!magenta!}}{}{{!input!}} says "{}{}{{!input!}}"'.format( torrent_data_fields['tracker']['name'], status['tracker_host'], tracker_color, @@ -566,13 +563,13 @@ class TorrentDetail(BaseMode, PopupsHandler): row = self.add_string(row, s) # Pieces and availability - s = '{!info!}%s: {!yellow!}%s {!input!}x {!yellow!}%s' % ( + s = '{{!info!}}{}: {{!yellow!}}{} {{!input!}}x {{!yellow!}}{}'.format( torrent_data_fields['pieces']['name'], status['num_pieces'], fsize(status['piece_length']), ) if status['distributed_copies']: - s += '{!info!}%s: {!input!}%s' % ( + s += '{{!info!}}{}: {{!input!}}{}'.format( torrent_data_fields['seed_rank']['name'], status['seed_rank'], ) @@ -710,7 +707,7 @@ class TorrentDetail(BaseMode, PopupsHandler): 'skip_priority', '_Skip', foreground='red', - cb_arg=FILE_PRIORITY['Low'], + cb_arg=FILE_PRIORITY['Skip'], was_empty=was_empty, ) popup.add_line( @@ -878,7 +875,7 @@ class TorrentDetail(BaseMode, PopupsHandler): idx += 1 continue if num == idx: - return '%s%s/' % (path, element[0]) + return f'{path}{element[0]}/' if element[4]: i = self._get_full_folder_path( num, element[3], path + element[0] + '/', idx + 1 @@ -923,7 +920,7 @@ class TorrentDetail(BaseMode, PopupsHandler): self.popup.close(None, call_cb=False) return old_fname = self._get_full_folder_path(self.current_file_idx) - new_fname = '%s/%s/' % ( + new_fname = '{}/{}/'.format( old_fname.strip('/').rpartition('/')[0], result['new_foldername']['value'], ) @@ -949,7 +946,7 @@ class TorrentDetail(BaseMode, PopupsHandler): ): self.popup.close(None, call_cb=False) return - fname = '%s/%s' % ( + fname = '{}/{}'.format( self.full_names[idx].rpartition('/')[0], result['new_filename']['value'], ) @@ -1019,8 +1016,8 @@ class TorrentDetail(BaseMode, PopupsHandler): elif c == ord('h'): self.push_popup(MessagePopup(self, 'Help', HELP_STR, width_req=0.75)) elif c == ord('j'): - self.file_list_up() - elif c == ord('k'): self.file_list_down() + elif c == ord('k'): + self.file_list_up() self.refresh() diff --git a/deluge/ui/console/modes/torrentlist/__init__.py b/deluge/ui/console/modes/torrentlist/__init__.py index 18c4db3..48c60ce 100644 --- a/deluge/ui/console/modes/torrentlist/__init__.py +++ b/deluge/ui/console/modes/torrentlist/__init__.py @@ -1,7 +1,4 @@ -from __future__ import unicode_literals - - -class ACTION(object): +class ACTION: PAUSE = 'pause' RESUME = 'resume' REANNOUNCE = 'update_tracker' diff --git a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py index b0ac483..3ff9ab7 100644 --- a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py +++ b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import deluge.common @@ -40,7 +37,7 @@ def show_torrent_add_popup(torrentlist): def fail_cb(msg, url): log.debug('failed to add torrent: %s: %s', url, msg) - error_msg = '{!input!} * %s: {!error!}%s' % (url, msg) + error_msg = f'{{!input!}} * {url}: {{!error!}}{msg}' report_add_status(torrentlist, 0, 1, [error_msg]) def success_cb(tid, url): diff --git a/deluge/ui/console/modes/torrentlist/filtersidebar.py b/deluge/ui/console/modes/torrentlist/filtersidebar.py index 0f39b5c..982e245 100644 --- a/deluge/ui/console/modes/torrentlist/filtersidebar.py +++ b/deluge/ui/console/modes/torrentlist/filtersidebar.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2016 bendikro <bro.devel+deluge@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import curses import logging diff --git a/deluge/ui/console/modes/torrentlist/queue_mode.py b/deluge/ui/console/modes/torrentlist/queue_mode.py index 0c44aaf..33af013 100644 --- a/deluge/ui/console/modes/torrentlist/queue_mode.py +++ b/deluge/ui/console/modes/torrentlist/queue_mode.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - from deluge.ui.client import client from deluge.ui.console.utils import curses_util as util from deluge.ui.console.widgets.popup import MessagePopup, SelectablePopup @@ -38,7 +35,7 @@ Change queue position of selected torrents """ -class QueueMode(object): +class QueueMode: def __init__(self, torrentslist, torrent_ids): self.torrentslist = torrentslist self.torrentview = torrentslist.torrentview diff --git a/deluge/ui/console/modes/torrentlist/search_mode.py b/deluge/ui/console/modes/torrentlist/search_mode.py index 57a8e5f..6f79628 100644 --- a/deluge/ui/console/modes/torrentlist/search_mode.py +++ b/deluge/ui/console/modes/torrentlist/search_mode.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,11 +6,8 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging -from deluge.common import PY2 from deluge.decorators import overrides from deluge.ui.console.modes.basemode import InputKeyHandler, move_cursor from deluge.ui.console.modes.torrentlist.torrentactions import torrent_actions_popup @@ -49,7 +45,7 @@ SEARCH_FORMAT = { class SearchMode(InputKeyHandler): def __init__(self, torrentlist): - super(SearchMode, self).__init__() + super().__init__() self.torrentlist = torrentlist self.torrentview = torrentlist.torrentview self.search_state = SEARCH_EMPTY @@ -176,7 +172,7 @@ class SearchMode(InputKeyHandler): elif c > 31 and c < 256: old_search_string = self.search_string stroke = chr(c) - uchar = '' if PY2 else stroke + uchar = stroke while not uchar: try: uchar = stroke.decode(self.torrentlist.encoding) diff --git a/deluge/ui/console/modes/torrentlist/torrentactions.py b/deluge/ui/console/modes/torrentlist/torrentactions.py index f3cd395..6450118 100644 --- a/deluge/ui/console/modes/torrentlist/torrentactions.py +++ b/deluge/ui/console/modes/torrentlist/torrentactions.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import os @@ -46,7 +43,7 @@ def action_remove(mode=None, torrent_ids=None, **kwargs): if errors: error_msgs = '' for t_id, e_msg in errors: - error_msgs += 'Error removing torrent %s : %s\n' % (t_id, e_msg) + error_msgs += f'Error removing torrent {t_id} : {e_msg}\n' mode.report_message( 'Error(s) occured when trying to delete torrent(s).', error_msgs ) @@ -77,7 +74,7 @@ def action_remove(mode=None, torrent_ids=None, **kwargs): show_max = 6 for i, (name, state) in enumerate(status): color = colors.state_color[state] - rem_msg += '\n %s* {!input!}%s' % (color, name) + rem_msg += f'\n {color}* {{!input!}}{name}' if i == show_max - 1: if i < len(status) - 1: rem_msg += '\n {!red!}And %i more' % (len(status) - show_max) diff --git a/deluge/ui/console/modes/torrentlist/torrentlist.py b/deluge/ui/console/modes/torrentlist/torrentlist.py index a427d65..d3c32ec 100644 --- a/deluge/ui/console/modes/torrentlist/torrentlist.py +++ b/deluge/ui/console/modes/torrentlist/torrentlist.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from collections import deque @@ -179,7 +176,7 @@ class TorrentList(BaseMode, PopupsHandler): @overrides(BaseMode) def resume(self): - super(TorrentList, self).resume() + super().resume() @overrides(BaseMode) def on_resize(self, rows, cols): @@ -222,7 +219,9 @@ class TorrentList(BaseMode, PopupsHandler): # Update the status bars statusbar_args = {'scr': self.stdscr, 'bottombar_help': True} if self.torrentview.curr_filter is not None: - statusbar_args['topbar'] = '%s {!filterstatus!}Current filter: %s' % ( + statusbar_args[ + 'topbar' + ] = '{} {{!filterstatus!}}Current filter: {}'.format( self.statusbars.topbar, self.torrentview.curr_filter, ) diff --git a/deluge/ui/console/modes/torrentlist/torrentview.py b/deluge/ui/console/modes/torrentlist/torrentview.py index 67de3e7..1ce5097 100644 --- a/deluge/ui/console/modes/torrentlist/torrentview.py +++ b/deluge/ui/console/modes/torrentlist/torrentview.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- # # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import deluge.component as component @@ -90,7 +87,7 @@ for col_i, col_name in enumerate(torrentviewcolumns.column_pref_names): class TorrentView(InputKeyHandler): def __init__(self, torrentlist, config): - super(TorrentView, self).__init__() + super().__init__() self.torrentlist = torrentlist self.config = config self.filter_dict = {} @@ -331,7 +328,7 @@ class TorrentView(InputKeyHandler): self.torrentlist.add_string( currow + self.torrentlist_offset, - '%s%s' % (colorstr, row[0]), + f'{colorstr}{row[0]}', trim=False, scr=self.torrentlist.torrentview_panel, ) @@ -467,9 +464,9 @@ class TorrentView(InputKeyHandler): ) self.torrentlist.refresh() elif c == ord('j'): - affected_lines = self._scroll_up(1) - elif c == ord('k'): affected_lines = self._scroll_down(1) + elif c == ord('k'): + affected_lines = self._scroll_up(1) elif c == ord('m'): self.mark_unmark(self.cursel) affected_lines = [self.cursel] diff --git a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py index 9dff843..586a569 100644 --- a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py +++ b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2016 bendikro <bro.devel+deluge@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - from deluge.decorators import overrides from deluge.ui.console.utils import curses_util as util from deluge.ui.console.utils.column import torrent_data_fields diff --git a/deluge/ui/console/parser.py b/deluge/ui/console/parser.py index 27f2485..c0686b1 100644 --- a/deluge/ui/console/parser.py +++ b/deluge/ui/console/parser.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2016 bendikro <bro.devel+deluge@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import print_function, unicode_literals - import argparse import shlex @@ -23,13 +20,13 @@ class OptionParserError(Exception): class ConsoleBaseParser(argparse.ArgumentParser): def format_help(self): """Differs from ArgumentParser.format_help by adding the raw epilog - as formatted in the string. Default bahavior mangles the formatting. + as formatted in the string. Default behavior mangles the formatting. """ # Handle epilog manually to keep the text formatting epilog = self.epilog self.epilog = '' - help_str = super(ConsoleBaseParser, self).format_help() + help_str = super().format_help() if epilog is not None: help_str += epilog self.epilog = epilog @@ -51,7 +48,7 @@ class ConsoleCommandParser(ConsoleBaseParser): for cmd_line in cmd_lines: cmds = shlex.split(cmd_line) - cmd_options = super(ConsoleCommandParser, self).parse_args(args=cmds) + cmd_options = super().parse_args(args=cmds) cmd_options.command = cmds[0] command_options.append(cmd_options) @@ -60,14 +57,14 @@ class ConsoleCommandParser(ConsoleBaseParser): def parse_args(self, args=None): """Parse known UI args and handle common and process group options. - Notes: - If started by deluge entry script this has already been done. + Notes: + If started by deluge entry script this has already been done. - Args: - args (list, optional): The arguments to parse. + Args: + args (list, optional): The arguments to parse. - Returns: - argparse.Namespace: The parsed arguments. + Returns: + argparse.Namespace: The parsed arguments. """ from deluge.ui.ui_entry import AMBIGUOUS_CMD_ARGS @@ -96,7 +93,7 @@ class ConsoleCommandParser(ConsoleBaseParser): options = self.base_parser.parse_args(args=args) options.parsed_cmds = [] else: - options = super(ConsoleCommandParser, self).parse_args(args=args) + options = super().parse_args(args=args) options.parsed_cmds = [options] if not hasattr(options, 'remaining'): @@ -107,7 +104,7 @@ class ConsoleCommandParser(ConsoleBaseParser): class OptionParser(ConsoleBaseParser): def __init__(self, **kwargs): - super(OptionParser, self).__init__(**kwargs) + super().__init__(**kwargs) self.formatter = ConsoleColorFormatter() def exit(self, status=0, msg=None): @@ -118,9 +115,9 @@ class OptionParser(ConsoleBaseParser): def error(self, msg): """error(msg : string) - Print a usage message incorporating 'msg' to stderr and exit. - If you override this in a subclass, it should not return -- it - should either exit or raise an exception. + Print a usage message incorporating 'msg' to stderr and exit. + If you override this in a subclass, it should not return -- it + should either exit or raise an exception. """ raise OptionParserError(msg) @@ -139,5 +136,5 @@ class OptionParser(ConsoleBaseParser): def format_help(self): """Return help formatted with colors.""" - help_str = super(OptionParser, self).format_help() + help_str = super().format_help() return self.formatter.format_colors(help_str) diff --git a/deluge/ui/console/utils/colors.py b/deluge/ui/console/utils/colors.py index 587c1f3..cc414fe 100644 --- a/deluge/ui/console/utils/colors.py +++ b/deluge/ui/console/utils/colors.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import re @@ -91,8 +88,8 @@ def init_colors(): curses.init_pair(counter, fg, bg) color_pairs[(fg_name, bg_name)] = counter counter += 1 - except curses.error as ex: - log.warning('Error: %s', ex) + except (curses.error, ValueError) as ex: + log.debug(f'Color pair {fg_name} {bg_name} not available: {ex}') return counter # Create the color_pairs dict @@ -271,7 +268,7 @@ def parse_color_string(string): last_color_attr = color_pair attrs = attrs[2:] # Remove colors except KeyError: - raise BadColorString('Bad color value in tag: %s,%s' % (fg, bg)) + raise BadColorString(f'Bad color value in tag: {fg},{bg}') # Check for additional attributes and OR them to the color_pair color_pair = apply_attrs(color_pair, attrs) last_color_attr = color_pair @@ -292,7 +289,7 @@ def parse_color_string(string): return ret -class ConsoleColorFormatter(object): +class ConsoleColorFormatter: """ Format help in a way suited to deluge CmdLine mode - colors, format, indentation... """ diff --git a/deluge/ui/console/utils/column.py b/deluge/ui/console/utils/column.py index d932159..ecbe04b 100644 --- a/deluge/ui/console/utils/column.py +++ b/deluge/ui/console/utils/column.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import copy import logging diff --git a/deluge/ui/console/utils/common.py b/deluge/ui/console/utils/common.py index df1c079..fdc88c4 100644 --- a/deluge/ui/console/utils/common.py +++ b/deluge/ui/console/utils/common.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- # # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # -from __future__ import unicode_literals - TORRENT_OPTIONS = { 'max_download_speed': float, 'max_upload_speed': float, diff --git a/deluge/ui/console/utils/curses_util.py b/deluge/ui/console/utils/curses_util.py index a0cd6dc..50b0444 100644 --- a/deluge/ui/console/utils/curses_util.py +++ b/deluge/ui/console/utils/curses_util.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2016 bendikro <bro.devel+deluge@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - try: import curses except ImportError: @@ -39,7 +36,7 @@ def is_int_chr(c): return c > 47 and c < 58 -class Curser(object): +class Curser: INVISIBLE = 0 NORMAL = 1 VERY_VISIBLE = 2 @@ -59,7 +56,7 @@ def safe_curs_set(visibility): pass -class ReadState(object): +class ReadState: IGNORED = 0 READ = 1 CHANGED = 2 diff --git a/deluge/ui/console/utils/format_utils.py b/deluge/ui/console/utils/format_utils.py index 029fb20..50ec191 100644 --- a/deluge/ui/console/utils/format_utils.py +++ b/deluge/ui/console/utils/format_utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import re from collections import deque from unicodedata import east_asian_width, normalize @@ -98,7 +95,7 @@ def f_seedrank_dash(seed_rank, seeding_time): def ftotal_sized(first, second): - return '%s (%s)' % ( + return '{} ({})'.format( deluge.common.fsize(first, shortform=True), deluge.common.fsize(second, shortform=True), ) @@ -159,7 +156,7 @@ def format_column(col, lim): if size >= lim - 1: return trim_string(col, lim, dbls > 0) else: - return '%s%s' % (col, ' ' * (lim - size)) + return '{}{}'.format(col, ' ' * (lim - size)) def format_row(row, column_widths): @@ -213,7 +210,7 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): mtc = mtchs.popleft() - offset clr = clrs.popleft() end_pos += len(clr) - s = '%s%s%s' % (s[:mtc], clr, s[mtc:]) + s = f'{s[:mtc]}{clr}{s[mtc:]}' return s for s in s1: @@ -238,11 +235,11 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): else: cstr = s - def append_indent(l, string, offset): + def append_indent(line, string, offset): """Prepends indent to string if specified""" if indent and offset != 0: string = indent + string - l.append(string) + line.append(string) while cstr: # max with for a line. If indent is specified, we account for this @@ -290,7 +287,7 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): last_color_string = '' for i, line in enumerate(ret): if i != 0: - ret[i] = '%s%s' % (last_color_string, ret[i]) + ret[i] = f'{last_color_string}{ret[i]}' colors = re.findall('\\{![^!]+!\\}', line) if colors: @@ -313,9 +310,9 @@ def pad_string(string, length, character=' ', side='right'): w = strwidth(string) diff = length - w if side == 'left': - return '%s%s' % (character * diff, string) + return f'{character * diff}{string}' elif side == 'right': - return '%s%s' % (string, character * diff) + return f'{string}{character * diff}' def delete_alt_backspace(input_text, input_cursor, sep_chars=' *?!._~-#$^;\'"/'): diff --git a/deluge/ui/console/widgets/__init__.py b/deluge/ui/console/widgets/__init__.py index a11e3f2..bc88a3b 100644 --- a/deluge/ui/console/widgets/__init__.py +++ b/deluge/ui/console/widgets/__init__.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - from deluge.ui.console.widgets.inputpane import BaseInputPane from deluge.ui.console.widgets.statusbars import StatusBars from deluge.ui.console.widgets.window import BaseWindow diff --git a/deluge/ui/console/widgets/fields.py b/deluge/ui/console/widgets/fields.py index 1966c66..d8d892d 100644 --- a/deluge/ui/console/widgets/fields.py +++ b/deluge/ui/console/widgets/fields.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> @@ -9,12 +8,9 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging import os -from deluge.common import PY2 from deluge.decorators import overrides from deluge.ui.console.modes.basemode import InputKeyHandler from deluge.ui.console.utils import colors @@ -35,7 +31,7 @@ log = logging.getLogger(__name__) class BaseField(InputKeyHandler): def __init__(self, parent=None, name=None, selectable=True, **kwargs): - super(BaseField, self).__init__() + super().__init__() self.name = name self.parent = parent self.fmt_keys = {} @@ -74,7 +70,7 @@ class BaseField(InputKeyHandler): def build_fmt_string(self, focused, active, value_key='msg', **kwargs): color_key, font_key = self.get_fmt_keys(focused, active, **kwargs) - return '{!%%(%s)s,%%(%s)s!}%%(%s)s{!%%(%s)s!}' % ( + return '{{!%({})s,%({})s!}}%({})s{{!%({})s!}}'.format( color_key, font_key, value_key, @@ -176,7 +172,7 @@ class InfoField(NoInputField): NoInputField.__init__(self, parent=parent, name=name, **kwargs) self.label = label self.value = value - self.txt = '%s %s' % (label, value) + self.txt = f'{label} {value}' @overrides(BaseField) def render(self, screen, row, col=0, **kwargs): @@ -187,9 +183,9 @@ class InfoField(NoInputField): def set_value(self, v): self.value = v if isinstance(v, float): - self.txt = '%s %.2f' % (self.label, self.value) + self.txt = f'{self.label} {self.value:.2f}' else: - self.txt = '%s %s' % (self.label, self.value) + self.txt = f'{self.label} {self.value}' class CheckedInput(InputField): @@ -202,7 +198,7 @@ class CheckedInput(InputField): checked_char='X', unchecked_char=' ', checkbox_format='[%s] ', - **kwargs + **kwargs, ): InputField.__init__(self, parent, name, message, **kwargs) self.set_value(checked) @@ -231,9 +227,7 @@ class CheckedInput(InputField): @overrides(BaseField) def get_fmt_keys(self, focused, active, **kwargs): - color_key, font_key = super(CheckedInput, self).get_fmt_keys( - focused, active, **kwargs - ) + color_key, font_key = super().get_fmt_keys(focused, active, **kwargs) if self.checked: color_key += '_checked' font_key += '_checked' @@ -284,7 +278,7 @@ class CheckedPlusInput(CheckedInput): child_always_visible=False, show_usage_hints=True, msg_fmt='%s ', - **kwargs + **kwargs, ): CheckedInput.__init__(self, parent, name, message, **kwargs) self.child = child @@ -372,7 +366,7 @@ class IntSpinInput(InputField): incr_large=10, strict_validation=False, fmt='%d', - **kwargs + **kwargs, ): InputField.__init__(self, parent, name, message, **kwargs) self.convert_func = int @@ -618,7 +612,7 @@ class SelectInput(InputField): active_index, active_default=False, require_select_action=True, - **kwargs + **kwargs, ): InputField.__init__(self, parent, name, message, **kwargs) self.opts = opts @@ -667,9 +661,7 @@ class SelectInput(InputField): @overrides(BaseField) def get_fmt_keys(self, focused, active, selected=False, **kwargs): - color_key, font_key = super(SelectInput, self).get_fmt_keys( - focused, active, **kwargs - ) + color_key, font_key = super().get_fmt_keys(focused, active, **kwargs) if selected: color_key += '_selected' font_key += '_selected' @@ -739,7 +731,7 @@ class TextInput(InputField): value, complete=False, activate_input=False, - **kwargs + **kwargs, ): InputField.__init__(self, parent, name, message, **kwargs) self.move_func = move_func @@ -815,7 +807,7 @@ class TextInput(InputField): focused=True, col=0, cursor_offset=0, - **kwargs + **kwargs, ): if not self.value and not active and len(self.default_value) != 0: self.value = self.default_value @@ -951,7 +943,7 @@ class TextInput(InputField): elif c > 31 and c < 256: # Emulate getwch stroke = chr(c) - uchar = '' if PY2 else stroke + uchar = stroke while not uchar: try: uchar = stroke.decode(self.parent.encoding) @@ -1061,9 +1053,9 @@ class ComboInput(InputField): # No match, so start at beginning select_in_range(0, selected) - from deluge.ui.console.widgets.popup import ( + from deluge.ui.console.widgets.popup import ( # Must import here SelectablePopup, - ) # Must import here + ) select_popup = SelectablePopup( self.parent, @@ -1081,7 +1073,7 @@ class ComboInput(InputField): choice[1], selectable=True, selected=choice[0] == self.get_value(), - **args + **args, ) self.parent.push_popup(select_popup) return util.ReadState.CHANGED @@ -1149,7 +1141,7 @@ class TextArea(TextField): for i, line in enumerate(lines): self.parent.add_string( row + i, - '%s%s' % (color, line), + f'{color}{line}', scr=screen, col=col, pad=False, @@ -1176,7 +1168,7 @@ class DividerField(NoInputField): selectable=False, fill_width=True, value_fmt='%s', - **kwargs + **kwargs, ): NoInputField.__init__( self, parent=parent, name=name, selectable=selectable, **kwargs diff --git a/deluge/ui/console/widgets/inputpane.py b/deluge/ui/console/widgets/inputpane.py index 097a6cb..d8d2175 100644 --- a/deluge/ui/console/widgets/inputpane.py +++ b/deluge/ui/console/widgets/inputpane.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> @@ -9,8 +8,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from deluge.decorators import overrides diff --git a/deluge/ui/console/widgets/popup.py b/deluge/ui/console/widgets/popup.py index d588bbb..4b0d027 100644 --- a/deluge/ui/console/widgets/popup.py +++ b/deluge/ui/console/widgets/popup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from deluge.decorators import overrides @@ -25,7 +22,7 @@ except ImportError: log = logging.getLogger(__name__) -class ALIGN(object): +class ALIGN: TOP_LEFT = 1 TOP_CENTER = 2 TOP_RIGHT = 3 @@ -38,7 +35,7 @@ class ALIGN(object): DEFAULT = MIDDLE_CENTER -class PopupsHandler(object): +class PopupsHandler: def __init__(self): self._popups = [] diff --git a/deluge/ui/console/widgets/sidebar.py b/deluge/ui/console/widgets/sidebar.py index cc23717..4015a13 100644 --- a/deluge/ui/console/widgets/sidebar.py +++ b/deluge/ui/console/widgets/sidebar.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2016 bendikro <bro.devel+deluge@gmail.com> # @@ -7,8 +6,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import curses import logging diff --git a/deluge/ui/console/widgets/statusbars.py b/deluge/ui/console/widgets/statusbars.py index fcf4f2f..1b91737 100644 --- a/deluge/ui/console/widgets/statusbars.py +++ b/deluge/ui/console/widgets/statusbars.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # @@ -7,13 +6,12 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import deluge.common import deluge.component as component -from deluge.core.preferencesmanager import DEFAULT_PREFS from deluge.ui.client import client +DEFAULT_DAEMON_PORT = 58846 + class StatusBars(component.Component): def __init__(self): @@ -38,19 +36,23 @@ class StatusBars(component.Component): def on_get_session_status(status): self.upload = deluge.common.fsize(status['payload_upload_rate']) self.download = deluge.common.fsize(status['payload_download_rate']) - self.connections = status['num_peers'] + self.connections = status['peer.num_peers_connected'] if 'dht_nodes' in status: - self.dht = status['dht_nodes'] + self.dht = status['dht.dht_nodes'] self.update_statusbars() def on_get_external_ip(external_ip): self.external_ip = external_ip - keys = ['num_peers', 'payload_upload_rate', 'payload_download_rate'] + keys = [ + 'peer.num_peers_connected', + 'payload_upload_rate', + 'payload_download_rate', + ] if self.config['dht']: - keys.append('dht_nodes') + keys.append('dht.dht_nodes') client.core.get_session_status(keys).addCallback(on_get_session_status) client.core.get_external_ip().addCallback(on_get_external_ip) @@ -76,7 +78,7 @@ class StatusBars(component.Component): connection_info += '{!white,blue,bold!}@{!red,blue,bold!}%s' # Port - if info[1] == DEFAULT_PREFS['daemon_port']: + if info[1] == DEFAULT_DAEMON_PORT: connection_info += '{!white,blue!}:%s' else: connection_info += '{!status!}:%s' diff --git a/deluge/ui/console/widgets/window.py b/deluge/ui/console/widgets/window.py index 2ef3528..77aff88 100644 --- a/deluge/ui/console/widgets/window.py +++ b/deluge/ui/console/widgets/window.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright (C) 2011 Nick Lanham <nick@afternight.org> # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> @@ -9,8 +8,6 @@ # See LICENSE for more details. # -from __future__ import unicode_literals - import logging from deluge.ui.console.modes.basemode import add_string, mkpad, mkpanel @@ -24,7 +21,7 @@ except ImportError: log = logging.getLogger(__name__) -class BaseWindow(object): +class BaseWindow: """ BaseWindow creates a curses screen to be used for showing panels and popup dialogs """ |