コード例 #1
0
    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
コード例 #2
0
    def getAllLinks(self, q):
        """return information about all links in queue q

        q0 queue
        q1 collector

        format:

        {
            id: {'name': name, ... 'package': id }, ...
        }

        """
        # Inner import to have _ function in builtins
        # TODO: Remove _ from builtins
        from module.util.constants import FILE_STATUS_MESSAGES

        self.c.execute('SELECT l.id,l.url,l.name,l.size,l.status,l.error,l.plugin,l.package,l.linkorder FROM links as l INNER JOIN packages as p ON l.package=p.id WHERE p.queue=? ORDER BY l.linkorder', (q,))
        data = {}
        for r in self.c:
            data[r[0]] = {
                'id': r[0],
                'url': r[1],
                'name': r[2],
                'size': r[3],
                'format_size': formatSize(r[3]),
                'status': r[4],
                'statusmsg': FILE_STATUS_MESSAGES[r[4]],
                'error': r[5],
                'plugin': r[6],
                'package': r[7],
                'order': r[8],
            }

        return data
コード例 #3
0
ファイル: IRCInterface.py プロジェクト: fener06/pyload
    def event_status(self, args):
        downloads = self.api.statusDownloads()
        if not downloads:
            return ["INFO: There are no active downloads currently."]
            
        temp_progress = ""
        lines = ["ID - Name - Status - Speed - ETA - Progress"]
        for data in downloads:

            if data.status == 5:
                temp_progress = data.format_wait
            else:
                temp_progress = "%d%% (%s)" % (data.percent, data.format_size)

            lines.append("#%d - %s - %s - %s - %s - %s" %
                     (
                     data.fid,
                     data.name,
                     data.statusmsg,
                     "%s/s" % formatSize(data.speed),
                     "%s" % data.format_eta,
                     temp_progress
                     )
                     )
        return lines
コード例 #4
0
ファイル: FileDatabase.py プロジェクト: EikeKre/pyload
    def getAllLinks(self, q):
        """return information about all links in queue q

        q0 queue
        q1 collector

        format:

        {
            id: {'name': name, ... 'package': id }, ...
        }

        """
        self.c.execute('SELECT l.id,l.url,l.name,l.size,l.status,l.error,l.plugin,l.package,l.linkorder FROM links as l INNER JOIN packages as p ON l.package=p.id WHERE p.queue=? ORDER BY l.linkorder', (q,))
        data = {}
        for r in self.c:
            data[r[0]] = {
                'id': r[0],
                'url': r[1],
                'name': r[2],
                'size': r[3],
                'format_size': formatSize(r[3]),
                'status': r[4],
                'statusmsg': self.manager.statusMsg[r[4]],
                'error': r[5],
                'plugin': r[6],
                'package': r[7],
                'order': r[8],
            }

        return data
コード例 #5
0
    def getLinkData(self, link_id):
        """get link information as dict"""
        link = Link.get_or_none(Link.id == link_id)

        if not link:
            return None

        # Inner import to have _ function in builtins
        # TODO: Remove _ from builtins
        from module.util.constants import FILE_STATUS_MESSAGES

        return {
            link.id: {
                'id': link.id,
                'url': link.url,
                'name': link.name,
                'size': link.size,
                'format_size': formatSize(link.size),
                'status': link.status,
                'statusmsg': FILE_STATUS_MESSAGES[link.status],
                'error': link.error,
                'plugin': link.plugin,
                'package': link.package_id,
                'order': link.linkorder,
            }
        }
コード例 #6
0
    def getPackageData(self, id):
        """get data about links for a package"""
        # Inner import to have _ function in builtins
        # TODO: Remove _ from builtins
        from module.util.constants import FILE_STATUS_MESSAGES

        self.c.execute('SELECT id,url,name,size,status,error,plugin,package,linkorder FROM links WHERE package=? ORDER BY linkorder', (str(id), ))

        data = {}
        for r in self.c:
            data[r[0]] = {
                'id': r[0],
                'url': r[1],
                'name': r[2],
                'size': r[3],
                'format_size': formatSize(r[3]),
                'status': r[4],
                'statusmsg': FILE_STATUS_MESSAGES[r[4]],
                'error': r[5],
                'plugin': r[6],
                'package': r[7],
                'order': r[8],
            }

        return data
コード例 #7
0
    def getAllLinks(self, q):
        """return information about all links in queue q

        q0 queue
        q1 collector

        format:

        {
            id: {'name': name, ... 'package': id }, ...
        }

        """
        self.c.execute(
            'SELECT l.id, l.url, l.name, l.size, l.status, l.error, l.plugin, l.package, l.linkorder FROM links as l INNER JOIN packages as p ON l.package=p.id WHERE p.queue=? ORDER BY l.linkorder',
            (q, ))
        data = {}
        for r in self.c:
            data[r[0]] = {
                'id': r[0],
                'url': r[1],
                'name': r[2],
                'size': r[3],
                'format_size': formatSize(r[3]),
                'status': r[4],
                'statusmsg': self.manager.statusMsg[r[4]],
                'error': r[5],
                'plugin': r[6],
                'package': r[7],
                'order': r[8],
            }

        return data
コード例 #8
0
ファイル: pyload-cli.py プロジェクト: 4Christopher/pyload
    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
コード例 #9
0
ファイル: Collector.py プロジェクト: Zerknechterer/pyload
 def data(self, index, role=Qt.DisplayRole):
     """
         return cell data
     """
     if not index.isValid():
         return QVariant()
     if role == Qt.DisplayRole:
         if index.column() == 0:
             return QVariant(index.internalPointer().data["name"])
         elif index.column() == 1:
             item = index.internalPointer()
             plugins = []
             if isinstance(item, Package):
                 for child in item.children:
                     if not child.data["plugin"] in plugins:
                         plugins.append(child.data["plugin"])
             else:
                 plugins.append(item.data["plugin"])
             return QVariant(", ".join(plugins))
         elif index.column() == 2:
             item = index.internalPointer()
             status = 0
             if isinstance(item, Package):
                 for child in item.children:
                     if child.data["status"] > status:
                         status = child.data["status"]
             else:
                 status = item.data["status"]
             return QVariant(self.translateStatus(statusMapReverse[status]))
         elif index.column() == 3:
             item = index.internalPointer()
             if isinstance(item, Link):
                 return QVariant(formatSize(item.data["size"]))
             else:
                 ms = 0
                 for c in item.children:
                     ms += c.data["size"]
                 return QVariant(formatSize(ms))
     elif role == Qt.EditRole:
         if index.column() == 0:
             return QVariant(index.internalPointer().data["name"])
     return QVariant()
コード例 #10
0
ファイル: Collector.py プロジェクト: EikeKre/pyload
 def data(self, index, role=Qt.DisplayRole):
     """
         return cell data
     """
     if not index.isValid():
         return QVariant()
     if role == Qt.DisplayRole:
         if index.column() == 0:
             return QVariant(index.internalPointer().data["name"])
         elif index.column() == 1:
             item = index.internalPointer()
             plugins = []
             if isinstance(item, Package):
                 for child in item.children:
                     if not child.data["plugin"] in plugins:
                         plugins.append(child.data["plugin"])
             else:
                 plugins.append(item.data["plugin"])
             return QVariant(", ".join(plugins))
         elif index.column() == 2:
             item = index.internalPointer()
             status = 0
             if isinstance(item, Package):
                 for child in item.children:
                     if child.data["status"] > status:
                         status = child.data["status"]
             else:
                 status = item.data["status"]
             return QVariant(self.translateStatus(statusMapReverse[status]))
         elif index.column() == 3:
             item = index.internalPointer()
             if isinstance(item, Link):
                 return QVariant(formatSize(item.data["size"]))
             else:
                 ms = 0
                 for c in item.children:
                     ms += c.data["size"]
                 return QVariant(formatSize(ms))
     elif role == Qt.EditRole:
         if index.column() == 0:
             return QVariant(index.internalPointer().data["name"])
     return QVariant()
コード例 #11
0
def config():
    conf = PYLOAD.getConfig()
    plugin = PYLOAD.getPluginConfig()

    conf_menu = []
    plugin_menu = []

    for entry in sorted(conf.keys()):
        conf_menu.append((entry, conf[entry].description))

    for entry in sorted(plugin.keys()):
        plugin_menu.append((entry, plugin[entry].description))

    accs = PYLOAD.getAccounts(False)

    for data in accs:
        if data.trafficleft == -1:
            data.trafficleft = _("unlimited")
        elif not data.trafficleft:
            data.trafficleft = _("not available")
        else:
            data.trafficleft = formatSize(data.trafficleft * 1024)

        if data.validuntil == -1:
            data.validuntil = _("unlimited")
        elif not data.validuntil:
            data.validuntil = _("not available")
        else:
            t = time.localtime(data.validuntil)
            data.validuntil = time.strftime("%d.%m.%Y", t)

        if "time" in data.options:
            try:
                data.options["time"] = data.options["time"][0]
            except:
                data.options["time"] = "0:00-0:00"

        if "limitDL" in data.options:
            data.options["limitdl"] = data.options["limitDL"][0]
        else:
            data.options["limitdl"] = "0"

    return render_to_response(
        'settings.html',
        {
            'conf': {
                'plugin': plugin_menu,
                'general': conf_menu,
                'accs': accs,
            },
            'types': PYLOAD.getAccountTypes(),
        },
        [pre_processor],
    )
コード例 #12
0
 def refreshServerStatus(self):
     """
         refresh server status and overall speed in the status bar
     """
     s = self.connector.statusServer()
     if s.pause:
         self.mainWindow.status.setText(_("paused"))
     else:
         self.mainWindow.status.setText(_("running"))
     self.mainWindow.speed.setText(formatSpeed(s.speed))
     self.mainWindow.space.setText(formatSize(self.serverStatus["freespace"]))
     self.mainWindow.actions["toggle_status"].setChecked(not s.pause)
コード例 #13
0
ファイル: pyload-cli.py プロジェクト: 4Christopher/pyload
    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
コード例 #14
0
    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
コード例 #15
0
ファイル: pyload.py プロジェクト: FedeG/pyload
def info():
    conf = PYLOAD.getConfigDict()
    extra = os.uname() if hasattr(os, "uname") else tuple()

    data = {"python": sys.version,
            "os": " ".join((os.name, sys.platform) + extra),
            "version": PYLOAD.getServerVersion(),
            "folder": abspath(PYLOAD_DIR), "config": abspath(""),
            "download": abspath(conf["general"]["download_folder"]["value"]),
            "freespace": formatSize(PYLOAD.freeSpace()),
            "remote": conf["remote"]["port"]["value"],
            "webif": conf["webinterface"]["port"]["value"],
            "language": conf["general"]["language"]["value"]}

    return render_to_response("info.html", data, [pre_processor])
コード例 #16
0
ファイル: pyload.py プロジェクト: B1GPY/pyload
def config():
    conf = PYLOAD.getConfig()
    plugin = PYLOAD.getPluginConfig()

    conf_menu = []
    plugin_menu = []

    for entry in sorted(conf.keys()):
        conf_menu.append((entry, conf[entry].description))

    for entry in sorted(plugin.keys()):
        plugin_menu.append((entry, plugin[entry].description))

    accs = PYLOAD.getAccounts(False)

    for data in accs:
        if data.trafficleft == -1:
            data.trafficleft = _("unlimited")
        elif not data.trafficleft:
            data.trafficleft = _("not available")
        else:
            data.trafficleft = formatSize(data.trafficleft * 1024)

        if data.validuntil == -1:
            data.validuntil = _("unlimited")
        elif not data.validuntil:
            data.validuntil = _("not available")
        else:
            t = time.localtime(data.validuntil)
            data.validuntil = time.strftime("%d.%m.%Y - %H:%M:%S", t)

        try:
            data.options["time"] = data.options["time"][0]
        except:
            data.options["time"] = "0:00-0:00"

        if "limitDL" in data.options:
            data.options["limitdl"] = data.options["limitDL"][0]
        else:
            data.options["limitdl"] = "0"

    return render_to_response(
        "settings.html",
        {"conf": {"plugin": plugin_menu, "general": conf_menu, "accs": accs}, "types": PYLOAD.getAccountTypes()},
        [pre_processor],
    )
コード例 #17
0
 def loadAccountInfo(self, req):
     req.load("http://oron.com/?op=change_lang&lang=german")
     src = req.load("http://oron.com/?op=my_account").replace("\n", "")
     validuntil = re.search(r"<td>Premiumaccount läuft bis:</td>\s*<td>(.*?)</td>", src)
     if validuntil:
         validuntil = validuntil.group(1)
         validuntil = int(mktime(strptime(validuntil, "%d %B %Y")))
         trafficleft = re.search(r'<td>Download Traffic verfügbar:</td>\s*<td>(.*?)</td>', src).group(1)
         self.logDebug("Oron left: " + formatSize(parseFileSize(trafficleft)))
         trafficleft = int(self.parseTraffic(trafficleft))
         premium = True
     else:
         validuntil = -1
         trafficleft = None
         premium = False
     tmp = {"validuntil": validuntil, "trafficleft": trafficleft, "premium" : premium}
     return tmp
コード例 #18
0
ファイル: IRCInterface.py プロジェクト: zaratozom/pyload
    def event_status(self, args):
        downloads = self.api.statusDownloads()
        if not downloads:
            return ["INFO: There are no active downloads currently."]

        temp_progress = ""
        lines = ["ID - Name - Status - Speed - ETA - Progress"]
        for data in downloads:

            if data.status == 5:
                temp_progress = data.format_wait
            else:
                temp_progress = "%d%% (%s)" % (data.percent, data.format_size)

            lines.append("#%d - %s - %s - %s - %s - %s" %
                         (data.fid, data.name, data.statusmsg,
                          "%s/s" % formatSize(data.speed),
                          "%s" % data.format_eta, temp_progress))
        return lines
コード例 #19
0
ファイル: pyload_app.py プロジェクト: Zerknechterer/pyload
def info():
    conf = PYLOAD.getConfigDict()

    if hasattr(os, "uname"):
        extra = os.uname()
    else:
        extra = tuple()

    data = {"python": sys.version,
            "os": " ".join((os.name, sys.platform) + extra),
            "version": PYLOAD.getServerVersion(),
            "folder": abspath(PYLOAD_DIR), "config": abspath(""),
            "download": abspath(conf["general"]["download_folder"]["value"]),
            "freespace": formatSize(PYLOAD.freeSpace()),
            "remote": conf["remote"]["port"]["value"],
            "webif": conf["webinterface"]["port"]["value"],
            "language": conf["general"]["language"]["value"]}

    return render_to_response("info.html", data, [pre_processor])
コード例 #20
0
ファイル: FileDatabase.py プロジェクト: EikeKre/pyload
    def getPackageData(self, id):
        """get data about links for a package"""
        self.c.execute('SELECT id,url,name,size,status,error,plugin,package,linkorder FROM links WHERE package=? ORDER BY linkorder', (str(id), ))

        data = {}
        for r in self.c:
            data[r[0]] = {
                'id': r[0],
                'url': r[1],
                'name': r[2],
                'size': r[3],
                'format_size': formatSize(r[3]),
                'status': r[4],
                'statusmsg': self.manager.statusMsg[r[4]],
                'error': r[5],
                'plugin': r[6],
                'package': r[7],
                'order': r[8],
            }

        return data
コード例 #21
0
ファイル: FileDatabase.py プロジェクト: EikeKre/pyload
    def getLinkData(self, id):
        """get link information as dict"""
        self.c.execute('SELECT id,url,name,size,status,error,plugin,package,linkorder FROM links WHERE id=?', (str(id), ))
        data = {}
        r = self.c.fetchone()
        if not r:
            return None
        data[r[0]] = {
            'id': r[0],
            'url': r[1],
            'name': r[2],
            'size': r[3],
            'format_size': formatSize(r[3]),
            'status': r[4],
            'statusmsg': self.manager.statusMsg[r[4]],
            'error': r[5],
            'plugin': r[6],
            'package': r[7],
            'order': r[8],
        }

        return data
コード例 #22
0
def links():
    try:
        links = [toDict(x) for x in PYLOAD.statusDownloads()]
        ids = []
        for link in links:
            ids.append(link['fid'])

            if link['status'] == 12:
                link['info'] = "%s @ %s/s" % (link['format_eta'], formatSize(link['speed']))
            elif link['status'] == 5:
                link['percent'] = 0
                link['size'] = 0
                link['bleft'] = 0
                link['info'] = _("waiting %s") % link['format_wait']
            else:
                link['info'] = ""

        data = {'links': links, 'ids': ids}
        return data
    except Exception, e:
        print_exc()
        return HTTPError()
コード例 #23
0
    def getPackageData(self, id):
        """get data about links for a package"""
        self.c.execute(
            'SELECT id, url, name, size, status, error, plugin, package, linkorder FROM links WHERE package=? ORDER BY linkorder',
            (str(id), ))

        data = {}
        for r in self.c:
            data[r[0]] = {
                'id': r[0],
                'url': r[1],
                'name': r[2],
                'size': r[3],
                'format_size': formatSize(r[3]),
                'status': r[4],
                'statusmsg': self.manager.statusMsg[r[4]],
                'error': r[5],
                'plugin': r[6],
                'package': r[7],
                'order': r[8],
            }

        return data
コード例 #24
0
    def getLinkData(self, id):
        """get link information as dict"""
        self.c.execute(
            'SELECT id, url, name, size, status, error, plugin, package, linkorder FROM links WHERE id=?',
            (str(id), ))
        data = {}
        r = self.c.fetchone()
        if not r:
            return None
        data[r[0]] = {
            'id': r[0],
            'url': r[1],
            'name': r[2],
            'size': r[3],
            'format_size': formatSize(r[3]),
            'status': r[4],
            'statusmsg': self.manager.statusMsg[r[4]],
            'error': r[5],
            'plugin': r[6],
            'package': r[7],
            'order': r[8],
        }

        return data
コード例 #25
0
ファイル: Overview.py プロジェクト: Zerknechterer/pyload
    def paint(self, painter, option, index):
        option.rect.setHeight(59 + 16)
        option.rect.setWidth(self.parent.width() - 20)

        #if option.state & QStyle.State_Selected:
        #    painter.fillRect(option.rect, option.palette.color(QPalette.Highlight))

        packagename = index.data(OverviewModel.PackageName).toString()
        partsf = index.data(OverviewModel.PartsFinished).toString()
        parts = index.data(OverviewModel.Parts).toString()
        eta = int(index.data(OverviewModel.ETA).toString())
        speed = index.data(OverviewModel.Speed).toString() or 0
        progress = int(index.data(OverviewModel.Progress).toString())
        currentSize = int(index.data(OverviewModel.CurrentSize).toString())
        maxSize = int(index.data(OverviewModel.MaxSize).toString())
        status = index.data(OverviewModel.Status).toString()

        def formatEta(seconds):  #TODO add to utils
            if seconds <= 0: return ""
            hours, seconds = divmod(seconds, 3600)
            minutes, seconds = divmod(seconds, 60)
            return _("ETA: ") + "%.2i:%.2i:%.2i" % (hours, minutes, seconds)

        statusline = QString(_("Parts: ") + "%s/%s" % (partsf, parts))
        if partsf == parts:
            speedline = _("Finished")
        elif not status == _("Downloading"):
            speedline = QString(status)
        else:
            speedline = QString(
                formatEta(eta) + "     " + _("Speed: %s") % formatSpeed(speed))

        if progress in (0, 100):
            sizeline = QString(_("Size:") + "%s" % formatSize(maxSize))
        else:
            sizeline = QString(
                _("Size:") + "%s / %s" %
                (formatSize(currentSize), formatSize(maxSize)))

        f = painter.font()
        f.setPointSize(12)
        f.setBold(True)
        painter.setFont(f)

        r = option.rect.adjusted(4, 4, -4, -4)
        painter.drawText(r.left(), r.top(), r.width(), r.height(),
                         Qt.AlignTop | Qt.AlignLeft, packagename)
        newr = painter.boundingRect(r.left(), r.top(), r.width(), r.height(),
                                    Qt.AlignTop | Qt.AlignLeft, packagename)

        f.setPointSize(10)
        f.setBold(False)
        painter.setFont(f)

        painter.drawText(r.left(),
                         newr.bottom() + 5, r.width(), r.height(),
                         Qt.AlignTop | Qt.AlignLeft, statusline)
        painter.drawText(r.left(),
                         newr.bottom() + 5, r.width(), r.height(),
                         Qt.AlignTop | Qt.AlignHCenter, sizeline)
        painter.drawText(r.left(),
                         newr.bottom() + 5, r.width(), r.height(),
                         Qt.AlignTop | Qt.AlignRight, speedline)
        newr = painter.boundingRect(r.left(),
                                    newr.bottom() + 2, r.width(), r.height(),
                                    Qt.AlignTop | Qt.AlignLeft, statusline)
        newr.setTop(newr.bottom() + 8)
        newr.setBottom(newr.top() + 20)
        newr.setRight(self.parent.width() - 25)

        f.setPointSize(10)
        painter.setFont(f)

        opts = QStyleOptionProgressBarV2()
        opts.maximum = 100
        opts.minimum = 0
        opts.progress = progress
        opts.rect = newr
        opts.textVisible = True
        opts.textAlignment = Qt.AlignCenter
        opts.text = QString.number(opts.progress) + "%"
        QApplication.style().drawControl(QStyle.CE_ProgressBar, opts, painter)
コード例 #26
0
 def formatSize(self):
     """ formats size to readable format """
     return formatSize(self.getSize())
コード例 #27
0
ファイル: Overview.py プロジェクト: EikeKre/pyload
 def paint(self, painter, option, index):
     option.rect.setHeight(59+16)
     option.rect.setWidth(self.parent.width()-20)
     
     #if option.state & QStyle.State_Selected:
     #    painter.fillRect(option.rect, option.palette.color(QPalette.Highlight))
     
     packagename = index.data(OverviewModel.PackageName).toString()
     partsf = index.data(OverviewModel.PartsFinished).toString()
     parts = index.data(OverviewModel.Parts).toString()
     eta = int(index.data(OverviewModel.ETA).toString())
     speed = index.data(OverviewModel.Speed).toString() or 0
     progress = int(index.data(OverviewModel.Progress).toString())
     currentSize = int(index.data(OverviewModel.CurrentSize).toString())
     maxSize = int(index.data(OverviewModel.MaxSize).toString())
     status = index.data(OverviewModel.Status).toString()
     
     def formatEta(seconds): #TODO add to utils
         if seconds <= 0: return ""
         hours, seconds = divmod(seconds, 3600)
         minutes, seconds = divmod(seconds, 60)
         return _("ETA: ") + "%.2i:%.2i:%.2i" % (hours, minutes, seconds)
     
     statusline = QString(_("Parts: ") + "%s/%s" % (partsf, parts))
     if partsf == parts:
         speedline = _("Finished")
     elif not status == _("Downloading"):
         speedline = QString(status)
     else:
         speedline = QString(formatEta(eta) + "     " + _("Speed: %s") % formatSpeed(speed))
     
     if progress in (0,100):
         sizeline = QString(_("Size:") + "%s" % formatSize(maxSize))
     else:
         sizeline = QString(_("Size:") + "%s / %s" % (formatSize(currentSize), formatSize(maxSize)))
     
     f = painter.font()
     f.setPointSize(12)
     f.setBold(True)
     painter.setFont(f)
     
     r = option.rect.adjusted(4, 4, -4, -4)
     painter.drawText(r.left(), r.top(), r.width(), r.height(), Qt.AlignTop | Qt.AlignLeft, packagename)
     newr = painter.boundingRect(r.left(), r.top(), r.width(), r.height(), Qt.AlignTop | Qt.AlignLeft, packagename)
     
     f.setPointSize(10)
     f.setBold(False)
     painter.setFont(f)
     
     painter.drawText(r.left(), newr.bottom()+5, r.width(), r.height(), Qt.AlignTop | Qt.AlignLeft, statusline)
     painter.drawText(r.left(), newr.bottom()+5, r.width(), r.height(), Qt.AlignTop | Qt.AlignHCenter, sizeline)
     painter.drawText(r.left(), newr.bottom()+5, r.width(), r.height(), Qt.AlignTop | Qt.AlignRight, speedline)
     newr = painter.boundingRect(r.left(), newr.bottom()+2, r.width(), r.height(), Qt.AlignTop | Qt.AlignLeft, statusline)
     newr.setTop(newr.bottom()+8)
     newr.setBottom(newr.top()+20)
     newr.setRight(self.parent.width()-25)
     
     f.setPointSize(10)
     painter.setFont(f)
     
     opts = QStyleOptionProgressBarV2()
     opts.maximum = 100
     opts.minimum = 0
     opts.progress = progress
     opts.rect = newr
     opts.textVisible = True
     opts.textAlignment = Qt.AlignCenter
     opts.text = QString.number(opts.progress) + "%"
     QApplication.style().drawControl(QStyle.CE_ProgressBar, opts, painter)
コード例 #28
0
    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

            f = open(join(owd, path), "rb")
            content = f.read()
            f.close()

            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()
コード例 #29
0
ファイル: Queue.py プロジェクト: EikeKre/pyload
    def data(self, index, role=Qt.DisplayRole):
        """
            return cell data
        """
        if not index.isValid():
            return QVariant()
        if role == Qt.DisplayRole:
            if index.column() == 0:
                return QVariant(index.internalPointer().data["name"])
            elif index.column() == 1:
                item = index.internalPointer()
                plugins = []
                if isinstance(item, Package):
                    for child in item.children:
                        if not child.data["plugin"] in plugins:
                            plugins.append(child.data["plugin"])
                else:
                    plugins.append(item.data["plugin"])
                return QVariant(", ".join(plugins))
            elif index.column() == 2:
                item = index.internalPointer()
                status = 0
                speed = self.getSpeed(item)
                if isinstance(item, Package):
                    for child in item.children:
                        if child.data["status"] > status:
                            status = child.data["status"]
                else:
                    status = item.data["status"]
                
                if speed is None or status == 7 or status == 10 or status == 5:
                    return QVariant(self.translateStatus(statusMapReverse[status]))
                else:
                    return QVariant("%s (%s)" % (self.translateStatus(statusMapReverse[status]), formatSpeed(speed)))
            elif index.column() == 3:
                item = index.internalPointer()
                if isinstance(item, Link):
                    if item.data["status"] == 0: #TODO needs change??
		            #self.getProgress(item, False) == 100:
                        return QVariant(formatSize(item.data["size"]))
                    elif self.getProgress(item, False) == 0:
                        try:
                            return QVariant("%s / %s" % (formatSize(item.data["size"]-item.data["downloading"]["bleft"]), formatSize(item.data["size"])))
                        except:
                            return QVariant("0 B / %s" % formatSize(item.data["size"]))
                    else:
                        try:
                            return QVariant("%s / %s" % (formatSize(item.data["size"]-item.data["downloading"]["bleft"]), formatSize(item.data["size"])))
                        except:
                            return QVariant("? / %s" % formatSize(item.data["size"]))
                else:
                    ms = 0
                    cs = 0
                    for c in item.children:
                        try:
                            s = c.data["downloading"]["size"]
                        except:
                            s = c.data["size"]
                        if c.data["downloading"]:
                            cs += s - c.data["downloading"]["bleft"]
                        elif self.getProgress(c, False) == 100:
                            cs += s
                        ms += s
                    if cs == 0 or cs == ms:
                        return QVariant(formatSize(ms))
                    else:
                        return QVariant("%s / %s" % (formatSize(cs), formatSize(ms)))
            elif index.column() == 4:
                item = index.internalPointer()
                if isinstance(item, Link):
                    if item.data["downloading"]:
                        return QVariant(item.data["downloading"]["format_eta"])
        elif role == Qt.EditRole:
            if index.column() == 0:
                return QVariant(index.internalPointer().data["name"])
        return QVariant()
コード例 #30
0
ファイル: pyLoadCore.py プロジェクト: vuolter/pyreload
    def start(self, rpc=True, web=True):
        """ starts the fun :D """

        self.version = CURRENT_VERSION

        if not exists("pyload.conf"):
            from module.setup import Setup

            print("This is your first start, running configuration assistent now.")
            self.config = ConfigParser()
            s = Setup(pypath, self.config)
            res = False
            try:
                res = s.start()
            except SystemExit:
                pass
            except KeyboardInterrupt:
                print("\nSetup interrupted")
            except:
                res = False
                print_exc()
                print("Setup failed")
            if not res:
                remove("pyload.conf")

            exit()

        try: signal.signal(signal.SIGQUIT, self.quit)
        except: pass

        self.config = ConfigParser()

        gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation("pyLoad", self.path("locale"),
                                          languages=[self.config['general']['language'],"en"],fallback=True)
        install_translation(translation)

        self.debug = self.doDebug or self.config['general']['debug_mode']
        self.remote &= self.config['remote']['activated']

        pid = self.isAlreadyRunning()
        if pid:
            print(_("pyLoad already running with pid %s") % pid)
            exit()

        if not IS_WINDOWS and self.config["general"]["renice"]:
            os.system("renice %d %d" % (self.config["general"]["renice"], os.getpid()))

        if self.config["permission"]["change_group"]:
            if not IS_WINDOWS:
                try:
                    from grp import getgrnam

                    group = getgrnam(self.config["permission"]["group"])
                    os.setgid(group[2])
                except Exception as e:
                    print(_("Failed changing group: %s") % e)

        if self.config["permission"]["change_user"]:
            if not IS_WINDOWS:
                try:
                    from pwd import getpwnam

                    user = getpwnam(self.config["permission"]["user"])
                    os.setuid(user[2])
                except Exception as e:
                    print(_("Failed changing user: %s") % e)

        self.check_file(
            self.config['log']['log_folder'],
            _("folder for logs"),
            is_folder=True,
        )

        if self.debug:
            self.init_logger(logging.DEBUG) # logging level
        else:
            self.init_logger(logging.INFO) # logging level

        sys.excepthook = exceptHook

        self.do_kill = False
        self.do_restart = False
        self.shuttedDown = False

        self.log.info(_("Starting") + " pyLoad %s" % CURRENT_VERSION)
        self.log.info(_("Using home directory: %s") % getcwd())

        self.writePidFile()

        #@TODO refractor

        remote.activated = self.remote
        self.log.debug("Remote activated: %s" % self.remote)

        self.check_install("Crypto", _("pycrypto to decode container files"))
        #img = self.check_install("Image", _("Python Image Libary (PIL) for captcha reading"))
        #self.check_install("pycurl", _("pycurl to download any files"), True, True)
        self.check_file("tmp", _("folder for temporary files"), is_folder=True)
        #tesser = self.check_install("tesseract", _("tesseract for captcha reading"), False) if not IS_WINDOWS else True

        self.captcha = True # checks seems to fail, althoug tesseract is available

        self.check_file(
            self.config['general']['download_folder'],
            _("folder for downloads"),
            is_folder=True,
        )

        if self.config['ssl']['activated']:
            self.check_install("OpenSSL", _("OpenSSL for secure connection"))

        self.setupDB()

        if self.deleteLinks:
            self.log.info(_("All links removed"))
            self.db.purgeLinks()

        set_request_factory(RequestFactory(self))

        self.lastClientConnected = 0

        # later imported because they would trigger api import, and remote value not set correctly
        from module import Api
        from module.HookManager import HookManager
        from module.ThreadManager import ThreadManager

        if Api.activated != self.remote:
            self.log.warning("Import error: API remote status not correct.")

        self.api = Api.Api(self)

        self.scheduler = Scheduler(self)

        #hell yeah, so many important managers :D
        set_plugin_manager(PluginManager(self))
        set_pull_manager(PullManager(self))
        set_thread_manager(ThreadManager(self))
        set_account_manager(AccountManager(self))
        set_captcha_manager(CaptchaManager(self))
        # HookManager sets itself as a singleton
        HookManager(self)
        set_remote_manager(RemoteManager(self))

        thread_manager = get_thread_manager()

        self.js = JsEngine()

        self.log.info(_("Downloadtime: %s") % self.api.isTimeDownload())

        if rpc:
            get_remote_manager().startBackends()

        if web:
            self.init_webserver()

        spaceLeft = freeSpace(self.config["general"]["download_folder"])

        self.log.info(_("Free space: %s") % formatSize(spaceLeft))

        self.config.save() #save so config files gets filled

        link_file = join(pypath, "links.txt")

        if exists(link_file):
            f = open(link_file, "rb")
            if f.read().strip():
                self.api.addPackage("links.txt", [link_file], 1)
            f.close()

        link_file = "links.txt"
        if exists(link_file):
            f = open(link_file, "rb")
            if f.read().strip():
                self.api.addPackage("links.txt", [link_file], 1)
            f.close()

        #self.scheduler.addJob(0, get_account_manager().getAccountInfos)
        self.log.info(_("Activating Accounts..."))
        get_account_manager().getAccountInfos()

        thread_manager.pause = False
        self.running = True

        self.log.info(_("Activating Plugins..."))
        get_hook_manager().coreReady()

        self.log.info(_("pyLoad is up and running"))

        #test api
#        from module.common.APIExerciser import startApiExerciser
#        startApiExerciser(self, 3)

        #some memory stats
#        from guppy import hpy
#        hp=hpy()
#        import objgraph
#        objgraph.show_most_common_types(limit=20)
#        import memdebug
#        memdebug.start(8002)

        locals().clear()

        while True:
            try:
                sleep(2)
            except IOError as e:
                if e.errno != 4:  # errno.EINTR
                    raise

            if self.do_restart:
                self.log.info(_("restarting pyLoad"))
                self.restart()

            if self.do_kill:
                self.shutdown()
                self.log.info(_("pyLoad quits"))
                self.removeLogger()
                _exit(0) #@TODO thrift blocks shutdown

            thread_manager.work()
            self.scheduler.work()
コード例 #31
0
ファイル: Queue.py プロジェクト: Tooker/pyreload
    def data(self, index, role=Qt.DisplayRole):
        """
            return cell data
        """
        if not index.isValid():
            return QVariant()
        if role == Qt.DisplayRole:
            if index.column() == 0:
                return QVariant(index.internalPointer().data["name"])
            elif index.column() == 1:
                item = index.internalPointer()
                plugins = []
                if isinstance(item, Package):
                    for child in item.children:
                        if not child.data["plugin"] in plugins:
                            plugins.append(child.data["plugin"])
                else:
                    plugins.append(item.data["plugin"])
                return QVariant(", ".join(plugins))
            elif index.column() == 2:
                item = index.internalPointer()
                status = 0
                speed = self.getSpeed(item)
                if isinstance(item, Package):
                    for child in item.children:
                        if child.data["status"] > status:
                            status = child.data["status"]
                else:
                    status = item.data["status"]

                if speed is None or status == 7 or status == 10 or status == 5:
                    return QVariant(
                        self.translateStatus(statusMapReverse[status]))
                else:
                    return QVariant("%s (%s)" % (self.translateStatus(
                        statusMapReverse[status]), formatSpeed(speed)))
            elif index.column() == 3:
                item = index.internalPointer()
                if isinstance(item, Link):
                    if item.data["status"] == 0:  #TODO needs change??
                        #self.getProgress(item, False) == 100:
                        return QVariant(formatSize(item.data["size"]))
                    elif self.getProgress(item, False) == 0:
                        try:
                            return QVariant(
                                "%s / %s" %
                                (formatSize(item.data["size"] -
                                            item.data["downloading"]["bleft"]),
                                 formatSize(item.data["size"])))
                        except:
                            return QVariant("0 B / %s" %
                                            formatSize(item.data["size"]))
                    else:
                        try:
                            return QVariant(
                                "%s / %s" %
                                (formatSize(item.data["size"] -
                                            item.data["downloading"]["bleft"]),
                                 formatSize(item.data["size"])))
                        except:
                            return QVariant("? / %s" %
                                            formatSize(item.data["size"]))
                else:
                    ms = 0
                    cs = 0
                    for c in item.children:
                        try:
                            s = c.data["downloading"]["size"]
                        except:
                            s = c.data["size"]
                        if c.data["downloading"]:
                            cs += s - c.data["downloading"]["bleft"]
                        elif self.getProgress(c, False) == 100:
                            cs += s
                        ms += s
                    if cs == 0 or cs == ms:
                        return QVariant(formatSize(ms))
                    else:
                        return QVariant("%s / %s" %
                                        (formatSize(cs), formatSize(ms)))
            elif index.column() == 4:
                item = index.internalPointer()
                if isinstance(item, Link):
                    if item.data["downloading"]:
                        return QVariant(item.data["downloading"]["format_eta"])
        elif role == Qt.EditRole:
            if index.column() == 0:
                return QVariant(index.internalPointer().data["name"])
        return QVariant()
コード例 #32
0
ファイル: pyload-cli.py プロジェクト: 4Christopher/pyload
    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

            f = open(join(owd, path), "rb")
            content = f.read()
            f.close()

            rid = self.client.checkOnlineStatusContainer([], basename(f.name), content).rid
            self.printOnlineCheck(self.client, rid)


        elif command == "pause":
            self.client.pauseServer()

        elif command == "unpause":
            self.client.unpauseServer()

        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()
コード例 #33
0
ファイル: PyFile.py プロジェクト: 3DMeny/pyload
 def formatSize(self):
     """ formats size to readable format """
     return formatSize(self.getSize())
コード例 #34
0
def config():
    conf = PYLOAD.getConfig()
    plugin = PYLOAD.getPluginConfig()

    conf_menu = []
    plugin_menu = []

    for entry in sorted(conf.keys()):
        conf_menu.append((entry, conf[entry].description))

    for entry in sorted(plugin.keys()):
        plugin_menu.append((entry, plugin[entry].description))

    accs = []

    for data in PYLOAD.getAccounts(False):
        if data.trafficleft == -1:
            trafficleft = _("unlimited")
        elif not data.trafficleft:
            trafficleft = _("not available")
        else:
            trafficleft = formatSize(data.trafficleft * 1024)

        if data.validuntil == -1:
            validuntil = _("unlimited")
        elif not data.validuntil:
            validuntil = _("not available")
        else:
            t = time.localtime(data.validuntil)
            validuntil = time.strftime("%d.%m.%Y", t)

        if "time" in data.options:
            try:
                _time = data.options["time"][0]
            except:
                _time = ""
        else:
            _time = ""

        if "limitDL" in data.options:
            try:
                limitdl = data.options["limitDL"][0]
            except:
                limitdl = "0"
        else:
            limitdl = "0"

        accs.append({
            'type': data.type,
            'login': data.login,
            'valid': data.valid,
            'premium': data.premium,
            'trafficleft': trafficleft,
            'validuntil': validuntil,
            'limitdl': limitdl,
            'time': _time
        })

    return render_to_response(
        'settings.html', {
            'conf': {
                'plugin': plugin_menu,
                'general': conf_menu,
                'accs': accs
            },
            'types': PYLOAD.getAccountTypes()
        }, [pre_processor])