change the console ui to command based rather than option based

This commit is contained in:
Jimmy Kiselak 2015-10-15 14:12:22 -04:00
parent c902d25524
commit 5787802077
9 changed files with 934 additions and 676 deletions

View file

@ -1,4 +1,8 @@
class DownloadChoice(object): class DownloadOptionChoice(object):
"""A possible choice that can be picked for some option.
An option can have one or more choices that can be picked from.
"""
def __init__(self, value, short_description, long_description, bool_options_description=None): def __init__(self, value, short_description, long_description, bool_options_description=None):
self.value = value self.value = value
self.short_description = short_description self.short_description = short_description
@ -7,6 +11,7 @@ class DownloadChoice(object):
class DownloadOption(object): class DownloadOption(object):
"""An option for a user to select a value from several different choices."""
def __init__(self, option_types, long_description, short_description, default_value, def __init__(self, option_types, long_description, short_description, default_value,
default_value_description): default_value_description):
self.option_types = option_types self.option_types = option_types

View file

@ -1,5 +1,5 @@
from lbrynet.lbryfile.StreamDescriptor import LBRYFileStreamType, LBRYFileStreamDescriptorValidator from lbrynet.lbryfile.StreamDescriptor import LBRYFileStreamType, LBRYFileStreamDescriptorValidator
from lbrynet.core.DownloadOption import DownloadOption, DownloadChoice from lbrynet.core.DownloadOption import DownloadOption, DownloadOptionChoice
def add_lbry_file_to_sd_identifier(sd_identifier): def add_lbry_file_to_sd_identifier(sd_identifier):
@ -20,14 +20,14 @@ class LBRYFileOptions(object):
return "%f LBC/MB" % prm.min_blob_data_payment_rate return "%f LBC/MB" % prm.min_blob_data_payment_rate
rate_choices = [] rate_choices = []
rate_choices.append(DownloadChoice(prm.min_blob_data_payment_rate, rate_choices.append(DownloadOptionChoice(prm.min_blob_data_payment_rate,
"No change - %s" % get_default_data_rate_description(), "No change - %s" % get_default_data_rate_description(),
"No change - %s" % get_default_data_rate_description())) "No change - %s" % get_default_data_rate_description()))
if prm.min_blob_data_payment_rate is not None: if prm.min_blob_data_payment_rate is not None:
rate_choices.append(DownloadChoice(None, rate_choices.append(DownloadOptionChoice(None,
"Application default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate), "Application default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate),
"Application default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate))) "Application default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate)))
rate_choices.append(DownloadChoice(float, rate_choices.append(DownloadOptionChoice(float,
"Enter rate in LBC/MB", "Enter rate in LBC/MB",
"Enter rate in LBC/MB")) "Enter rate in LBC/MB"))
@ -41,7 +41,7 @@ class LBRYFileOptions(object):
), ),
DownloadOption( DownloadOption(
[ [
DownloadChoice(bool, DownloadOptionChoice(bool,
None, None,
None, None,
bool_options_description=("Allow", "Disallow")), bool_options_description=("Allow", "Disallow")),

View file

@ -1,5 +1,5 @@
from lbrynet.lbrylive.StreamDescriptor import LiveStreamType, LBRYLiveStreamDescriptorValidator from lbrynet.lbrylive.StreamDescriptor import LiveStreamType, LBRYLiveStreamDescriptorValidator
from lbrynet.core.DownloadOption import DownloadOption, DownloadChoice from lbrynet.core.DownloadOption import DownloadOption, DownloadOptionChoice
def add_live_stream_to_sd_identifier(sd_identifier, base_live_stream_payment_rate_manager): def add_live_stream_to_sd_identifier(sd_identifier, base_live_stream_payment_rate_manager):
@ -23,13 +23,13 @@ class LiveStreamOptions(object):
options = [ options = [
DownloadOption( DownloadOption(
[ [
DownloadChoice(None, DownloadOptionChoice(None,
"No change", "No change",
"No change"), "No change"),
DownloadChoice(None, DownloadOptionChoice(None,
"Application default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate), "Application default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate),
"Default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate)), "Default (%s LBC/MB)" % str(prm.base.min_blob_data_payment_rate)),
DownloadChoice(float, DownloadOptionChoice(float,
"Rate in LBC/MB", "Rate in LBC/MB",
"Rate in LBC/MB") "Rate in LBC/MB")
], ],
@ -40,13 +40,13 @@ class LiveStreamOptions(object):
), ),
DownloadOption( DownloadOption(
[ [
DownloadChoice(None, DownloadOptionChoice(None,
"No change", "No change",
"No change"), "No change"),
DownloadChoice(None, DownloadOptionChoice(None,
"Application default (%s LBC/MB)" % str(self.base_live_stream_prm.min_live_blob_info_payment_rate), "Application default (%s LBC/MB)" % str(self.base_live_stream_prm.min_live_blob_info_payment_rate),
"Default (%s LBC/MB)" % str(self.base_live_stream_prm.min_live_blob_info_payment_rate)), "Default (%s LBC/MB)" % str(self.base_live_stream_prm.min_live_blob_info_payment_rate)),
DownloadChoice(float, DownloadOptionChoice(float,
"Rate in LBC/MB", "Rate in LBC/MB",
"Rate in LBC/MB") "Rate in LBC/MB")
], ],
@ -57,10 +57,10 @@ class LiveStreamOptions(object):
), ),
DownloadOption( DownloadOption(
[ [
DownloadChoice(True, DownloadOptionChoice(True,
"Allow reuploading data downloaded for this file", "Allow reuploading data downloaded for this file",
"Allow reuploading"), "Allow reuploading"),
DownloadChoice(False, DownloadOptionChoice(False,
"Disallow reuploading data downloaded for this file", "Disallow reuploading data downloaded for this file",
"Disallow reuploading") "Disallow reuploading")
], ],

View file

@ -1,40 +0,0 @@
import logging
from zope.interface import implements
from twisted.internet import defer
from lbrynet.lbrynet_console.interfaces import ICommandHandlerFactory, ICommandHandler
log = logging.getLogger(__name__)
class CommandHandlerFactory(object):
implements(ICommandHandlerFactory)
short_help = "This should be overridden"
full_help = "This should really be overridden"
control_handler_class = None
def __init__(self, *args):
self.args = args
def get_handler(self, *args):
all_args = self.args + args
return self.control_handler_class(*all_args)
class CommandHandler(object):
implements(ICommandHandler)
def __init__(self):
self.finished_deferred = defer.Deferred()
def handle_line(self):
raise NotImplementedError()
class AddStream(CommandHandler):
pass
class AddStreamFactory(CommandHandlerFactory):
control_handler_class = AddStream
short_help = "Pull from the network"
full_help = "Pull from the network"

View file

@ -9,66 +9,8 @@ log = logging.getLogger(__name__)
class ConsoleControl(basic.LineReceiver): class ConsoleControl(basic.LineReceiver):
from os import linesep as delimiter from os import linesep as delimiter
def __init__(self, control_handlers):
self.control_handlers = {}
self.categories = {}
categories = set([category for category, handler in control_handlers])
prompt_number = 0
for category in categories:
self.categories[prompt_number] = category
for handler in [handler for cat, handler in control_handlers if cat == category]:
self.control_handlers[prompt_number] = handler
prompt_number += 1
self.current_handler = None
def connectionMade(self):
self.show_prompt()
def lineReceived(self, line):
def show_response(response):
if response is not None:
self.sendLine(response)
def show_error(err):
self.sendLine(err.getErrorMessage())
if self.current_handler is None:
try:
num = int(line)
except ValueError:
num = None
if num in self.control_handlers:
self.current_handler = self.control_handlers[num].get_handler()
line = None
if self.current_handler is not None:
try:
r = self.current_handler.handle_line(line)
done, ds = r[0], [d for d in r[1:] if d is not None]
except Exception as e:
done = True
ds = [defer.fail(e)]
if done is True:
self.current_handler = None
map(lambda d: d.addCallbacks(show_response, show_error), ds)
if self.current_handler is None:
self.show_prompt()
def show_prompt(self):
self.sendLine("Options:")
for num, handler in self.control_handlers.iteritems():
if num in self.categories:
self.sendLine("")
self.sendLine(self.categories[num])
self.sendLine("")
self.sendLine("[" + str(num) + "] " + handler.get_prompt_description())
class ConsoleControl2(basic.LineReceiver):
from os import linesep as delimiter
def __init__(self, command_handlers): def __init__(self, command_handlers):
self.command_handlers = command_handlers self.command_handlers = {h.command: h for h in command_handlers}
self.current_handler = None self.current_handler = None
def connectionMade(self): def connectionMade(self):
@ -79,7 +21,7 @@ class ConsoleControl2(basic.LineReceiver):
self.transport.write(s) self.transport.write(s)
def show_prompt(self): def show_prompt(self):
self.send(">") self.send("> ")
def show_help_overview(self): def show_help_overview(self):
self.sendLine("Available commands:") self.sendLine("Available commands:")
@ -93,9 +35,18 @@ class ConsoleControl2(basic.LineReceiver):
self.current_handler = None self.current_handler = None
self.show_prompt() self.show_prompt()
def handler_failed(self, err):
self.current_handler = None
self.sendLine("An error occurred:")
self.sendLine(err.getTraceback())
self.show_prompt()
def lineReceived(self, line): def lineReceived(self, line):
if self.current_handler is None: if self.current_handler is None:
words = line.split() words = line.split()
if len(words) == 0:
self.show_prompt()
return
command, args = words[0], words[1:] command, args = words[0], words[1:]
if command == "help": if command == "help":
if len(args) == 0: if len(args) == 0:
@ -127,22 +78,32 @@ class ConsoleControl2(basic.LineReceiver):
else: else:
command_handler = self.command_handlers[candidates[0]] command_handler = self.command_handlers[candidates[0]]
try: try:
self.current_handler = command_handler.get_handler(self, *args) self.current_handler = command_handler.get_handler(self)
except Exception as e: except Exception:
self.current_handler = None self.current_handler = None
import traceback import traceback
self.sendline(traceback.format_exc()) self.sendLine(traceback.format_exc())
log.error(traceback.format_exc()) log.error(traceback.format_exc())
self.show_prompt() self.show_prompt()
return return
self.current_handler.finished_deferred.addCallback(lambda _: self.handler_done()) try:
self.current_handler.start(*args)
except TypeError:
self.current_handler = None
self.sendLine("Invalid arguments. Type 'help <command>' for the argument list.")
import traceback
log.error(traceback.format_exc())
self.show_prompt()
return
self.current_handler.finished_deferred.addCallbacks(lambda _: self.handler_done(),
self.handler_failed)
else: else:
try: try:
self.current_handler.handle_line(line) self.current_handler.handle_line(line)
except Exception as e: except Exception as e:
self.current_handler = None self.current_handler = None
import traceback import traceback
self.sendline(traceback.format_exc()) self.sendLine(traceback.format_exc())
log.error(traceback.format_exc()) log.error(traceback.format_exc())
self.show_prompt() self.show_prompt()
return return

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@ import os.path
import argparse import argparse
from yapsy.PluginManager import PluginManager from yapsy.PluginManager import PluginManager
from twisted.internet import defer, threads, stdio, task from twisted.internet import defer, threads, stdio, task
from lbrynet.lbrynet_console.ConsoleControl import ConsoleControl, ConsoleControl2 from lbrynet.lbrynet_console.ConsoleControl import ConsoleControl
from lbrynet.lbrynet_console.LBRYSettings import LBRYSettings from lbrynet.lbrynet_console.LBRYSettings import LBRYSettings
from lbrynet.lbryfilemanager.LBRYFileManager import LBRYFileManager from lbrynet.lbryfilemanager.LBRYFileManager import LBRYFileManager
from lbrynet.conf import MIN_BLOB_DATA_PAYMENT_RATE # , MIN_BLOB_INFO_PAYMENT_RATE from lbrynet.conf import MIN_BLOB_DATA_PAYMENT_RATE # , MIN_BLOB_INFO_PAYMENT_RATE
@ -79,7 +79,6 @@ class LBRYConsole():
os.path.join(self.db_dir, "plugins"), os.path.join(self.db_dir, "plugins"),
os.path.join(os.path.dirname(__file__), "plugins"), os.path.join(os.path.dirname(__file__), "plugins"),
]) ])
self.control_handlers = []
self.command_handlers = [] self.command_handlers = []
self.query_handlers = {} self.query_handlers = {}
@ -120,7 +119,7 @@ class LBRYConsole():
def add_control_handlers(self, control_handlers): def add_control_handlers(self, control_handlers):
for control_handler in control_handlers: for control_handler in control_handlers:
self.control_handlers.append(control_handler) self.command_handlers.append(control_handler)
def add_query_handlers(self, query_handlers): def add_query_handlers(self, query_handlers):
@ -300,65 +299,42 @@ class LBRYConsole():
return defer.succeed(True) return defer.succeed(True)
def _setup_control_handlers(self): def _setup_control_handlers(self):
self.command_handlers = [('get', AddStreamFactory(self.sd_identifier, self.session,
self.session.wallet))]
handlers = [ handlers = [
('General', ApplicationStatusFactory(self.session.rate_limiter, self.session.dht_node),
ApplicationStatusFactory(self.session.rate_limiter, self.session.dht_node)), GetWalletBalancesFactory(self.session.wallet),
('General', ModifyApplicationDefaultsFactory(self),
GetWalletBalancesFactory(self.session.wallet)), ShutDownFactory(self),
('General', PeerStatsAndSettingsChooserFactory(self.session.peer_manager),
ModifyApplicationDefaultsFactory(self)), LBRYFileStatusFactory(self.lbry_file_manager),
('General', AddStreamFromSDFactory(self.sd_identifier, self.session.base_payment_rate_manager),
ShutDownFactory(self)),
('General',
PeerStatsAndSettingsChooserFactory(self.session.peer_manager)),
('lbryfile',
LBRYFileStatusFactory(self.lbry_file_manager)),
('Stream Downloading',
AddStreamFromSDFactory(self.sd_identifier, self.session.base_payment_rate_manager)),
('lbryfile',
DeleteLBRYFileChooserFactory(self.lbry_file_metadata_manager, self.session.blob_manager, DeleteLBRYFileChooserFactory(self.lbry_file_metadata_manager, self.session.blob_manager,
self.lbry_file_manager)), self.lbry_file_manager),
('lbryfile', ToggleLBRYFileRunningChooserFactory(self.lbry_file_manager),
ToggleLBRYFileRunningChooserFactory(self.lbry_file_manager)), CreateLBRYFileFactory(self.session, self.lbry_file_manager),
('lbryfile',
CreateLBRYFileFactory(self.session, self.lbry_file_manager)),
('lbryfile',
PublishStreamDescriptorChooserFactory(self.lbry_file_metadata_manager, PublishStreamDescriptorChooserFactory(self.lbry_file_metadata_manager,
self.session.blob_manager, self.session.blob_manager,
self.lbry_file_manager)), self.lbry_file_manager),
('lbryfile',
ShowPublishedSDHashesChooserFactory(self.lbry_file_metadata_manager, ShowPublishedSDHashesChooserFactory(self.lbry_file_metadata_manager,
self.lbry_file_manager)), self.lbry_file_manager),
('lbryfile', CreatePlainStreamDescriptorChooserFactory(self.lbry_file_manager),
CreatePlainStreamDescriptorChooserFactory(self.lbry_file_manager)), ShowLBRYFileStreamHashChooserFactory(self.lbry_file_manager),
('lbryfile', ModifyLBRYFileOptionsChooserFactory(self.lbry_file_manager),
ShowLBRYFileStreamHashChooserFactory(self.lbry_file_manager)), AddStreamFromHashFactory(self.sd_identifier, self.session),
('lbryfile',
ModifyLBRYFileOptionsChooserFactory(self.lbry_file_manager)),
('Stream Downloading',
AddStreamFromHashFactory(self.sd_identifier, self.session))
] ]
self.add_control_handlers(handlers) self.add_control_handlers(handlers)
if self.wallet_type == 'lbrycrd': if self.wallet_type == 'lbrycrd':
lbrycrd_handlers = [ lbrycrd_handlers = [
('Stream Downloading',
AddStreamFromLBRYcrdNameFactory(self.sd_identifier, self.session, AddStreamFromLBRYcrdNameFactory(self.sd_identifier, self.session,
self.session.wallet)), self.session.wallet),
('General',
ClaimNameFactory(self.session. wallet, self.lbry_file_manager, ClaimNameFactory(self.session. wallet, self.lbry_file_manager,
self.session.blob_manager, self.sd_identifier)), self.session.blob_manager, self.sd_identifier),
('General', GetNewWalletAddressFactory(self.session.wallet),
GetNewWalletAddressFactory(self.session.wallet))
] ]
self.add_control_handlers(lbrycrd_handlers) self.add_control_handlers(lbrycrd_handlers)
if self.peer_port is not None: if self.peer_port is not None:
server_handlers = [ server_handlers = [
('Server', ShowServerStatusFactory(self),
ShowServerStatusFactory(self)), ModifyServerSettingsFactory(self),
('Server',
ModifyServerSettingsFactory(self)),
] ]
self.add_control_handlers(server_handlers) self.add_control_handlers(server_handlers)
@ -435,8 +411,7 @@ class LBRYConsole():
return defer.succeed(True) return defer.succeed(True)
def _start_controller(self): def _start_controller(self):
#self.control_class(self.control_handlers) self.control_class(self.command_handlers)
ConsoleControl2(self.command_handlers)
return defer.succeed(True) return defer.succeed(True)
def _shut_down(self): def _shut_down(self):

View file

@ -12,3 +12,13 @@ class IControlHandlerFactory(Interface):
class IControlHandler(Interface): class IControlHandler(Interface):
def handle_line(self, line): def handle_line(self, line):
pass pass
class ICommandHandlerFactory(Interface):
def get_handler(self):
pass
class ICommandHandler(Interface):
def handle_line(self, line):
pass

View file

@ -1,111 +1,121 @@
from lbrynet.lbrynet_console.ControlHandlers import ControlHandler, ControlHandlerFactory from lbrynet.lbrynet_console.ControlHandlers import CommandHandler, CommandHandlerFactory
from lbrynet.lbrynet_console.ControlHandlers import RecursiveControlHandler, ModifyPaymentRate from lbrynet.lbrynet_console.ControlHandlers import RecursiveCommandHandler, ModifyPaymentRate
from twisted.internet import defer from twisted.internet import defer
class StartRepeater(ControlHandler): class StartRepeater(CommandHandler):
prompt_description = "Start the blind repeater" prompt_description = "Start the blind repeater"
def __init__(self, repeater, settings): def __init__(self, console, repeater, settings):
CommandHandler.__init__(self, console)
self.repeater = repeater self.repeater = repeater
self.settings = settings self.settings = settings
def handle_line(self, line): def start(self):
assert line is None, "Start repeater should not be passed any arguments" #assert line is None, "Start repeater should not be passed any arguments"
d = self.settings.save_repeater_status(running=True) d = self.settings.save_repeater_status(running=True)
d.addCallback(lambda _: self.repeater.start()) d.addCallback(lambda _: self.repeater.start())
d.addCallback(lambda _: "Started the repeater") d.addCallback(lambda _: self.console.sendLine("Started the repeater"))
return True, d d.chainDeferred(self.finished_deferred)
class StartRepeaterFactory(ControlHandlerFactory): class StartRepeaterFactory(CommandHandlerFactory):
control_handler_class = StartRepeater control_handler_class = StartRepeater
class StopRepeater(ControlHandler): class StopRepeater(CommandHandler):
prompt_description = "Stop the blind repeater" prompt_description = "Stop the blind repeater"
def __init__(self, repeater, settings): def __init__(self, console, repeater, settings):
CommandHandler.__init__(self, console)
self.repeater = repeater self.repeater = repeater
self.settings = settings self.settings = settings
def handle_line(self, line): def start(self):
assert line is None, "Stop repeater should not be passed any arguments" #assert line is None, "Stop repeater should not be passed any arguments"
d = self.settings.save_repeater_status(running=False) d = self.settings.save_repeater_status(running=False)
d.addCallback(lambda _: self.repeater.stop()) d.addCallback(lambda _: self.repeater.stop())
d.addCallback(lambda _: "Stopped the repeater") d.addCallback(lambda _: self.console.sendLine("Stopped the repeater"))
return True, d d.chainDeferred(self.finished_deferred)
class StopRepeaterFactory(ControlHandlerFactory): class StopRepeaterFactory(CommandHandlerFactory):
control_handler_class = StopRepeater control_handler_class = StopRepeater
class UpdateMaxSpace(ControlHandler): class UpdateMaxSpace(CommandHandler):
prompt_description = "Set the maximum space to be used by the blind repeater" prompt_description = "Set the maximum space to be used by the blind repeater"
line_prompt = "Maximum space (in bytes):" line_prompt = "Maximum space (in bytes):"
def __init__(self, repeater, settings): def __init__(self, console, repeater, settings):
CommandHandler.__init__(self, console)
self.repeater = repeater self.repeater = repeater
self.settings = settings self.settings = settings
def start(self):
self.console.sendLine(self.line_prompt)
def handle_line(self, line): def handle_line(self, line):
if line is None: d = self._set_max_space(line)
return False, defer.succeed(self.line_prompt) d.chainDeferred(self.finished_deferred)
return True, self._set_max_space(line)
def _set_max_space(self, line): def _set_max_space(self, line):
max_space = int(line) max_space = int(line)
d = self.settings.save_max_space(max_space) d = self.settings.save_max_space(max_space)
d.addCallback(lambda _: self.repeater.set_max_space(max_space)) d.addCallback(lambda _: self.repeater.set_max_space(max_space))
d.addCallback(lambda _: "Set the maximum space to " + str(max_space) + " bytes") d.addCallback(lambda _: self.console.sendLine("Set the maximum space to " + str(max_space) + " bytes"))
return d return d
class UpdateMaxSpaceFactory(ControlHandlerFactory): class UpdateMaxSpaceFactory(CommandHandlerFactory):
control_handler_class = UpdateMaxSpace control_handler_class = UpdateMaxSpace
class AddApprovedPeer(ControlHandler): class AddApprovedPeer(CommandHandler):
prompt_description = "Add a peer to the approved list of peers to check for valuable blob hashes" prompt_description = "Add a peer to the approved list of peers to check for valuable blob hashes"
host_prompt = "Peer host in dotted quad (e.g. 127.0.0.1)" host_prompt = "Peer host in dotted quad (e.g. 127.0.0.1)"
port_prompt = "Peer port (e.g. 4444)" port_prompt = "Peer port (e.g. 4444)"
def __init__(self, repeater, peer_manager, settings): def __init__(self, console, repeater, peer_manager, settings):
CommandHandler.__init__(self, console)
self.repeater = repeater self.repeater = repeater
self.peer_manager = peer_manager self.peer_manager = peer_manager
self.settings = settings self.settings = settings
self.host_to_add = None self.host_to_add = None
def start(self):
self.console.sendLine(self.host_prompt)
def handle_line(self, line): def handle_line(self, line):
if line is None: #if line is None:
return False, defer.succeed(self.host_prompt) # return False, defer.succeed(self.host_prompt)
elif self.host_to_add is None: if self.host_to_add is None:
self.host_to_add = line self.host_to_add = line
return False, defer.succeed(self.port_prompt) self.console.sendLine(self.port_prompt)
else: else:
self.host_to_add, host = None, self.host_to_add self.host_to_add, host = None, self.host_to_add
return True, self._add_peer(host, line) d = self._add_peer(host, line)
d.chainDeferred(self.finished_deferred)
def _add_peer(self, host, port): def _add_peer(self, host, port):
peer = self.peer_manager.get_peer(host, int(port)) peer = self.peer_manager.get_peer(host, int(port))
d = self.settings.save_approved_peer(host, int(port)) d = self.settings.save_approved_peer(host, int(port))
d.addCallback(lambda _: self.repeater.add_approved_peer(peer)) d.addCallback(lambda _: self.repeater.add_approved_peer(peer))
d.addCallback(lambda _: "Successfully added peer") d.addCallback(lambda _: self.console.sendLine("Successfully added peer"))
return d return d
class AddApprovedPeerFactory(ControlHandlerFactory): class AddApprovedPeerFactory(CommandHandlerFactory):
control_handler_class = AddApprovedPeer control_handler_class = AddApprovedPeer
class ApprovedPeerChooser(RecursiveControlHandler): class ApprovedPeerChooser(RecursiveCommandHandler):
def __init__(self, repeater, factory_class, *args, **kwargs): def __init__(self, console, repeater, factory_class, *args, **kwargs):
self.repeater = repeater self.repeater = repeater
self.factory_class = factory_class self.factory_class = factory_class
self.args = args self.args = args
RecursiveControlHandler.__init__(self, **kwargs) RecursiveCommandHandler.__init__(self, console, **kwargs)
def _get_control_handler_factories(self): def _get_control_handler_factories(self):
control_handler_factories = [] control_handler_factories = []
@ -114,7 +124,7 @@ class ApprovedPeerChooser(RecursiveControlHandler):
return control_handler_factories return control_handler_factories
class ApprovedPeerChooserFactory(ControlHandlerFactory): class ApprovedPeerChooserFactory(CommandHandlerFactory):
def get_prompt_description(self): def get_prompt_description(self):
peer = self.args[0] peer = self.args[0]
return str(peer) return str(peer)
@ -123,30 +133,32 @@ class ApprovedPeerChooserFactory(ControlHandlerFactory):
class DeleteApprovedPeerChooser(ApprovedPeerChooser): class DeleteApprovedPeerChooser(ApprovedPeerChooser):
prompt_description = "Remove a peer from the approved list of peers to check for valuable blob hashes" prompt_description = "Remove a peer from the approved list of peers to check for valuable blob hashes"
def __init__(self, repeater, settings): def __init__(self, console, repeater, settings):
ApprovedPeerChooser.__init__(self, repeater, DeleteApprovedPeerFactory, repeater, settings, ApprovedPeerChooser.__init__(self, console, repeater, DeleteApprovedPeerFactory, repeater,
exit_after_one_done=True) settings, exit_after_one_done=True)
class DeleteApprovedPeerChooserFactory(ControlHandlerFactory): class DeleteApprovedPeerChooserFactory(CommandHandlerFactory):
control_handler_class = DeleteApprovedPeerChooser control_handler_class = DeleteApprovedPeerChooser
class DeleteApprovedPeer(ControlHandler): class DeleteApprovedPeer(CommandHandler):
prompt_description = "Remove a peer from the approved list of peers to check for valuable blob hashes" prompt_description = "Remove a peer from the approved list of peers to check for valuable blob hashes"
def __init__(self, peer, repeater, settings): def __init__(self, console, peer, repeater, settings):
CommandHandler.__init__(self, console)
self.repeater = repeater self.repeater = repeater
self.settings = settings self.settings = settings
self.peer_to_remove = peer self.peer_to_remove = peer
def handle_line(self, line): def start(self):
return True, self._remove_peer() d = self._remove_peer()
d.chainDeferred(self.finished_deferred)
def _remove_peer(self): def _remove_peer(self):
d = self.settings.remove_approved_peer(self.peer_to_remove.host, int(self.peer_to_remove.port)) d = self.settings.remove_approved_peer(self.peer_to_remove.host, int(self.peer_to_remove.port))
d.addCallback(lambda _: self.repeater.remove_approved_peer(self.peer_to_remove)) d.addCallback(lambda _: self.repeater.remove_approved_peer(self.peer_to_remove))
d.addCallback(lambda _: "Successfully removed peer") d.addCallback(lambda _: self.console.sendLine("Successfully removed peer"))
return d return d
@ -154,38 +166,43 @@ class DeleteApprovedPeerFactory(ApprovedPeerChooserFactory):
control_handler_class = DeleteApprovedPeer control_handler_class = DeleteApprovedPeer
class ShowApprovedPeers(ControlHandler): class ShowApprovedPeers(CommandHandler):
prompt_description = "Show the list of peers approved to be checked for valuable blob hashes" prompt_description = "Show the list of peers approved to be checked for valuable blob hashes"
def __init__(self, repeater): def __init__(self, console, repeater):
CommandHandler.__init__(self, console)
self.repeater = repeater self.repeater = repeater
def handle_line(self, line): def start(self):
assert line is None, "Show approved peers should not be passed any arguments" #assert line is None, "Show approved peers should not be passed any arguments"
return True, self._show_peers() d = self._show_peers()
d.chainDeferred(self.finished_deferred)
def _show_peers(self): def _show_peers(self):
peer_string = "Approved peers:\n" peer_string = "Approved peers:\n"
for peer in self.repeater.approved_peers: for peer in self.repeater.approved_peers:
peer_string += str(peer) + "\n" peer_string += str(peer) + "\n"
return defer.succeed(peer_string) self.console.sendLine(peer_string)
return defer.succeed(None)
class ShowApprovedPeersFactory(ControlHandlerFactory): class ShowApprovedPeersFactory(CommandHandlerFactory):
control_handler_class = ShowApprovedPeers control_handler_class = ShowApprovedPeers
class RepeaterStatus(ControlHandler): class RepeaterStatus(CommandHandler):
prompt_description = "Show the repeater's status" prompt_description = "Show the repeater's status"
def __init__(self, repeater): def __init__(self, console, repeater):
CommandHandler.__init__(self, console)
self.repeater = repeater self.repeater = repeater
def handle_line(self, line): def start(self):
assert line is None, "Show repeater status should not be passed any arguments" #assert line is None, "Show repeater status should not be passed any arguments"
return True, defer.maybeDeferred(self._get_status) self._show_status()
self.finished_deferred.callback(None)
def _get_status(self): def _show_status(self):
status_string = "Repeater status: " + self.repeater.status() + "\n" status_string = "Repeater status: " + self.repeater.status() + "\n"
if self.repeater.stopped is False: if self.repeater.stopped is False:
@ -197,25 +214,25 @@ class RepeaterStatus(ControlHandler):
status_string += "Maximum space: " + str(max_space) + " bytes\n" status_string += "Maximum space: " + str(max_space) + " bytes\n"
status_string += "Space used: " + str(space_used) + " bytes\n" status_string += "Space used: " + str(space_used) + " bytes\n"
return defer.succeed(status_string) self.console.sendLine(status_string)
class RepeaterStatusFactory(ControlHandlerFactory): class RepeaterStatusFactory(CommandHandlerFactory):
control_handler_class = RepeaterStatus control_handler_class = RepeaterStatus
class ModifyDataPaymentRate(ModifyPaymentRate): class ModifyDataPaymentRate(ModifyPaymentRate):
prompt_description = "Modify Blind Repeater data payment rate" prompt_description = "Modify Blind Repeater data payment rate"
def __init__(self, repeater, settings): def __init__(self, console, repeater, settings):
ModifyPaymentRate.__init__(self) ModifyPaymentRate.__init__(self, console)
self._prompt_choices['unset'] = (self._unset, "Use the application default data rate") self._prompt_choices['unset'] = (self._unset, "Use the application default data rate")
self.payment_rate_manager = repeater.payment_rate_manager self.payment_rate_manager = repeater.payment_rate_manager
self.settings = settings self.settings = settings
def _unset(self): def _unset(self):
self._set_rate(None) self._set_rate(None)
return True, defer.succeed("Using the application default data rate") return defer.succeed("Using the application default data rate")
def _set_rate(self, rate): def _set_rate(self, rate):
@ -237,15 +254,15 @@ class ModifyDataPaymentRate(ModifyPaymentRate):
return status return status
class ModifyDataPaymentRateFactory(ControlHandlerFactory): class ModifyDataPaymentRateFactory(CommandHandlerFactory):
control_handler_class = ModifyDataPaymentRate control_handler_class = ModifyDataPaymentRate
class ModifyInfoPaymentRate(ModifyPaymentRate): class ModifyInfoPaymentRate(ModifyPaymentRate):
prompt_description = "Modify Blind Repeater valuable info payment rate" prompt_description = "Modify Blind Repeater valuable info payment rate"
def __init__(self, repeater, settings): def __init__(self, console, repeater, settings):
ModifyPaymentRate.__init__(self) ModifyPaymentRate.__init__(self, console)
self.payment_rate_manager = repeater.payment_rate_manager self.payment_rate_manager = repeater.payment_rate_manager
self.settings = settings self.settings = settings
@ -264,15 +281,15 @@ class ModifyInfoPaymentRate(ModifyPaymentRate):
return status return status
class ModifyInfoPaymentRateFactory(ControlHandlerFactory): class ModifyInfoPaymentRateFactory(CommandHandlerFactory):
control_handler_class = ModifyInfoPaymentRate control_handler_class = ModifyInfoPaymentRate
class ModifyHashPaymentRate(ModifyPaymentRate): class ModifyHashPaymentRate(ModifyPaymentRate):
prompt_description = "Modify Blind Repeater valuable hash payment rate" prompt_description = "Modify Blind Repeater valuable hash payment rate"
def __init__(self, repeater, settings): def __init__(self, console, repeater, settings):
ModifyPaymentRate.__init__(self) ModifyPaymentRate.__init__(self, console)
self.payment_rate_manager = repeater.payment_rate_manager self.payment_rate_manager = repeater.payment_rate_manager
self.settings = settings self.settings = settings
@ -291,18 +308,18 @@ class ModifyHashPaymentRate(ModifyPaymentRate):
return status return status
class ModifyHashPaymentRateFactory(ControlHandlerFactory): class ModifyHashPaymentRateFactory(CommandHandlerFactory):
control_handler_class = ModifyHashPaymentRate control_handler_class = ModifyHashPaymentRate
class ModifyRepeaterOptions(RecursiveControlHandler): class ModifyRepeaterOptions(RecursiveCommandHandler):
prompt_description = "Modify Blind Repeater options" prompt_description = "Modify Blind Repeater options"
def __init__(self, repeater, lbry_session, settings): def __init__(self, console, repeater, lbry_session, settings):
self.repeater = repeater self.repeater = repeater
self.lbry_session = lbry_session self.lbry_session = lbry_session
self.settings = settings self.settings = settings
RecursiveControlHandler.__init__(self) RecursiveCommandHandler.__init__(self, console)
def _get_control_handler_factories(self): def _get_control_handler_factories(self):
return [ModifyDataPaymentRateFactory(self.repeater, self.settings), return [ModifyDataPaymentRateFactory(self.repeater, self.settings),
@ -314,5 +331,5 @@ class ModifyRepeaterOptions(RecursiveControlHandler):
] ]
class ModifyRepeaterOptionsFactory(ControlHandlerFactory): class ModifyRepeaterOptionsFactory(CommandHandlerFactory):
control_handler_class = ModifyRepeaterOptions control_handler_class = ModifyRepeaterOptions