summaryrefslogtreecommitdiffstats
path: root/interfaces
diff options
context:
space:
mode:
authorGravatar RaNaN <Mast3rRaNaN@hotmail.de> 2010-08-29 18:42:09 +0200
committerGravatar RaNaN <Mast3rRaNaN@hotmail.de> 2010-08-29 18:42:09 +0200
commitfe017986229a92a29541329650b25e1b326dc87f (patch)
treeafb4b74c4ce62e8d1b8940eff723e1a9094f9f17 /interfaces
parentplugin updater (diff)
downloadpyload-fe017986229a92a29541329650b25e1b326dc87f.tar.xz
moved interfaces
Diffstat (limited to 'interfaces')
-rwxr-xr-xinterfaces/pyLoadCli.py558
-rwxr-xr-xinterfaces/pyLoadGui.py703
2 files changed, 0 insertions, 1261 deletions
diff --git a/interfaces/pyLoadCli.py b/interfaces/pyLoadCli.py
deleted file mode 100755
index 8fdd75016..000000000
--- a/interfaces/pyLoadCli.py
+++ /dev/null
@@ -1,558 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#Copyright (C) 2010 RaNaN
-#
-#This program is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 3 of the License,
-#or (at your option) any later version.
-#
-#This program is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-#See the GNU General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-# along with this program; if not, see <http://www.gnu.org/licenses/>.
-#
-###
-from getopt import GetoptError
-from getopt import getopt
-import gettext
-from itertools import islice
-import os
-import os.path
-from os.path import join
-from os.path import abspath
-from os.path import dirname
-import sys
-from sys import exit
-import threading
-import time
-from time import sleep
-import xmlrpclib
-from traceback import print_exc
-
-try:
- sys.path.append(join(dirname(abspath(__file__)), ".."))
-except:
- pass
-
-from module import InitHomeDir
-from module.ConfigParser import ConfigParser
-
-import codecs
-
-sys.stdout = codecs.getwriter("utf8")(sys.stdout, errors = "replace")
-
-if sys.stdout.encoding.lower().startswith("utf"):
- conv = unicode
-else:
- conv = str
-
-class pyLoadCli:
- def __init__(self, server_url, add=False):
- self.core = xmlrpclib.ServerProxy(server_url, allow_none=True)
- self.getch = _Getch()
- self.input = ""
- self.pos = [0, 0, 0]
- self.inputline = 0
- self.menuline = 0
-
- self.new_package = {}
-
- try:
- self.core.get_server_version()
- except:
- print _("pyLoadCore not running")
- exit()
-
- if add:
- self.core.add_package(add, [add])
- print _("Linklist added")
- exit()
-
- self.links_added = 0
-
- os.system("clear")
- self.println(1, blue("py") + yellow("Load") + white(_(" Command Line Interface")))
- self.println(2, "")
-
-
- self.file_list = {}
-
- self.thread = RefreshThread(self)
- self.thread.start()
-
- self.start()
-
- def start(self):
- while True:
- #inp = raw_input()
- inp = self.getch.impl()
- if ord(inp) == 3:
- os.system("clear")
- sys.exit() # ctrl + c
- elif ord(inp) == 13:
- try:
- self.handle_input()
- except Exception, e:
- self.println(2, red(conv(e)))
- self.input = "" #enter
- self.print_input()
- elif ord(inp) == 127:
- self.input = self.input[:-1] #backspace
- self.print_input()
- elif ord(inp) == 27: #ugly symbol
- pass
- else:
- self.input += inp
- self.print_input()
-
- def format_time(self, seconds):
- seconds = int(seconds)
-
- hours, seconds = divmod(seconds, 3600)
- 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"
-
- def print_input(self):
- self.println(self.inputline, white(" Input: ") + self.input)
- self.println(self.inputline + 1, "")
- self.println(self.inputline + 2, "")
- self.println(self.inputline + 3, "")
- self.println(self.inputline + 4, "")
-
- def refresh(self):
- """Handle incoming data"""
- data = self.core.status_downloads()
- #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))))
- line = 4
- speed = 0
- for download in data:
- if download["status"] == 12: # downloading
- percent = download["percent"]
- z = percent / 4
- 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'])))
- line += 1
- if download["status"] == 5:
- self.println(line, cyan(download["name"]))
- line += 1
- self.println(line, _("waiting: ") + green(download["format_wait"]) )
- line += 1
- self.println(line, "")
- line += 1
- status = self.core.status_server()
- if status['pause']:
- self.println(line, _("Status: ") + red("paused") + _(" total Speed: ") + red(conv(int(speed)) + " kb/s") + _(" Files in queue: ") + red(conv(status["queue"])))
- else:
- self.println(line, _("Status: ") + red("running") + _(" total Speed: ") + red(conv(int(speed)) + " kb/s") + _(" Files in queue: ") + red(conv(status["queue"])))
- line += 1
- self.println(line, "")
- line += 1
- self.menuline = line
-
- self.build_menu()
- #
- self.file_list = data
-
- def build_menu(self):
- line = self.menuline
- self.println(line, white(_("Menu:")))
- line += 1
- if self.pos[0] == 0:# main menu
- self.println(line, "")
- line += 1
- self.println(line, mag("1.") + _(" Add Links"))
- line += 1
- self.println(line, mag("2.") + _(" Manage Links"))
- line += 1
- self.println(line, mag("3.") + _(" (Un)Pause Server"))
- line += 1
- self.println(line, mag("4.") + _(" Kill Server"))
- line += 1
- self.println(line, mag("5.") + _(" Quit"))
- line += 1
- self.println(line, "")
- line += 1
- self.println(line, "")
- elif self.pos[0] == 1:#add links
-
- if self.pos[1] == 0:
- self.println(line, "")
- line += 1
- self.println(line, _("Name your package."))
- line += 1
- self.println(line, "")
- line += 1
- self.println(line, "")
- line += 1
- self.println(line, "")
- line += 1
- self.println(line, "")
- line += 1
- self.println(line, mag("0.") + _(" back to main menu"))
- line += 1
- self.println(line, "")
-
- else:
- self.println(line, _("Package: %s") % self.new_package['name'])
- line += 1
- self.println(line, _("Parse the links you want to add."))
- line += 1
- self.println(line, _("Type %s when done.") % mag("END"))
- line += 1
- self.println(line, _("Links added: ") + mag(conv(self.links_added)))
- line += 1
- self.println(line, "")
- line += 1
- self.println(line, "")
- line += 1
- self.println(line, mag("0.") + _(" back to main menu"))
- line += 1
- self.println(line, "")
- elif self.pos[0] == 2:#remove links
- if self.pos[1] == 0:
- pack = self.core.get_queue()
- 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):
- try:
- self.println(line, mag(conv(id)) + ": " + value['name'])
- line += 1
- i += 1
- except Exception, e:
- pass
- for x in range(5-i):
- self.println(line, "")
- line += 1
-
- else:
- links = self.core.get_package_data(self.pos[1])
- 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):
- try:
-
- self.println(line, mag(conv(id)) + ": %s | %s | %s" % (value['name'], value['statusmsg'], value['plugin']))
- line += 1
- i += 1
-
- except Exception, e:
- pass
- for x in range(5-i):
- self.println(line, "")
- line += 1
-
- self.println(line, mag("p") + _(" - previous") + " | " + mag("n") + _(" - next"))
- line += 1
- self.println(line, mag("0.") + _(" back to main menu"))
-
- self.inputline = line + 1
- self.print_input()
-
- def handle_input(self):
- inp = self.input.strip()
- if inp == "0":
- self.pos = [0, 0, 0]
- self.build_menu()
- return True
-
- if self.pos[0] == 0:
- if inp == "1":
- self.links_added = 0
- self.pos[0] = 1
- elif inp == "2":
- self.pos[0] = 2
- self.pos[1] = 0
- elif inp == "3":
- self.core.toggle_pause()
- elif inp == "4":
- self.core.kill()
- sys.exit()
- elif inp == "5":
- os.system('clear')
- sys.exit()
-
- elif self.pos[0] == 1: #add links
- if self.pos[1] == 0:
- 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.pos = [0, 0, 0]
- self.links_added = 0
- else: #@TODO validation
- self.new_package['links'].append(inp)
- self.links_added += 1
-
- elif self.pos[0] == 2: #remove links
- if self.pos[1] == 0:
- if inp.startswith("d"):
- if inp.find("-") > -1:
- self.core.del_packages(range(*map(int, inp[1:].split("-"))))
- else:
- self.core.del_packages([int(inp[1:])])
- if inp.startswith("r"):
- self.core.restart_package(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("-"))))
- else:
- self.core.restart_file(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("-"))))
- else:
- self.core.del_links([int(inp[1:])])
- if inp == "p":
- self.pos[2] -= 5
- elif inp == "n":
- self.pos[2] += 5
-
- self.build_menu()
-
-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 Exception, e:
- self.cli.println(2, red(conv(e)))
- self.cli.pos[1] = 0
- self.cli.pos[2] = 0
- print_exc()
-
-
-
-
-class _Getch:
- """
- Gets a single character from standard input. Does not echo to
- the screen.
- """
- def __init__(self):
- try:
- self.impl = _GetchWindows()
- except ImportError:
- try:
- self.impl = _GetchMacCarbon()
- except(AttributeError, ImportError):
- self.impl = _GetchUnix()
-
- def __call__(self): return self.impl()
-
-
-class _GetchUnix:
- def __init__(self):
- import tty
- import sys
-
- def __call__(self):
- import sys
- import tty
- import termios
-
- fd = sys.stdin.fileno()
- old_settings = termios.tcgetattr(fd)
- try:
- tty.setraw(sys.stdin.fileno())
- ch = sys.stdin.read(1)
- finally:
- termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
- return ch
-
-
-class _GetchWindows:
- def __init__(self):
- import msvcrt
-
- def __call__(self):
- import msvcrt
- return msvcrt.getch()
-
-class _GetchMacCarbon:
- """
- A function which returns the current ASCII key that is down;
- if no ASCII key is down, the null string is returned. The
- page http://www.mactech.com/macintosh-c/chap02-1.html was
- very helpful in figuring out how to do this.
- """
- def __init__(self):
- import Carbon
- Carbon.Evt #see if it has this (in Unix, it doesn't)
-
- def __call__(self):
- import Carbon
- if Carbon.Evt.EventAvail(0x0008)[0] == 0: # 0x0008 is the keyDownMask
- return ''
- else:
- #
- # The event contains the following info:
- # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
- #
- # The message (msg) contains the ASCII char which is
- # extracted with the 0x000000FF charCodeMask; this
- # number is converted to an ASCII character with chr() and
- # returned
- #
- (what, msg, when, where, mod) = Carbon.Evt.GetNextEvent(0x0008)[1]
- return chr(msg)
-
-def blue(string):
- return "\033[1;34m" + string + "\033[0m"
-
-def green(string):
- return "\033[1;32m" + string + "\033[0m"
-
-def yellow(string):
- return "\033[1;33m" + string + "\033[0m"
-
-def red(string):
- return "\033[1;31m" + string + "\033[0m"
-
-def cyan(string):
- return "\033[1;36m" + string + "\033[0m"
-
-def mag(string):
- return "\033[1;35m" + string + "\033[0m"
-
-def white(string):
- return "\033[1;37m" + string + "\033[0m"
-
-def print_help():
- print ""
- print "pyLoadCli Copyright (c) 2008-2010 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 "<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 ""
-
-
-
-if __name__ == "__main__":
- config = ConfigParser()
-
- translation = gettext.translation("pyLoadCli", join(pypath, "locale"), languages=[config['general']['language']])
- translation.install(unicode=(True if sys.stdout.encoding.lower().startswith("utf") else False))
-
- server_url = ""
- username = ""
- password = ""
- addr = ""
- port = ""
- ssl = None
-
- add = ""
-
- if len(sys.argv) > 1:
-
-
- addr = "127.0.0.1"
- port = "7272"
- ssl = ""
-
- shortOptions = 'lu:a:p:s:h'
- longOptions = ['local', "username=", "address=", "port=", "ssl=", "help", "linklist=", "pw=", "configdir="]
-
- 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
- except GetoptError:
- print 'Unknown Argument(s) "%s"' % " ".join(sys.argv[1:])
- print_help()
- exit()
-
- if len(extraparams) == 1:
- server_url = sys.argv[1]
-
- 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: "))
-
- server_url = "http%s://%s:%s@%s:%s/" % (ssl, username, password, addr, port)
-
- print server_url
- if add:
- cli = pyLoadCli(server_url, add)
- else:
- cli = pyLoadCli(server_url)
diff --git a/interfaces/pyLoadGui.py b/interfaces/pyLoadGui.py
deleted file mode 100755
index 441207487..000000000
--- a/interfaces/pyLoadGui.py
+++ /dev/null
@@ -1,703 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-"""
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 3 of the License,
- or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, see <http://www.gnu.org/licenses/>.
-
- @author: mkaay
- @version: v0.4.0
-"""
-
-import sys
-
-from time import sleep
-
-from PyQt4.QtCore import *
-from PyQt4.QtGui import *
-
-from uuid import uuid4 as uuid
-import re
-import gettext
-from xmlrpclib import Binary
-from os.path import join
-from os.path import abspath
-from os.path import dirname
-
-try:
- sys.path.append(join(dirname(abspath(__file__)),".."))
-except:
- pass
-
-from module import InitHomeDir
-
-from module.gui.ConnectionManager import *
-from module.gui.connector import Connector
-from module.gui.MainWindow import *
-from module.gui.Queue import *
-from module.gui.Collector import *
-from module.gui.XMLParser import *
-from module.gui.CoreConfigParser import ConfigParser
-
-from os.path import expanduser
-from os.path import join
-from os.path import basename
-from os.path import dirname
-from os import chdir
-from os import makedirs
-from os import name as platform
-
-try:
- import pynotify
-except ImportError:
- pass
-
-class main(QObject):
- def __init__(self):
- """
- main setup
- """
- QObject.__init__(self)
- self.app = QApplication(sys.argv)
- self.path = pypath
- self.homedir = abspath("")
-
- self.configdir = ""
-
- self.init(True)
-
- def init(self, first=False):
- """
- set main things up
- """
- self.parser = XMLParser(join(self.configdir, "gui.xml"), join(self.path, "module", "config", "gui_default.xml"))
- lang = self.parser.xml.elementsByTagName("language").item(0).toElement().text()
- if not lang:
- parser = XMLParser(join(self.path, "module", "config", "gui_default.xml"))
- lang = parser.xml.elementsByTagName("language").item(0).toElement().text()
-
- translation = gettext.translation("pyLoadGui", join(pypath, "locale"), languages=[str(lang)])
- try:
- translation.install(unicode=(True if sys.stdout.encoding.lower().startswith("utf") else False))
- except:
- translation.install(unicode=False)
-
- self.connector = Connector()
- self.mainWindow = MainWindow(self.connector)
- self.connWindow = ConnectionManager()
- self.mainloop = self.Loop(self)
- self.connectSignals()
-
- self.checkClipboard = False
- default = self.refreshConnections()
- self.connData = None
- self.captchaProcessing = False
-
- if True:
- self.tray = TrayIcon()
- self.tray.show()
- self.notification = Notification(self.tray)
- self.connect(self, SIGNAL("showMessage"), self.notification.showMessage)
- self.connect(self.tray.exitAction, SIGNAL("triggered()"), self.app.quit)
- self.connect(self.tray.showAction, SIGNAL("toggled(bool)"), self.mainWindow.setVisible)
- self.connect(self.mainWindow, SIGNAL("hidden"), self.tray.mainWindowHidden)
-
- if not first:
- self.connWindow.show()
- else:
- self.connWindow.edit.setData(default)
- data = self.connWindow.edit.getData()
- self.slotConnect(data)
-
- def startMain(self):
- """
- start all refresh threads and show main window
- """
- if not self.connector.canConnect():
- self.init()
- return
- self.connector.start()
- self.connect(self.connector, SIGNAL("connectionLost"), sys.exit)
- sleep(1)
- self.restoreMainWindow()
- self.mainWindow.show()
- self.initQueue()
- self.initPackageCollector()
- self.mainloop.start()
- self.clipboard = self.app.clipboard()
- self.connect(self.clipboard, SIGNAL('dataChanged()'), self.slotClipboardChange)
- self.mainWindow.actions["clipboard"].setChecked(self.checkClipboard)
-
- self.mainWindow.tabs["settings"]["w"].setConnector(self.connector)
- self.mainWindow.tabs["settings"]["w"].loadConfig()
- self.tray.showAction.setDisabled(False)
-
- def stopMain(self):
- """
- stop all refresh threads and hide main window
- """
- self.tray.showAction.setDisabled(True)
- self.disconnect(self.clipboard, SIGNAL('dataChanged()'), self.slotClipboardChange)
- self.disconnect(self.connector, SIGNAL("connectionLost"), sys.exit)
- self.mainloop.stop()
- self.connector.stop()
- self.mainWindow.saveWindow()
- self.mainWindow.hide()
- self.queue.stop()
- self.connector.wait()
-
- def connectSignals(self):
- """
- signal and slot stuff, yay!
- """
- self.connect(self.connector, SIGNAL("error_box"), self.slotErrorBox)
- self.connect(self.connWindow, SIGNAL("saveConnection"), self.slotSaveConnection)
- self.connect(self.connWindow, SIGNAL("removeConnection"), self.slotRemoveConnection)
- self.connect(self.connWindow, SIGNAL("connect"), self.slotConnect)
- self.connect(self.mainWindow, SIGNAL("connector"), self.slotShowConnector)
- self.connect(self.mainWindow, SIGNAL("addPackage"), self.slotAddPackage)
- self.connect(self.mainWindow, SIGNAL("setDownloadStatus"), self.slotSetDownloadStatus)
- self.connect(self.mainWindow, SIGNAL("saveMainWindow"), self.slotSaveMainWindow)
- self.connect(self.mainWindow, SIGNAL("pushPackageToQueue"), self.slotPushPackageToQueue)
- self.connect(self.mainWindow, SIGNAL("restartDownload"), self.slotRestartDownload)
- self.connect(self.mainWindow, SIGNAL("removeDownload"), self.slotRemoveDownload)
- self.connect(self.mainWindow, SIGNAL("abortDownload"), self.slotAbortDownload)
- self.connect(self.mainWindow, SIGNAL("addContainer"), self.slotAddContainer)
- self.connect(self.mainWindow, SIGNAL("stopAllDownloads"), self.slotStopAllDownloads)
- self.connect(self.mainWindow, SIGNAL("setClipboardStatus"), self.slotSetClipboardStatus)
- self.connect(self.mainWindow, SIGNAL("changePackageName"), self.slotChangePackageName)
- self.connect(self.mainWindow, SIGNAL("pullOutPackage"), self.slotPullOutPackage)
- self.connect(self.mainWindow, SIGNAL("setPriority"), self.slotSetPriority)
- self.connect(self.mainWindow, SIGNAL("reloadAccounts"), self.slotReloadAccounts)
-
- self.connect(self.mainWindow, SIGNAL("quit"), self.quit)
- self.connect(self.mainWindow.captchaDock, SIGNAL("done"), self.slotCaptchaDone)
-
- def slotShowConnector(self):
- """
- emitted from main window (menu)
- hide the main window and show connection manager
- (to switch to other core)
- """
- self.stopMain()
- self.init()
-
- def quit(self):
- """
- quit gui
- """
- self.app.quit()
-
- def loop(self):
- """
- start application loop
- """
- sys.exit(self.app.exec_())
-
- def slotErrorBox(self, msg):
- """
- display a nice error box
- """
- msgb = QMessageBox(QMessageBox.Warning, "Error", msg)
- msgb.exec_()
-
- def initPackageCollector(self):
- """
- init the package collector view
- * columns
- * selection
- * refresh thread
- * drag'n'drop
- """
- view = self.mainWindow.tabs["collector"]["package_view"]
- view.setSelectionBehavior(QAbstractItemView.SelectRows)
- view.setSelectionMode(QAbstractItemView.ExtendedSelection)
- def dropEvent(klass, event):
- event.setDropAction(Qt.CopyAction)
- event.accept()
- view = event.source()
- if view == klass:
- items = view.selectedItems()
- for item in items:
- if not hasattr(item.parent(), "getPackData"):
- continue
- target = view.itemAt(event.pos())
- if not hasattr(target, "getPackData"):
- target = target.parent()
- klass.emit(SIGNAL("droppedToPack"), target.getPackData()["id"], item.getFileData()["id"])
- event.ignore()
- return
- items = view.selectedItems()
- for item in items:
- row = view.indexOfTopLevelItem(item)
- view.takeTopLevelItem(row)
- def dragEvent(klass, event):
- view = event.source()
- #dragOkay = False
- #items = view.selectedItems()
- #for item in items:
- # if hasattr(item, "_data"):
- # if item._data["id"] == "fixed" or item.parent()._data["id"] == "fixed":
- # dragOkay = True
- # else:
- # dragOkay = True
- #if dragOkay:
- event.accept()
- #else:
- # event.ignore()
- view.dropEvent = dropEvent
- view.dragEnterEvent = dragEvent
- view.setDragEnabled(True)
- view.setDragDropMode(QAbstractItemView.DragDrop)
- view.setDropIndicatorShown(True)
- view.setDragDropOverwriteMode(True)
- view.connect(view, SIGNAL("droppedToPack"), self.slotAddFileToPackage)
- #self.packageCollector = PackageCollector(view, self.connector)
- self.packageCollector = view.model()
-
- def initQueue(self):
- """
- init the queue view
- * columns
- * progressbar
- """
- view = self.mainWindow.tabs["queue"]["view"]
- view.setSelectionBehavior(QAbstractItemView.SelectRows)
- view.setSelectionMode(QAbstractItemView.ExtendedSelection)
- self.queue = view.model()
- self.queue.start()
-
- def refreshServerStatus(self):
- """
- refresh server status and overall speed in the status bar
- """
- status = self.connector.getServerStatus()
- if status["pause"]:
- status["status"] = _("Paused")
- else:
- status["status"] = _("Running")
- status["speed"] = int(status["speed"])
- text = _("Status: %(status)s | Speed: %(speed)s kb/s") % status
- self.mainWindow.actions["toggle_status"].setChecked(not status["pause"])
- self.mainWindow.serverStatus.setText(text)
-
- def refreshLog(self):
- """
- update log window
- """
- offset = self.mainWindow.tabs["log"]["text"].logOffset
- lines = self.connector.getLog(offset)
- if not lines:
- return
- self.mainWindow.tabs["log"]["text"].logOffset += len(lines)
- for line in lines:
- self.mainWindow.tabs["log"]["text"].emit(SIGNAL("append(QString)"), line.strip("\n"))
- cursor = self.mainWindow.tabs["log"]["text"].textCursor()
- cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
- self.mainWindow.tabs["log"]["text"].setTextCursor(cursor)
-
- def getConnections(self):
- """
- parse all connections in the config file
- """
- connectionsNode = self.parser.xml.elementsByTagName("connections").item(0)
- if connectionsNode.isNull():
- raise Exception("null")
- connections = self.parser.parseNode(connectionsNode)
- ret = []
- for conn in connections:
- data = {}
- data["type"] = conn.attribute("type", "remote")
- data["default"] = conn.attribute("default", "False")
- data["id"] = conn.attribute("id", uuid().hex)
- if data["default"] == "True":
- data["default"] = True
- else:
- data["default"] = False
- subs = self.parser.parseNode(conn, "dict")
- if not subs.has_key("name"):
- data["name"] = _("Unnamed")
- else:
- data["name"] = subs["name"].text()
- if data["type"] == "remote":
- if not subs.has_key("server"):
- continue
- else:
- data["host"] = subs["server"].text()
- data["ssl"] = subs["server"].attribute("ssl", "False")
- if data["ssl"] == "True":
- data["ssl"] = True
- else:
- data["ssl"] = False
- data["user"] = subs["server"].attribute("user", "admin")
- data["port"] = int(subs["server"].attribute("port", "7227"))
- data["password"] = subs["server"].attribute("password", "")
- ret.append(data)
- return ret
-
- def slotSaveConnection(self, data):
- """
- save connection to config file
- """
- connectionsNode = self.parser.xml.elementsByTagName("connections").item(0)
- if connectionsNode.isNull():
- raise Exception("null")
- connections = self.parser.parseNode(connectionsNode)
- connNode = self.parser.xml.createElement("connection")
- connNode.setAttribute("default", str(data["default"]))
- connNode.setAttribute("type", data["type"])
- connNode.setAttribute("id", data["id"])
- nameNode = self.parser.xml.createElement("name")
- nameText = self.parser.xml.createTextNode(data["name"])
- nameNode.appendChild(nameText)
- connNode.appendChild(nameNode)
- if data["type"] == "remote":
- serverNode = self.parser.xml.createElement("server")
- serverNode.setAttribute("ssl", data["ssl"])
- serverNode.setAttribute("user", data["user"])
- serverNode.setAttribute("port", data["port"])
- serverNode.setAttribute("password", data["password"])
- hostText = self.parser.xml.createTextNode(data["host"])
- serverNode.appendChild(hostText)
- connNode.appendChild(serverNode)
- found = False
- for c in connections:
- cid = c.attribute("id", "None")
- if str(cid) == str(data["id"]):
- found = c
- break
- if found:
- connectionsNode.replaceChild(connNode, found)
- else:
- connectionsNode.appendChild(connNode)
- self.parser.saveData()
- self.refreshConnections()
-
- def slotRemoveConnection(self, data):
- """
- remove connection from config file
- """
- connectionsNode = self.parser.xml.elementsByTagName("connections").item(0)
- if connectionsNode.isNull():
- raise Exception("null")
- connections = self.parser.parseNode(connectionsNode)
- found = False
- for c in connections:
- cid = c.attribute("id", "None")
- if str(cid) == str(data["id"]):
- found = c
- break
- if found:
- connectionsNode.removeChild(found)
- self.parser.saveData()
- self.refreshConnections()
-
- def slotConnect(self, data):
- """
- connect to a core
- if connection is local, parse the core config file for data
- set up connector, show main window
- """
- self.connWindow.hide()
- if not data["type"] == "remote":
-
- coreparser = ConfigParser(self.configdir)
- if not coreparser.config:
- raise Exception
- #except:
- # data["port"] = 7227
- # data["user"] = "admin"
- # data["password"] = "pwhere"
- # data["host"] = "127.0.0.1"
- # data["ssl"] = False
-
- data["port"] = coreparser.get("remote","port")
- data["user"] = coreparser.get("remote","username")
- data["password"] = coreparser.get("remote","password")
- data["host"] = "127.0.0.1"
- data["ssl"] = coreparser.get("ssl","activated")
- data["ssl"] = "s" if data["ssl"] else ""
- server_url = "http%(ssl)s://%(user)s:%(password)s@%(host)s:%(port)s/" % data
- self.connector.setAddr(str(server_url))
- self.startMain()
-
- def refreshConnections(self):
- """
- reload connetions and display them
- """
- self.parser.loadData()
- conns = self.getConnections()
- self.connWindow.emit(SIGNAL("setConnections"), conns)
- for conn in conns:
- if conn["default"]:
- return conn
- return None
-
- def slotSetDownloadStatus(self, status):
- """
- toolbar start/pause slot
- """
- self.connector.setPause(not status)
-
- def slotAddPackage(self, name, links):
- """
- emitted from main window
- add package to the collector
- """
- self.connector.proxy.add_package(name, links)
-
- def slotAddFileToPackage(self, pid, fid):
- """
- emitted from collector view after a drop action
- """
- self.connector.addFileToPackage(fid, pid)
-
- def slotAddContainer(self, path):
- """
- emitted from main window
- add container
- """
- filename = basename(path)
- type = "".join(filename.split(".")[-1])
- fh = open(path, "r")
- content = fh.read()
- fh.close()
- self.connector.proxy.upload_container(filename, Binary(content))
-
- def slotSaveMainWindow(self, state, geo):
- """
- save the window geometry and toolbar/dock position to config file
- """
- mainWindowNode = self.parser.xml.elementsByTagName("mainWindow").item(0)
- if mainWindowNode.isNull():
- mainWindowNode = self.parser.xml.createElement("mainWindow")
- self.parser.root.appendChild(mainWindowNode)
- stateNode = mainWindowNode.toElement().elementsByTagName("state").item(0)
- geoNode = mainWindowNode.toElement().elementsByTagName("geometry").item(0)
- newStateNode = self.parser.xml.createTextNode(state)
- newGeoNode = self.parser.xml.createTextNode(geo)
-
- stateNode.removeChild(stateNode.firstChild())
- geoNode.removeChild(geoNode.firstChild())
- stateNode.appendChild(newStateNode)
- geoNode.appendChild(newGeoNode)
-
- self.parser.saveData()
-
- def restoreMainWindow(self):
- """
- load and restore main window geometry and toolbar/dock position from config
- """
- mainWindowNode = self.parser.xml.elementsByTagName("mainWindow").item(0)
- if mainWindowNode.isNull():
- return
- nodes = self.parser.parseNode(mainWindowNode, "dict")
-
- state = str(nodes["state"].text())
- geo = str(nodes["geometry"].text())
-
- self.mainWindow.restoreWindow(state, geo)
- self.mainWindow.captchaDock.hide()
-
- def slotPushPackageToQueue(self, id):
- """
- emitted from main window
- push the collector package to queue
- """
- self.connector.proxy.push_package_to_queue(id)
-
- def slotRestartDownload(self, id, isPack):
- """
- emitted from main window
- restart download
- """
- if isPack:
- self.connector.restartPackage(id)
- else:
- self.connector.restartFile(id)
-
- def slotRemoveDownload(self, id, isPack):
- """
- emitted from main window
- remove download
- """
- if isPack:
- self.connector.removePackage(id)
- else:
- self.connector.removeFile(id)
-
- def slotAbortDownload(self, id, isPack):
- """
- emitted from main window
- remove download
- """
- if isPack:
- data = self.connector.proxy.get_package_data(id)
- self.connector.proxy.abort_files(data["links"].keys())
- else:
- self.connector.proxy.abort_files([id])
-
- def slotStopAllDownloads(self):
- """
- emitted from main window
- stop all running downloads
- """
- self.connector.stopAllDownloads()
-
- def slotClipboardChange(self):
- """
- called if clipboard changes
- """
- if self.checkClipboard:
- text = self.clipboard.text()
- pattern = re.compile(r"(http|https)://[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?/.*)?")
- matches = pattern.finditer(text)
- for match in matches:
- self.slotAddLinks([str(match.group(0))])
-
- def slotSetClipboardStatus(self, status):
- """
- set clipboard checking
- """
- self.checkClipboard = status
-
- def slotChangePackageName(self, pid, name):
- """
- package name edit finished
- """
- self.connector.setPackageName(pid, str(name))
-
- def slotPullOutPackage(self, pid):
- """
- pull package out of the queue
- """
- self.connector.proxy.pull_out_package(pid)
-
- def slotSetPriority(self, pid, level):
- """
- set package priority
- """
- self.connector.proxy.set_priority(pid, level)
-
- def checkCaptcha(self):
- if self.connector.captchaWaiting() and self.mainWindow.captchaDock.isFree():
- cid, img, imgType = self.connector.getCaptcha()
- self.mainWindow.captchaDock.emit(SIGNAL("setTask"), cid, str(img), imgType)
- self.mainWindow.show()
- elif not self.mainWindow.captchaDock.isFree():
- status = self.connector.getCaptchaStatus(self.mainWindow.captchaDock.currentID)
- if not (status == "user" or status == "shared-user"):
- self.mainWindow.captchaDock.hide()
- self.mainWindow.captchaDock.processing = False
- self.mainWindow.captchaDock.currentID = None
-
- def slotCaptchaDone(self, cid, result):
- self.connector.setCaptchaResult(str(cid), str(result))
-
- def pullEvents(self):
- events = self.connector.getEvents()
- for event in events:
- if event[1] == "queue":
- self.queue.addEvent(event)
- try:
- if event[0] == "update" and event[2] == "file":
- info = self.connector.getLinkInfo(event[3])
- if info["status_type"] == "finished":
- self.emit(SIGNAL("showMessage"), _("Finished downloading of '%s'") % info["status_filename"])
- elif info["status_type"] == "downloading":
- self.emit(SIGNAL("showMessage"), _("Started downloading '%s'") % info["status_filename"])
- elif info["status_type"] == "failed":
- self.emit(SIGNAL("showMessage"), _("Failed downloading '%s'!") % info["status_filename"])
- if event[0] == "insert" and event[2] == "file":
- info = self.connector.getLinkInfo(event[3])
- self.emit(SIGNAL("showMessage"), _("Added '%s' to queue") % info["status_filename"])
- except:
- pass
- elif event[1] == "collector":
- self.packageCollector.addEvent(event)
-
- def slotReloadAccounts(self):
- self.mainWindow.tabs["accounts"]["view"].model().reloadData()
-
- class Loop():
- def __init__(self, parent):
- self.parent = parent
- self.timer = QTimer()
- self.timer.connect(self.timer, SIGNAL("timeout()"), self.update)
-
- def start(self):
- self.update()
- self.timer.start(1000)
-
- def update(self):
- """
- methods to call
- """
- self.parent.refreshServerStatus()
- self.parent.refreshLog()
- self.parent.checkCaptcha()
- self.parent.pullEvents()
-
- def stop(self):
- self.timer.stop()
-
-
-class TrayIcon(QSystemTrayIcon):
- def __init__(self):
- QSystemTrayIcon.__init__(self, QIcon(join(pypath, "icons", "logo.png")))
- self.contextMenu = QMenu()
- self.showAction = QAction(_("Show"), self.contextMenu)
- self.showAction.setCheckable(True)
- self.showAction.setChecked(True)
- self.showAction.setDisabled(True)
- self.contextMenu.addAction(self.showAction)
- self.exitAction = QAction(QIcon(join(pypath, "icons", "close.png")), _("Exit"), self.contextMenu)
- self.contextMenu.addAction(self.exitAction)
- self.setContextMenu(self.contextMenu)
-
- self.connect(self, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.doubleClicked)
-
- def mainWindowHidden(self):
- self.showAction.setChecked(False)
-
- def doubleClicked(self, reason):
- if self.showAction.isEnabled():
- if reason == QSystemTrayIcon.DoubleClick:
- self.showAction.toggle()
-
-class Notification(QObject):
- def __init__(self, tray):
- QObject.__init__(self)
- self.tray = tray
- self.usePynotify = False
-
- try:
- self.usePynotify = pynotify.init("icon-summary-body")
- except:
- pass
-
- def showMessage(self, body):
- if self.usePynotify:
- n = pynotify.Notification("pyload", body, join(pypath, "icons", "logo.png"))
- try:
- n.set_hint_string("x-canonical-append", "")
- except:
- pass
- n.show()
- else:
- self.tray.showMessage("pyload", body)
-
-if __name__ == "__main__":
- app = main()
- app.loop()
-