예제 #1
0
def print_totals(totals):
    for name, value in totals.items():
        print(name, fsize(value))

    print('overhead:')
    print('up:', fsize(totals['total_upload'] - totals['total_payload_upload']))
    print('down:', fsize(totals['total_download'] - totals['total_payload_download']))
예제 #2
0
파일: test_total.py 프로젝트: Ashod/Deluge
def print_totals(totals):
    for name, value in totals.iteritems():
        print name , fsize(value)

    print "overhead:"
    print "up:", fsize(totals["total_upload"]  - totals["total_payload_upload"] )
    print "down:", fsize(totals["total_download"]  - totals["total_payload_download"] )
예제 #3
0
def print_totals(totals):
    for name, value in totals.iteritems():
        print name, fsize(value)

    print "overhead:"
    print "up:", fsize(totals["total_upload"] - totals["total_payload_upload"])
    print "down:", fsize(totals["total_download"] -
                         totals["total_payload_download"])
예제 #4
0
 def on_part(data, current_length, total_length):
     if total_length:
         percent = current_length / total_length
         pb.set_fraction(percent)
         pb.set_text('%.2f%% (%s / %s)' %
                     (percent * 100, fsize(current_length),
                      fsize(total_length)))
     else:
         pb.pulse()
         pb.set_text('%s' % fsize(current_length))
예제 #5
0
    def log_rpc_stats(self):
        """Log RPC statistics for thinclient mode."""
        if not client.connected():
            return

        t = time.time()
        recv = client.get_bytes_recv()
        sent = client.get_bytes_sent()
        delta_time = t - self.daemon_bps[0]
        delta_sent = sent - self.daemon_bps[1]
        delta_recv = recv - self.daemon_bps[2]
        self.daemon_bps = (t, sent, recv)
        sent_rate = fspeed(delta_sent / delta_time)
        recv_rate = fspeed(delta_recv / delta_time)
        log.debug('RPC: Sent %s (%s) Recv %s (%s)', fsize(sent), sent_rate, fsize(recv), recv_rate)
예제 #6
0
 def _on_get_free_space(self, space):
     if space >= 0:
         self.diskspace_item.set_markup('<small>%s</small>' %
                                        fsize(space, shortform=True))
     else:
         self.diskspace_item.set_markup('<span foreground="red">' +
                                        _('Error') + '</span>')
예제 #7
0
    def log_rpc_stats(self):
        """Log RPC statistics for thinclient mode."""
        if not client.connected():
            return

        t = time.time()
        recv = client.get_bytes_recv()
        sent = client.get_bytes_sent()
        delta_time = t - self.daemon_bps[0]
        delta_sent = sent - self.daemon_bps[1]
        delta_recv = recv - self.daemon_bps[2]
        self.daemon_bps = (t, sent, recv)
        sent_rate = fspeed(delta_sent / delta_time)
        recv_rate = fspeed(delta_recv / delta_time)
        log.debug('RPC: Sent %s (%s) Recv %s (%s)', fsize(sent), sent_rate,
                  fsize(recv), recv_rate)
예제 #8
0
    def draw_files(self, files, depth, off, idx):

        color_selected = 'blue'
        color_partially_selected = 'magenta'
        color_highlighted = 'white'
        for fl in files:
            # from sys import stderr
            # print >> stderr, fl[6]
            # kick out if we're going to draw too low on the screen
            if off >= self.rows - 1:
                self.more_to_draw = True
                return -1, -1

            # default color values
            fg = 'white'
            bg = 'black'
            attr = ''

            priority_fg_color = {
                -2: 'white',  # Mixed
                0: 'red',  # Skip
                1: 'yellow',  # Low
                2: 'yellow',
                3: 'yellow',
                4: 'white',  # Normal
                5: 'green',
                6: 'green',
                7: 'green',  # High
            }

            fg = priority_fg_color[fl[6]]

            if idx >= self.file_off:
                # set fg/bg colors based on whether the file is selected/marked or not

                if fl[1] in self.marked:
                    bg = color_selected
                    if fl[3]:
                        if self.marked[
                                fl[1]] < self.__get_contained_files_count(
                                    file_list=fl[3]):
                            bg = color_partially_selected
                    attr = 'bold'

                if idx == self.current_file_idx:
                    self.current_file = fl
                    bg = color_highlighted
                    if fl[1] in self.marked:
                        fg = color_selected
                        if fl[3]:
                            if self.marked[
                                    fl[1]] < self.__get_contained_files_count(
                                        file_list=fl[3]):
                                fg = color_partially_selected
                    else:
                        if fg == 'white':
                            fg = 'black'
                        attr = 'bold'

                if attr:
                    color_string = '{!%s,%s,%s!}' % (fg, bg, attr)
                else:
                    color_string = '{!%s,%s!}' % (fg, bg)

                # actually draw the dir/file string
                if fl[3] and fl[4]:  # this is an expanded directory
                    xchar = 'v'
                elif fl[3]:  # collapsed directory
                    xchar = '>'
                else:  # file
                    xchar = '-'

                r = format_row(
                    [
                        '%s%s %s' % (' ' * depth, xchar, fl[0]),
                        fsize(fl[2]),
                        fl[5],
                        format_priority(fl[6]),
                    ],
                    self.column_widths,
                )

                self.add_string(off, '%s%s' % (color_string, r), trim=False)
                off += 1

            if fl[3] and fl[4]:
                # recurse if we have children and are expanded
                off, idx = self.draw_files(fl[3], depth + 1, off, idx + 1)
                if off < 0:
                    return (off, idx)
            else:
                idx += 1

        return (off, idx)
예제 #9
0
def fpieces_num_size(num_pieces, piece_size):
    return '%s (%s)' % (num_pieces, fsize(piece_size, precision=0))
예제 #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__())
def cell_data_size(column, cell, model, row, data):
    """Display value in terms of size, eg. 2 MB"""
    size = model.get_value(row, data)
    cell.set_property('text', common.fsize(size, shortform=True))
예제 #12
0
    'eta': 'ETA',
    'error': 'Error',
    'not_magnet': 'Aw man... That\'s not a magnet link',
    'not_file': 'Aw man... That\'s not a torrent file',
    'not_url': 'Aw man... Bad link',
    'download_fail': 'Aw man... Download failed',
    'no_items': 'No items'
}

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):
예제 #13
0
           'added': 'Added',
           'eta': 'ETA',
           'error': 'Error',
           'not_magnet': 'Aw man... That\'s not a magnet link',
           'not_file': 'Aw man... That\'s not a torrent file',
           'not_url': 'Aw man... Bad link',
           'download_fail': 'Aw man... Download failed',
           'no_items': 'No items'}

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]
예제 #14
0
파일: info.py 프로젝트: zluca/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

        sep = ' '

        if verbose or detailed:
            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 += sep
                    s += '{!info!}Down Speed: {!input!}%s' % fspeed(
                        status['download_payload_rate'], shortform=True)
                s += sep
                s += '{!info!}Up Speed: {!input!}%s' % fspeed(
                    status['upload_payload_rate'], shortform=True)
            self.console.write(s)

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

            total_done = fsize(status['total_done'], shortform=True)
            total_size = fsize(status['total_size'], shortform=True)
            if total_done == total_size:
                s = '{!info!}Size: {!input!}%s' % (total_size)
            else:
                s = '{!info!}Size: {!input!}%s/%s' % (total_done, total_size)
            s += sep
            s += '{!info!}Downloaded: {!input!}%s' % fsize(
                status['all_time_download'], shortform=True)
            s += sep
            s += '{!info!}Uploaded: {!input!}%s' % fsize(
                status['total_uploaded'], shortform=True)
            s += sep
            s += '{!info!}Share Ratio: {!input!}%.2f' % status['ratio']
            self.console.write(s)

            s = '{!info!}ETA: {!input!}%s' % format_time(status['eta'])
            s += sep
            s += '{!info!}Seeding: {!input!}%s' % format_time(
                status['seeding_time'])
            s += sep
            s += '{!info!}Active: {!input!}%s' % format_time(
                status['active_time'])
            self.console.write(s)

            s = '{!info!}Last Transfer: {!input!}%s' % format_time(
                status['time_since_transfer'])
            s += sep
            s += '{!info!}Complete Seen: {!input!}%s' % format_date_never(
                status['last_seen_complete'])
            self.console.write(s)

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

            self.console.write('{!info!}Tracker status: {!input!}%s' %
                               status['tracker_status'])

            if not status['is_finished']:
                pbar = f_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 Folder: {!input!}%s' % status[
                'download_location']
            self.console.write(s + '\n')

            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:
            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!}' + format_progress(status['progress']).rjust(
                6, ' ')
            s += ' {!input!}%s' % (status['name'])

            # Shorten the ID if it's necessary. Pretty hacky
            # XXX: should make a nice function for it that can partition and shorten stuff
            space_left = cols - strwidth('[S] 99.99% ' + status['name'])

            if self.console.interactive and space_left >= len(sep +
                                                              torrent_id):
                # Not enough line space so shorten the hash (for interactive mode).
                torrent_id = shorten_hash(torrent_id, space_left)
            s += sep
            s += '{!cyan!}%s' % torrent_id
            self.console.write(s)

            dl_info = '{!info!}DL: {!input!}'
            dl_info += '%s' % ftotal_sized(status['all_time_download'],
                                           status['total_payload_download'])

            if status['download_payload_rate'] > 0:
                dl_info += ' @ %s%s' % (
                    down_color,
                    fspeed(status['download_payload_rate'], shortform=True),
                )

            ul_info = ' {!info!}UL: {!input!}'
            ul_info += '%s' % ftotal_sized(status['total_uploaded'],
                                           status['total_payload_upload'])
            if status['upload_payload_rate'] > 0:
                ul_info += ' @ %s%s' % (
                    up_color,
                    fspeed(status['upload_payload_rate'], shortform=True),
                )

            eta = ' {!info!}ETA: {!magenta!}%s' % format_time(status['eta'])

            self.console.write('    ' + dl_info + ul_info + eta + '\n')

        self.console.set_batch_write(False)
예제 #15
0
def fpieces_num_size(num_pieces, piece_size):
    return '%s (%s)' % (num_pieces, fsize(piece_size, precision=0))
예제 #16
0
def cell_data_size(column, cell, model, row, data):
    """Display value in terms of size, eg. 2 MB"""
    size = model.get_value(row, data)
    cell.set_property('text', common.fsize(size, shortform=True))
예제 #17
0
 def test_fsize(self):
     self.assertEqual(fsize(0), '0 B')
     self.assertEqual(fsize(100), '100 B')
     self.assertEqual(fsize(1023), '1023 B')
     self.assertEqual(fsize(1024), '1.0 KiB')
     self.assertEqual(fsize(1048575), '1024.0 KiB')
     self.assertEqual(fsize(1048576), '1.0 MiB')
     self.assertEqual(fsize(1073741823), '1024.0 MiB')
     self.assertEqual(fsize(1073741824), '1.0 GiB')
     self.assertEqual(fsize(112245), '109.6 KiB')
     self.assertEqual(fsize(110723441824), '103.1 GiB')
     self.assertEqual(fsize(1099511627775), '1024.0 GiB')
     self.assertEqual(fsize(1099511627777), '1.0 TiB')
     self.assertEqual(fsize(766148267453245), '696.8 TiB')
예제 #18
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__())
예제 #19
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)
예제 #20
0
    def show_file_info(self, torrent_id, status):
        SPACES_PER_LEVEL = 2

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

        dirs = []
        prevpath = []
        for i, file in enumerate(status["files"]):
            filename = file["path"].split(dirsep)[-1]
            filepath = file["path"].split(dirsep)[:-1]

            for depth, subdir in enumerate(filepath):
                indent = " " * depth * SPACES_PER_LEVEL
                if depth >= len(prevpath):
                    self.console.write("%s{!cyan!}%s" % (indent, subdir))
                elif subdir != prevpath[depth]:
                    self.console.write("%s{!cyan!}%s" % (indent, subdir))

            depth = len(filepath)

            indent = " " * depth * SPACES_PER_LEVEL

            col_filename = indent + filename
            col_size = " ({!cyan!}%s{!input!})" % common.fsize(file["size"])
            col_progress = " {!input!}%.2f%%" % (status["file_progress"][i] *
                                                 100)

            col_priority = " {!info!}Priority: "

            fp = common.FILE_PRIORITY[status["file_priorities"][i]].replace(
                "Priority", "")
            if status["file_progress"][i] != 1.0:
                if fp == "Do Not Download":
                    col_priority += "{!error!}"
                else:
                    col_priority += "{!success!}"
            else:
                col_priority += "{!input!}"
            col_priority += fp

            rf = format_utils.remove_formatting
            tlen = lambda s: strwidth(rf(s))

            if not isinstance(col_filename, unicode):
                col_filename = unicode(col_filename, 'utf-8')

            col_all_info = col_size + col_progress + col_priority
            #Check how much space we've got left after writing all the info
            space_left = cols - tlen(col_all_info)
            #And how much we will potentially have with the longest possible column
            maxlen_space_left = cols - tlen(
                " (1000.0 MiB) 100.00% Priority: Do Not Download")
            if maxlen_space_left > tlen(col_filename) + 1:
                #If there is enough space, pad it all nicely
                col_all_info = ""
                col_all_info += " ("
                spaces_to_add = tlen(" (1000.0 MiB)") - tlen(col_size)
                col_all_info += " " * spaces_to_add
                col_all_info += col_size[2:]
                spaces_to_add = tlen(" 100.00%") - tlen(col_progress)
                col_all_info += " " * spaces_to_add
                col_all_info += col_progress
                spaces_to_add = tlen(" Priority: Do Not Download") - tlen(
                    col_priority)
                col_all_info += col_priority
                col_all_info += " " * spaces_to_add
                #And remember to put it to the left!
                col_filename = format_utils.pad_string(col_filename,
                                                       maxlen_space_left - 2,
                                                       side="right")
            elif space_left > tlen(col_filename) + 1:
                #If there is enough space, put the info to the right
                col_filename = format_utils.pad_string(col_filename,
                                                       space_left - 2,
                                                       side="right")
            else:
                #And if there is not, shorten the name
                col_filename = format_utils.trim_string(
                    col_filename, space_left, True)
            self.console.write(col_filename + col_all_info)

            prevpath = filepath
예제 #21
0
    def render_header(self, row):
        status = self.torrent_state

        download_color = '{!info!}'
        if status['download_payload_rate'] > 0:
            download_color = colors.state_color['Downloading']

        def add_field(name, row, pre_color='{!info!}', post_color='{!input!}'):
            s = '%s%s: %s%s' % (
                pre_color,
                torrent_data_fields[name]['name'],
                post_color,
                get_column_value(name, status),
            )
            if row:
                row = self.add_string(row, s)
                return row
            return s

        # Name
        row = add_field('name', row)
        # State
        row = add_field('state', row)

        # Print DL info and ETA
        s = add_field('downloaded', 0, download_color)
        if status['progress'] != 100.0:
            s += '/%s' % fsize(status['total_wanted'])
        if status['download_payload_rate'] > 0:
            s += ' {!yellow!}@ %s%s' % (
                download_color,
                fsize(status['download_payload_rate']),
            )
            s += add_field('eta', 0)
        if s:
            row = self.add_string(row, s)

        # Print UL info and ratio
        s = add_field('uploaded', 0, download_color)
        if status['upload_payload_rate'] > 0:
            s += ' {!yellow!}@ %s%s' % (
                colors.state_color['Seeding'],
                fsize(status['upload_payload_rate']),
            )
        s += ' ' + add_field('ratio', 0)
        row = self.add_string(row, s)

        # Seed/peer info
        s = '{!info!}%s:{!green!} %s {!input!}(%s)' % (
            torrent_data_fields['seeds']['name'],
            status['num_seeds'],
            status['total_seeds'],
        )
        row = self.add_string(row, s)
        s = '{!info!}%s:{!red!} %s {!input!}(%s)' % (
            torrent_data_fields['peers']['name'],
            status['num_peers'],
            status['total_peers'],
        )
        row = self.add_string(row, s)

        # Tracker
        tracker_color = '{!green!}' if status['message'] == 'OK' else '{!red!}'
        s = '{!info!}%s: {!magenta!}%s{!input!} says "%s%s{!input!}"' % (
            torrent_data_fields['tracker']['name'],
            status['tracker_host'],
            tracker_color,
            status['message'],
        )
        row = self.add_string(row, s)

        # Pieces and availability
        s = '{!info!}%s: {!yellow!}%s {!input!}x {!yellow!}%s' % (
            torrent_data_fields['pieces']['name'],
            status['num_pieces'],
            fsize(status['piece_length']),
        )
        if status['distributed_copies']:
            s += '{!info!}%s: {!input!}%s' % (
                torrent_data_fields['seed_rank']['name'],
                status['seed_rank'],
            )
        row = self.add_string(row, s)

        # Time added
        row = add_field('time_added', row)
        # Time active
        row = add_field('active_time', row)
        if status['seeding_time']:
            row = add_field('seeding_time', row)
        # Download Folder
        row = add_field('download_location', row)
        # Seed Rank
        row = add_field('seed_rank', row)
        # Super Seeding
        row = add_field('super_seeding', row)
        # Last seen complete
        row = add_field('last_seen_complete', row)
        # Last activity
        row = add_field('time_since_transfer', row)
        # Owner
        if status['owner']:
            row = add_field('owner', row)
        return row
예제 #22
0
파일: info.py 프로젝트: Ashod/Deluge
    def show_file_info(self, torrent_id, status):
        SPACES_PER_LEVEL = 2

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

        dirs = []
        prevpath = []
        for i, file in enumerate(status["files"]):
            filename = file["path"].split(dirsep)[-1]
            filepath = file["path"].split(dirsep)[:-1]

            for depth, subdir in enumerate(filepath):
                indent = " "*depth*SPACES_PER_LEVEL
                if   depth >= len(prevpath):
                    self.console.write("%s{!cyan!}%s" % (indent, subdir))
                elif subdir != prevpath[depth]:
                    self.console.write("%s{!cyan!}%s" % (indent, subdir))

            depth = len(filepath)

            indent = " " * depth * SPACES_PER_LEVEL

            col_filename = indent + filename
            col_size = " ({!cyan!}%s{!input!})" % common.fsize(file["size"])
            col_progress = " {!input!}%.2f%%" % (status["file_progress"][i] * 100)

            col_priority = " {!info!}Priority: "

            fp = common.FILE_PRIORITY[status["file_priorities"][i]].replace("Priority", "")
            if status["file_progress"][i] != 1.0:
                if fp == "Do Not Download":
                    col_priority += "{!error!}"
                else:
                    col_priority += "{!success!}"
            else:
                col_priority += "{!input!}"
            col_priority+= fp

            rf = format_utils.remove_formatting
            tlen = lambda s: strwidth(rf(s))

            if not isinstance(col_filename, unicode):
                col_filename = unicode(col_filename, 'utf-8')

            col_all_info = col_size + col_progress + col_priority
            #Check how much space we've got left after writing all the info
            space_left = cols - tlen(col_all_info)
            #And how much we will potentially have with the longest possible column
            maxlen_space_left = cols - tlen(" (1000.0 MiB) 100.00% Priority: Do Not Download")
            if   maxlen_space_left > tlen(col_filename) + 1:
                #If there is enough space, pad it all nicely
                col_all_info = ""
                col_all_info += " ("
                spaces_to_add = tlen(" (1000.0 MiB)") - tlen(col_size)
                col_all_info += " " * spaces_to_add
                col_all_info += col_size[2:]
                spaces_to_add = tlen(" 100.00%") - tlen(col_progress)
                col_all_info += " " * spaces_to_add
                col_all_info += col_progress
                spaces_to_add = tlen(" Priority: Do Not Download") - tlen(col_priority)
                col_all_info += col_priority
                col_all_info += " " * spaces_to_add
                #And remember to put it to the left!
                col_filename = format_utils.pad_string(col_filename, maxlen_space_left - 2, side = "right")
            elif space_left > tlen(col_filename) + 1:
                #If there is enough space, put the info to the right
                col_filename = format_utils.pad_string(col_filename, space_left - 2, side = "right")
            else:
                #And if there is not, shorten the name
                col_filename = format_utils.trim_string( col_filename, space_left, True)
            self.console.write(col_filename + col_all_info)


            prevpath = filepath
예제 #23
0
파일: info.py 프로젝트: zluca/deluge
    def show_file_info(self, torrent_id, status):
        spaces_per_level = 2

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

        prevpath = []
        for index, torrent_file in enumerate(status['files']):
            filename = torrent_file['path'].split(dirsep)[-1]
            filepath = torrent_file['path'].split(dirsep)[:-1]

            for depth, subdir in enumerate(filepath):
                indent = ' ' * depth * spaces_per_level
                if depth >= len(prevpath):
                    self.console.write('%s{!cyan!}%s' % (indent, subdir))
                elif subdir != prevpath[depth]:
                    self.console.write('%s{!cyan!}%s' % (indent, subdir))

            depth = len(filepath)

            indent = ' ' * depth * spaces_per_level

            col_filename = indent + filename
            col_size = ' ({!cyan!}%s{!input!})' % fsize(torrent_file['size'])
            col_progress = ' {!input!}%.2f%%' % (
                status['file_progress'][index] * 100)

            col_priority = ' {!info!}Priority: '

            file_priority = FILE_PRIORITY[status['file_priorities'][index]]

            if status['file_progress'][index] != 1.0:
                if file_priority == 'Skip':
                    col_priority += '{!error!}'
                else:
                    col_priority += '{!success!}'
            else:
                col_priority += '{!input!}'
            col_priority += file_priority

            def tlen(string):
                return strwidth(remove_formatting(string))

            col_all_info = col_size + col_progress + col_priority
            # Check how much space we've got left after writing all the info
            space_left = cols - tlen(col_all_info)
            # And how much we will potentially have with the longest possible column
            maxlen_space_left = cols - tlen(
                ' (1000.0 MiB) 100.00% Priority: Normal')
            if maxlen_space_left > tlen(col_filename) + 1:
                # If there is enough space, pad it all nicely
                col_all_info = ''
                col_all_info += ' ('
                spaces_to_add = tlen(' (1000.0 MiB)') - tlen(col_size)
                col_all_info += ' ' * spaces_to_add
                col_all_info += col_size[2:]
                spaces_to_add = tlen(' 100.00%') - tlen(col_progress)
                col_all_info += ' ' * spaces_to_add
                col_all_info += col_progress
                spaces_to_add = tlen(' Priority: Normal') - tlen(col_priority)
                col_all_info += col_priority
                col_all_info += ' ' * spaces_to_add
                # And remember to put it to the left!
                col_filename = pad_string(col_filename,
                                          maxlen_space_left - 2,
                                          side='right')
            elif space_left > tlen(col_filename) + 1:
                # If there is enough space, put the info to the right
                col_filename = pad_string(col_filename,
                                          space_left - 2,
                                          side='right')
            else:
                # And if there is not, shorten the name
                col_filename = trim_string(col_filename, space_left, True)
            self.console.write(col_filename + col_all_info)

            prevpath = filepath
예제 #24
0
def fsize2(size, second_size=None):
    if second_size:
        return "%s (%s)" % (fsize(size), fsize(second_size))
    return fsize(size)
예제 #25
0
    def show_file_info(self, torrent_id, status):
        spaces_per_level = 2

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

        prevpath = []
        for index, torrent_file in enumerate(status['files']):
            filename = torrent_file['path'].split(dirsep)[-1]
            filepath = torrent_file['path'].split(dirsep)[:-1]

            for depth, subdir in enumerate(filepath):
                indent = ' ' * depth * spaces_per_level
                if depth >= len(prevpath):
                    self.console.write('%s{!cyan!}%s' % (indent, subdir))
                elif subdir != prevpath[depth]:
                    self.console.write('%s{!cyan!}%s' % (indent, subdir))

            depth = len(filepath)

            indent = ' ' * depth * spaces_per_level

            col_filename = indent + filename
            col_size = ' ({!cyan!}%s{!input!})' % fsize(torrent_file['size'])
            col_progress = ' {!input!}%.2f%%' % (status['file_progress'][index] * 100)

            col_priority = ' {!info!}Priority: '

            file_priority = FILE_PRIORITY[status['file_priorities'][index]].replace('Priority', '')
            if status['file_progress'][index] != 1.0:
                if file_priority == 'Do Not Download':
                    col_priority += '{!error!}'
                else:
                    col_priority += '{!success!}'
            else:
                col_priority += '{!input!}'
            col_priority += file_priority

            def tlen(string):
                return strwidth(remove_formatting(string))

            col_all_info = col_size + col_progress + col_priority
            # Check how much space we've got left after writing all the info
            space_left = cols - tlen(col_all_info)
            # And how much we will potentially have with the longest possible column
            maxlen_space_left = cols - tlen(' (1000.0 MiB) 100.00% Priority: Do Not Download')
            if maxlen_space_left > tlen(col_filename) + 1:
                # If there is enough space, pad it all nicely
                col_all_info = ''
                col_all_info += ' ('
                spaces_to_add = tlen(' (1000.0 MiB)') - tlen(col_size)
                col_all_info += ' ' * spaces_to_add
                col_all_info += col_size[2:]
                spaces_to_add = tlen(' 100.00%') - tlen(col_progress)
                col_all_info += ' ' * spaces_to_add
                col_all_info += col_progress
                spaces_to_add = tlen(' Priority: Do Not Download') - tlen(col_priority)
                col_all_info += col_priority
                col_all_info += ' ' * spaces_to_add
                # And remember to put it to the left!
                col_filename = pad_string(col_filename, maxlen_space_left - 2, side='right')
            elif space_left > tlen(col_filename) + 1:
                # If there is enough space, put the info to the right
                col_filename = pad_string(col_filename, space_left - 2, side='right')
            else:
                # And if there is not, shorten the name
                col_filename = trim_string(col_filename, space_left, True)
            self.console.write(col_filename + col_all_info)

            prevpath = filepath
예제 #26
0
파일: info.py 프로젝트: 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)
예제 #27
0
def ftotal_sized(first, second):
    return '%s (%s)' % (fsize(first,
                              shortform=True), fsize(second, shortform=True))
예제 #28
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

        sep = ' '

        if verbose or detailed:
            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 += sep
                    s += '{!info!}Down Speed: {!input!}%s' % fspeed(
                        status['download_payload_rate'], shortform=True)
                s += sep
                s += '{!info!}Up Speed: {!input!}%s' % fspeed(
                    status['upload_payload_rate'], shortform=True)
            self.console.write(s)

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

            total_done = fsize(status['total_done'], shortform=True)
            total_size = fsize(status['total_size'], shortform=True)
            if total_done == total_size:
                s = '{!info!}Size: {!input!}%s' % (total_size)
            else:
                s = '{!info!}Size: {!input!}%s/%s' % (total_done, total_size)
            s += sep
            s += '{!info!}Downloaded: {!input!}%s' % fsize(status['all_time_download'], shortform=True)
            s += sep
            s += '{!info!}Uploaded: {!input!}%s' % fsize(status['total_uploaded'], shortform=True)
            s += sep
            s += '{!info!}Share Ratio: {!input!}%.2f' % status['ratio']
            self.console.write(s)

            s = '{!info!}ETA: {!input!}%s' % format_time(status['eta'])
            s += sep
            s += '{!info!}Seeding: {!input!}%s' % format_time(status['seeding_time'])
            s += sep
            s += '{!info!}Active: {!input!}%s' % format_time(status['active_time'])
            self.console.write(s)

            s = '{!info!}Last Transfer: {!input!}%s' % format_time(status['time_since_transfer'])
            s += sep
            s += '{!info!}Complete Seen: {!input!}%s' % format_date_never(
                status['last_seen_complete'])
            self.console.write(s)

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

            self.console.write('{!info!}Tracker status: {!input!}%s' % status['tracker_status'])

            if not status['is_finished']:
                pbar = f_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 Folder: {!input!}%s' % status['download_location']
            self.console.write(s + '\n')

            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:
            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!}' + format_progress(status['progress']).rjust(6, ' ')
            s += ' {!input!}%s' % (status['name'])

            # Shorten the ID if it's necessary. Pretty hacky
            # XXX: should make a nice function for it that can partition and shorten stuff
            space_left = cols - strwidth('[S] 99.99% ' + status['name'])

            if self.console.interactive and space_left >= len(sep + torrent_id):
                # Not enough line space so shorten the hash (for interactive mode).
                torrent_id = shorten_hash(torrent_id, space_left)
            s += sep
            s += '{!cyan!}%s' % torrent_id
            self.console.write(s)

            dl_info = '{!info!}DL: {!input!}'
            dl_info += '%s' % ftotal_sized(status['all_time_download'], status['total_payload_download'])

            if status['download_payload_rate'] > 0:
                dl_info += ' @ %s%s' % (down_color, fspeed(
                    status['download_payload_rate'], shortform=True))

            ul_info = ' {!info!}UL: {!input!}'
            ul_info += '%s' % ftotal_sized(status['total_uploaded'], status['total_payload_upload'])
            if status['upload_payload_rate'] > 0:
                ul_info += ' @ %s%s' % (up_color, fspeed(
                    status['upload_payload_rate'], shortform=True))

            eta = ' {!info!}ETA: {!magenta!}%s' % format_time(status['eta'])

            self.console.write('    ' + dl_info + ul_info + eta + '\n')

        self.console.set_batch_write(False)
예제 #29
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
예제 #30
0
def fsize2(size, second_size=None):
    if second_size:
        return "%s (%s)" % (fsize(size), fsize(second_size))
    return fsize(size)
예제 #31
0
파일: info.py 프로젝트: s0undt3ch/Deluge
    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)
예제 #32
0
def fpieces(pieces, length):
    return "%s (%s)" % (pieces, fsize(length))
예제 #33
0
def fpieces(pieces, length):
    return "%s (%s)" % (pieces, fsize(length))
예제 #34
0
    def draw_files(self, files, depth, off, idx):

        color_selected = 'blue'
        color_partially_selected = 'magenta'
        color_highlighted = 'white'
        for fl in files:
            # from sys import stderr
            # print >> stderr, fl[6]
            # kick out if we're going to draw too low on the screen
            if off >= self.rows - 1:
                self.more_to_draw = True
                return -1, -1

            # default color values
            fg = 'white'
            bg = 'black'
            attr = ''

            priority_fg_color = {
                -2: 'white',  # Mixed
                0: 'red',  # Ignore
                1: 'yellow',  # Low
                2: 'yellow',
                3: 'yellow',
                4: 'white',  # Normal
                5: 'green',
                6: 'green',
                7: 'green'   # High
            }

            fg = priority_fg_color[fl[6]]

            if idx >= self.file_off:
                # set fg/bg colors based on whether the file is selected/marked or not

                if fl[1] in self.marked:
                    bg = color_selected
                    if fl[3]:
                        if self.marked[fl[1]] < self.__get_contained_files_count(file_list=fl[3]):
                            bg = color_partially_selected
                    attr = 'bold'

                if idx == self.current_file_idx:
                    self.current_file = fl
                    bg = color_highlighted
                    if fl[1] in self.marked:
                        fg = color_selected
                        if fl[3]:
                            if self.marked[fl[1]] < self.__get_contained_files_count(file_list=fl[3]):
                                fg = color_partially_selected
                    else:
                        if fg == 'white':
                            fg = 'black'
                        attr = 'bold'

                if attr:
                    color_string = '{!%s,%s,%s!}' % (fg, bg, attr)
                else:
                    color_string = '{!%s,%s!}' % (fg, bg)

                # actually draw the dir/file string
                if fl[3] and fl[4]:  # this is an expanded directory
                    xchar = 'v'
                elif fl[3]:  # collapsed directory
                    xchar = '>'
                else:  # file
                    xchar = '-'

                r = format_row(['%s%s %s' % (' ' * depth, xchar, fl[0]),
                                fsize(fl[2]), fl[5],
                                format_priority(fl[6])],
                               self.column_widths)

                self.add_string(off, '%s%s' % (color_string, r), trim=False)
                off += 1

            if fl[3] and fl[4]:
                # recurse if we have children and are expanded
                off, idx = self.draw_files(fl[3], depth + 1, off, idx + 1)
                if off < 0:
                    return (off, idx)
            else:
                idx += 1

        return (off, idx)
예제 #35
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
예제 #36
0
    def render_header(self, row):
        status = self.torrent_state

        download_color = '{!info!}'
        if status['download_payload_rate'] > 0:
            download_color = colors.state_color['Downloading']

        def add_field(name, row, pre_color='{!info!}', post_color='{!input!}'):
            s = '%s%s: %s%s' % (pre_color, torrent_data_fields[name]['name'],
                                post_color, get_column_value(name, status))
            if row:
                row = self.add_string(row, s)
                return row
            return s

        # Name
        row = add_field('name', row)
        # State
        row = add_field('state', row)

        # Print DL info and ETA
        s = add_field('downloaded', 0, download_color)
        if status['progress'] != 100.0:
            s += '/%s' % fsize(status['total_wanted'])
        if status['download_payload_rate'] > 0:
            s += ' {!yellow!}@ %s%s' % (download_color, fsize(status['download_payload_rate']))
            s += add_field('eta', 0)
        if s:
            row = self.add_string(row, s)

        # Print UL info and ratio
        s = add_field('uploaded', 0, download_color)
        if status['upload_payload_rate'] > 0:
            s += ' {!yellow!}@ %s%s' % (colors.state_color['Seeding'], fsize(status['upload_payload_rate']))
        s += ' ' + add_field('ratio', 0)
        row = self.add_string(row, s)

        # Seed/peer info
        s = '{!info!}%s:{!green!} %s {!input!}(%s)' % (torrent_data_fields['seeds']['name'],
                                                       status['num_seeds'], status['total_seeds'])
        row = self.add_string(row, s)
        s = '{!info!}%s:{!red!} %s {!input!}(%s)' % (torrent_data_fields['peers']['name'],
                                                     status['num_peers'], status['total_peers'])
        row = self.add_string(row, s)

        # Tracker
        tracker_color = '{!green!}' if status['message'] == 'OK' else '{!red!}'
        s = '{!info!}%s: {!magenta!}%s{!input!} says "%s%s{!input!}"' % (
            torrent_data_fields['tracker']['name'], status['tracker_host'], tracker_color, status['message'])
        row = self.add_string(row, s)

        # Pieces and availability
        s = '{!info!}%s: {!yellow!}%s {!input!}x {!yellow!}%s' % (
            torrent_data_fields['pieces']['name'], status['num_pieces'], fsize(status['piece_length']))
        if status['distributed_copies']:
            s += '{!info!}%s: {!input!}%s' % (torrent_data_fields['seed_rank']['name'], status['seed_rank'])
        row = self.add_string(row, s)

        # Time added
        row = add_field('time_added', row)
        # Time active
        row = add_field('active_time', row)
        if status['seeding_time']:
            row = add_field('seeding_time', row)
        # Download Folder
        row = add_field('download_location', row)
        # Seed Rank
        row = add_field('seed_rank', row)
        # Last seen complete
        row = add_field('last_seen_complete', row)
        # Last activity
        row = add_field('time_since_transfer', row)
        # Owner
        if status['owner']:
            row = add_field('owner', row)
        return row
예제 #37
0
 def test_fsize(self):
     self.assertEqual(fsize(0), '0 B')
     self.assertEqual(fsize(100), '100 B')
     self.assertEqual(fsize(1023), '1023 B')
     self.assertEqual(fsize(1024), '1.0 KiB')
     self.assertEqual(fsize(1048575), '1024.0 KiB')
     self.assertEqual(fsize(1048576), '1.0 MiB')
     self.assertEqual(fsize(1073741823), '1024.0 MiB')
     self.assertEqual(fsize(1073741824), '1.0 GiB')
     self.assertEqual(fsize(112245), '109.6 KiB')
     self.assertEqual(fsize(110723441824), '103.1 GiB')
     self.assertEqual(fsize(1099511627775), '1024.0 GiB')
     self.assertEqual(fsize(1099511627777), '1.0 TiB')
     self.assertEqual(fsize(766148267453245), '696.8 TiB')
예제 #38
0
 def _on_get_free_space(self, space):
     if space >= 0:
         self.diskspace_item.set_markup('<small>%s</small>' % fsize(space, shortform=True))
     else:
         self.diskspace_item.set_markup('<span foreground="red">' + _('Error') + '</span>')
예제 #39
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)
예제 #40
0
def ftotal_sized(first, second):
    return '%s (%s)' % (fsize(first, shortform=True), fsize(second, shortform=True))