replace tabs with spaces

This commit is contained in:
Marcos Pinto 2008-07-18 03:04:02 +00:00
commit dac01416f0

View file

@ -33,9 +33,9 @@ import gobject
import sys import sys
class Enumerate(object): class Enumerate(object):
def __init__(self, names): def __init__(self, names):
for number, name in enumerate(names.split()): for number, name in enumerate(names.split()):
setattr(self, name, number) setattr(self, name, number)
NORMAL = chr(27) + '[00;00m' NORMAL = chr(27) + '[00;00m'
NORMAL_B = chr(27) + '[01m' NORMAL_B = chr(27) + '[01m'
@ -56,444 +56,444 @@ COLORS = Enumerate('RED GREEN YELLOW BLUE MAGENTA CYAN DEFAULT')
ATTRS = Enumerate('BOLD NORMAL') ATTRS = Enumerate('BOLD NORMAL')
def ATTR(color, attr, str): def ATTR(color, attr, str):
ret = chr(27) + '[' ret = chr(27) + '['
if attr == ATTRS.BOLD: if attr == ATTRS.BOLD:
ret = ret + "01" ret = ret + "01"
else: else:
ret = ret + "02" ret = ret + "02"
colormaps = { colormaps = {
COLORS.RED : "31", COLORS.RED : "31",
COLORS.GREEN : "32", COLORS.GREEN : "32",
COLORS.YELLOW : "33", COLORS.YELLOW : "33",
COLORS.BLUE : "34", COLORS.BLUE : "34",
COLORS.MAGENTA : "35", COLORS.MAGENTA : "35",
COLORS.CYAN : "36", COLORS.CYAN : "36",
COLORS.DEFAULT : "39" COLORS.DEFAULT : "39"
} }
if color in colormaps: if color in colormaps:
ret = ret + ";" + colormaps[color] ret = ret + ";" + colormaps[color]
ret = ret + "m" ret = ret + "m"
return ret + str + chr(27) + "[0m" return ret + str + chr(27) + "[0m"
status_keys = ["state", status_keys = ["state",
"save_path", "save_path",
"tracker", "tracker",
"next_announce", "next_announce",
"name", "name",
"total_size", "total_size",
"progress", "progress",
"num_seeds", "num_seeds",
"total_seeds", "total_seeds",
"num_peers", "num_peers",
"total_peers", "total_peers",
"eta", "eta",
"download_payload_rate", "download_payload_rate",
"upload_payload_rate", "upload_payload_rate",
"ratio", "ratio",
"distributed_copies", "distributed_copies",
"num_pieces", "num_pieces",
"piece_length", "piece_length",
"total_done", "total_done",
"files", "files",
"file_priorities", "file_priorities",
"file_progress", "file_progress",
"peers", "peers",
"is_seed", "is_seed",
] ]
class Command: class Command:
def __init__(self): def __init__(self):
pass pass
def execute(self, cmd): def execute(self, cmd):
pass pass
def usage(self): def usage(self):
print "" print ""
def help(self): def help(self):
pass pass
def match_torrents(self, array): def match_torrents(self, array):
torrents = [] torrents = []
def _got_session_state(tors): def _got_session_state(tors):
if not array or len(array) == 0: if not array or len(array) == 0:
for tor in tors: for tor in tors:
torrents.append(tor) torrents.append(tor)
return return
for match in array: for match in array:
for tor in tors: for tor in tors:
if match == tor[0:len(match)]: if match == tor[0:len(match)]:
torrents.append(tor) torrents.append(tor)
break break
client.get_session_state(_got_session_state) client.get_session_state(_got_session_state)
client.force_call() client.force_call()
return torrents return torrents
class CommandAdd(Command): class CommandAdd(Command):
"""Command to add a torrent.""" """Command to add a torrent."""
def execute(self, cmd): def execute(self, cmd):
if len(cmd) < 2: if len(cmd) < 2:
self.usage() self.usage()
return return
save_path = None save_path = None
readpath = False readpath = False
if cmd[1] == '-p': if cmd[1] == '-p':
if len(cmd) < 4: if len(cmd) < 4:
self.usage() self.usage()
return return
del cmd[1] del cmd[1]
readpath = True readpath = True
else: else:
def _got_config(configs): def _got_config(configs):
global save_path global save_path
save_path = configs['download_location'] save_path = configs['download_location']
client.get_config(_got_config) client.get_config(_got_config)
client.force_call() client.force_call()
command = " ".join(cmd[1:]) command = " ".join(cmd[1:])
paths = command.split(';') paths = command.split(';')
if readpath: if readpath:
save_path = paths[0].strip() # Perhaps verify that the path exists? save_path = paths[0].strip() # Perhaps verify that the path exists?
client.set_config({'download_location': save_path}) client.set_config({'download_location': save_path})
del paths[0] del paths[0]
if not save_path: if not save_path:
print "There's no save-path specified. You must specify a path to save the downloaded files.\n" print "There's no save-path specified. You must specify a path to save the downloaded files.\n"
return return
for iter in range(0, len(paths)): for iter in range(0, len(paths)):
paths[iter] = paths[iter].strip() paths[iter] = paths[iter].strip()
if len(paths[iter]) == 0: if len(paths[iter]) == 0:
del paths[iter] del paths[iter]
try: try:
client.add_torrent_file(paths) client.add_torrent_file(paths)
except Exception, msg: except Exception, msg:
print "*** Error:", str(msg), "\n" print "*** Error:", str(msg), "\n"
def usage(self): def usage(self):
print "Usage: add [-p <save-location>;] <torrent-file>; [<torrent-file>; ...]" print "Usage: add [-p <save-location>;] <torrent-file>; [<torrent-file>; ...]"
print " (Note that a ';' must follow a path)" print " (Note that a ';' must follow a path)"
print "" print ""
def help(self): def help(self):
print "Add a torrent" print "Add a torrent"
class CommandConfig(Command): class CommandConfig(Command):
def execute(self, cmd): def execute(self, cmd):
del cmd[0] del cmd[0]
def _on_get_config(config): def _on_get_config(config):
keys = config.keys() keys = config.keys()
keys.sort() keys.sort()
for key in keys: for key in keys:
if cmd and key not in cmd: continue if cmd and key not in cmd: continue
color = NORMAL color = NORMAL
value = config[key] value = config[key]
if isinstance(value, bool): if isinstance(value, bool):
color = YELLOW color = YELLOW
elif isinstance(value, int) or isinstance(value, float): elif isinstance(value, int) or isinstance(value, float):
color = GREEN color = GREEN
elif isinstance(value, str): elif isinstance(value, str):
color = CYAN color = CYAN
elif isinstance(value, list): elif isinstance(value, list):
color = MAGENTA color = MAGENTA
print ("* " + BLUE_B + "%s:" + color + " %s" + NORMAL) % (key, value) print ("* " + BLUE_B + "%s:" + color + " %s" + NORMAL) % (key, value)
client.get_config(_on_get_config) client.get_config(_on_get_config)
def usage(self): def usage(self):
print "Usage: configs [key1 [key2 ...]]" print "Usage: configs [key1 [key2 ...]]"
print "" print ""
def help(self): def help(self):
print "Show configuration values" print "Show configuration values"
class CommandConfigSet(Command): class CommandConfigSet(Command):
def execute(self, cmd): def execute(self, cmd):
key = cmd[1] key = cmd[1]
# Returns (correct_type, type_value) # Returns (correct_type, type_value)
def convert_type(target, source): def convert_type(target, source):
if isinstance(source, list): if isinstance(source, list):
return False, None return False, None
if isinstance(source, bool): if isinstance(source, bool):
# Because every non-empty string becomes 'True' # Because every non-empty string becomes 'True'
if target in ["True", "true", "1"]: if target in ["True", "true", "1"]:
return True, True return True, True
elif target in ["False", "false", "0"]: elif target in ["False", "false", "0"]:
return True, False return True, False
return False, None return False, None
try: try:
val = type(source)(target) val = type(source)(target)
return True, val return True, val
except: except:
pass pass
return False, None return False, None
def update_config_value(value, config_val): def update_config_value(value, config_val):
if config_val == None: if config_val == None:
print RED + "* Invalid configuration name '%s'" % key + NORMAL print RED + "* Invalid configuration name '%s'" % key + NORMAL
return return
success, value = convert_type(value, config_val) success, value = convert_type(value, config_val)
if not success: if not success:
print RED + "* Configuration value provided has incorrect type." + NORMAL print RED + "* Configuration value provided has incorrect type." + NORMAL
else: else:
client.set_config({key: value}) client.set_config({key: value})
client.force_call() client.force_call()
print GREEN + "* Configuration value successfully updated." + NORMAL print GREEN + "* Configuration value successfully updated." + NORMAL
return False return False
def _got_config_value(config_val): def _got_config_value(config_val):
global c_val global c_val
c_val = config_val c_val = config_val
value = " ".join(cmd[2:]) value = " ".join(cmd[2:])
client.get_config_value(_got_config_value, key) client.get_config_value(_got_config_value, key)
client.force_call() client.force_call()
update_config_value(value, c_val) update_config_value(value, c_val)
def help(self): def help(self):
print "Change a configuration setting" print "Change a configuration setting"
def usage(self): def usage(self):
print "Usage: config-set key value" print "Usage: config-set key value"
class CommandExit(Command): class CommandExit(Command):
def execute(self, cmd): def execute(self, cmd):
print "Thanks" print "Thanks"
sys.exit(0) sys.exit(0)
def help(self): def help(self):
print "Exit from the client." print "Exit from the client."
class CommandHelp(Command): class CommandHelp(Command):
def execute(self, cmd): def execute(self, cmd):
if len(cmd) < 2: if len(cmd) < 2:
print NORMAL_B + "Available commands:" + NORMAL print NORMAL_B + "Available commands:" + NORMAL
for cmd in sorted(commands.keys()): for cmd in sorted(commands.keys()):
print "\t*", "%s:" % (BLUE_B + cmd + NORMAL), print "\t*", "%s:" % (BLUE_B + cmd + NORMAL),
command = commands[cmd] command = commands[cmd]
command.help() command.help()
else: else:
for c in cmd[1:]: for c in cmd[1:]:
if c not in commands: if c not in commands:
print RED + "Unknown command:", c + NORMAL print RED + "Unknown command:", c + NORMAL
else: else:
print "*", "%s:" % (BLUE_B + c + NORMAL), print "*", "%s:" % (BLUE_B + c + NORMAL),
command = commands[c] command = commands[c]
command.help() command.help()
print GREEN, print GREEN,
command.usage() command.usage()
print NORMAL, print NORMAL,
def usage(self): def usage(self):
print "Usage: help [cmd1 [cmd2 ...]]" print "Usage: help [cmd1 [cmd2 ...]]"
print "" print ""
def help(self): def help(self):
print "Show help" print "Show help"
class CommandInfo(Command): class CommandInfo(Command):
def execute(self, cmd): def execute(self, cmd):
brief = (len(cmd) < 2) brief = (len(cmd) < 2)
torrents = self.match_torrents(cmd[1:]) torrents = self.match_torrents(cmd[1:])
for tor in torrents: for tor in torrents:
self.show_info(tor, brief) self.show_info(tor, brief)
def usage(self): def usage(self):
print "Usage: info [<torrent-id> [<torrent-id> ...]]" print "Usage: info [<torrent-id> [<torrent-id> ...]]"
print " You can give the first few characters of a torrent-id to identify the torrent." print " You can give the first few characters of a torrent-id to identify the torrent."
print "" print ""
def help(self): def help(self):
print "Show information about the torrents" print "Show information about the torrents"
def show_info(self, torrent, brief): def show_info(self, torrent, brief):
def _got_torrent_status(state): def _got_torrent_status(state):
print ATTR(COLORS.BLUE, ATTRS.BOLD, "*** ID:"), torrent print ATTR(COLORS.BLUE, ATTRS.BOLD, "*** ID:"), torrent
print ATTR(COLORS.BLUE, ATTRS.BOLD, "*** Name:"), state['name'] print ATTR(COLORS.BLUE, ATTRS.BOLD, "*** Name:"), state['name']
print ATTR(COLORS.BLUE, ATTRS.BOLD, "*** Path:"), state['save_path'] print ATTR(COLORS.BLUE, ATTRS.BOLD, "*** Path:"), state['save_path']
if not state['is_seed']: if not state['is_seed']:
print ATTR(COLORS.GREEN, 0, "*** Completed:"), common.fsize(state['total_done']) + "/" + common.fsize(state['total_size']) print ATTR(COLORS.GREEN, 0, "*** Completed:"), common.fsize(state['total_done']) + "/" + common.fsize(state['total_size'])
print ATTR(COLORS.GREEN, 0, "*** Status:"), state['state'] print ATTR(COLORS.GREEN, 0, "*** Status:"), state['state']
state['state_i'] = common.TORRENT_STATE.index(state['state']) state['state_i'] = common.TORRENT_STATE.index(state['state'])
if state['state_i'] == 2: # Downloading if state['state_i'] == 2: # Downloading
print ATTR(COLORS.GREEN, 0, "*** Download Speed:"), common.fspeed(state['download_payload_rate']) print ATTR(COLORS.GREEN, 0, "*** Download Speed:"), common.fspeed(state['download_payload_rate'])
if state['state_i'] in [2, 3]: # Downloading, or Seeding if state['state_i'] in [2, 3]: # Downloading, or Seeding
print ATTR(COLORS.GREEN, 0, "*** Upload Speed:"), common.fspeed(state['upload_payload_rate']) print ATTR(COLORS.GREEN, 0, "*** Upload Speed:"), common.fspeed(state['upload_payload_rate'])
if state['state_i'] == 2: # Downloading if state['state_i'] == 2: # Downloading
print ATTR(COLORS.GREEN, 0, "*** ETA:"), "%s" % common.ftime(state['eta']) print ATTR(COLORS.GREEN, 0, "*** ETA:"), "%s" % common.ftime(state['eta'])
if brief == False: if brief == False:
print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Seeders:"), "%s (%s)" % (state['num_seeds'], state['total_seeds']) print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Seeders:"), "%s (%s)" % (state['num_seeds'], state['total_seeds'])
print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Peers:"), "%s (%s)" % (state['num_peers'], state['total_peers']) print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Peers:"), "%s (%s)" % (state['num_peers'], state['total_peers'])
print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Share Ratio:"), "%.1f" % state['ratio'] print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Share Ratio:"), "%.1f" % state['ratio']
print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Availability:"), "%.1f" % state['distributed_copies'] print ATTR(COLORS.DEFAULT, ATTRS.BOLD, "*** Availability:"), "%.1f" % state['distributed_copies']
print ATTR(COLORS.CYAN, ATTRS.BOLD, "*** Files:") print ATTR(COLORS.CYAN, ATTRS.BOLD, "*** Files:")
for i, file in enumerate(state['files']): for i, file in enumerate(state['files']):
status = "" status = ""
if not state['is_seed']: if not state['is_seed']:
if state['file_priorities'][i] == 0: if state['file_priorities'][i] == 0:
status = " - Do not download" status = " - Do not download"
else: else:
status = " - %1.f%% completed" % (state['file_progress'][i] * 100) status = " - %1.f%% completed" % (state['file_progress'][i] * 100)
print "\t* %s (%s)%s" % (file['path'], common.fsize(file['size']), status) print "\t* %s (%s)%s" % (file['path'], common.fsize(file['size']), status)
print ATTR(COLORS.MAGENTA, ATTRS.BOLD, "*** Peers:") print ATTR(COLORS.MAGENTA, ATTRS.BOLD, "*** Peers:")
if len(state['peers']) == 0: if len(state['peers']) == 0:
print "\t* None" print "\t* None"
for peer in state['peers']: for peer in state['peers']:
print ("\t*" + BLUE_B + " %-21s" + GREEN_B + " %-25s " + CYAN + "Up: %-12s" + MAGENTA_B + " Down: %-12s" + NORMAL) % \ print ("\t*" + BLUE_B + " %-21s" + GREEN_B + " %-25s " + CYAN + "Up: %-12s" + MAGENTA_B + " Down: %-12s" + NORMAL) % \
(peer['ip'], peer['client'] + ["", " (seed)"][not not peer['seed']], (peer['ip'], peer['client'] + ["", " (seed)"][not not peer['seed']],
common.fspeed(peer['up_speed']), common.fspeed(peer['down_speed'])) common.fspeed(peer['up_speed']), common.fspeed(peer['down_speed']))
print "" print ""
client.get_torrent_status(_got_torrent_status, torrent, status_keys) client.get_torrent_status(_got_torrent_status, torrent, status_keys)
class CommandPause(Command): class CommandPause(Command):
def execute(self, cmd): def execute(self, cmd):
if len(cmd) < 2: if len(cmd) < 2:
self.usage() self.usage()
return return
try: try:
torrents = self.match_torrents(cmd[1:]) torrents = self.match_torrents(cmd[1:])
client.pause_torrent(torrents) client.pause_torrent(torrents)
except Exception, msg: except Exception, msg:
print "Error:", str(msg), "\n" print "Error:", str(msg), "\n"
def usage(self): def usage(self):
print "Usage: pause <torrent-id> [<torrent-id> ...]" print "Usage: pause <torrent-id> [<torrent-id> ...]"
print "" print ""
def help(self): def help(self):
print "Pause a torrent" print "Pause a torrent"
class CommandResume(Command): class CommandResume(Command):
def execute(self, cmd): def execute(self, cmd):
if len(cmd) < 2: if len(cmd) < 2:
self.usage() self.usage()
return return
try: try:
torrents = self.match_torrents(cmd[1:]) torrents = self.match_torrents(cmd[1:])
client.resume_torrent(torrents) client.resume_torrent(torrents)
except Exception, msg: except Exception, msg:
print "Error:", str(msg), "\n" print "Error:", str(msg), "\n"
def usage(self): def usage(self):
print "Usage: resume <torrent-id> [<torrent-id> ...]" print "Usage: resume <torrent-id> [<torrent-id> ...]"
print "" print ""
def help(self): def help(self):
print "Resume a torrent" print "Resume a torrent"
class CommandRemove(Command): class CommandRemove(Command):
def execute(self, cmd): def execute(self, cmd):
if len(cmd) < 2: if len(cmd) < 2:
self.usage() self.usage()
return return
try: try:
torrents = self.match_torrents(cmd[1:]) torrents = self.match_torrents(cmd[1:])
client.remove_torrent(torrents, False, False) client.remove_torrent(torrents, False, False)
except Exception, msg: except Exception, msg:
print "*** Error:", str(msg), "\n" print "*** Error:", str(msg), "\n"
def usage(self): def usage(self):
print "Usage: rm <torrent-id>" print "Usage: rm <torrent-id>"
print "" print ""
def help(self): def help(self):
print "Remove a torrent" print "Remove a torrent"
class CommandHalt(Command): class CommandHalt(Command):
def execute(self, cmd): def execute(self, cmd):
client.shutdown() client.shutdown()
def help(self): def help(self):
print "Shutdown the deluge server." print "Shutdown the deluge server."
class CommandConnect(Command): class CommandConnect(Command):
def execute(self, cmd): def execute(self, cmd):
host = 'localhost' host = 'localhost'
port = 58846 port = 58846
if len(cmd) > 1: if len(cmd) > 1:
host = cmd[1] host = cmd[1]
if len(cmd) > 2: if len(cmd) > 2:
port = int(cmd[2]) port = int(cmd[2])
if host[:7] != "http://": if host[:7] != "http://":
host = "http://" + host host = "http://" + host
client.set_core_uri("%s:%d" % (host, port)) client.set_core_uri("%s:%d" % (host, port))
def usage(self): def usage(self):
print "Usage: connect [<host> [<port>]]" print "Usage: connect [<host> [<port>]]"
print " 'localhost' is the default server. 58846 is the default port." print " 'localhost' is the default server. 58846 is the default port."
print "" print ""
def help(self): def help(self):
print "Connect to a new deluge server." print "Connect to a new deluge server."
commands = { commands = {
'add' : CommandAdd(), 'add' : CommandAdd(),
'configs' : CommandConfig(), 'configs' : CommandConfig(),
'config-set' : CommandConfigSet(), 'config-set' : CommandConfigSet(),
'exit' : CommandExit(), 'exit' : CommandExit(),
'help' : CommandHelp(), 'help' : CommandHelp(),
'info' : CommandInfo(), 'info' : CommandInfo(),
'pause' : CommandPause(), 'pause' : CommandPause(),
'quit' : CommandExit(), 'quit' : CommandExit(),
'resume' : CommandResume(), 'resume' : CommandResume(),
'rm' : CommandRemove(), 'rm' : CommandRemove(),
'del' : CommandRemove(), 'del' : CommandRemove(),
'halt' : CommandHalt(), 'halt' : CommandHalt(),
'connect' : CommandConnect(), 'connect' : CommandConnect(),
} }
logging.disable(logging.ERROR) logging.disable(logging.ERROR)
client.set_core_uri("http://localhost:58846") client.set_core_uri("http://localhost:58846")
class NullUI: class NullUI:
def __init__(self, args): def __init__(self, args):
print "Welcome to deluge-shell. Type 'help' to see a list of available commands." print "Welcome to deluge-shell. Type 'help' to see a list of available commands."
readline.read_init_file() readline.read_init_file()
while True: while True:
try: try:
inp = raw_input("> ").strip() inp = raw_input("> ").strip()
except: except:
inp = 'quit' inp = 'quit'
if len(inp) == 0: continue if len(inp) == 0: continue
inp = inp.split(" ") inp = inp.split(" ")
print "" print ""
cmd = inp[0] cmd = inp[0]
found = False found = False
if cmd not in commands: if cmd not in commands:
print RED + "Invalid command!" + NORMAL print RED + "Invalid command!" + NORMAL
commands['help'].execute([]) commands['help'].execute([])
else: else:
command = commands[cmd] command = commands[cmd]
try: try:
command.execute(inp) command.execute(inp)
client.force_call() client.force_call()
except deluge.error.NoCoreError, e: except deluge.error.NoCoreError, e:
print "*** Operation failed. You are not connected to a deluge daemon." print "*** Operation failed. You are not connected to a deluge daemon."
print " Perhaps you want to 'connect' first." print " Perhaps you want to 'connect' first."
print "" print ""
#except deluge.error.InvalidTorrent, e: #except deluge.error.InvalidTorrent, e:
# print "*** Operation failed. You tried to perform an operation on a non-existent torrent." # print "*** Operation failed. You tried to perform an operation on a non-existent torrent."
# print " Use the 'info' command for the list of torrents." # print " Use the 'info' command for the list of torrents."
# print "" # print ""
print print
print "Thanks." print "Thanks."