summaryrefslogtreecommitdiffstats
path: root/module/gui
diff options
context:
space:
mode:
authorGravatar mkaay <mkaay@mkaay.de> 2011-02-12 18:04:24 +0100
committerGravatar mkaay <mkaay@mkaay.de> 2011-02-12 18:04:24 +0100
commit5a6bcc04e4a0b0088b7ca08c2a782fbc1212d674 (patch)
treecdbdda06598c0f2dd85273b2f32642e1ab1a5405 /module/gui
parentFileserveCom: Fixes download check (diff)
downloadpyload-5a6bcc04e4a0b0088b7ca08c2a782fbc1212d674.tar.xz
GUI refactoring (now Thrift powered), closes #233
please test!
Diffstat (limited to 'module/gui')
-rw-r--r--module/gui/Accounts.py30
-rw-r--r--module/gui/Collector.py124
-rw-r--r--module/gui/ConnectionManager.py1
-rw-r--r--module/gui/MainWindow.py21
-rw-r--r--module/gui/Overview.py13
-rw-r--r--module/gui/Queue.py47
-rw-r--r--module/gui/SettingsWidget.py100
-rw-r--r--module/gui/connector.py276
8 files changed, 241 insertions, 371 deletions
diff --git a/module/gui/Accounts.py b/module/gui/Accounts.py
index a4a047920..62971f3ed 100644
--- a/module/gui/Accounts.py
+++ b/module/gui/Accounts.py
@@ -31,11 +31,7 @@ class AccountModel(QAbstractItemModel):
self.mutex = QMutex()
def reloadData(self, force=False):
- data = self.connector.proxy.get_accounts(force, False)
-
- accounts = []
- for li in data.values():
- accounts += li
+ accounts = self.connector.proxy.getAccounts(False)
if self._data == accounts:
return
@@ -58,15 +54,15 @@ class AccountModel(QAbstractItemModel):
return QVariant()
if role == Qt.DisplayRole:
if index.column() == 0:
- return QVariant(self.toData(index)["type"])
+ return QVariant(self.toData(index).type)
elif index.column() == 1:
- return QVariant(self.toData(index)["login"])
+ return QVariant(self.toData(index).login)
elif index.column() == 2:
- if not self.toData(index)["valid"]:
+ if not self.toData(index).valid:
return QVariant(_("not valid"))
- if not self.toData(index)["validuntil"]:
+ if not self.toData(index).validuntil:
return QVariant(_("n/a"))
- until = int(self.toData(index)["validuntil"])
+ until = int(self.toData(index).validuntil)
if until > 0:
fmtime = strftime(_("%a, %d %b %Y %H:%M"), gmtime(until))
return QVariant(fmtime)
@@ -155,22 +151,22 @@ class AccountDelegate(QItemDelegate):
data = self.model.toData(index)
opts = QStyleOptionProgressBarV2()
opts.minimum = 0
- if data["trafficleft"]:
- if data["trafficleft"] == -1 or data["trafficleft"] is None:
+ if data.trafficleft:
+ if data.trafficleft == -1 or data.trafficleft is None:
opts.maximum = opts.progress = 1
else:
- opts.maximum = opts.progress = data["trafficleft"]
- if data["maxtraffic"]:
- opts.maximum = data["maxtraffic"]
+ opts.maximum = opts.progress = data.trafficleft
+ if data.maxtraffic:
+ opts.maximum = data.maxtraffic
opts.rect = option.rect
opts.rect.setRight(option.rect.right()-1)
opts.rect.setHeight(option.rect.height()-1)
opts.textVisible = True
opts.textAlignment = Qt.AlignCenter
- if data["trafficleft"] and data["trafficleft"] == -1:
+ if data.trafficleft and data.trafficleft == -1:
opts.text = QString(_("unlimited"))
- elif data["trafficleft"] is None:
+ elif data.trafficleft is None:
opts.text = QString(_("n/a"))
else:
opts.text = QString.number(round(float(opts.progress)/1024/1024, 2)) + " GB"
diff --git a/module/gui/Collector.py b/module/gui/Collector.py
index 87d433566..0711a811e 100644
--- a/module/gui/Collector.py
+++ b/module/gui/Collector.py
@@ -19,6 +19,8 @@
from PyQt4.QtCore import *
from PyQt4.QtGui import *
+from module.remote.thriftbackend.thriftgen.pyload.ttypes import *
+
statusMap = {
"finished": 0,
"offline": 1,
@@ -72,90 +74,84 @@ class CollectorModel(QAbstractItemModel):
def addEvent(self, event):
locker = QMutexLocker(self.mutex)
- if event[0] == "reload":
+ if event.event == "reload":
self.fullReload()
- elif event[0] == "remove":
+ elif event.event == "remove":
self.removeEvent(event)
- elif event[0] == "insert":
+ elif event.event == "insert":
self.insertEvent(event)
- elif event[0] == "update":
+ elif event.event == "update":
self.updateEvent(event)
def fullReload(self):
self._data = []
- packs = self.connector.getPackageCollector()
- self.beginInsertRows(QModelIndex(), 0, len(packs))
- for pid, data in packs.items():
- package = Package(pid, data)
+ order = self.connector.getPackageOrder(Destination.Collector)
+ self.beginInsertRows(QModelIndex(), 0, len(order.values()))
+ for position, pid in order.iteritems():
+ pack = self.connector.getPackageData(pid)
+ package = Package(pack)
self._data.append(package)
self._data = sorted(self._data, key=lambda p: p.data["order"])
self.endInsertRows()
def removeEvent(self, event):
- if event[2] == "file":
+ if event.type == ElementType.File:
for p, package in enumerate(self._data):
for k, child in enumerate(package.children):
- if child.id == int(event[3]):
+ if child.id == event.id:
self.beginRemoveRows(self.index(p, 0), k, k)
del package.children[k]
self.endRemoveRows()
break
else:
for k, package in enumerate(self._data):
- if package.id == int(event[3]):
+ if package.id == event.id:
self.beginRemoveRows(QModelIndex(), k, k)
del self._data[k]
self.endRemoveRows()
break
def insertEvent(self, event):
- if event[2] == "file":
- info = self.connector.proxy.get_file_data(int(event[3]))
- fid = info.keys()[0]
- info = info.values()[0]
+ if event.type == ElementType.File:
+ info = self.connector.getFileData(event.id)
for k, package in enumerate(self._data):
- if package.id == int(info["package"]):
- if package.getChild(fid):
- del event[4]
+ if package.id == info.package:
+ if package.getChild(info.fid):
self.updateEvent(event)
break
- self.beginInsertRows(self.index(k, 0), info["order"], info["order"])
- package.addChild(fid, info, info["order"])
+ self.beginInsertRows(self.index(k, 0), info.order, info.order)
+ package.addChild(info)
self.endInsertRows()
break
else:
- data = self.connector.proxy.get_package_data(event[3])
- package = Package(event[3], data)
- self.beginInsertRows(QModelIndex(), data["order"], data["order"])
- self._data.insert(data["order"], package)
+ data = self.connector.getPackageData(event.id)
+ package = Package(data)
+ self.beginInsertRows(QModelIndex(), data.order, data.order)
+ self._data.insert(data.order, package)
self.endInsertRows()
def updateEvent(self, event):
- if event[2] == "file":
- info = self.connector.proxy.get_file_data(int(event[3]))
+ if event.type == ElementType.File:
+ info = self.connector.proxy.getFileData(event.id)
if not info:
return
- fid = info.keys()[0]
- info = info.values()[0]
for p, package in enumerate(self._data):
- if package.id == int(info["package"]):
+ if package.id == info.package:
for k, child in enumerate(package.children):
- if child.id == int(event[3]):
- child.data.update(info)
- if not info["status"] == 12:
+ if child.id == event.id:
+ child.update(info)
+ if not info.status == 12:
child.data["downloading"] = None
self.emit(SIGNAL("dataChanged(const QModelIndex &, const QModelIndex &)"), self.index(k, 0, self.index(p, 0)), self.index(k, self.cols, self.index(p, self.cols)))
break
else:
- data = self.connector.proxy.get_package_data(int(event[3]))
+ data = self.connector.getPackageData(event.id)
if not data:
return
- pid = event[3]
- del data["links"]
for p, package in enumerate(self._data):
- if package.id == int(pid):
- package.data = data
+ if package.id == event.id:
+ package.update(data)
self.emit(SIGNAL("dataChanged(const QModelIndex &, const QModelIndex &)"), self.index(p, 0), self.index(p, self.cols))
break
@@ -265,19 +261,27 @@ class CollectorModel(QAbstractItemModel):
return True
class Package(object):
- def __init__(self, pid, data):
- self.id = int(pid)
+ def __init__(self, pack):
+ self.id = pack.pid
self.children = []
- for fid, fdata in data["links"].items():
- self.addChild(int(fid), fdata)
- del data["links"]
- self.data = data
+ for f in pack.links:
+ self.addChild(f)
+ self.data = {}
+ self.update(pack)
- def addChild(self, fid, data, pos=None):
- if pos is None:
- self.children.insert(data["order"], Link(fid, data, self))
- else:
- self.children.insert(pos, Link(fid, data, self))
+ def update(self, pack):
+ data = {
+ "name": pack.name,
+ "folder": pack.folder,
+ "site": pack.site,
+ "password": pack.password,
+ "order": pack.order,
+ "priority": pack.priority,
+ }
+ self.data.update(data)
+
+ def addChild(self, f):
+ self.children.insert(f.order, Link(f, self))
self.children = sorted(self.children, key=lambda l: l.data["order"])
def getChild(self, fid):
@@ -298,11 +302,27 @@ class Package(object):
del self.children[k]
class Link(object):
- def __init__(self, fid, data, pack):
- self.data = data
- self.data["downloading"] = None
- self.id = int(fid)
+ def __init__(self, f, pack):
+ self.data = {"downloading": None}
+ self.update(f)
+ self.id = f.fid
self.package = pack
+
+ def update(self, f):
+ data = {
+ "url": f.url,
+ "name": f.name,
+ "plugin": f.plugin,
+ "size": f.size,
+ "forrmat_size": f.format_size,
+ "status": f.status,
+ "statusmsg": f.statusmsg,
+ "package": f.package,
+ "error": f.error,
+ "order": f.order,
+ "progress": f.progress
+ }
+ self.data.update(data)
class CollectorView(QTreeView):
def __init__(self, connector):
diff --git a/module/gui/ConnectionManager.py b/module/gui/ConnectionManager.py
index 92c1540d7..c101a7add 100644
--- a/module/gui/ConnectionManager.py
+++ b/module/gui/ConnectionManager.py
@@ -61,6 +61,7 @@ class ConnectionManager(QWidget):
form.setAlignment(Qt.AlignRight)
checkbox = QCheckBox()
+ checkbox.setDisabled(True)
form.addRow(_("Use internal Core:"), checkbox)
boxLayout.addLayout(form)
diff --git a/module/gui/MainWindow.py b/module/gui/MainWindow.py
index b5ec345cb..ff54e8d76 100644
--- a/module/gui/MainWindow.py
+++ b/module/gui/MainWindow.py
@@ -32,6 +32,8 @@ from module.gui.Overview import OverviewView
from module.gui.Accounts import AccountView
from module.gui.AccountEdit import AccountEdit
+from module.remote.thriftbackend.thriftgen.pyload.ttypes import *
+
class MainWindow(QMainWindow):
def __init__(self, connector):
"""
@@ -411,7 +413,7 @@ class MainWindow(QMainWindow):
for index in smodel.selectedRows(0):
item = index.internalPointer()
if isinstance(item, Package):
- self.connector.proxy.add_files(item.id, links)
+ self.connector.proxy.addFiles(item.id, links)
break
def slotShowAddContainer(self):
@@ -652,13 +654,17 @@ class MainWindow(QMainWindow):
def save(data):
if data["password"]:
self.accountEdit.close()
- self.connector.proxy.update_account(data["acctype"], data["login"], data["password"])
+ a = AccountData()
+ a.type = data["acctype"]
+ a.login = data["login"]
+ a.password = data["password"]
+ self.connector.updateAccounts(a)
self.accountEdit.connect(self.accountEdit, SIGNAL("done"), save)
self.accountEdit.show()
def slotEditAccount(self):
- types = self.connector.proxy.get_accounts(False, False).keys()
+ types = self.connector.getAccountTypes()
data = self.tabs["accounts"]["view"].selectedIndexes()
if len(data) < 1:
@@ -670,7 +676,12 @@ class MainWindow(QMainWindow):
def save(data):
self.accountEdit.close()
- self.connector.proxy.update_account(data["acctype"], data["login"], data["password"] if data["password"] else None)
+ a = AccountData()
+ a.type = data["acctype"]
+ a.login = data["login"]
+ if data["password"]:
+ a.password = data["password"]
+ self.connector.updateAccounts(a)
self.accountEdit.connect(self.accountEdit, SIGNAL("done"), save)
self.accountEdit.show()
@@ -682,7 +693,7 @@ class MainWindow(QMainWindow):
data = data[0].internalPointer()
- self.connector.proxy.remove_account(data["type"], data["login"])
+ self.connector.removeAccount(data["type"], data["login"])
def slotAccountContextMenu(self, pos):
globalPos = self.tabs["accounts"]["view"].mapToGlobal(pos)
diff --git a/module/gui/Overview.py b/module/gui/Overview.py
index 1ac790515..ad63bf9fd 100644
--- a/module/gui/Overview.py
+++ b/module/gui/Overview.py
@@ -21,6 +21,15 @@ from PyQt4.QtGui import *
from time import sleep, time
+def formatSpeed(speed):
+ speed = int(speed)
+ steps = 0
+ sizes = ["B/s", "KiB/s", "MiB/s", "GiB/s"]
+ while speed > 1000:
+ speed /= 1024.0
+ steps += 1
+ return "%i %s" % (speed, sizes[steps])
+
class OverviewModel(QAbstractListModel):
PackageName = 10
Progress = 11
@@ -76,7 +85,7 @@ class OverviewModel(QAbstractListModel):
maxsize, currentsize = maxSize(p)
speed = self.queue.getSpeed(p)
if speed:
- eta = (maxsize - (maxsize * (progress/100.0)))/1024/speed
+ eta = (maxsize - (maxsize * (progress/100.0)))/speed
else:
eta = 0
if not speed and not progress:
@@ -152,7 +161,7 @@ class OverviewDelegate(QItemDelegate):
elif not status == _("Downloading"):
speedline = QString(status)
else:
- speedline = QString(formatEta(eta) + " " + _("Speed: %s kb/s") % speed)
+ speedline = QString(formatEta(eta) + " " + _("Speed: %s") % formatSpeed(speed))
def formatSize(size):
from math import ceil
diff --git a/module/gui/Queue.py b/module/gui/Queue.py
index d2541f024..5acbf2eb3 100644
--- a/module/gui/Queue.py
+++ b/module/gui/Queue.py
@@ -19,6 +19,8 @@
from PyQt4.QtCore import *
from PyQt4.QtGui import *
+from module.remote.thriftbackend.thriftgen.pyload.ttypes import *
+
from time import sleep, time
from module.gui.Collector import CollectorModel, Package, Link, CollectorView, statusMap, statusMapReverse
@@ -35,6 +37,15 @@ def formatSize(size):
return "%.2f %s" % (size, sizes[steps])
+def formatSpeed(speed):
+ speed = int(speed)
+ steps = 0
+ sizes = ["B/s", "KiB/s", "MiB/s", "GiB/s"]
+ while speed > 1000:
+ speed /= 1024.0
+ steps += 1
+ return "%i %s" % (speed, sizes[steps])
+
class QueueModel(CollectorModel):
def __init__(self, view, connector):
CollectorModel.__init__(self, view, connector)
@@ -66,10 +77,11 @@ class QueueModel(CollectorModel):
def fullReload(self):
self._data = []
- packs = self.connector.getPackageQueue()
- self.beginInsertRows(QModelIndex(), 0, len(packs))
- for pid, data in packs.items():
- package = Package(pid, data)
+ order = self.connector.getPackageOrder(Destination.Queue)
+ self.beginInsertRows(QModelIndex(), 0, len(order.values()))
+ for position, pid in order.iteritems():
+ pack = self.connector.getPackageData(pid)
+ package = Package(pack)
self._data.append(package)
self._data = sorted(self._data, key=lambda p: p.data["order"])
self.endInsertRows()
@@ -94,16 +106,29 @@ class QueueModel(CollectorModel):
def update(self):
locker = QMutexLocker(self.mutex)
- downloading = self.connector.getDownloadQueue()
- if downloading is None:
+ downloading = self.connector.statusDownloads()
+ if not downloading:
return
for p, pack in enumerate(self._data):
for d in downloading:
- child = pack.getChild(d["id"])
+ child = pack.getChild(d.id)
if child:
- child.data["downloading"] = d
- #child.data["progress"] = child.data["downloading"]["percent"]
- k = pack.getChildKey(d["id"])
+ dd = {
+ "name": d.name,
+ "speed": d.speed,
+ "eta": d.eta,
+ "format_eta": d.format_eta,
+ "bleft": d.bleft,
+ "size": d.size,
+ "format_size": d.format_size,
+ "percent": d.percent,
+ "status": d.status,
+ "statusmsg": d.statusmsg,
+ "format_wait": d.format_wait,
+ "wait_until": d.wait_until
+ }
+ child.data["downloading"] = dd
+ k = pack.getChildKey(d.id)
self.emit(SIGNAL("dataChanged(const QModelIndex &, const QModelIndex &)"), self.index(k, 0, self.index(p, 0)), self.index(k, self.cols, self.index(p, self.cols)))
self.updateCount()
@@ -222,7 +247,7 @@ class QueueModel(CollectorModel):
if speed is None or status == 7 or status == 10 or status == 5:
return QVariant(self.translateStatus(statusMapReverse[status]))
else:
- return QVariant("%s (%s KiB/s)" % (self.translateStatus(statusMapReverse[status]), speed))
+ return QVariant("%s (%s)" % (self.translateStatus(statusMapReverse[status]), formatSpeed(speed)))
elif index.column() == 3:
item = index.internalPointer()
if isinstance(item, Package):
diff --git a/module/gui/SettingsWidget.py b/module/gui/SettingsWidget.py
index cdb5fba93..7218cc570 100644
--- a/module/gui/SettingsWidget.py
+++ b/module/gui/SettingsWidget.py
@@ -20,6 +20,8 @@ from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sip import delete
+from module.remote.thriftbackend.thriftgen.pyload.ttypes import *
+
class SettingsWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
@@ -35,8 +37,8 @@ class SettingsWidget(QWidget):
def loadConfig(self):
if self.sections and self.psections:
- self.data = self.connector.proxy.get_config()
- self.pdata = self.connector.proxy.get_plugin_config()
+ self.data = self.connector.getConfig()
+ self.pdata = self.connector.getPluginConfig()
self.reloadSection(self.sections, self.data)
self.reloadSection(self.psections, self.pdata)
@@ -75,13 +77,13 @@ class SettingsWidget(QWidget):
layout.addWidget(tab)
- self.data = self.connector.proxy.get_config()
- self.pdata = self.connector.proxy.get_plugin_config()
- for k, section in self.data.items():
+ self.data = self.connector.getConfig()
+ self.pdata = self.connector.getPluginConfig()
+ for k, section in enumerate(self.data):
s = Section(section, general)
self.sections[k] = s
- for k, section in self.pdata.items():
+ for k, section in enumerate(self.pdata):
s = Section(section, plugins, "plugin")
self.psections[k] = s
@@ -104,59 +106,59 @@ class SettingsWidget(QWidget):
def reloadSection(self, sections, pdata):
- for k, section in pdata.iteritems():
+ for k, section in enumerate(pdata):
if sections.has_key(k):
widget = sections[k]
- for option,data in section.iteritems():
- if widget.inputs.has_key(option):
- i = widget.inputs[option]
-
- if data["type"] == "int":
- i.setValue(int(data["value"]))
- elif not data["type"].find(";") == -1:
- i.setCurrentIndex(i.findText(data["value"]))
- elif data["type"] == "bool":
- if data["value"]:
+ for item in section.items:
+ if widget.inputs.has_key(item.name):
+ i = widget.inputs[item.name]
+
+ if item.type == "int":
+ i.setValue(int(item.value))
+ elif not item.type.find(";") == -1:
+ i.setCurrentIndex(i.findText(item.value))
+ elif item.type == "bool":
+ if (True if item.value.lower() in ("1","true", "on", "an","yes") else False):
i.setCurrentIndex(0)
else:
i.setCurrentIndex(1)
else:
- i.setText(data["value"])
+ i.setText(item.value)
def saveConfig(self):
- self.data = self.connector.proxy.get_config()
- self.pdata = self.connector.proxy.get_plugin_config()
+ self.data = self.connector.getConfig()
+ self.pdata = self.connector.getPluginConfig()
self.saveSection(self.sections, self.data)
self.saveSection(self.psections, self.pdata, "plugin")
def saveSection(self, sections, pdata, sec="core"):
- for k, section in pdata.iteritems():
+ for k, section in enumerate(pdata):
if sections.has_key(k):
widget = sections[k]
- for option,data in section.iteritems():
- if widget.inputs.has_key(option):
- i = widget.inputs[option]
-
- if data["type"] == "int":
- if i.value() != data["value"]:
- self.connector.proxy.set_conf_val(k, option, i.value(), sec)
- elif not data["type"].find(";") == -1:
- if i.currentText() != data["value"]:
- self.connector.proxy.set_conf_val(k, option, i.currentText(), sec)
- elif data["type"] == "bool":
- if (data["value"] ^ (not i.currentIndex())):
- self.connector.proxy.set_conf_val(k, option, not i.currentIndex(), sec)
+ for item in section.items:
+ if widget.inputs.has_key(item.name):
+ i = widget.inputs[item.name]
+
+ if item.type == "int":
+ if i.value() != int(item.value):
+ self.connector.setConfigValue(k, option, i.value(), sec)
+ elif not item.type.find(";") == -1:
+ if i.currentText() != item.value:
+ self.connector.setConfigValue(k, option, i.currentText(), sec)
+ elif item.type == "bool":
+ if ((True if item.value.lower() in ("1","true", "on", "an","yes") else False) ^ (not i.currentIndex())):
+ self.connector.setConfigValue(k, option, not i.currentIndex(), sec)
else:
- if i.text() != data["value"]:
- self.connector.proxy.set_conf_val(k, option, str(i.text()), sec)
+ if i.text() != item.value:
+ self.connector.setConfigValue(k, option, str(i.text()), sec)
class Section(QGroupBox):
def __init__(self, data, parent, ctype="core"):
self.data = data
- QGroupBox.__init__(self, data["desc"], parent)
+ QGroupBox.__init__(self, data.description, parent)
self.labels = {}
self.inputs = {}
self.ctype = ctype
@@ -172,30 +174,28 @@ class Section(QGroupBox):
sa.setWidget(sw)
sa.setFrameShape(sa.NoFrame)
- parent.addTab(sa, data["desc"])
+ parent.addTab(sa, data.description)
- for k, option in self.data.iteritems():
- if k == "desc":
- continue
- if option["type"] == "int":
+ for option in self.data.items:
+ if option.type == "int":
i = QSpinBox(self)
i.setMaximum(999999)
- i.setValue(int(option["value"]))
- elif not option["type"].find(";") == -1:
- choices = option["type"].split(";")
+ i.setValue(int(option.value))
+ elif not option.type.find(";") == -1:
+ choices = option.type.split(";")
i = QComboBox(self)
i.addItems(choices)
- i.setCurrentIndex(i.findText(option["value"]))
- elif option["type"] == "bool":
+ i.setCurrentIndex(i.findText(option.value))
+ elif option.type == "bool":
i = QComboBox(self)
i.addItem(_("Yes"), QVariant(True))
i.addItem(_("No"), QVariant(False))
- if option["value"]:
+ if (True if option.value.lower() in ("1","true", "on", "an","yes") else False):
i.setCurrentIndex(0)
else:
i.setCurrentIndex(1)
else:
i = QLineEdit(self)
- i.setText(option["value"])
- layout.addRow(option["desc"], i)
+ i.setText(option.value)
+ layout.addRow(option.description, i)
layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
diff --git a/module/gui/connector.py b/module/gui/connector.py
index 907475726..a9cb0610c 100644
--- a/module/gui/connector.py
+++ b/module/gui/connector.py
@@ -24,269 +24,77 @@ from uuid import uuid4 as uuid
from PyQt4.QtCore import *
from PyQt4.QtGui import *
-from xmlrpclib import ServerProxy
import socket
-class Connector(QThread):
+from module.remote.thriftbackend.thriftgen.pyload import Pyload
+from module.remote.thriftbackend.thriftgen.pyload.ttypes import *
+from module.remote.thriftbackend.Socket import Socket
+from module.remote.thriftbackend.Protocol import Protocol
+
+from thrift import Thrift
+from thrift.transport import TTransport
+
+class Connector(QObject):
def __init__(self):
- QThread.__init__(self)
+ QObject.__init__(self)
self.mutex = QMutex()
- self.addr = None
- self.errorQueue = []
self.connectionID = None
+ self.host = None
+ self.port = None
+ self.user = None
+ self.password = None
+ self.ssl = None
self.running = True
self.proxy = self.Dummy()
- def setAddr(self, addr):
- """
- set new address
- """
- self.mutex.lock()
- self.addr = addr
- self.mutex.unlock()
+ def setConnectionData(self, host, port, user, password, ssl=False):
+ self.host = host
+ self.port = port
+ self.user = user
+ self.password = password
+ self.ssl = ssl
def connectProxy(self):
- if isinstance(self.addr, tuple):
- while not hasattr(self.addr[1], "server_methods"):
- sleep(1)
-
- self.proxy = self.addr[1].server_methods
- else:
- self.proxy = DispatchRPC(self.mutex, ServerProxy(self.addr, allow_none=True, verbose=False))
+ transport = Socket(self.host, self.port, self.ssl)
+ transport = TTransport.TBufferedTransport(transport)
+ protocol = Protocol(transport)
+ client = Pyload.Client(protocol)
- self.connect(self.proxy, SIGNAL("proxy_error"), self._proxyError)
- self.connect(self.proxy, SIGNAL("connectionLost"), self, SIGNAL("connectionLost"))
+ transport.open()
- try:
- server_version = self.proxy.get_server_version()
- self.connectionID = uuid().hex
- except:
+ if not client.login(self.user, self.password):
+ self.emit(SIGNAL("error_box"), "bad login credentials")
return False
- if not server_version:
- return False
- elif not server_version == SERVER_VERSION:
+
+ self.proxy = DispatchRPC(self.mutex, client)
+ self.connect(self.proxy, SIGNAL("proxy_error"), self._proxyError)
+ self.connect(self.proxy, SIGNAL("connectionLost"), self, SIGNAL("connectionLost"))
+
+ server_version = self.proxy.getServerVersion()
+ self.connectionID = uuid().hex
+
+ if not server_version == SERVER_VERSION:
self.emit(SIGNAL("error_box"), "server is version %s client accepts version %s" % (server_version, SERVER_VERSION))
return False
+
return True
- def canConnect(self):
- return self.connectProxy()
-
def _proxyError(self, func, e):
"""
formats proxy error msg
"""
msg = "proxy error in '%s':\n%s" % (func, e)
- self.errorQueue.append(msg)
+ print msg
+ self.emit(SIGNAL("error_box"), msg)
- def getError(self):
- self.mutex.lock()
- if len(self.errorQueue) > 0:
- err = self.errorQueue.pop()
- print err
- self.emit(SIGNAL("error_box"), err)
- self.mutex.unlock()
-
- def stop(self):
- """
- stop thread
- """
- self.running = False
-
- def run(self):
- """
- start thread
- (called from thread.start())
- """
- self.canConnect()
- while self.running:
- sleep(1)
- self.getError()
+ def __getattr__(self, attr):
+ return getattr(self.proxy, attr)
class Dummy(object):
def __getattr__(self, attr):
def dummy(*args, **kwargs):
return None
return dummy
-
- def getPackageCollector(self):
- """
- grab packages from collector and return the data
- """
- return self.proxy.get_collector()
-
- def getLinkInfo(self, id):
- """
- grab file info for the given id and return it
- """
- w = self.proxy.get_file_data
- w.error = False
- info = w(id)
- if not info: return None
- info["downloading"] = None
- return info
-
- def getPackageInfo(self, id):
- """
- grab package info for the given id and return it
- """
- w = self.proxy.get_package_data
- w.error = False
- return w(id)
-
- def getPackageQueue(self):
- """
- grab queue return the data
- """
- return self.proxy.get_queue()
-
- def getPackageFiles(self, id):
- """
- grab package files and return ids
- """
- return self.proxy.get_package_files(id)
-
- def getDownloadQueue(self):
- """
- grab files that are currently downloading and return info
- """
- return self.proxy.status_downloads()
-
- def getServerStatus(self):
- """
- return server status
- """
- return self.proxy.status_server()
-
- def addURLs(self, links):
- """
- add links to collector
- """
- self.proxy.add_urls(links)
-
- def togglePause(self):
- """
- toogle pause
- """
- return self.proxy.toggle_pause()
-
- def setPause(self, pause):
- """
- set pause
- """
- if pause:
- self.proxy.pause_server()
- else:
- self.proxy.unpause_server()
-
- def newPackage(self, name):
- """
- create a new package and return id
- """
- return self.proxy.new_package(name)
-
- def addFileToPackage(self, fileid, packid):
- """
- add a file from collector to package
- """
- self.proxy.move_file_2_package(fileid, packid)
-
- def pushPackageToQueue(self, packid):
- """
- push a package to queue
- """
- self.proxy.push_package_2_queue(packid)
-
- def restartPackage(self, packid):
- """
- restart a package
- """
- self.proxy.restart_package(packid)
-
- def restartFile(self, fileid):
- """
- restart a file
- """
- self.proxy.restart_file(fileid)
-
- def removePackage(self, packid):
- """
- remove a package
- """
- self.proxy.del_packages([packid,])
-
- def removeFile(self, fileid):
- """
- remove a file
- """
- self.proxy.del_links([fileid,])
-
- def uploadContainer(self, filename, type, content):
- """
- upload a container
- """
- self.proxy.upload_container(filename, type, content)
-
- def getLog(self, offset):
- """
- get log
- """
- return self.proxy.get_log(offset)
-
- def stopAllDownloads(self):
- """
- get log
- """
- self.proxy.pause_server()
- self.proxy.stop_downloads()
-
- def updateAvailable(self):
- """
- update available
- """
- return self.proxy.update_available()
-
- def setPackageName(self, pid, name):
- """
- set new package name
- """
- return self.proxy.set_package_name(pid, name)
-
- def pullOutPackage(self, pid):
- """
- pull out package
- """
- return self.proxy.pull_out_package(pid)
-
- def captchaWaiting(self):
- """
- is the a captcha waiting?
- """
- return self.proxy.is_captcha_waiting()
-
- def getCaptcha(self):
- """
- get captcha
- """
- return self.proxy.get_captcha_task()
-
- def setCaptchaResult(self, cid, result):
- """
- get captcha
- """
- return self.proxy.set_captcha_result(cid, result)
-
- def getCaptchaStatus(self, cid):
- """
- get captcha status
- """
- return self.proxy.get_task_status(cid)
-
- def getEvents(self):
- """
- get events
- """
- return self.proxy.get_events(self.connectionID)
class DispatchRPC(QObject):
def __init__(self, mutex, server):