diff options
author | RaNaN <Mast3rRaNaN@hotmail.de> | 2011-02-14 14:26:29 +0100 |
---|---|---|
committer | RaNaN <Mast3rRaNaN@hotmail.de> | 2011-02-14 14:26:29 +0100 |
commit | e811e55a8e8e451c6fc7b723f26a6351f997a14e (patch) | |
tree | 026b350bd54b40aa73ec115ff9b83800351e1a8d | |
parent | little SO fix (diff) | |
download | pyload-e811e55a8e8e451c6fc7b723f26a6351f997a14e.tar.xz |
some parts of cli working again
-rw-r--r-- | module/database/FileDatabase.py | 5 | ||||
-rw-r--r-- | module/remote/thriftbackend/Handler.py | 8 | ||||
-rw-r--r-- | module/remote/thriftbackend/ThriftClient.py | 5 | ||||
-rw-r--r-- | module/remote/thriftbackend/pyload.thrift | 13 | ||||
-rw-r--r-- | module/remote/thriftbackend/thriftgen/pyload/Pyload.py | 44 | ||||
-rw-r--r-- | module/remote/thriftbackend/thriftgen/pyload/ttypes.py | 124 | ||||
-rwxr-xr-x | pyLoadCli.py | 371 | ||||
-rwxr-xr-x | pyLoadCore.py | 2 |
8 files changed, 348 insertions, 224 deletions
diff --git a/module/database/FileDatabase.py b/module/database/FileDatabase.py index 66dfd3c6c..c539bcaf6 100644 --- a/module/database/FileDatabase.py +++ b/module/database/FileDatabase.py @@ -184,11 +184,10 @@ class FileHandler: """deletes links""" f = self.getFile(id) - pid = f.packageid - if not f: return None - + + pid = f.packageid e = RemoveEvent("file", id, "collector" if not f.package().queue else "queue") diff --git a/module/remote/thriftbackend/Handler.py b/module/remote/thriftbackend/Handler.py index 91848941b..b1a7349bc 100644 --- a/module/remote/thriftbackend/Handler.py +++ b/module/remote/thriftbackend/Handler.py @@ -74,7 +74,7 @@ class Handler(Iface): self.serverMethods.unpause_server() def togglePause(self): - return self.serverMethods.toggle_server() + return self.serverMethods.toggle_pause() def statusServer(self): status = self.serverMethods.status_server() @@ -172,6 +172,9 @@ class Handler(Iface): pdata = PackageData() rawData = self.serverMethods.get_package_data(pid) + if not rawData: + raise PackageDoesNotExists(pid) + pdata.pid = rawData["id"] pdata.name = rawData["name"] pdata.folder = rawData["folder"] @@ -195,7 +198,8 @@ class Handler(Iface): if rawData: rawData = rawData.values()[0] else: - return None + raise FileDoesNotExists(fid) + fdata = self._convertPyFile(rawData) return fdata diff --git a/module/remote/thriftbackend/ThriftClient.py b/module/remote/thriftbackend/ThriftClient.py index 16bba7d1f..c6a48df2b 100644 --- a/module/remote/thriftbackend/ThriftClient.py +++ b/module/remote/thriftbackend/ThriftClient.py @@ -14,6 +14,11 @@ from Socket import Socket from Protocol import Protocol from thriftgen.pyload import Pyload +from thriftgen.pyload.Pyload import PackageDoesNotExists +from thriftgen.pyload.Pyload import FileDoesNotExists + + +ConnectionClosed = TTransport.TTransportException class WrongLogin(Exception): pass diff --git a/module/remote/thriftbackend/pyload.thrift b/module/remote/thriftbackend/pyload.thrift index 3cbd62d7a..a8c295339 100644 --- a/module/remote/thriftbackend/pyload.thrift +++ b/module/remote/thriftbackend/pyload.thrift @@ -151,6 +151,15 @@ struct AccountData { 4: optional map<string, string> options } +exception PackageDoesNotExists{ + 1: PackageID pid +} + +exception FileDoesNotExists{ + 1: FileID fid +} + + service Pyload { //general string getConfigValue(1: string category, 2: string option, 3: string section), @@ -173,8 +182,8 @@ service Pyload { //downloads list<DownloadInfo> statusDownloads(), PackageID addPackage(1: string name, 2: LinkList links, 3: Destination dest), - PackageData getPackageData(1: PackageID pid), - FileData getFileData(1: FileID fid), + PackageData getPackageData(1: PackageID pid) throws (1: PackageDoesNotExists e), + FileData getFileData(1: FileID fid) throws (1: FileDoesNotExists e), void deleteFiles(1: list<FileID> fids), void deletePackages(1: list<PackageID> pids), list<PackageInfo> getQueue(), diff --git a/module/remote/thriftbackend/thriftgen/pyload/Pyload.py b/module/remote/thriftbackend/thriftgen/pyload/Pyload.py index 19e972559..7c2372745 100644 --- a/module/remote/thriftbackend/thriftgen/pyload/Pyload.py +++ b/module/remote/thriftbackend/thriftgen/pyload/Pyload.py @@ -843,6 +843,8 @@ class Client(Iface): self._iprot.readMessageEnd() if result.success != None: return result.success + if result.e != None: + raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, "getPackageData failed: unknown result"); def getFileData(self, fid): @@ -873,6 +875,8 @@ class Client(Iface): self._iprot.readMessageEnd() if result.success != None: return result.success + if result.e != None: + raise result.e raise TApplicationException(TApplicationException.MISSING_RESULT, "getFileData failed: unknown result"); def deleteFiles(self, fids): @@ -2111,7 +2115,10 @@ class Processor(Iface, TProcessor): args.read(iprot) iprot.readMessageEnd() result = getPackageData_result() - result.success = self._handler.getPackageData(args.pid) + try: + result.success = self._handler.getPackageData(args.pid) + except PackageDoesNotExists, e: + result.e = e oprot.writeMessageBegin("getPackageData", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() @@ -2122,7 +2129,10 @@ class Processor(Iface, TProcessor): args.read(iprot) iprot.readMessageEnd() result = getFileData_result() - result.success = self._handler.getFileData(args.fid) + try: + result.success = self._handler.getFileData(args.fid) + except FileDoesNotExists, e: + result.e = e oprot.writeMessageBegin("getFileData", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() @@ -4501,14 +4511,17 @@ class getPackageData_result: """ Attributes: - success + - e """ thrift_spec = ( (0, TType.STRUCT, 'success', (PackageData, PackageData.thrift_spec), None, ), # 0 + (1, TType.STRUCT, 'e', (PackageDoesNotExists, PackageDoesNotExists.thrift_spec), None, ), # 1 ) - def __init__(self, success=None,): + def __init__(self, success=None, e=None,): self.success = success + self.e = e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: @@ -4525,6 +4538,12 @@ class getPackageData_result: self.success.read(iprot) else: iprot.skip(ftype) + elif fid == 1: + if ftype == TType.STRUCT: + self.e = PackageDoesNotExists() + self.e.read(iprot) + else: + iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() @@ -4539,6 +4558,10 @@ class getPackageData_result: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() + if self.e != None: + oprot.writeFieldBegin('e', TType.STRUCT, 1) + self.e.write(oprot) + oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): @@ -4619,14 +4642,17 @@ class getFileData_result: """ Attributes: - success + - e """ thrift_spec = ( (0, TType.STRUCT, 'success', (FileData, FileData.thrift_spec), None, ), # 0 + (1, TType.STRUCT, 'e', (FileDoesNotExists, FileDoesNotExists.thrift_spec), None, ), # 1 ) - def __init__(self, success=None,): + def __init__(self, success=None, e=None,): self.success = success + self.e = e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: @@ -4643,6 +4669,12 @@ class getFileData_result: self.success.read(iprot) else: iprot.skip(ftype) + elif fid == 1: + if ftype == TType.STRUCT: + self.e = FileDoesNotExists() + self.e.read(iprot) + else: + iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() @@ -4657,6 +4689,10 @@ class getFileData_result: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() + if self.e != None: + oprot.writeFieldBegin('e', TType.STRUCT, 1) + self.e.write(oprot) + oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): diff --git a/module/remote/thriftbackend/thriftgen/pyload/ttypes.py b/module/remote/thriftbackend/thriftgen/pyload/ttypes.py index 10964d127..370858d4e 100644 --- a/module/remote/thriftbackend/thriftgen/pyload/ttypes.py +++ b/module/remote/thriftbackend/thriftgen/pyload/ttypes.py @@ -1689,3 +1689,127 @@ class AccountData: def __ne__(self, other): return not (self == other) + +class PackageDoesNotExists(Exception): + """ + Attributes: + - pid + """ + + thrift_spec = ( + None, # 0 + (1, TType.I32, 'pid', None, None, ), # 1 + ) + + def __init__(self, pid=None,): + self.pid = pid + + def read(self, iprot): + if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: + fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.I32: + self.pid = iprot.readI32(); + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() + + def write(self, oprot): + if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: + oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) + return + oprot.writeStructBegin('PackageDoesNotExists') + if self.pid != None: + oprot.writeFieldBegin('pid', TType.I32, 1) + oprot.writeI32(self.pid) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() + def validate(self): + return + + + def __str__(self): + return repr(self) + + def __repr__(self): + L = ['%s=%r' % (key, value) + for key, value in self.__dict__.iteritems()] + return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + + def __ne__(self, other): + return not (self == other) + +class FileDoesNotExists(Exception): + """ + Attributes: + - fid + """ + + thrift_spec = ( + None, # 0 + (1, TType.I32, 'fid', None, None, ), # 1 + ) + + def __init__(self, fid=None,): + self.fid = fid + + def read(self, iprot): + if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: + fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.I32: + self.fid = iprot.readI32(); + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() + + def write(self, oprot): + if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: + oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) + return + oprot.writeStructBegin('FileDoesNotExists') + if self.fid != None: + oprot.writeFieldBegin('fid', TType.I32, 1) + oprot.writeI32(self.fid) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() + def validate(self): + return + + + def __str__(self): + return repr(self) + + def __repr__(self): + L = ['%s=%r' % (key, value) + for key, value in self.__dict__.iteritems()] + return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + + def __ne__(self, other): + return not (self == other) diff --git a/pyLoadCli.py b/pyLoadCli.py index 3a1a13384..cc5e08e35 100755 --- a/pyLoadCli.py +++ b/pyLoadCli.py @@ -17,18 +17,17 @@ # along with this program; if not, see <http://www.gnu.org/licenses/>. # ### -from getopt import GetoptError -from getopt import getopt +from getopt import GetoptError, getopt + import gettext from itertools import islice import os -import os.path +from os import _exit from os.path import join import sys from sys import exit import threading from time import sleep -import xmlrpclib from traceback import print_exc from codecs import getwriter @@ -37,15 +36,13 @@ sys.stdout = getwriter("utf8")(sys.stdout, errors="replace") from module import InitHomeDir from module.ConfigParser import ConfigParser +from module.remote.thriftbackend.ThriftClient import ThriftClient, NoConnection, NoSSL, WrongLogin, PackageDoesNotExists, ConnectionClosed -if sys.stdout.encoding.lower().startswith("utf"): - conv = unicode -else: - conv = str - -class pyLoadCli: - def __init__(self, server_url): - self.core = xmlrpclib.ServerProxy(server_url, allow_none=True) +class Cli: + def __init__(self, client, command): + self.client = client + self.command = command + self.getch = _Getch() self.input = "" self.pos = [0, 0, 0] @@ -54,12 +51,6 @@ class pyLoadCli: self.new_package = {} - try: - self.core.get_server_version() - except: - print _("pyLoadCore not running") - exit() - self.links_added = 0 os.system("clear") @@ -84,7 +75,7 @@ class pyLoadCli: try: self.handle_input() except Exception, e: - self.println(2, red(conv(e))) + self.println(2, red(e)) self.input = "" #enter self.print_input() elif ord(inp) == 127: @@ -103,12 +94,9 @@ class pyLoadCli: minutes, seconds = divmod(seconds, 60) return "%.2i:%.2i:%.2i" % (hours, minutes, seconds) - def format_size(self, size): - return conv(size / 1024 ** 2) + " MiB" - def println(self, line, content): - print "\033[" + conv(line) + ";0H\033[2K" + content + "\033[" + conv( - (self.inputline if self.inputline > 0 else self.inputline + 1) - 1) + ";0H" + print "\033[" + str(line) + ";0H\033[2K" + content + "\033[" + \ + str((self.inputline if self.inputline > 0 else self.inputline + 1) - 1) + ";0H" def print_input(self): self.println(self.inputline, white(" Input: ") + self.input) @@ -119,7 +107,7 @@ class pyLoadCli: def refresh(self): """Handle incoming data""" - data = self.core.status_downloads() + data = self.client.statusDownloads() #print updated information print "\033[J" #clear screen self.println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface"))) @@ -128,34 +116,34 @@ class pyLoadCli: line = 4 speed = 0 for download in data: - if download["status"] == 12: # downloading - percent = download["percent"] + if download.status == 12: # downloading + percent = download.percent z = percent / 4 - speed += download['speed'] - self.println(line, cyan(download["name"])) + speed += download.speed + self.println(line, cyan(download.name)) line += 1 self.println(line, - blue("[") + yellow(z * "#" + (25 - z) * " ") + blue("] ") + green(conv(percent) + "%") + _( - " Speed: ") + green(conv(int(download['speed'])) + " kb/s") + _(" Size: ") + green( - download['format_size']) + _(" Finished in: ") + green(download['format_eta']) + _( - " ID: ") + green(conv(download['id']))) + blue("[") + yellow(z * "#" + (25 - z) * " ") + blue("] ") + green(str(percent) + "%") + _( + " Speed: ") + green(str(int(download.speed)) + " kb/s") + _(" Size: ") + green( + download.format_size) + _(" Finished in: ") + green(download.format_eta) + _( + " ID: ") + green(download.id)) line += 1 - if download["status"] == 5: - self.println(line, cyan(download["name"])) + if download.status == 5: + self.println(line, cyan(download.name)) line += 1 - self.println(line, _("waiting: ") + green(download["format_wait"])) + self.println(line, _("waiting: ") + green(download.format_wait)) line += 1 self.println(line, "") line += 1 - status = self.core.status_server() - if status['pause']: + status = self.client.statusServer() + if status.pause: self.println(line, - _("Status: ") + red("paused") + _(" total Speed: ") + red(conv(int(speed)) + " kb/s") + _( - " Files in queue: ") + red(conv(status["queue"]))) + _("Status: ") + red("paused") + _(" total Speed: ") + red(str(int(speed)) + " kb/s") + _( + " Files in queue: ") + red(status.queue)) else: self.println(line, - _("Status: ") + red("running") + _(" total Speed: ") + red(conv(int(speed)) + " kb/s") + _( - " Files in queue: ") + red(conv(status["queue"]))) + _("Status: ") + red("running") + _(" total Speed: ") + red(str(int(speed)) + " kb/s") + _( + " Files in queue: ") + red(status.queue)) line += 1 self.println(line, "") line += 1 @@ -169,7 +157,7 @@ class pyLoadCli: line = self.menuline self.println(line, white(_("Menu:"))) line += 1 - if self.pos[0] == 0:# main menu + if not self.pos[0]:# main menu self.println(line, "") line += 1 self.println(line, mag("1.") + _(" Add Links")) @@ -187,7 +175,7 @@ class pyLoadCli: self.println(line, "") elif self.pos[0] == 1:#add links - if self.pos[1] == 0: + if not self.pos[1]: self.println(line, "") line += 1 self.println(line, _("Name your package.")) @@ -211,7 +199,7 @@ class pyLoadCli: line += 1 self.println(line, _("Type %s when done.") % mag("END")) line += 1 - self.println(line, _("Links added: ") + mag(conv(self.links_added))) + self.println(line, _("Links added: ") + mag(self.links_added)) line += 1 self.println(line, "") line += 1 @@ -221,15 +209,15 @@ class pyLoadCli: line += 1 self.println(line, "") elif self.pos[0] == 2:#remove links - if self.pos[1] == 0: - pack = self.core.get_queue() + if not self.pos[1]: + pack = self.client.getQueue() self.println(line, _( "Type d(number of package) to delete a package, r to restart, or w/o d,r to look into it.")) line += 1 i = 0 - for id, value in islice(pack.iteritems(), self.pos[2], self.pos[2] + 5): + for value in islice(pack, self.pos[2], self.pos[2] + 5): try: - self.println(line, mag(conv(id)) + ": " + value['name']) + self.println(line, mag(str(value.pid)) + ": " + value.name) line += 1 i += 1 except Exception, e: @@ -239,14 +227,20 @@ class pyLoadCli: line += 1 else: - links = self.core.get_package_data(self.pos[1]) + try: + pack = self.client.getPackageData(self.pos[1]) + except PackageDoesNotExists: + self.pos[1] = 0 + self.print_input() + return + self.println(line, _("Type d(number) of the link you want to delete or r(number) to restart.")) line += 1 i = 0 - for id, value in islice(links["links"].iteritems(), self.pos[2], self.pos[2] + 5): + for value in islice(pack.links, self.pos[2], self.pos[2] + 5): try: - self.println(line, mag(conv(id)) + ": %s | %s | %s" % ( - value['name'], value['statusmsg'], value['plugin'])) + self.println(line, mag(value.fid) + ": %s | %s | %s" % ( + value.name, value.statusmsg, value.plugin)) line += 1 i += 1 @@ -270,7 +264,7 @@ class pyLoadCli: self.build_menu() return True - if self.pos[0] == 0: + if not self.pos[0]: if inp == "1": self.links_added = 0 self.pos[0] = 1 @@ -278,22 +272,23 @@ class pyLoadCli: self.pos[0] = 2 self.pos[1] = 0 elif inp == "3": - self.core.toggle_pause() + self.client.togglePause() elif inp == "4": - self.core.kill() + self.client.kill() + self.client.close() sys.exit() elif inp == "5": os.system('clear') sys.exit() elif self.pos[0] == 1: #add links - if self.pos[1] == 0: + if not self.pos[1]: self.new_package['name'] = inp self.new_package['links'] = [] self.pos[1] = 1 else: if inp == "END": - self.core.add_package(self.new_package['name'], self.new_package['links'], 1) # add package + self.client.addPackage(self.new_package['name'], self.new_package['links'], 1) # add package self.pos = [0, 0, 0] self.links_added = 0 else: #TODO validation @@ -301,27 +296,27 @@ class pyLoadCli: self.links_added += 1 elif self.pos[0] == 2: #remove links - if self.pos[1] == 0: + if not self.pos[1]: if inp.startswith("d"): if inp.find("-") > -1: - self.core.del_packages(range(*map(int, inp[1:].split("-")))) + self.client.deletePackages(range(*map(int, inp[1:].split("-")))) else: - self.core.del_packages([int(inp[1:])]) + self.client.deletePackages([int(inp[1:])]) if inp.startswith("r"): - self.core.restart_package(int(inp[1:])) + self.client.restartPackage(int(inp[1:])) elif inp != "p" and inp != "n": self.pos[1] = int(inp) self.pos[2] = 0 elif inp.startswith('r'): if inp.find("-") > -1: - map(self.core.restart_file, range(*map(int, inp[1:].split("-")))) + map(self.client.restartFile, range(*map(int, inp[1:].split("-")))) else: - self.core.restart_file(int(inp[1:])) + self.client.restartFile(int(inp[1:])) elif inp.startswith('d') and inp != "p" and inp != "n": if inp.find("-") > -1: - self.core.del_links(range(*map(int, inp[1:].split("-")))) + self.client.deleteFiles(range(*map(int, inp[1:].split("-")))) else: - self.core.del_links([int(inp[1:])]) + self.client.deleteFiles([int(inp[1:])]) if inp == "p": self.pos[2] -= 5 elif inp == "n": @@ -340,8 +335,12 @@ class RefreshThread(threading.Thread): sleep(1) try: self.cli.refresh() + except ConnectionClosed: + os.system("clear") + print _("pyLoad was terminated") + _exit(0) except Exception, e: - self.cli.println(2, red(conv(e))) + self.cli.println(2, red(str(e))) self.cli.pos[1] = 0 self.cli.pos[2] = 0 print_exc() @@ -404,7 +403,6 @@ class _GetchMacCarbon: def __init__(self): import Carbon - Carbon.Evt #see if it has this (in Unix, it doesn't) def __call__(self): @@ -426,52 +424,46 @@ class _GetchMacCarbon: return chr(msg) def blue(string): - return "\033[1;34m" + string + "\033[0m" + return "\033[1;34m" + str(string) + "\033[0m" def green(string): - return "\033[1;32m" + string + "\033[0m" + return "\033[1;32m" + str(string) + "\033[0m" def yellow(string): - return "\033[1;33m" + string + "\033[0m" + return "\033[1;33m" + str(string) + "\033[0m" def red(string): - return "\033[1;31m" + string + "\033[0m" + return "\033[1;31m" + str(string) + "\033[0m" def cyan(string): - return "\033[1;36m" + string + "\033[0m" + return "\033[1;36m" + str(string) + "\033[0m" def mag(string): - return "\033[1;35m" + string + "\033[0m" + return "\033[1;35m" + str(string) + "\033[0m" def white(string): - return "\033[1;37m" + string + "\033[0m" + return "\033[1;37m" + str(string) + "\033[0m" def print_help(): - print "" + print print "pyLoadCli Copyright (c) 2008-2011 the pyLoad Team" - print "" - print "Usage: [python] pyLoadCli.py [options] [server url]" - print "" - print "<server url>" - print "The server url has this format: http://username:passwort@address:port" - print "" + print + print "Usage: [python] pyLoadCli.py [options] [command]" + print + print "<Commands>" + print "See pyLoadCli.py -c for a complete listing." + print print "<Options>" - print " -l, --local", " " * 6, "Use the local settings in config file" - print " -u, --username=<username>" - print " " * 20, "Specify username" - print "" - print " -a, --address=<address>" - print " " * 20, "Specify address (default=127.0.0.1)" - print "" - print " --linklist=<path>" - print " " * 20, "Add container to pyLoad" - print "" - print " -p, --port", " " * 7, "Specify port (default=7272)" - print " -s, --ssl", " " * 8, "Enable ssl (default=off)" - print " -h, --help", " " * 7, "Display this help screen" + print " -i, --interactive", " Start in interactive mode" + print + print " -u, --username=", " " * 2, "Specify Username" print " --pw=<password>", " " * 2, "Password (default=ask for it)" - print " -c, --command=", " " * 3, "Sends a command to pyLoadCore (use help for list)" - print "" + print " -a, --address=", " "*3, "Specify address (default=127.0.0.1)" + print " -p, --port", " " * 7, "Specify port (default=7227)" + print + print " -h, --help", " " * 7, "Display this help screen" + print " -c, --commands", " " * 3, "List all available commands" + print def print_packages(data): @@ -500,134 +492,89 @@ if __name__ == "__main__": languages=["en", config['general']['language']]) translation.install(unicode=True) - server_url = "" username = "" password = "" - addr = "" - port = "" - ssl = None - command = None + addr = "127.0.0.1" + port = 7228 - add = "" + interactive = False + command = None - if len(sys.argv) > 1: - addr = "127.0.0.1" - port = "7272" - ssl = "" + shortOptions = 'ilu:p:a:hc' + longOptions = ['interactive', 'local', "username=", "pw=", "address=", "port=", "help", "commands"] - shortOptions = 'lu:a:p:s:hc:' - longOptions = ['local', "username=", "address=", "port=", "ssl=", "help", "linklist=", "pw=", "command="] + try: + opts, extraparams = getopt(sys.argv[1:], shortOptions, longOptions) + for option, params in opts: + if option in ("-i", "--interactive"): + pass + elif option in ("-u", "--username"): + username = params + elif option in ("-a", "--address"): + addr = params + elif option in ("-p", "--port"): + port = int(params) + elif option in ("-h", "--help"): + print_help() + exit() + elif option in ("--pw"): + password = params + elif option in ("-c", "--comands"): + print_commands() + exit() + + except GetoptError: + print 'Unknown Argument(s) "%s"' % " ".join(sys.argv[1:]) + print_help() + exit() + + if len(extraparams) == 1: + command = sys.argv[1] + + + client = False + + if interactive: try: - opts, extraparams = getopt(sys.argv[1:], shortOptions, longOptions) - for option, params in opts: - if option in ("-l", "--local"): - if config['ssl']['activated']: - ssl = "s" - - username = config.username - password = config.password - addr = config['remote']['listenaddr'] - port = config['remote']['port'] - elif option in ("-u", "--username"): - username = params - elif option in ("-a", "--address"): - addr = params - elif option in ("-p", "--port"): - port = params - elif option in ("-s", "--ssl"): - if params.lower() == "true": - ssl = "s" - elif option in ("-h", "--help"): - print_help() - exit() - elif option in ("--linklist"): - add = params - elif option in ("--pw"): - password = params - elif option in ("-c"): - if "help" in params: - print_commands() - exit() - command = params - - except GetoptError: - print 'Unknown Argument(s) "%s"' % " ".join(sys.argv[1:]) - print_help() + client = ThriftClient(addr, port, username, password) + except WrongLogin: + pass + except NoSSL: + print _("You need py-openssl to connect to this pyLoad Core.") exit() + except NoConnection: + addr = False + port = False - if len(extraparams) == 1: - server_url = sys.argv[1] + if not client: + if not addr: addr = raw_input(_("Address: ")) + if not port: port = int(raw_input(_("Port: "))) + if not username: username = raw_input(_("Username: ")) + if not password: + from getpass import getpass - if not server_url: - if not username: username = raw_input(_("Username: ")) - if not addr: addr = raw_input(_("address: ")) - if ssl is None: - ssl = raw_input(_("Use SSL? ([y]/n): ")) - if ssl == "y" or ssl == "": - ssl = "s" - else: - ssl = "" - if not port: port = raw_input(_("Port: ")) - if not password: - from getpass import getpass - - password = getpass(_("Password: ")) + password = getpass(_("Password: ")) - server_url = "http%s://%s:%s@%s:%s/" % (ssl, username, password, addr, port) + try: + client = ThriftClient(addr, port, username, password) + except WrongLogin: + print _("Login data are wrong.") + except NoConnection: + print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": addr, "port" : port }) - if command: - core = xmlrpclib.ServerProxy(server_url, allow_none=True) + else: try: - core.get_server_version() - except: - print _("pyLoadCore not running") + client = ThriftClient(addr, port, username, password) + except WrongLogin: + print _("Login data are wrong.") + except NoConnection: + print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": addr, "port" : port }) + except NoSSL: + print _("You need py-openssl to connect to this pyLoad.") - if add: - core.add_package(add, [add]) - print _("Linklist added") - if command == "pause": - core.pause_server() - elif command == "unpause": - core.unpause_server() - elif command == "kill": - core.kill() + if interactive and command: print _("Interactive mode ignored since you passed some commands.") - elif command == "queue": - data = core.get_queue() - print_packages(data) - - elif command == "collector": - data = core.get_collector() - print_packages(data) - - - elif command == "toggle": - if core.status_server()['pause']: - core.unpause_server() - else: - core.pause_server() - - elif command == "status": - data = core.status_downloads() - status = core.status_server() - - if status['pause']: - print _('Status: paused') - else: - print _('Status: running') - - print _('%s Downloads') % len(data) - for download in data: - if download["status"] == 12: #downloading - print _('Downloading: %(name)-40s %(percent)s%% @%(speed)dkB/s') % download - elif download["status"] == 5: - print _("Waiting: %(name)s-40s: %(format_wait)s") % download - - else: - if command != "help": print _("Unknown Command") - print_commands() - - else: - cli = pyLoadCli(server_url)
\ No newline at end of file + if client: + cli = Cli(client, command)
\ No newline at end of file diff --git a/pyLoadCore.py b/pyLoadCore.py index 5d11824d7..d045581b5 100755 --- a/pyLoadCore.py +++ b/pyLoadCore.py @@ -379,7 +379,7 @@ class Core(object): self.shutdown() self.log.info(_("pyLoad quits")) self.removeLogger() - exit() + _exit(0) #@TODO thrift blocks shutdown self.threadManager.work() self.scheduler.work() |