diff options
author | Walter Purcaro <vuolter@users.noreply.github.com> | 2015-05-10 17:01:05 +0200 |
---|---|---|
committer | Walter Purcaro <vuolter@users.noreply.github.com> | 2015-05-10 17:01:05 +0200 |
commit | 8606b72470e0e506d9da26f190a2880d47d289a4 (patch) | |
tree | 6225bba54bafb655ca969a1287673807c7c2d131 | |
parent | Merge branch 'stable' into 0.4.10 (diff) | |
download | pyload-8606b72470e0e506d9da26f190a2880d47d289a4.tar.xz |
Improve and fix file structure a bit
31 files changed, 641 insertions, 643 deletions
diff --git a/docs/module_overview.rst b/docs/module_overview.rst index 9a2d445b6..a69aa9d9d 100644 --- a/docs/module_overview.rst +++ b/docs/module_overview.rst @@ -15,5 +15,5 @@ You can find an overview of some important classes here: pyload.plugin.Account.Account pyload.plugin.Addon.Addon pyload.manager.Addon.AddonManager - pyload.datatypes.PyFile.PyFile - pyload.datatypes.PyPackage.PyPackage + pyload.Datatype.File.PyFile + pyload.Datatype.Package.PyPackage diff --git a/docs/write_addons.rst b/docs/write_addons.rst index 58e73e675..9b94a0233 100644 --- a/docs/write_addons.rst +++ b/docs/write_addons.rst @@ -50,8 +50,8 @@ The easiest way is to overwrite specific methods defined by the :class:`Addon <p The name is indicating when the function gets called. See :class:`Addon <pyload.plugin.Addon.Addon>` page for a complete listing. -You should be aware of the arguments the Addon is called with, whether its a :class:`PyFile <pyload.datatype.File.PyFile>` -or :class:`PyPackage <pyload.datatype.Package.PyPackage>` you should read its related documentation to know how to access her great power and manipulate them. +You should be aware of the arguments the Addon is called with, whether its a :class:`PyFile <pyload.Datatype.File.PyFile>` +or :class:`PyPackage <pyload.Datatype.Package.PyPackage>` you should read its related documentation to know how to access her great power and manipulate them. A basic excerpt would look like: :: diff --git a/docs/write_plugins.rst b/docs/write_plugins.rst index 8d42aea7f..0b568f74c 100644 --- a/docs/write_plugins.rst +++ b/docs/write_plugins.rst @@ -60,7 +60,7 @@ An example ``process`` function could look like this :: # download the file, destination is determined by pyLoad self.download(parsed_url) -You need to know about the :class:`PyFile <pyload.datatype.File.PyFile>` class, since an instance of it is given as parameter to every pyfile. +You need to know about the :class:`PyFile <pyload.Datatype.File.PyFile>` class, since an instance of it is given as parameter to every pyfile. Some tasks your plugin should handle: proof if file is online, get filename, wait if needed, download the file, etc.. Wait times diff --git a/pyload-cli.py b/pyload-cli.py deleted file mode 100644 index 0ef70368b..000000000 --- a/pyload-cli.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from pyload.cli.Cli import main - -if __name__ == "__main__": - main() diff --git a/pyload/Core.py b/pyload/Core.py index 2230b3fed..2b356b9fb 100755 --- a/pyload/Core.py +++ b/pyload/Core.py @@ -25,15 +25,15 @@ from sys import argv, executable, exit from time import time, sleep from pyload import remote -from pyload.database import DatabaseBackend, FileHandler +from pyload.Database import DatabaseBackend, FileHandler from pyload.config.Parser import ConfigParser from pyload.manager.Account import AccountManager from pyload.manager.Captcha import CaptchaManager from pyload.manager.Event import PullManager from pyload.manager.Plugin import PluginManager from pyload.manager.Remote import RemoteManager -from pyload.manager.event.Scheduler import Scheduler -from pyload.manager.thread.Server import WebServer +from pyload.manager.Scheduler import Scheduler +from pyload.Thread.Server import WebServer from pyload.network.JsEngine import JsEngine from pyload.network.RequestFactory import RequestFactory from pyload.utils import freeSpace, formatSize @@ -364,14 +364,14 @@ class Core(object): self.lastClientConnected = 0 # later imported because they would trigger api import, and remote value not set correctly - from pyload import api + from pyload.api import Api from pyload.manager.Addon import AddonManager from pyload.manager.Thread import ThreadManager - if api.activated != self.remote: + if pyload.api.activated != self.remote: self.log.warning("Import error: API remote status not correct.") - self.api = api.Api(self) + self.api = Api(self) self.scheduler = Scheduler(self) diff --git a/pyload/manager/thread/Addon.py b/pyload/Thread/Addon.py index 3cda99950..bf3b62eb1 100644 --- a/pyload/manager/thread/Addon.py +++ b/pyload/Thread/Addon.py @@ -12,7 +12,7 @@ from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime from types import MethodType -from pyload.manager.thread.Plugin import PluginThread +from pyload.Thread.Plugin import PluginThread class AddonThread(PluginThread): diff --git a/pyload/manager/thread/Decrypter.py b/pyload/Thread/Decrypter.py index 3554feac4..dcb18b929 100644 --- a/pyload/manager/thread/Decrypter.py +++ b/pyload/Thread/Decrypter.py @@ -12,7 +12,7 @@ from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime from types import MethodType -from pyload.manager.thread.Plugin import PluginThread +from pyload.Thread.Plugin import PluginThread from pyload.plugin.Plugin import Abort, Fail, Retry diff --git a/pyload/manager/thread/Download.py b/pyload/Thread/Download.py index 04f73b2ed..77f4f163f 100644 --- a/pyload/manager/thread/Download.py +++ b/pyload/Thread/Download.py @@ -14,7 +14,7 @@ from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime from types import MethodType -from pyload.manager.thread.Plugin import PluginThread +from pyload.Thread.Plugin import PluginThread from pyload.plugin.Plugin import Abort, Fail, Reconnect, Retry, SkipDownload diff --git a/pyload/manager/thread/Info.py b/pyload/Thread/Info.py index 856c8facf..db1b6d79c 100644 --- a/pyload/manager/thread/Info.py +++ b/pyload/Thread/Info.py @@ -13,8 +13,8 @@ from time import sleep, time, strftime, gmtime from types import MethodType from pyload.api import OnlineStatus -from pyload.datatype.File import PyFile -from pyload.manager.thread.Plugin import PluginThread +from pyload.Datatype import PyFile +from pyload.Thread.Plugin import PluginThread class InfoThread(PluginThread): diff --git a/pyload/manager/thread/Plugin.py b/pyload/Thread/Plugin.py index 0163152f3..f8cfba9c4 100644 --- a/pyload/manager/thread/Plugin.py +++ b/pyload/Thread/Plugin.py @@ -16,7 +16,7 @@ from time import sleep, time, strftime, gmtime from types import MethodType from pyload.api import OnlineStatus -from pyload.datatype.File import PyFile +from pyload.Datatype import PyFile from pyload.plugin.Plugin import Abort, Fail, Reconnect, Retry, SkipDownload from pyload.utils.packagetools import parseNames from pyload.utils import fs_join diff --git a/pyload/manager/thread/Server.py b/pyload/Thread/Server.py index a26ffe6a1..6b6ef6989 100644 --- a/pyload/manager/thread/Server.py +++ b/pyload/Thread/Server.py @@ -31,7 +31,7 @@ class WebServer(threading.Thread): def run(self): - import pyload.webui as webinterface + import pyload.Webui as webinterface global webinterface reset = False diff --git a/pyload/Thread/__init__.py b/pyload/Thread/__init__.py new file mode 100644 index 000000000..30eda15c2 --- /dev/null +++ b/pyload/Thread/__init__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- + +from pyload.Thread.Addon import AddonThread +from pyload.Thread.Decrypter import DecrypterThread +from pyload.Thread.Download import DownloadThread +from pyload.Thread.Info import InfoThread +from pyload.Thread.Plugin import PluginThread diff --git a/pyload/__init__.py b/pyload/__init__.py index 7f5ac0667..32235c68f 100644 --- a/pyload/__init__.py +++ b/pyload/__init__.py @@ -2,16 +2,6 @@ from __future__ import with_statement -import __builtin__ - -import os -import platform -import sys - -from codecs import getwriter - -from pyload.utils import get_console_encoding - __all__ = ["__status_code__", "__status__", "__version_info__", "__version__", "__author_name__", "__author_mail__", "__license__"] @@ -45,6 +35,9 @@ __authors__ = [("Marius" , "mkaay@mkaay.de" ), ################################# InitHomeDir ################################# +import __builtin__ +import os + __builtin__.owd = os.path.abspath("") #: original working directory __builtin__.homedir = os.path.expanduser("~") __builtin__.rootdir = os.path.abspath(os.path.join(__file__, "..")) @@ -52,14 +45,19 @@ __builtin__.configdir = "" __builtin__.pypath = os.path.abspath(os.path.join(rootdir, "..")) -if "64" in platform.machine(): - sys.path.append(os.path.join(pypath, "lib64")) +import sys + sys.path.append(os.path.join(pypath, "lib", "Python", "Lib")) sys.path.append(os.path.join(pypath, "lib")) +from codecs import getwriter + +from pyload.utils import get_console_encoding + sys.stdout = getwriter(get_console_encoding(sys.stdout.encoding))(sys.stdout, errors="replace") + if homedir == "~" and os.name == "nt": import ctypes @@ -78,6 +76,7 @@ if homedir == "~" and os.name == "nt": __builtin__.homedir = path_buf.value + try: p = os.path.join(rootdir, "config", "configdir") @@ -90,6 +89,7 @@ except IOError: else: configdir = os.path.join(homedir, "pyload") + try: if not os.path.exists(configdir): os.makedirs(configdir, 0700) diff --git a/pyload/api/__init__.py b/pyload/api/__init__.py index 442e9ef95..ddb3e16ff 100644 --- a/pyload/api/__init__.py +++ b/pyload/api/__init__.py @@ -10,7 +10,7 @@ import re from urlparse import urlparse -from pyload.datatype.File import PyFile +from pyload.Datatype import PyFile from pyload.utils.packagetools import parseNames from pyload.network.RequestFactory import getURL from pyload.remote import activated diff --git a/pyload/cli/AddPackage.py b/pyload/cli/AddPackage.py index e750274ca..3a9471cbe 100644 --- a/pyload/cli/AddPackage.py +++ b/pyload/cli/AddPackage.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # @author: RaNaN -from pyload.cli.Handler import Handler +from pyload.Cli.Handler import Handler from pyload.utils.printer import * diff --git a/pyload/cli/Cli.py b/pyload/cli/Cli.py deleted file mode 100644 index 617b65b0f..000000000 --- a/pyload/cli/Cli.py +++ /dev/null @@ -1,578 +0,0 @@ -# -*- coding: utf-8 -*- -# @author: RaNaN - -from __future__ import with_statement - -import os -import sys -import threading -import traceback - -import pyload.utils.pylgettext as gettext - -from codecs import getwriter -from getopt import GetoptError, getopt -from os import _exit -from os.path import join, exists, basename -from sys import exit -from time import sleep - -from Getch import Getch -from rename_process import renameProcess - -from pyload.api import Destination -from pyload.cli import AddPackage, ManageFiles -from pyload.config.Parser import ConfigParser -from pyload.remote.thriftbackend.ThriftClient import ThriftClient, NoConnection, NoSSL, WrongLogin, ConnectionClosed -from pyload.utils import formatSize, decode -from pyload.utils.printer import * - - -class Cli(object): - - def __init__(self, client, command): - self.client = client - self.command = command - - if not self.command: - renameProcess('pyload-cli') - self.getch = Getch() - self.input = "" - self.inputline = 0 - self.lastLowestLine = 0 - self.menuline = 0 - - self.lock = threading.Lock() - - # processor funcions, these will be changed dynamically depending on control flow - self.headerHandler = self #: the download status - self.bodyHandler = self #: the menu section - self.inputHandler = self - - os.system("clear") - println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface"))) - println(2, "") - - self.thread = RefreshThread(self) - self.thread.start() - - self.start() - else: - self.processCommand() - - - def reset(self): - """ reset to initial main menu """ - self.input = "" - self.headerHandler = self.bodyHandler = self.inputHandler = self - - - def start(self): - """ main loop. handle input """ - while True: - # inp = raw_input() - inp = self.getch.impl() - if ord(inp) == 3: - os.system("clear") - sys.exit() #: ctrl + c - elif ord(inp) == 13: #: enter - try: - self.lock.acquire() - self.inputHandler.onEnter(self.input) - - except Exception, e: - println(2, red(e)) - finally: - self.lock.release() - - elif ord(inp) == 127: - self.input = self.input[:-1] #: backspace - try: - self.lock.acquire() - self.inputHandler.onBackSpace() - finally: - self.lock.release() - - elif ord(inp) == 27: #: ugly symbol - pass - else: - self.input += inp - try: - self.lock.acquire() - self.inputHandler.onChar(inp) - finally: - self.lock.release() - - self.inputline = self.bodyHandler.renderBody(self.menuline) - self.renderFooter(self.inputline) - - - def refresh(self): - """refresh screen""" - - println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface"))) - println(2, "") - - self.lock.acquire() - - self.menuline = self.headerHandler.renderHeader(3) + 1 - println(self.menuline - 1, "") - self.inputline = self.bodyHandler.renderBody(self.menuline) - self.renderFooter(self.inputline) - - self.lock.release() - - - def setInput(self, string=""): - self.input = string - - - def setHandler(self, klass): - # create new handler with reference to cli - self.bodyHandler = self.inputHandler = klass(self) - self.input = "" - - - def renderHeader(self, line): - """ prints download status """ - # print updated information - # print "\033[J" #: clear screen - # self.println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface"))) - # self.println(2, "") - # self.println(3, white(_("%s Downloads:") % (len(data)))) - - data = self.client.statusDownloads() - speed = 0 - - println(line, white(_("%s Downloads:") % (len(data)))) - line += 1 - - for download in data: - if download.status == 12: #: downloading - percent = download.percent - z = percent / 4 - speed += download.speed - println(line, cyan(download.name)) - line += 1 - println(line, - blue("[") + yellow(z * "#" + (25 - z) * " ") + blue("] ") + green(str(percent) + "%") + _( - " Speed: ") + green(formatSize(download.speed) + "/s") + _(" Size: ") + green( - download.format_size) + _(" Finished in: ") + green(download.format_eta) + _( - " ID: ") + green(download.fid)) - line += 1 - if download.status == 5: - println(line, cyan(download.name)) - line += 1 - println(line, _("waiting: ") + green(download.format_wait)) - line += 1 - - println(line, "") - line += 1 - status = self.client.statusServer() - if status.pause: - paused = _("Status:") + " " + red(_("paused")) - else: - paused = _("Status:") + " " + red(_("running")) - - println(line, "%s %s: %s %s: %s %s: %s" % ( - paused, _("total Speed"), red(formatSize(speed) + "/s"), _("Files in queue"), red( - status.queue), _("Total"), red(status.total))) - - return line + 1 - - - def renderBody(self, line): - """ prints initial menu """ - println(line, white(_("Menu:"))) - println(line + 1, "") - println(line + 2, mag("1.") + _(" Add Links")) - println(line + 3, mag("2.") + _(" Manage Queue")) - println(line + 4, mag("3.") + _(" Manage Collector")) - println(line + 5, mag("4.") + _(" (Un)Pause Server")) - println(line + 6, mag("5.") + _(" Kill Server")) - println(line + 7, mag("6.") + _(" Quit")) - - return line + 8 - - - def renderFooter(self, line): - """ prints out the input line with input """ - println(line, "") - line += 1 - - println(line, white(" Input: ") + decode(self.input)) - - # clear old output - if line < self.lastLowestLine: - for i in xrange(line + 1, self.lastLowestLine + 1): - println(i, "") - - self.lastLowestLine = line - - # set cursor to position - print "\033[" + str(self.inputline) + ";0H" - - - def onChar(self, char): - """ default no special handling for single chars """ - if char == "1": - self.setHandler(AddPackage) - elif char == "2": - self.setHandler(ManageFiles) - elif char == "3": - self.setHandler(ManageFiles) - self.bodyHandler.target = Destination.Collector - elif char == "4": - self.client.togglePause() - self.setInput() - elif char == "5": - self.client.kill() - self.client.close() - sys.exit() - elif char == "6": - os.system('clear') - sys.exit() - - - def onEnter(self, inp): - pass - - - def onBackSpace(self): - pass - - - def processCommand(self): - command = self.command[0] - args = [] - if len(self.command) > 1: - args = self.command[1:] - - if command == "status": - files = self.client.statusDownloads() - - if not files: - print "No downloads running." - - for download in files: - if download.status == 12: #: downloading - print print_status(download) - print "\tDownloading: %s @ %s/s\t %s (%s%%)" % ( - download.format_eta, formatSize(download.speed), formatSize(download.size - download.bleft), - download.percent) - elif download.status == 5: - print print_status(download) - print "\tWaiting: %s" % download.format_wait - else: - print print_status(download) - - elif command == "queue": - print_packages(self.client.getQueueData()) - - elif command == "collector": - print_packages(self.client.getCollectorData()) - - elif command == "add": - if len(args) < 2: - print _("Please use this syntax: add <Package name> <link> <link2> ...") - return - - self.client.addPackage(args[0], args[1:], Destination.Queue) - - elif command == "add_coll": - if len(args) < 2: - print _("Please use this syntax: add <Package name> <link> <link2> ...") - return - - self.client.addPackage(args[0], args[1:], Destination.Collector) - - elif command == "del_file": - self.client.deleteFiles([int(x) for x in args]) - print "Files deleted." - - elif command == "del_package": - self.client.deletePackages([int(x) for x in args]) - print "Packages deleted." - - elif command == "move": - for pid in args: - pack = self.client.getPackageInfo(int(pid)) - self.client.movePackage((pack.dest + 1) % 2, pack.pid) - - elif command == "check": - print _("Checking %d links:") % len(args) - print - rid = self.client.checkOnlineStatus(args).rid - self.printOnlineCheck(self.client, rid) - - elif command == "check_container": - path = args[0] - if not exists(join(owd, path)): - print _("File does not exists.") - return - - with open(join(owd, path), "rb") as f: - content = f.read() - - rid = self.client.checkOnlineStatusContainer([], basename(f.name), content).rid - self.printOnlineCheck(self.client, rid) - - elif command == "pause": - self.client.pause() - - elif command == "unpause": - self.client.unpause() - - elif command == "toggle": - self.client.togglePause() - - elif command == "kill": - self.client.kill() - elif command == "restart_file": - for x in args: - self.client.restartFile(int(x)) - print "Files restarted." - elif command == "restart_package": - for pid in args: - self.client.restartPackage(int(pid)) - print "Packages restarted." - - else: - print_commands() - - - def printOnlineCheck(self, client, rid): - while True: - sleep(1) - result = client.pollResults(rid) - for url, status in result.data.iteritems(): - if status.status == 2: - check = "Online" - elif status.status == 1: - check = "Offline" - else: - check = "Unknown" - - print "%-45s %-12s\t %-15s\t %s" % (status.name, formatSize(status.size), status.plugin, check) - - if result.rid == -1: - break - - -class RefreshThread(threading.Thread): - - def __init__(self, cli): - threading.Thread.__init__(self) - self.setDaemon(True) - self.cli = cli - - - def run(self): - while True: - sleep(1) - try: - self.cli.refresh() - except ConnectionClosed: - os.system("clear") - print _("pyLoad was terminated") - _exit(0) - except Exception, e: - println(2, red(str(e))) - self.cli.reset() - traceback.print_exc() - - -def print_help(config): - print - print "pyLoad CLI Copyright (c) 2008-2015 the pyLoad Team" - print - print "Usage: [python] pyload-cli.py [options] [command]" - print - print "<Commands>" - print "See pyload-cli.py -c for a complete listing." - print - print "<Options>" - print " -i, --interactive", " Start in interactive mode" - print - print " -u, --username=", " " * 2, "Specify Username" - print " --pw=<password>", " " * 2, "Password" - print " -a, --address=", " " * 3, "Specify address (current=%s)" % config['addr'] - print " -p, --port", " " * 7, "Specify port (current=%s)" % config['port'] - print - print " -l, --language", " " * 3, "Set user interface language (current=%s)" % config['language'] - print " -h, --help", " " * 7, "Display this help screen" - print " -c, --commands", " " * 3, "List all available commands" - print - - -def print_packages(data): - for pack in data: - print "Package %s (#%s):" % (pack.name, pack.pid) - for download in pack.links: - print "\t" + print_file(download) - print - - -def print_file(download): - return "#%(id)-6d %(name)-30s %(statusmsg)-10s %(plugin)-8s" % { - "id": download.fid, - "name": download.name, - "statusmsg": download.statusmsg, - "plugin": download.plugin - } - - -def print_status(download): - return "#%(id)-6s %(name)-40s Status: %(statusmsg)-10s Size: %(size)s" % { - "id": download.fid, - "name": download.name, - "statusmsg": download.statusmsg, - "size": download.format_size - } - - -def print_commands(): - commands = [("status", _("Prints server status")), - ("queue", _("Prints downloads in queue")), - ("collector", _("Prints downloads in collector")), - ("add <name> <link1> <link2>...", _("Adds package to queue")), - ("add_coll <name> <link1> <link2>...", _("Adds package to collector")), - ("del_file <fid> <fid2>...", _("Delete Files from Queue/Collector")), - ("del_package <pid> <pid2>...", _("Delete Packages from Queue/Collector")), - ("move <pid> <pid2>...", _("Move Packages from Queue to Collector or vice versa")), - ("restart_file <fid> <fid2>...", _("Restart files")), - ("restart_package <pid> <pid2>...", _("Restart packages")), - ("check <container|url> ...", _("Check online status, works with local container")), - ("check_container path", _("Checks online status of a container file")), - ("pause", _("Pause the server")), - ("unpause", _("continue downloads")), - ("toggle", _("Toggle pause/unpause")), - ("kill", _("kill server")), ] - - print _("List of commands:") - print - for c in commands: - print "%-35s %s" % c - - -def writeConfig(opts): - try: - with open(join(homedir, ".pyload-cli"), "w") as cfgfile: - cfgfile.write("[cli]") - for opt in opts: - cfgfile.write("%s=%s\n" % (opt, opts[opt])) - except Exception: - print _("Couldn't write user config file") - - -def main(): - config = {"addr": "127.0.0.1", "port": "7227", "language": "en"} - try: - config['language'] = os.environ['LANG'][0:2] - except Exception: - pass - - if (not exists(join(pypath, "locale", config['language']))) or config['language'] == "": - config['language'] = "en" - - configFile = ConfigParser.ConfigParser() - configFile.read(join(homedir, ".pyload-cli")) - - if configFile.has_section("cli"): - for opt in configFile.items("cli"): - config[opt[0]] = opt[1] - - gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) - translation = gettext.translation("Cli", join(pypath, "locale"), - languages=[config['language'], "en"], fallback=True) - translation.install(unicode=True) - - interactive = False - command = None - username = "" - password = "" - - shortOptions = 'iu:p:a:hcl:' - longOptions = ['interactive', "username=", "pw=", "address=", "port=", "help", "commands", "language="] - - try: - opts, extraparams = getopt(sys.argv[1:], shortOptions, longOptions) - for option, params in opts: - if option in ("-i", "--interactive"): - interactive = True - elif option in ("-u", "--username"): - username = params - elif option in ("-a", "--address"): - config['addr'] = params - elif option in ("-p", "--port"): - config['port'] = params - elif option in ("-l", "--language"): - config['language'] = params - gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) - translation = gettext.translation("Cli", join(pypath, "locale"), - languages=[config['language'], "en"], fallback=True) - translation.install(unicode=True) - elif option in ("-h", "--help"): - print_help(config) - 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(config) - exit() - - if len(extraparams) >= 1: - command = extraparams - - client = False - - if interactive: - try: - client = ThriftClient(config['addr'], int(config['port']), username, password) - except WrongLogin: - pass - except NoSSL: - print _("You need py-openssl to connect to this pyLoad Core.") - exit() - except NoConnection: - config['addr'] = False - config['port'] = False - - if not client: - if not config['addr']: config['addr'] = raw_input(_("Address: ")) - if not config['port']: config['port'] = raw_input(_("Port: ")) - if not username: username = raw_input(_("Username: ")) - if not password: - from getpass import getpass - - password = getpass(_("Password: ")) - - try: - client = ThriftClient(config['addr'], int(config['port']), username, password) - except WrongLogin: - print _("Login data is wrong.") - except NoConnection: - print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config['addr'], - "port": config['port']}) - - else: - try: - client = ThriftClient(config['addr'], int(config['port']), username, password) - except WrongLogin: - print _("Login data is wrong.") - except NoConnection: - print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config['addr'], - "port": config['port']}) - except NoSSL: - print _("You need py-openssl to connect to this pyLoad core.") - - if interactive and command: print _("Interactive mode ignored since you passed some commands.") - - if client: - writeConfig(config) - cli = Cli(client, command) diff --git a/pyload/cli/ManageFiles.py b/pyload/cli/ManageFiles.py index 3833b2c48..017529852 100644 --- a/pyload/cli/ManageFiles.py +++ b/pyload/cli/ManageFiles.py @@ -4,7 +4,7 @@ from itertools import islice from time import time -from pyload.cli.Handler import Handler +from pyload.Cli.Handler import Handler from pyload.utils.printer import * from pyload.api import Destination, PackageData diff --git a/pyload/cli/__init__.py b/pyload/cli/__init__.py index a64fc0c0c..3449109ba 100644 --- a/pyload/cli/__init__.py +++ b/pyload/cli/__init__.py @@ -1,4 +1,583 @@ # -*- coding: utf-8 -*- +# @author: RaNaN -from pyload.cli.AddPackage import AddPackage -from pyload.cli.ManageFiles import ManageFiles +from __future__ import with_statement + +import os +import sys +import threading +import traceback + +import pyload.utils.pylgettext as gettext + +from codecs import getwriter +from getopt import GetoptError, getopt +from os import _exit +from os.path import join, exists, basename +from sys import exit +from time import sleep + +from Getch import Getch +from rename_process import renameProcess + +from pyload.api import Destination +from pyload.Cli.AddPackage import AddPackage +from pyload.Cli.ManageFiles import ManageFiles +from pyload.config.Parser import ConfigParser +from pyload.remote.thriftbackend.ThriftClient import ThriftClient, NoConnection, NoSSL, WrongLogin, ConnectionClosed +from pyload.utils import formatSize, decode +from pyload.utils.printer import * + + +class Cli(object): + + def __init__(self, client, command): + self.client = client + self.command = command + + if not self.command: + renameProcess('pyload-cli') + self.getch = Getch() + self.input = "" + self.inputline = 0 + self.lastLowestLine = 0 + self.menuline = 0 + + self.lock = threading.Lock() + + # processor funcions, these will be changed dynamically depending on control flow + self.headerHandler = self #: the download status + self.bodyHandler = self #: the menu section + self.inputHandler = self + + os.system("clear") + println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface"))) + println(2, "") + + self.thread = RefreshThread(self) + self.thread.start() + + self.start() + else: + self.processCommand() + + + def reset(self): + """ reset to initial main menu """ + self.input = "" + self.headerHandler = self.bodyHandler = self.inputHandler = self + + + def start(self): + """ main loop. handle input """ + while True: + # inp = raw_input() + inp = self.getch.impl() + if ord(inp) == 3: + os.system("clear") + sys.exit() #: ctrl + c + elif ord(inp) == 13: #: enter + try: + self.lock.acquire() + self.inputHandler.onEnter(self.input) + + except Exception, e: + println(2, red(e)) + finally: + self.lock.release() + + elif ord(inp) == 127: + self.input = self.input[:-1] #: backspace + try: + self.lock.acquire() + self.inputHandler.onBackSpace() + finally: + self.lock.release() + + elif ord(inp) == 27: #: ugly symbol + pass + else: + self.input += inp + try: + self.lock.acquire() + self.inputHandler.onChar(inp) + finally: + self.lock.release() + + self.inputline = self.bodyHandler.renderBody(self.menuline) + self.renderFooter(self.inputline) + + + def refresh(self): + """refresh screen""" + + println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface"))) + println(2, "") + + self.lock.acquire() + + self.menuline = self.headerHandler.renderHeader(3) + 1 + println(self.menuline - 1, "") + self.inputline = self.bodyHandler.renderBody(self.menuline) + self.renderFooter(self.inputline) + + self.lock.release() + + + def setInput(self, string=""): + self.input = string + + + def setHandler(self, klass): + # create new handler with reference to cli + self.bodyHandler = self.inputHandler = klass(self) + self.input = "" + + + def renderHeader(self, line): + """ prints download status """ + # print updated information + # print "\033[J" #: clear screen + # self.println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface"))) + # self.println(2, "") + # self.println(3, white(_("%s Downloads:") % (len(data)))) + + data = self.client.statusDownloads() + speed = 0 + + println(line, white(_("%s Downloads:") % (len(data)))) + line += 1 + + for download in data: + if download.status == 12: #: downloading + percent = download.percent + z = percent / 4 + speed += download.speed + println(line, cyan(download.name)) + line += 1 + println(line, + blue("[") + yellow(z * "#" + (25 - z) * " ") + blue("] ") + green(str(percent) + "%") + _( + " Speed: ") + green(formatSize(download.speed) + "/s") + _(" Size: ") + green( + download.format_size) + _(" Finished in: ") + green(download.format_eta) + _( + " ID: ") + green(download.fid)) + line += 1 + if download.status == 5: + println(line, cyan(download.name)) + line += 1 + println(line, _("waiting: ") + green(download.format_wait)) + line += 1 + + println(line, "") + line += 1 + status = self.client.statusServer() + if status.pause: + paused = _("Status:") + " " + red(_("paused")) + else: + paused = _("Status:") + " " + red(_("running")) + + println(line, "%s %s: %s %s: %s %s: %s" % ( + paused, _("total Speed"), red(formatSize(speed) + "/s"), _("Files in queue"), red( + status.queue), _("Total"), red(status.total))) + + return line + 1 + + + def renderBody(self, line): + """ prints initial menu """ + println(line, white(_("Menu:"))) + println(line + 1, "") + println(line + 2, mag("1.") + _(" Add Links")) + println(line + 3, mag("2.") + _(" Manage Queue")) + println(line + 4, mag("3.") + _(" Manage Collector")) + println(line + 5, mag("4.") + _(" (Un)Pause Server")) + println(line + 6, mag("5.") + _(" Kill Server")) + println(line + 7, mag("6.") + _(" Quit")) + + return line + 8 + + + def renderFooter(self, line): + """ prints out the input line with input """ + println(line, "") + line += 1 + + println(line, white(" Input: ") + decode(self.input)) + + # clear old output + if line < self.lastLowestLine: + for i in xrange(line + 1, self.lastLowestLine + 1): + println(i, "") + + self.lastLowestLine = line + + # set cursor to position + print "\033[" + str(self.inputline) + ";0H" + + + def onChar(self, char): + """ default no special handling for single chars """ + if char == "1": + self.setHandler(AddPackage) + elif char == "2": + self.setHandler(ManageFiles) + elif char == "3": + self.setHandler(ManageFiles) + self.bodyHandler.target = Destination.Collector + elif char == "4": + self.client.togglePause() + self.setInput() + elif char == "5": + self.client.kill() + self.client.close() + sys.exit() + elif char == "6": + os.system('clear') + sys.exit() + + + def onEnter(self, inp): + pass + + + def onBackSpace(self): + pass + + + def processCommand(self): + command = self.command[0] + args = [] + if len(self.command) > 1: + args = self.command[1:] + + if command == "status": + files = self.client.statusDownloads() + + if not files: + print "No downloads running." + + for download in files: + if download.status == 12: #: downloading + print print_status(download) + print "\tDownloading: %s @ %s/s\t %s (%s%%)" % ( + download.format_eta, formatSize(download.speed), formatSize(download.size - download.bleft), + download.percent) + elif download.status == 5: + print print_status(download) + print "\tWaiting: %s" % download.format_wait + else: + print print_status(download) + + elif command == "queue": + print_packages(self.client.getQueueData()) + + elif command == "collector": + print_packages(self.client.getCollectorData()) + + elif command == "add": + if len(args) < 2: + print _("Please use this syntax: add <Package name> <link> <link2> ...") + return + + self.client.addPackage(args[0], args[1:], Destination.Queue) + + elif command == "add_coll": + if len(args) < 2: + print _("Please use this syntax: add <Package name> <link> <link2> ...") + return + + self.client.addPackage(args[0], args[1:], Destination.Collector) + + elif command == "del_file": + self.client.deleteFiles([int(x) for x in args]) + print "Files deleted." + + elif command == "del_package": + self.client.deletePackages([int(x) for x in args]) + print "Packages deleted." + + elif command == "move": + for pid in args: + pack = self.client.getPackageInfo(int(pid)) + self.client.movePackage((pack.dest + 1) % 2, pack.pid) + + elif command == "check": + print _("Checking %d links:") % len(args) + print + rid = self.client.checkOnlineStatus(args).rid + self.printOnlineCheck(self.client, rid) + + elif command == "check_container": + path = args[0] + if not exists(join(owd, path)): + print _("File does not exists.") + return + + with open(join(owd, path), "rb") as f: + content = f.read() + + rid = self.client.checkOnlineStatusContainer([], basename(f.name), content).rid + self.printOnlineCheck(self.client, rid) + + elif command == "pause": + self.client.pause() + + elif command == "unpause": + self.client.unpause() + + elif command == "toggle": + self.client.togglePause() + + elif command == "kill": + self.client.kill() + elif command == "restart_file": + for x in args: + self.client.restartFile(int(x)) + print "Files restarted." + elif command == "restart_package": + for pid in args: + self.client.restartPackage(int(pid)) + print "Packages restarted." + + else: + print_commands() + + + def printOnlineCheck(self, client, rid): + while True: + sleep(1) + result = client.pollResults(rid) + for url, status in result.data.iteritems(): + if status.status == 2: + check = "Online" + elif status.status == 1: + check = "Offline" + else: + check = "Unknown" + + print "%-45s %-12s\t %-15s\t %s" % (status.name, formatSize(status.size), status.plugin, check) + + if result.rid == -1: + break + + +class RefreshThread(threading.Thread): + + def __init__(self, cli): + threading.Thread.__init__(self) + self.setDaemon(True) + self.cli = cli + + + def run(self): + while True: + sleep(1) + try: + self.cli.refresh() + except ConnectionClosed: + os.system("clear") + print _("pyLoad was terminated") + _exit(0) + except Exception, e: + println(2, red(str(e))) + self.cli.reset() + traceback.print_exc() + + +def print_help(config): + print + print "pyLoad CLI Copyright (c) 2008-2015 the pyLoad Team" + print + print "Usage: [python] pyload-cli.py [options] [command]" + print + print "<Commands>" + print "See pyload-cli.py -c for a complete listing." + print + print "<Options>" + print " -i, --interactive", " Start in interactive mode" + print + print " -u, --username=", " " * 2, "Specify Username" + print " --pw=<password>", " " * 2, "Password" + print " -a, --address=", " " * 3, "Specify address (current=%s)" % config['addr'] + print " -p, --port", " " * 7, "Specify port (current=%s)" % config['port'] + print + print " -l, --language", " " * 3, "Set user interface language (current=%s)" % config['language'] + print " -h, --help", " " * 7, "Display this help screen" + print " -c, --commands", " " * 3, "List all available commands" + print + + +def print_packages(data): + for pack in data: + print "Package %s (#%s):" % (pack.name, pack.pid) + for download in pack.links: + print "\t" + print_file(download) + print + + +def print_file(download): + return "#%(id)-6d %(name)-30s %(statusmsg)-10s %(plugin)-8s" % { + "id": download.fid, + "name": download.name, + "statusmsg": download.statusmsg, + "plugin": download.plugin + } + + +def print_status(download): + return "#%(id)-6s %(name)-40s Status: %(statusmsg)-10s Size: %(size)s" % { + "id": download.fid, + "name": download.name, + "statusmsg": download.statusmsg, + "size": download.format_size + } + + +def print_commands(): + commands = [("status", _("Prints server status")), + ("queue", _("Prints downloads in queue")), + ("collector", _("Prints downloads in collector")), + ("add <name> <link1> <link2>...", _("Adds package to queue")), + ("add_coll <name> <link1> <link2>...", _("Adds package to collector")), + ("del_file <fid> <fid2>...", _("Delete Files from Queue/Collector")), + ("del_package <pid> <pid2>...", _("Delete Packages from Queue/Collector")), + ("move <pid> <pid2>...", _("Move Packages from Queue to Collector or vice versa")), + ("restart_file <fid> <fid2>...", _("Restart files")), + ("restart_package <pid> <pid2>...", _("Restart packages")), + ("check <container|url> ...", _("Check online status, works with local container")), + ("check_container path", _("Checks online status of a container file")), + ("pause", _("Pause the server")), + ("unpause", _("continue downloads")), + ("toggle", _("Toggle pause/unpause")), + ("kill", _("kill server")), ] + + print _("List of commands:") + print + for c in commands: + print "%-35s %s" % c + + +def writeConfig(opts): + try: + with open(join(homedir, ".pyload-cli"), "w") as cfgfile: + cfgfile.write("[cli]") + for opt in opts: + cfgfile.write("%s=%s\n" % (opt, opts[opt])) + except Exception: + print _("Couldn't write user config file") + + +def main(): + config = {"addr": "127.0.0.1", "port": "7227", "language": "en"} + try: + config['language'] = os.environ['LANG'][0:2] + except Exception: + pass + + if (not exists(join(pypath, "locale", config['language']))) or config['language'] == "": + config['language'] = "en" + + configFile = ConfigParser.ConfigParser() + configFile.read(join(homedir, ".pyload-cli")) + + if configFile.has_section("cli"): + for opt in configFile.items("cli"): + config[opt[0]] = opt[1] + + gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) + translation = gettext.translation("Cli", join(pypath, "locale"), + languages=[config['language'], "en"], fallback=True) + translation.install(unicode=True) + + interactive = False + command = None + username = "" + password = "" + + shortOptions = 'iu:p:a:hcl:' + longOptions = ['interactive', "username=", "pw=", "address=", "port=", "help", "commands", "language="] + + try: + opts, extraparams = getopt(sys.argv[1:], shortOptions, longOptions) + for option, params in opts: + if option in ("-i", "--interactive"): + interactive = True + elif option in ("-u", "--username"): + username = params + elif option in ("-a", "--address"): + config['addr'] = params + elif option in ("-p", "--port"): + config['port'] = params + elif option in ("-l", "--language"): + config['language'] = params + gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) + translation = gettext.translation("Cli", join(pypath, "locale"), + languages=[config['language'], "en"], fallback=True) + translation.install(unicode=True) + elif option in ("-h", "--help"): + print_help(config) + 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(config) + exit() + + if len(extraparams) >= 1: + command = extraparams + + client = False + + if interactive: + try: + client = ThriftClient(config['addr'], int(config['port']), username, password) + except WrongLogin: + pass + except NoSSL: + print _("You need py-openssl to connect to this pyLoad Core.") + exit() + except NoConnection: + config['addr'] = False + config['port'] = False + + if not client: + if not config['addr']: config['addr'] = raw_input(_("Address: ")) + if not config['port']: config['port'] = raw_input(_("Port: ")) + if not username: username = raw_input(_("Username: ")) + if not password: + from getpass import getpass + + password = getpass(_("Password: ")) + + try: + client = ThriftClient(config['addr'], int(config['port']), username, password) + except WrongLogin: + print _("Login data is wrong.") + except NoConnection: + print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config['addr'], + "port": config['port']}) + + else: + try: + client = ThriftClient(config['addr'], int(config['port']), username, password) + except WrongLogin: + print _("Login data is wrong.") + except NoConnection: + print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config['addr'], + "port": config['port']}) + except NoSSL: + print _("You need py-openssl to connect to this pyLoad core.") + + if interactive and command: print _("Interactive mode ignored since you passed some commands.") + + if client: + writeConfig(config) + cli = Cli(client, command) + + +if __name__ == "__main__": + main() diff --git a/pyload/config/Setup.py b/pyload/config/Setup.py index e2f96c802..2143632c2 100644 --- a/pyload/config/Setup.py +++ b/pyload/config/Setup.py @@ -295,7 +295,7 @@ class SetupAssistant(object): print print _("The following logindata is valid for CLI and webinterface.") - from pyload.database import DatabaseBackend + from pyload.Database import DatabaseBackend db = DatabaseBackend(None) db.setup() @@ -375,7 +375,7 @@ class SetupAssistant(object): def set_user(self): load_translation("setup", self.config.get("general", "language")) - from pyload.database import DatabaseBackend + from pyload.Database import DatabaseBackend db = DatabaseBackend(None) db.setup() diff --git a/pyload/database/File.py b/pyload/database/File.py index db4b13a52..f28535ffa 100644 --- a/pyload/database/File.py +++ b/pyload/database/File.py @@ -3,11 +3,10 @@ import threading -from pyload.utils import formatSize, lock +from pyload.Datatype import PyFile, PyPackage +from pyload.Database import DatabaseBackend, style from pyload.manager.Event import InsertEvent, ReloadAllEvent, RemoveEvent, UpdateEvent -from pyload.datatype.Package import PyPackage -from pyload.datatype.File import PyFile -from pyload.database import DatabaseBackend, style +from pyload.utils import formatSize, lock try: from pysqlite2 import dbapi2 as sqlite3 diff --git a/pyload/database/Storage.py b/pyload/database/Storage.py index 70932b55c..a19f67606 100644 --- a/pyload/database/Storage.py +++ b/pyload/database/Storage.py @@ -1,13 +1,12 @@ # -*- coding: utf-8 -*- # @author: mkaay -from pyload.database import style -from pyload.database import DatabaseBackend +from pyload.Database import style +from pyload.Database import DatabaseBackend class StorageMethods(object): - @style.queue def setStorage(db, identifier, key, value): db.c.execute("SELECT id FROM storage WHERE identifier=? AND key=?", (identifier, key)) diff --git a/pyload/database/User.py b/pyload/database/User.py index b5b44c50a..dc60ce23a 100644 --- a/pyload/database/User.py +++ b/pyload/database/User.py @@ -4,7 +4,7 @@ from hashlib import sha1 import random -from pyload.database import DatabaseBackend, style +from pyload.Database import DatabaseBackend, style class UserMethods(object): diff --git a/pyload/database/__init__.py b/pyload/database/__init__.py index 4e0edc5d1..b4200a698 100644 --- a/pyload/database/__init__.py +++ b/pyload/database/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from pyload.database.Backend import DatabaseBackend, style -from pyload.database.File import FileHandler -from pyload.database.Storage import StorageMethods -from pyload.database.User import UserMethods +from pyload.Database.Backend import DatabaseBackend, style +from pyload.Database.File import FileHandler +from pyload.Database.Storage import StorageMethods +from pyload.Database.User import UserMethods diff --git a/pyload/datatype/__init__.py b/pyload/datatype/__init__.py index 40a96afc6..29f0d40aa 100644 --- a/pyload/datatype/__init__.py +++ b/pyload/datatype/__init__.py @@ -1 +1,4 @@ # -*- coding: utf-8 -*- + +from pyload.Datatype.File import PyFile +from pyload.Datatype.Package import PyPackage diff --git a/pyload/manager/Addon.py b/pyload/manager/Addon.py index 2b3d1c456..98b66189a 100644 --- a/pyload/manager/Addon.py +++ b/pyload/manager/Addon.py @@ -9,7 +9,7 @@ import traceback from types import MethodType -from pyload.manager.thread.Addon import AddonThread +from pyload.Thread import AddonThread from pyload.manager.Plugin import literal_eval from pyload.utils import lock diff --git a/pyload/manager/event/Scheduler.py b/pyload/manager/Scheduler.py index d7098ae10..d7098ae10 100644 --- a/pyload/manager/event/Scheduler.py +++ b/pyload/manager/Scheduler.py diff --git a/pyload/manager/Thread.py b/pyload/manager/Thread.py index ecfcb3e26..6df8ab622 100644 --- a/pyload/manager/Thread.py +++ b/pyload/manager/Thread.py @@ -13,10 +13,8 @@ from random import choice from subprocess import Popen from time import sleep, time -from pyload.datatype.File import PyFile -from pyload.manager.thread.Decrypter import DecrypterThread -from pyload.manager.thread.Download import DownloadThread -from pyload.manager.thread.Info import InfoThread +from pyload.Datatype import PyFile +from pyload.Thread import DecrypterThread, DownloadThread, InfoThread from pyload.network.RequestFactory import getURL from pyload.utils import freeSpace, lock diff --git a/pyload/manager/event/__init__.py b/pyload/manager/event/__init__.py deleted file mode 100644 index 40a96afc6..000000000 --- a/pyload/manager/event/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/pyload/manager/thread/__init__.py b/pyload/manager/thread/__init__.py deleted file mode 100644 index 40a96afc6..000000000 --- a/pyload/manager/thread/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/pyload/plugin/Extractor.py b/pyload/plugin/Extractor.py index 539ab624d..3e497fc78 100644 --- a/pyload/plugin/Extractor.py +++ b/pyload/plugin/Extractor.py @@ -3,7 +3,7 @@ import os import re -from pyload.datatype.File import PyFile +from pyload.Datatype import PyFile from pyload.plugin.Plugin import Base diff --git a/pyload/webui/__init__.py b/pyload/webui/__init__.py index 3b3d62b26..665be763a 100644 --- a/pyload/webui/__init__.py +++ b/pyload/webui/__init__.py @@ -24,7 +24,7 @@ from middlewares import StripPathMiddleware, GZipMiddleWare, PrefixMiddleware SETUP = None PYLOAD = None -from pyload.manager.thread import Server +from pyload.Thread import Server from pyload.network.JsEngine import JsEngine if not Server.core: |