Esempio n. 1
0
 def test_ftime(self):
     self.assertTrue(ftime(0) == '')
     self.assertTrue(ftime(5) == '5s')
     self.assertTrue(ftime(100) == '1m 40s')
     self.assertTrue(ftime(3789) == '1h 3m')
     self.assertTrue(ftime(23011) == '6h 23m')
     self.assertTrue(ftime(391187) == '4d 12h')
     self.assertTrue(ftime(604800) == '1w 0d')
     self.assertTrue(ftime(13893086) == '22w 6d')
     self.assertTrue(ftime(59740269) == '1y 46w')
Esempio n. 2
0
 def test_ftime(self):
     self.assertTrue(ftime(0) == '')
     self.assertTrue(ftime(5) == '5s')
     self.assertTrue(ftime(100) == '1m 40s')
     self.assertTrue(ftime(3789) == '1h 3m')
     self.assertTrue(ftime(23011) == '6h 23m')
     self.assertTrue(ftime(391187) == '4d 12h')
     self.assertTrue(ftime(604800) == '1w 0d')
     self.assertTrue(ftime(13893086) == '22w 6d')
     self.assertTrue(ftime(59740269) == '1y 46w')
Esempio n. 3
0
def ftime_or_dash(value):
    """Display value as time, eg 2h 30m or dash"""
    if value > 0:
        return ftime(value)
    elif value == 0:
        return '-'
    else:
        return '∞'
def cell_data_time(column, cell, model, row, data):
    """Display value as time, eg 1m10s"""
    time = model.get_value(row, data)
    if func_last_value['cell_data_time'] == time:
        return
    func_last_value['cell_data_time'] = time

    if time <= 0:
        time_str = ''
    else:
        time_str = common.ftime(time)
    cell.set_property('text', time_str)
Esempio n. 5
0
def cell_data_time(column, cell, model, row, data):
    """Display value as time, eg 1m10s"""
    time = model.get_value(row, data)
    if func_last_value['cell_data_time'] == time:
        return
    func_last_value['cell_data_time'] = time

    if time <= 0:
        time_str = ''
    else:
        time_str = common.ftime(time)
    cell.set_property('text', time_str)
Esempio n. 6
0
    def render_header(self, off):
        status = self.torrent_state

        up_color = colors.state_color["Seeding"]
        down_color = colors.state_color["Downloading"]

        #Name
        s = "{!info!}Name: {!input!}%s" % status["name"]
        self.add_string(off, s); off += 1

        #Print DL info and ETA
        if status["download_payload_rate"] > 0:
            s = "%sDownloading: {!input!}" % down_color
        else:
            s = "{!info!}Downloaded: {!input!}"
        s+= common.fsize(status["all_time_download"])
        if status["progress"] != 100.0:
            s+= "/%s" % common.fsize(status["total_wanted"])
        if status["download_payload_rate"] > 0:
            s+= " {!yellow!}@ %s%s" % (down_color, common.fsize(status["download_payload_rate"]))
            s+= "{!info!} ETA: {!input!}%s" % format_utils.format_time(status["eta"])
        self.add_string(off, s); off += 1

        #Print UL info and ratio
        if status["upload_payload_rate"] > 0:
            s = "%sUploading: {!input!}" % up_color
        else:
            s = "{!info!}Uploaded: {!input!}"
        s+= common.fsize(status["total_uploaded"])
        if status["upload_payload_rate"] > 0:
            s+= " {!yellow!}@ %s%s" % (up_color, common.fsize(status["upload_payload_rate"]))
        ratio_str = format_utils.format_float(status["ratio"])
        if ratio_str == "-": ratio_str = "inf"
        s+= " {!info!}Ratio: {!input!}%s" % ratio_str
        self.add_string(off, s); off += 1

        #Seeder/leecher info
        s = "{!info!}Seeders:{!green!} %s {!input!}(%s)" % (status["num_seeds"], status["total_seeds"])
        self.add_string(off, s); off += 1
        s = "{!info!}Leechers:{!red!} %s {!input!}(%s)" % (status["num_peers"], status["total_peers"])
        self.add_string(off, s); off += 1

        #Tracker
        if status["message"] == "OK":
            color = "{!green!}"
        else:
            color = "{!red!}"
        s = "{!info!}Tracker: {!magenta!}%s{!input!} says \"%s%s{!input!}\"" % (status["tracker_host"], color, status["message"])
        self.add_string(off, s); off += 1

        #Pieces and availability
        s = "{!info!}Pieces: {!yellow!}%s {!input!}x {!yellow!}%s" % (status["num_pieces"], common.fsize(status["piece_length"]))
        if status["distributed_copies"]:
            s+= " {!info!}Availability: {!input!}%s" % format_utils.format_float(status["distributed_copies"])
        self.add_string(off, s); off += 1

        #Time added
        s = "{!info!}Added: {!input!}%s" % common.fdate(status["time_added"])
        self.add_string(off, s); off += 1

        #Time active
        s = "{!info!}Time active: {!input!}%s" % ( common.ftime(status["active_time"]) )
        if status["seeding_time"]:
            s+= ", {!cyan!}%s{!input!} seeding" % ( common.ftime(status["seeding_time"]) )
        self.add_string(off, s); off += 1

        #Save Path
        s = "{!info!}Save path: {!input!}%s" % status["save_path"]
        self.add_string(off, s); off += 1

        #Owner
        if status["owner"]:
            s = "{!info!}Owner: {!input!}%s" % status["owner"]

        return off
Esempio n. 7
0
INFO_DICT = (
    ('queue', lambda i, s: i != -1 and str(i) or '#'), ('state', None),
    ('name', lambda i, s: u' %s *%s* ' %
     (s['state']
      if s['state'].lower() not in EMOJI else EMOJI[s['state'].lower()], i)),
    ('total_wanted',
     lambda i, s: '(%s) ' % fsize(i)), ('progress',
                                        lambda i, s: '%s\n' % fpcnt(i / 100)),
    ('num_seeds', None), ('num_peers', None), ('total_seeds', None),
    ('total_peers', lambda i, s: '%s / %s seeds\n' % tuple(
        map(fpeer, (s['num_seeds'], s['num_peers']),
            (s['total_seeds'], s['total_peers'])))), ('download_payload_rate',
                                                      None),
    ('upload_payload_rate', lambda i, s: '%s : %s\n' % tuple(
        map(fspeed, (s['download_payload_rate'], i)))),
    ('eta', lambda i, s: i > 0 and '*ETA:* %s ' % ftime(i) or ''),
    ('time_added', lambda i, s: '*Added:* %s' % fdate(i)))

INFOS = [i[0] for i in INFO_DICT]


def is_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


def format_torrent_info(torrent):
    status = torrent.get_status(INFOS)
Esempio n. 8
0
    def show_info(self, torrent_id, status, verbose=False):
        """
        Writes out the torrents information to the screen.

        :param torrent_id: str, the torrent_id
        :param status: dict, the torrents status, this should have the same keys
            as status_keys
        :param verbose: bool, if true, we print out more information about the
            the torrent
        """
        self.console.set_batch_write(True)

        self.console.write(" ")
        self.console.write("{!info!}Name: {!input!}%s" % (status["name"]))
        self.console.write("{!info!}ID: {!input!}%s" % (torrent_id))
        s = "{!info!}State: %s%s" % (colors.state_color[status["state"]], status["state"])
        # Only show speed if active
        if status["state"] in ("Seeding", "Downloading"):
            if status["state"] != "Seeding":
                s += " {!info!}Down Speed: {!input!}%s" % common.fspeed(status["download_payload_rate"])
            s += " {!info!}Up Speed: {!input!}%s" % common.fspeed(status["upload_payload_rate"])

            if common.ftime(status["eta"]):
                s += " {!info!}ETA: {!input!}%s" % common.ftime(status["eta"])

        self.console.write(s)

        if status["state"] in ("Seeding", "Downloading", "Queued"):
            s = "{!info!}Seeds: {!input!}%s (%s)" % (status["num_seeds"], status["total_seeds"])
            s += " {!info!}Peers: {!input!}%s (%s)" % (status["num_peers"], status["total_peers"])
            s += " {!info!}Availibility: {!input!}%.2f" % status["distributed_copies"]
            self.console.write(s)

        s = "{!info!}Size: {!input!}%s/%s" % (common.fsize(status["total_done"]), common.fsize(status["total_size"]))
        s += " {!info!}Ratio: {!input!}%.3f" % status["ratio"]
        self.console.write(s)

        if not status["is_finished"]:
            if hasattr(self.console, "screen"):
                cols = self.console.screen.cols
            else:
                cols = 80

            pbar = format_progressbar(status["progress"], cols - (13 + len("%.2f%%" % status["progress"])))
            s = "{!info!}Progress: {!input!}%.2f%% %s" % (status["progress"], pbar)
            self.console.write(s)


        if verbose:
            self.console.write("  {!info!}::Files")
            for i, f in enumerate(status["files"]):
                s = "    {!input!}%s (%s)" % (f["path"], common.fsize(f["size"]))
                s += " {!info!}Progress: {!input!}%.2f%%" % (status["file_progress"][i] * 100)
                s += " {!info!}Priority:"
                fp = common.FILE_PRIORITY[status["file_priorities"][i]].replace("Priority", "")
                if fp == "Do Not Download":
                    s += "{!error!}"
                else:
                    s += "{!success!}"

                s += " %s" % (fp)
                # Check if this is too long for the screen and reduce the path
                # if necessary
                if hasattr(self.console, "screen"):
                    cols = self.console.screen.cols
                    slen = colors.get_line_length(s, self.console.screen.encoding)
                    if slen > cols:
                        s = s.replace(f["path"], f["path"][slen - cols + 1:])
                self.console.write(s)

            self.console.write("  {!info!}::Peers")
            if len(status["peers"]) == 0:
                self.console.write("    None")
            else:
                s = ""
                for peer in status["peers"]:
                    if peer["seed"]:
                        s += "%sSeed\t{!input!}" % colors.state_color["Seeding"]
                    else:
                        s += "%sPeer\t{!input!}" % colors.state_color["Downloading"]

                    s += peer["country"] + "\t"
                    s += peer["ip"]

                    c = peer["client"]
                    s += "\t" + c

                    if len(c) < 16:
                        s += "\t\t"
                    else:
                        s += "\t"
                    s += "%s%s\t%s%s" % (
                        colors.state_color["Seeding"],
                        common.fspeed(peer["up_speed"]),
                        colors.state_color["Downloading"],
                        common.fspeed(peer["down_speed"]))
                    s += "\n"

                self.console.write(s[:-1])

        self.console.set_batch_write(False)
Esempio n. 9
0
    def render_header(self, off):
        status = self.torrent_state

        up_color = colors.state_color["Seeding"]
        down_color = colors.state_color["Downloading"]

        #Name
        s = "{!info!}Name: {!input!}%s" % status["name"]
        self.add_string(off, s)
        off += 1

        #Print DL info and ETA
        if status["download_payload_rate"] > 0:
            s = "%sDownloading: {!input!}" % down_color
        else:
            s = "{!info!}Downloaded: {!input!}"
        s += common.fsize(status["all_time_download"])
        if status["progress"] != 100.0:
            s += "/%s" % common.fsize(status["total_wanted"])
        if status["download_payload_rate"] > 0:
            s += " {!yellow!}@ %s%s" % (
                down_color, common.fsize(status["download_payload_rate"]))
            s += "{!info!} ETA: {!input!}%s" % format_utils.format_time(
                status["eta"])
        self.add_string(off, s)
        off += 1

        #Print UL info and ratio
        if status["upload_payload_rate"] > 0:
            s = "%sUploading: {!input!}" % up_color
        else:
            s = "{!info!}Uploaded: {!input!}"
        s += common.fsize(status["total_uploaded"])
        if status["upload_payload_rate"] > 0:
            s += " {!yellow!}@ %s%s" % (
                up_color, common.fsize(status["upload_payload_rate"]))
        ratio_str = format_utils.format_float(status["ratio"])
        if ratio_str == "-": ratio_str = "inf"
        s += " {!info!}Ratio: {!input!}%s" % ratio_str
        self.add_string(off, s)
        off += 1

        #Seeder/leecher info
        s = "{!info!}Seeders:{!green!} %s {!input!}(%s)" % (
            status["num_seeds"], status["total_seeds"])
        self.add_string(off, s)
        off += 1
        s = "{!info!}Leechers:{!red!} %s {!input!}(%s)" % (
            status["num_peers"], status["total_peers"])
        self.add_string(off, s)
        off += 1

        #Tracker
        if status["message"] == "OK":
            color = "{!green!}"
        else:
            color = "{!red!}"
        s = "{!info!}Tracker: {!magenta!}%s{!input!} says \"%s%s{!input!}\"" % (
            status["tracker_host"], color, status["message"])
        self.add_string(off, s)
        off += 1

        #Pieces and availability
        s = "{!info!}Pieces: {!yellow!}%s {!input!}x {!yellow!}%s" % (
            status["num_pieces"], common.fsize(status["piece_length"]))
        if status["distributed_copies"]:
            s += " {!info!}Availability: {!input!}%s" % format_utils.format_float(
                status["distributed_copies"])
        self.add_string(off, s)
        off += 1

        #Time added
        s = "{!info!}Added: {!input!}%s" % common.fdate(status["time_added"])
        self.add_string(off, s)
        off += 1

        #Time active
        s = "{!info!}Time active: {!input!}%s" % (common.ftime(
            status["active_time"]))
        if status["seeding_time"]:
            s += ", {!cyan!}%s{!input!} seeding" % (common.ftime(
                status["seeding_time"]))
        self.add_string(off, s)
        off += 1

        #Save Path
        s = "{!info!}Save path: {!input!}%s" % status["save_path"]
        self.add_string(off, s)
        off += 1

        #Owner
        if status["owner"]:
            s = "{!info!}Owner: {!input!}%s" % status["owner"]

        return off
Esempio n. 10
0
    def writeOutput(self):

        try:

            self.logInfo("Proceeding with torrent data interpretation...")

            torrentDataList = []
            torrentItemList = ["num_peers","num_seeds","name","state","total_done","total_size","total_wanted","progress","files","eta","download_payload_rate","upload_payload_rate","total_peers","total_seeds","ratio","queue"]
            highesteta = 0

            # summary variables
            summary_notorrent = 0
            summary_totaldone = 0
            summary_totalsize = 0
            summary_totaldownloadrate = 0.0
            summary_totaluploadrate = 0.0
            summary_totaleta = 0
            summary_currentpeers = 0
            summary_currentseeds = 0
            summary_totalpeers = 0
            summary_totalseeds = 0
            summary_totalratio = 0.0

            self.logInfo("Preparing templates...")

            if self.options.summarytemplate == None:
                # create default summary template
                summarytemplate = "Total Torrents Queued:[notorrents] \n[totaldone]/[totalsize] - [totalprogress]\n" + "DL: [totaldownloadrate] UL: [totaluploadrate]\n"
            else:
                # load the template file contents
                try:
                    #fileinput = open(self.options.summarytemplate)
                    fileinput = codecs.open(os.path.expanduser(self.options.summarytemplate), encoding='utf-8')
                    summarytemplate = fileinput.read()
                    fileinput.close()
                except:
                    self.logError("Summary Template file no found!")
                    sys.exit(2)

            if self.options.torrenttemplate == None:
                # create default template
                torrenttemplate = "[name]\n[state]\n[totaldone]/[totalsize] - [progress]\n" + "DL: [downloadrate] UL: [uploadrate] ETA:[eta]\n"
            else:
                # load the template file contents
                try:
                    #fileinput = open(self.options.torrenttemplate)
                    fileinput = codecs.open(os.path.expanduser(self.options.torrenttemplate), encoding='utf-8')
                    torrenttemplate = fileinput.read()
                    fileinput.close()
                except:
                    self.logError("Torrent Template file no found!")
                    sys.exit(2)

            if len(self.torrents_status) > 0:

                self.logInfo("Processing %s torrent(s)..."%str(len(self.torrents_status)))

                for torrentid in self.torrents_status:
                    torrent_status = self.torrents_status[torrentid]

                    if torrent_status != None:

                        if self.options.activeonly == True:

                            active = False

                            # check for activity
                            if "num_peers" in torrent_status:
                                if torrent_status["num_peers"] > 0:
                                    active = True

                            if "num_seeds" in torrent_status:
                                if torrent_status["num_seeds"] > 0:
                                    active = True

                        # output details if all required or if active
                        if self.options.activeonly == False or active == True:

                            if "name" in torrent_status:
                                name = torrent_status["name"]
                            else:
                                name = "Unknown"

                            if "state" in torrent_status:
                                state = torrent_status["state"]

                                if state == "Downloading":
                                    statecode = self.STATE_DOWNLOADING
                                elif state == "Seeding":
                                    statecode = self.STATE_SEEDING
                                elif state == "Queued":
                                    statecode = self.STATE_QUEUED
                                elif state == "Paused":
                                    statecode = self.STATE_PAUSED
                                else:
                                    statecode = self.STATE_UNKNOWN
                            else:
                                state = "Unknown"
                                statecode = self.STATE_UNKNOWN

                            if "total_done" in torrent_status:
                                totaldone = fsize(torrent_status["total_done"])
                                summary_totaldone = summary_totaldone + int(torrent_status["total_done"])
                            else:
                                totaldone = "??.? KiB"

                            if "total_size" in torrent_status:
                                totalsize = fsize(torrent_status["total_wanted"])
                                summary_totalsize = summary_totalsize + int(torrent_status["total_wanted"])
                            else:
                                totalsize = "??.? KiB"

                            if "progress" in torrent_status:
                                progress = str(round(torrent_status["progress"],2))+"%"
                            else:
                                progress = "?.?%"

                            if "files" in torrent_status:
                                nofiles = str(len(torrent_status["files"]))
                            else:
                                nofiles = "?"

                            if "eta" in torrent_status:
                                eta = torrent_status["eta"]

                                if eta > highesteta:
                                    highesteta = eta

                                etatext = ftime(eta)
                            else:
                                eta = None
                                etatext = "Unknown"

                            if "download_payload_rate" in torrent_status:
                                downloadrate = float(torrent_status["download_payload_rate"])
                                summary_totaldownloadrate = summary_totaldownloadrate + downloadrate
                                downloadtext = fspeed(downloadrate)
                            else:
                                downloadrate = 0
                                downloadtext = "?.? KiB/s"

                            if "upload_payload_rate" in torrent_status:
                                uploadrate = float(torrent_status["upload_payload_rate"])
                                summary_totaluploadrate = summary_totaluploadrate + uploadrate
                                uploadtext = fspeed(uploadrate)
                            else:
                                uploadrate = 0
                                uploadtext = "?.? KiB/s"

                            if "num_peers" in torrent_status:
                                currentpeers = str(torrent_status["num_peers"])
                                summary_currentpeers = summary_currentpeers + int(torrent_status["num_peers"])
                            else:
                                currentpeers = "?"

                            if "num_seeds" in torrent_status:
                                currentseeds = str(torrent_status["num_seeds"])
                                summary_currentseeds = summary_currentseeds + int(torrent_status["num_seeds"])
                            else:
                                currentseeds = "?"

                            if "total_peers" in torrent_status:
                                totalpeers = str(torrent_status["total_peers"])
                                summary_totalpeers = summary_totalpeers + int(torrent_status["total_peers"])
                            else:
                                totalpeers = "?"

                            if "total_seeds" in torrent_status:
                                totalseeds = str(torrent_status["total_seeds"])
                                summary_totalseeds = summary_totalseeds + int(torrent_status["total_seeds"])
                            else:
                                totalseeds = "?"

                            if "ratio" in torrent_status:
                                ratio = str(round(torrent_status["ratio"],3)).ljust(5,"0")
                            else:
                                ratio = "?.???"

                            # for sorting in the same way as progress, we need to order from high to low
                            if "queue" in torrent_status:
                                queueorder = torrent_status["queue"]
                            else:
                                queueorder = -1

                            sortby = self.options.sortby

                            summary_notorrent = summary_notorrent + 1

                            # add torrent data to list
                            torrentData = TorrentData(name, state, statecode, totaldone, totalsize, progress, nofiles, downloadrate, downloadtext, uploadrate, uploadtext, eta, etatext, currentpeers, currentseeds, totalpeers, totalseeds, ratio, queueorder, sortby)
                            torrentDataList.append(torrentData)

                    else:
                        self.logInfo("No torrent status data available for torrentid: "+torrentid)

                if summary_notorrent > 0:

                    output = u""

                    if self.options.showsummary == True:

                        # sort out summary data for output
                        summary_notorrent = str(summary_notorrent)
                        summary_totalprogress = str(round((float(summary_totaldone) / float(summary_totalsize)) *100,2))+"%"
                        summary_totaldone = fsize(summary_totaldone)
                        summary_totalsize = fsize(summary_totalsize)
                        summary_totaldownloadrate = fspeed(summary_totaldownloadrate)
                        summary_totaluploadrate = fspeed(summary_totaluploadrate)
                        summary_totaleta = ftime(highesteta)
                        summary_currentpeers = str(summary_currentpeers)
                        summary_currentseeds = str(summary_currentseeds)
                        summary_totalpeers = str(summary_totalpeers)
                        summary_totalseeds = str(summary_totalseeds)
                        summary_totalratio = "?.???"

                        output = self.getSummaryTemplateOutput(summarytemplate, summary_notorrent, summary_totalprogress, summary_totaldone, summary_totalsize, summary_totaldownloadrate, summary_totaluploadrate, summary_totaleta, summary_currentpeers, summary_currentseeds, summary_totalpeers, summary_totalseeds, summary_totalratio)

                    if self.options.hidetorrentdetail == False:

                        outputCount = 0

                        # sort list, eta based
                        self.logInfo("Sorting torrent list using: %s"%self.options.sortby)
                        torrentDataList.sort(reverse = True)

                        # output torrent data using the template
                        for torrentData in torrentDataList:

                            # keep a tally of torrent output, if past the limit then exit
                            if self.options.limit <> 0:
                                outputCount = outputCount + 1
                                if outputCount > self.options.limit:
                                    break

                            output = output + self.getTorrentTemplateOutput(torrenttemplate, torrentData.name, torrentData.state, torrentData.totaldone, torrentData.totalsize, torrentData.progress, torrentData.nofiles, torrentData.downloadtext, torrentData.uploadtext, torrentData.etatext, torrentData.currentpeers, torrentData.currentseeds, torrentData.totalpeers, torrentData.totalseeds, torrentData.ratio)+"\n"

                    print output.encode("utf-8")

                else:
                    print u"No torrent info to display"

            else:
                self.logInfo("No torrents found")

        except Exception,e:
            self.logError("writeOutput:Unexpected error:" + e.__str__())
Esempio n. 11
0
    def writeOutput(self):

        try:

            self.logInfo("Proceeding with torrent data interpretation...")

            torrentDataList = []
            torrentItemList = [
                "num_peers", "num_seeds", "name", "state", "total_done",
                "total_size", "total_wanted", "progress", "files", "eta",
                "download_payload_rate", "upload_payload_rate", "total_peers",
                "total_seeds", "ratio", "queue"
            ]
            highesteta = 0

            # summary variables
            summary_notorrent = 0
            summary_totaldone = 0
            summary_totalsize = 0
            summary_totaldownloadrate = 0.0
            summary_totaluploadrate = 0.0
            summary_totaleta = 0
            summary_currentpeers = 0
            summary_currentseeds = 0
            summary_totalpeers = 0
            summary_totalseeds = 0
            summary_totalratio = 0.0

            self.logInfo("Preparing templates...")

            if self.options.summarytemplate == None:
                # create default summary template
                summarytemplate = "Total Torrents Queued:[notorrents] \n[totaldone]/[totalsize] - [totalprogress]\n" + "DL: [totaldownloadrate] UL: [totaluploadrate]\n"
            else:
                # load the template file contents
                try:
                    #fileinput = open(self.options.summarytemplate)
                    fileinput = codecs.open(
                        os.path.expanduser(self.options.summarytemplate),
                        encoding='utf-8')
                    summarytemplate = fileinput.read()
                    fileinput.close()
                except:
                    self.logError("Summary Template file no found!")
                    sys.exit(2)

            if self.options.torrenttemplate == None:
                # create default template
                torrenttemplate = "[name]\n[state]\n[totaldone]/[totalsize] - [progress]\n" + "DL: [downloadrate] UL: [uploadrate] ETA:[eta]\n"
            else:
                # load the template file contents
                try:
                    #fileinput = open(self.options.torrenttemplate)
                    fileinput = codecs.open(
                        os.path.expanduser(self.options.torrenttemplate),
                        encoding='utf-8')
                    torrenttemplate = fileinput.read()
                    fileinput.close()
                except:
                    self.logError("Torrent Template file no found!")
                    sys.exit(2)

            if len(self.torrents_status) > 0:

                self.logInfo("Processing %s torrent(s)..." % str(
                    len(self.torrents_status)))

                for torrentid in self.torrents_status:
                    torrent_status = self.torrents_status[torrentid]

                    if torrent_status != None:

                        if self.options.activeonly == True:

                            active = False

                            # check for activity
                            if "num_peers" in torrent_status:
                                if torrent_status["num_peers"] > 0:
                                    active = True

                            if "num_seeds" in torrent_status:
                                if torrent_status["num_seeds"] > 0:
                                    active = True

                        # output details if all required or if active
                        if self.options.activeonly == False or active == True:

                            if "name" in torrent_status:
                                name = torrent_status["name"]
                            else:
                                name = "Unknown"

                            if "state" in torrent_status:
                                state = torrent_status["state"]

                                if state == "Downloading":
                                    statecode = self.STATE_DOWNLOADING
                                elif state == "Seeding":
                                    statecode = self.STATE_SEEDING
                                elif state == "Queued":
                                    statecode = self.STATE_QUEUED
                                elif state == "Paused":
                                    statecode = self.STATE_PAUSED
                                else:
                                    statecode = self.STATE_UNKNOWN
                            else:
                                state = "Unknown"
                                statecode = self.STATE_UNKNOWN

                            if "total_done" in torrent_status:
                                totaldone = fsize(torrent_status["total_done"])
                                summary_totaldone = summary_totaldone + int(
                                    torrent_status["total_done"])
                            else:
                                totaldone = "??.? KiB"

                            if "total_size" in torrent_status:
                                totalsize = fsize(
                                    torrent_status["total_wanted"])
                                summary_totalsize = summary_totalsize + int(
                                    torrent_status["total_wanted"])
                            else:
                                totalsize = "??.? KiB"

                            if "progress" in torrent_status:
                                progress = str(
                                    round(torrent_status["progress"], 2)) + "%"
                            else:
                                progress = "?.?%"

                            if "files" in torrent_status:
                                nofiles = str(len(torrent_status["files"]))
                            else:
                                nofiles = "?"

                            if "eta" in torrent_status:
                                eta = torrent_status["eta"]

                                if eta > highesteta:
                                    highesteta = eta

                                etatext = ftime(eta)
                            else:
                                eta = None
                                etatext = "Unknown"

                            if "download_payload_rate" in torrent_status:
                                downloadrate = float(
                                    torrent_status["download_payload_rate"])
                                summary_totaldownloadrate = summary_totaldownloadrate + downloadrate
                                downloadtext = fspeed(downloadrate)
                            else:
                                downloadrate = 0
                                downloadtext = "?.? KiB/s"

                            if "upload_payload_rate" in torrent_status:
                                uploadrate = float(
                                    torrent_status["upload_payload_rate"])
                                summary_totaluploadrate = summary_totaluploadrate + uploadrate
                                uploadtext = fspeed(uploadrate)
                            else:
                                uploadrate = 0
                                uploadtext = "?.? KiB/s"

                            if "num_peers" in torrent_status:
                                currentpeers = str(torrent_status["num_peers"])
                                summary_currentpeers = summary_currentpeers + int(
                                    torrent_status["num_peers"])
                            else:
                                currentpeers = "?"

                            if "num_seeds" in torrent_status:
                                currentseeds = str(torrent_status["num_seeds"])
                                summary_currentseeds = summary_currentseeds + int(
                                    torrent_status["num_seeds"])
                            else:
                                currentseeds = "?"

                            if "total_peers" in torrent_status:
                                totalpeers = str(torrent_status["total_peers"])
                                summary_totalpeers = summary_totalpeers + int(
                                    torrent_status["total_peers"])
                            else:
                                totalpeers = "?"

                            if "total_seeds" in torrent_status:
                                totalseeds = str(torrent_status["total_seeds"])
                                summary_totalseeds = summary_totalseeds + int(
                                    torrent_status["total_seeds"])
                            else:
                                totalseeds = "?"

                            if "ratio" in torrent_status:
                                ratio = str(round(torrent_status["ratio"],
                                                  3)).ljust(5, "0")
                            else:
                                ratio = "?.???"

                            # for sorting in the same way as progress, we need to order from high to low
                            if "queue" in torrent_status:
                                queueorder = torrent_status["queue"]
                            else:
                                queueorder = -1

                            sortby = self.options.sortby

                            summary_notorrent = summary_notorrent + 1

                            # add torrent data to list
                            torrentData = TorrentData(
                                name, state, statecode, totaldone, totalsize,
                                progress, nofiles, downloadrate, downloadtext,
                                uploadrate, uploadtext, eta, etatext,
                                currentpeers, currentseeds, totalpeers,
                                totalseeds, ratio, queueorder, sortby)
                            torrentDataList.append(torrentData)

                    else:
                        self.logInfo(
                            "No torrent status data available for torrentid: "
                            + torrentid)

                if summary_notorrent > 0:

                    output = u""

                    if self.options.showsummary == True:

                        # sort out summary data for output
                        summary_notorrent = str(summary_notorrent)
                        summary_totalprogress = str(
                            round((float(summary_totaldone) /
                                   float(summary_totalsize)) * 100, 2)) + "%"
                        summary_totaldone = fsize(summary_totaldone)
                        summary_totalsize = fsize(summary_totalsize)
                        summary_totaldownloadrate = fspeed(
                            summary_totaldownloadrate)
                        summary_totaluploadrate = fspeed(
                            summary_totaluploadrate)
                        summary_totaleta = ftime(highesteta)
                        summary_currentpeers = str(summary_currentpeers)
                        summary_currentseeds = str(summary_currentseeds)
                        summary_totalpeers = str(summary_totalpeers)
                        summary_totalseeds = str(summary_totalseeds)
                        summary_totalratio = "?.???"

                        output = self.getSummaryTemplateOutput(
                            summarytemplate, summary_notorrent,
                            summary_totalprogress, summary_totaldone,
                            summary_totalsize, summary_totaldownloadrate,
                            summary_totaluploadrate, summary_totaleta,
                            summary_currentpeers, summary_currentseeds,
                            summary_totalpeers, summary_totalseeds,
                            summary_totalratio)

                    if self.options.hidetorrentdetail == False:

                        outputCount = 0

                        # sort list, eta based
                        self.logInfo("Sorting torrent list using: %s" %
                                     self.options.sortby)
                        torrentDataList.sort(reverse=True)

                        # output torrent data using the template
                        for torrentData in torrentDataList:

                            # keep a tally of torrent output, if past the limit then exit
                            if self.options.limit <> 0:
                                outputCount = outputCount + 1
                                if outputCount > self.options.limit:
                                    break

                            output = output + self.getTorrentTemplateOutput(
                                torrenttemplate, torrentData.name,
                                torrentData.state, torrentData.totaldone,
                                torrentData.totalsize, torrentData.progress,
                                torrentData.nofiles, torrentData.downloadtext,
                                torrentData.uploadtext, torrentData.etatext,
                                torrentData.currentpeers,
                                torrentData.currentseeds,
                                torrentData.totalpeers, torrentData.totalseeds,
                                torrentData.ratio) + "\n"

                    print output.encode("utf-8")

                else:
                    print u"No torrent info to display"

            else:
                self.logInfo("No torrents found")

        except Exception, e:
            self.logError("writeOutput:Unexpected error:" + e.__str__())
Esempio n. 12
0
 def get_torrent_download_status(self, torrent_id):
     # response = str(self.torrents_status[torrent_id]["time_since_upload"])
     response = common.ftime(
         self.torrents_status[torrent_id]["time_since_upload"])
     # print response
     return response or ""
Esempio n. 13
0
    def show_info(self, torrent_id, status, verbose=False, detailed=False):
        """
        Writes out the torrents information to the screen.

        Format depends on switches given.
        """
        self.console.set_batch_write(True)

        if hasattr(self.console, "screen"):
            cols = self.console.screen.cols
        else:
            cols = 80

        if verbose or detailed:
            self.console.write(" ")
            self.console.write("{!info!}Name: {!input!}%s" % (status["name"]))
            self.console.write("{!info!}ID: {!input!}%s" % (torrent_id))
            s = "{!info!}State: %s%s" % (colors.state_color[status["state"]],
                                         status["state"])
            # Only show speed if active
            if status["state"] in ("Seeding", "Downloading"):
                if status["state"] != "Seeding":
                    s += " {!info!}Down Speed: {!input!}%s" % common.fspeed(
                        status["download_payload_rate"])
                s += " {!info!}Up Speed: {!input!}%s" % common.fspeed(
                    status["upload_payload_rate"])

                if common.ftime(status["eta"]):
                    s += " {!info!}ETA: {!input!}%s" % common.ftime(
                        status["eta"])

            self.console.write(s)

            if status["state"] in ("Seeding", "Downloading", "Queued"):
                s = "{!info!}Seeds: {!input!}%s (%s)" % (status["num_seeds"],
                                                         status["total_seeds"])
                s += " {!info!}Peers: {!input!}%s (%s)" % (
                    status["num_peers"], status["total_peers"])
                s += " {!info!}Availibility: {!input!}%.2f" % status[
                    "distributed_copies"]
                self.console.write(s)

            total_done = common.fsize(status["total_done"])
            total_size = common.fsize(status["total_size"])
            if total_done == total_size:
                s = "{!info!}Size: {!input!}%s" % (total_size)
            else:
                s = "{!info!}Size: {!input!}%s/%s" % (total_done, total_size)
            s += " {!info!}Ratio: {!input!}%.3f" % status["ratio"]
            s += " {!info!}Uploaded: {!input!}%s" % common.fsize(
                status["ratio"] * status["total_done"])
            self.console.write(s)

            s = "{!info!}Tracker: {!input!}%s" % status["tracker"]
            self.console.write(s)

            if not status["is_finished"]:
                pbar = format_progressbar(
                    status["progress"],
                    cols - (13 + len("%.2f%%" % status["progress"])))
                s = "{!info!}Progress: {!input!}%.2f%% %s" % (
                    status["progress"], pbar)
                self.console.write(s)

            s = "{!info!}Download location: {!input!}%s" % status["save_path"]
            self.console.write(s)

            if detailed:
                self.console.write("{!info!}Files in torrent")
                self.show_file_info(torrent_id, status)
                self.console.write("{!info!}Connected peers")
                self.show_peer_info(torrent_id, status)
        else:
            self.console.write(" ")
            up_color = colors.state_color["Seeding"]
            down_color = colors.state_color["Downloading"]

            s = "%s%s" % (colors.state_color[status["state"]],
                          "[" + status["state"][0] + "]")

            s += " {!info!}" + ("%.2f%%" % status["progress"]).ljust(7, " ")
            s += " {!input!}%s" % (status["name"])

            #Shorten the ID if it's necessary. Pretty hacky
            #I _REALLY_ should make a nice function for it that can partition and shorten stuff
            space_left = cols - strwidth("[s] 100.00% " + status["name"] +
                                         " " * 3) - 2

            if space_left >= len(torrent_id) - 2:
                #There's enough space, print it
                s += " {!cyan!}%s" % torrent_id
            else:
                #Shorten the ID
                a = int(space_left * 2 / 3.0)
                b = space_left - a
                if a < 8:
                    b = b - (8 - a)
                    a = 8
                    if b < 0:
                        a += b
                        b = 0
                if a > 8:
                    #Print the shortened ID
                    s += " {!cyan!}%s" % (torrent_id[0:a] + ".." +
                                          torrent_id[-b - 1:-1])
                else:
                    #It has wrapped over to the second row anyway
                    s += " {!cyan!}%s" % torrent_id
            self.console.write(s)

            dl_info = "{!info!}DL: {!input!}"
            dl_info += "%s" % common.fsize(status["total_done"])
            if status["total_done"] != status["total_size"]:
                dl_info += "/%s" % common.fsize(status["total_size"])
            if status["download_payload_rate"] > 0:
                dl_info += " @ %s%s" % (
                    down_color, common.fspeed(status["download_payload_rate"]))

            ul_info = " {!info!}UL: {!input!}"
            ul_info += "%s" % common.fsize(
                status["ratio"] * status["total_done"])
            if status["upload_payload_rate"] > 0:
                ul_info += " @ %s%s" % (
                    up_color, common.fspeed(status["upload_payload_rate"]))

            eta = ""
            if common.ftime(status["eta"]):
                eta = " {!info!}ETA: {!magenta!}%s" % common.ftime(
                    status["eta"])

            self.console.write("    " + dl_info + ul_info + eta)
        self.console.set_batch_write(False)
Esempio n. 14
0
             ('name', lambda i, s: u' %s *%s* ' %
              (s['state'] if s['state'].lower() not in EMOJI
               else EMOJI[s['state'].lower()],
               i)),
             ('total_wanted', lambda i, s: '(%s) ' % fsize(i)),
             ('progress', lambda i, s: '%s\n' % fpcnt(i/100)),
             ('num_seeds', None),
             ('num_peers', None),
             ('total_seeds', None),
             ('total_peers', lambda i, s: '%s / %s seeds\n' %
              tuple(map(fpeer, (s['num_seeds'], s['num_peers']),
                               (s['total_seeds'], s['total_peers'])))),
             ('download_payload_rate', None),
             ('upload_payload_rate', lambda i, s: '%s : %s\n' %
              tuple(map(fspeed, (s['download_payload_rate'], i)))),
             ('eta', lambda i, s: i > 0 and '*ETA:* %s ' % ftime(i) or ''),
             ('time_added', lambda i, s: '*Added:* %s' % fdate(i)))

INFOS = [i[0] for i in INFO_DICT]


def is_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


def format_torrent_info(torrent):
    status = torrent.get_status(INFOS)
Esempio n. 15
0
File: info.py Progetto: Ashod/Deluge
    def show_info(self, torrent_id, status, verbose=False, detailed=False):
        """
        Writes out the torrents information to the screen.

        Format depends on switches given.
        """
        self.console.set_batch_write(True)

        if hasattr(self.console, "screen"):
            cols = self.console.screen.cols
        else:
            cols = 80

        if verbose or detailed:
            self.console.write(" ")
            self.console.write("{!info!}Name: {!input!}%s" % (status["name"]))
            self.console.write("{!info!}ID: {!input!}%s" % (torrent_id))
            s = "{!info!}State: %s%s" % (colors.state_color[status["state"]], status["state"])
            # Only show speed if active
            if status["state"] in ("Seeding", "Downloading"):
                if status["state"] != "Seeding":
                    s += " {!info!}Down Speed: {!input!}%s" % common.fspeed(status["download_payload_rate"])
                s += " {!info!}Up Speed: {!input!}%s" % common.fspeed(status["upload_payload_rate"])

                if common.ftime(status["eta"]):
                    s += " {!info!}ETA: {!input!}%s" % common.ftime(status["eta"])

            self.console.write(s)

            if status["state"] in ("Seeding", "Downloading", "Queued"):
                s = "{!info!}Seeds: {!input!}%s (%s)" % (status["num_seeds"], status["total_seeds"])
                s += " {!info!}Peers: {!input!}%s (%s)" % (status["num_peers"], status["total_peers"])
                s += " {!info!}Availibility: {!input!}%.2f" % status["distributed_copies"]
                self.console.write(s)

            total_done = common.fsize(status["total_done"])
            total_size = common.fsize(status["total_size"])
            if total_done == total_size:
                s = "{!info!}Size: {!input!}%s" % (total_size)
            else:
                s = "{!info!}Size: {!input!}%s/%s" % (total_done, total_size)
            s += " {!info!}Ratio: {!input!}%.3f" % status["ratio"]
            s += " {!info!}Uploaded: {!input!}%s" % common.fsize(status["ratio"] * status["total_done"])
            self.console.write(s)

            s = "{!info!}Tracker: {!input!}%s" % status["tracker"]
            self.console.write(s)


            if not status["is_finished"]:
                pbar = format_progressbar(status["progress"], cols - (13 + len("%.2f%%" % status["progress"])))
                s = "{!info!}Progress: {!input!}%.2f%% %s" % (status["progress"], pbar)
                self.console.write(s)

            s = "{!info!}Download location: {!input!}%s" % status["save_path"]
            self.console.write(s)

            if detailed:
                self.console.write("{!info!}Files in torrent")
                self.show_file_info(torrent_id, status)
                self.console.write("{!info!}Connected peers")
                self.show_peer_info(torrent_id, status)
        else:
            self.console.write(" ")
            up_color = colors.state_color["Seeding"]
            down_color = colors.state_color["Downloading"]

            s = "%s%s" % (colors.state_color[status["state"]], "[" + status["state"][0] + "]")

            s+= " {!info!}" + ("%.2f%%" % status["progress"]).ljust(7, " ")
            s+= " {!input!}%s" % (status["name"])

            #Shorten the ID if it's necessary. Pretty hacky
            #I _REALLY_ should make a nice function for it that can partition and shorten stuff
            space_left = cols - strwidth("[s] 100.00% " + status["name"] + " "*3) - 2

            if space_left >= len(torrent_id) - 2:
                #There's enough space, print it
                s += " {!cyan!}%s" % torrent_id
            else:
                #Shorten the ID
                a = int(space_left * 2/3.0)
                b = space_left - a
                if a < 8:
                    b = b - (8-a)
                    a = 8
                    if b < 0:
                        a+= b
                        b = 0
                if a > 8:
                    #Print the shortened ID
                    s += " {!cyan!}%s" % (torrent_id[0:a] + ".." + torrent_id[-b-1:-1])
                else:
                    #It has wrapped over to the second row anyway
                    s += " {!cyan!}%s" % torrent_id
            self.console.write(s)

            dl_info = "{!info!}DL: {!input!}"
            dl_info+= "%s" % common.fsize(status["total_done"])
            if status["total_done"] != status["total_size"]:
                dl_info+= "/%s" % common.fsize(status["total_size"])
            if status["download_payload_rate"] > 0:
                dl_info += " @ %s%s" % (down_color, common.fspeed(status["download_payload_rate"]))

            ul_info = " {!info!}UL: {!input!}"
            ul_info+= "%s" % common.fsize(status["ratio"] * status["total_done"])
            if status["upload_payload_rate"] > 0:
                ul_info += " @ %s%s" % (up_color, common.fspeed(status["upload_payload_rate"]))

            eta = ""
            if common.ftime(status["eta"]):
                eta = " {!info!}ETA: {!magenta!}%s" % common.ftime(status["eta"])

            self.console.write("    " + dl_info + ul_info + eta)
        self.console.set_batch_write(False)
Esempio n. 16
0
 def test_ftime(self):
     self.assertEqual(ftime(0), '')
     self.assertEqual(ftime(5), '5s')
     self.assertEqual(ftime(100), '1m 40s')
     self.assertEqual(ftime(3789), '1h 3m')
     self.assertEqual(ftime(23011), '6h 23m')
     self.assertEqual(ftime(391187), '4d 12h')
     self.assertEqual(ftime(604800), '1w 0d')
     self.assertEqual(ftime(13893086), '22w 6d')
     self.assertEqual(ftime(59740269), '1y 46w')
     self.assertEqual(ftime(61.25), '1m 1s')
     self.assertEqual(ftime(119.9), '1m 59s')
Esempio n. 17
0
    def show_info(self, torrent_id, status, verbose=False):
        """
        Writes out the torrents information to the screen.

        :param torrent_id: str, the torrent_id
        :param status: dict, the torrents status, this should have the same keys
            as status_keys
        :param verbose: bool, if true, we print out more information about the
            the torrent
        """
        self.console.set_batch_write(True)

        self.console.write(" ")
        self.console.write("{!info!}Name: {!input!}%s" % (status["name"]))
        self.console.write("{!info!}ID: {!input!}%s" % (torrent_id))
        s = "{!info!}State: %s%s" % (colors.state_color[status["state"]],
                                     status["state"])
        # Only show speed if active
        if status["state"] in ("Seeding", "Downloading"):
            if status["state"] != "Seeding":
                s += " {!info!}Down Speed: {!input!}%s" % common.fspeed(
                    status["download_payload_rate"])
            s += " {!info!}Up Speed: {!input!}%s" % common.fspeed(
                status["upload_payload_rate"])

            if common.ftime(status["eta"]):
                s += " {!info!}ETA: {!input!}%s" % common.ftime(status["eta"])

        self.console.write(s)

        if status["state"] in ("Seeding", "Downloading", "Queued"):
            s = "{!info!}Seeds: {!input!}%s (%s)" % (status["num_seeds"],
                                                     status["total_seeds"])
            s += " {!info!}Peers: {!input!}%s (%s)" % (status["num_peers"],
                                                       status["total_peers"])
            s += " {!info!}Availability: {!input!}%.2f" % status[
                "distributed_copies"]
            self.console.write(s)

        s = "{!info!}Size: {!input!}%s/%s" % (common.fsize(
            status["total_done"]), common.fsize(status["total_size"]))
        s += " {!info!}Ratio: {!input!}%.3f" % status["ratio"]
        self.console.write(s)

        s = "{!info!}Seed time: {!input!}%s" % format_time(
            status["seeding_time"])
        s += " {!info!}Active: {!input!}%s" % format_time(
            status["active_time"])
        self.console.write(s)
        self.console.write("{!info!}Tracker status: {!input!}%s" %
                           status["tracker_status"])

        if not status["is_finished"]:
            if hasattr(self.console, "screen"):
                cols = self.console.screen.cols
            else:
                cols = 80

            pbar = format_progressbar(
                status["progress"],
                cols - (13 + len("%.2f%%" % status["progress"])))
            s = "{!info!}Progress: {!input!}%.2f%% %s" % (status["progress"],
                                                          pbar)
            self.console.write(s)

        if verbose:
            self.console.write("  {!info!}::Files")
            for i, f in enumerate(status["files"]):
                s = "    {!input!}%s (%s)" % (f["path"], common.fsize(
                    f["size"]))
                s += " {!info!}Progress: {!input!}%.2f%%" % (
                    status["file_progress"][i] * 100)
                s += " {!info!}Priority:"
                fp = common.FILE_PRIORITY[status["file_priorities"]
                                          [i]].replace("Priority", "")
                if fp == "Do Not Download":
                    s += "{!error!}"
                else:
                    s += "{!success!}"

                s += " %s" % (fp)
                # Check if this is too long for the screen and reduce the path
                # if necessary
                if hasattr(self.console, "screen"):
                    cols = self.console.screen.cols
                    slen = colors.get_line_length(s,
                                                  self.console.screen.encoding)
                    if slen > cols:
                        s = s.replace(f["path"], f["path"][slen - cols + 1:])
                self.console.write(s)

            self.console.write("  {!info!}::Peers")
            if len(status["peers"]) == 0:
                self.console.write("    None")
            else:
                s = ""
                for peer in status["peers"]:
                    if peer["seed"]:
                        s += "%sSeed\t{!input!}" % colors.state_color["Seeding"]
                    else:
                        s += "%sPeer\t{!input!}" % colors.state_color[
                            "Downloading"]

                    s += peer["country"] + "\t"

                    if peer["ip"].count(":") == 1:
                        # IPv4
                        s += peer["ip"]
                    else:
                        # IPv6
                        s += "[%s]:%s" % (":".join(peer["ip"].split(":")[:-1]),
                                          peer["ip"].split(":")[-1])

                    c = peer["client"]
                    s += "\t" + c

                    if len(c) < 16:
                        s += "\t\t"
                    else:
                        s += "\t"
                    s += "%s%s\t%s%s" % (colors.state_color["Seeding"],
                                         common.fspeed(peer["up_speed"]),
                                         colors.state_color["Downloading"],
                                         common.fspeed(peer["down_speed"]))
                    s += "\n"

                self.console.write(s[:-1])

        self.console.set_batch_write(False)
Esempio n. 18
0
def ftime_or_dash(value):
    """Display value as time, eg 2h 30m or dash"""
    return ftime(value) if value > 0 else '-'