#! /usr/bin/env python

"""View the local aria2 queue.

Note the aria2 XML-RPC server must be running on localhost:6800
and it needs to be a newer version (one with --enable-rpc not --enable-xml-rpc).
"""

import sys
import argparse
import xmlrpclib
import os.path
from pprint import pprint

secret = "token:ubuntu"

def main(options):
    """Main program."""
    url = os.getenv('ARIA2Q_URL', 'http://localhost:6800/rpc')
    server = xmlrpclib.ServerProxy(url)

    print("Starting interrogation to the Aria2 server...")
    keys = ['gid', 'totalLength', 'completedLength', 'status', 'downloadSpeed', 'uploadSpeed', 'bittorrent']
    jobs = server.aria2.tellActive(secret, keys)
    jobs.extend(server.aria2.tellWaiting(secret, 0, 100, keys))
    jobs.extend(server.aria2.tellStopped(secret, 0, 100, keys))
    list_jobs(server, jobs)
    return

def list_jobs(server, job_list):
    if len(job_list) == 0:
        return

    print "GID                 STATUS  PERCENT TOTSIZE DLSPEED  ULSPEED   NFILES  TORRENT NAME/FILENAME"

    for dl in job_list:
        print job_details(server, dl)

def job_details(server, job_status):
    #pprint(job_status)
        
    gid = job_status['gid']
    status = job_status['status']
    percent = percentage(job_status)
    totsize = sizeof_fmt(float(job_status['totalLength'])) 
    dlspeed = b2kb(job_status['downloadSpeed'])
    ulspeed = b2kb(job_status['uploadSpeed'])
    
    # these two make RPC calls:
    nfiles = getfilecount(server,gid)
    filename = getname(server,job_status,gid)
    
    return "%4s  %8s  %5.1f%%  %s % 4dkB/s % 4dkB/s  %d     %s" % (gid, status, percent, totsize, dlspeed, ulspeed, nfiles, filename)

def b2kb(sz):
    return int(sz)/1024
    
def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)
    
def getname(server, job_status, gid):
    try:
        filename = job_status['bittorrent']['info']['name']
    except:
        filename = os.path.basename(top_file_name(server, gid))
    
    return filename


def percentage(job_status):
    length = float(job_status['totalLength'])
    completed = float(job_status['completedLength'])
    if length > 0:
        return (completed * 100) / length
    return 0

def top_file_name(server, gid):
    return server.aria2.getFiles(secret,gid)[0]['path']

def getfilecount(server, gid):
    files = server.aria2.getFiles(secret,gid)
    #pprint(files)
    return len(files)

def get_options():
    """Get options for the script."""
    parser = argparse.ArgumentParser(
            description="view the aria2 queue on localhost:6800",
             )
    # parser.add_argument() calls here
    options = parser.parse_args()
    # extra processing of options here
    return options

if __name__ == "__main__":
    main(get_options())

c90a27691ae59de1fb666c9a0e23c1b5c8e76d46
#! /usr/bin/env python

"""View the local aria2 queue.

Note the aria2 XML-RPC server must be running on localhost:6800
and it needs to be a newer version (one with --enable-rpc not --enable-xml-rpc).
"""

import sys
import argparse
import xmlrpclib
import os.path
from pprint import pprint

secret = "token:ubuntu"

def main(options):
    """Main program."""
    url = os.getenv('ARIA2Q_URL', 'http://localhost:6800/rpc')
    server = xmlrpclib.ServerProxy(url)

    print("Starting interrogation to the Aria2 server...")
    keys = ['gid', 'totalLength', 'completedLength', 'status', 'downloadSpeed', 'uploadSpeed', 'bittorrent']
    jobs = server.aria2.tellActive(secret, keys)
    jobs.extend(server.aria2.tellWaiting(secret, 0, 100, keys))
    jobs.extend(server.aria2.tellStopped(secret, 0, 100, keys))
    list_jobs(server, jobs)
    return

def list_jobs(server, job_list):
    if len(job_list) == 0:
        return

    print "GID                 STATUS  PERCENT TOTSIZE DLSPEED  ULSPEED   NFILES  TORRENT NAME/FILENAME"

    for dl in job_list:
        print job_details(server, dl)

def job_details(server, job_status):
    #pprint(job_status)
        
    gid = job_status['gid']
    status = job_status['status']
    percent = percentage(job_status)
    totsize = sizeof_fmt(float(job_status['totalLength'])) 
    dlspeed = b2kb(job_status['downloadSpeed'])
    ulspeed = b2kb(job_status['uploadSpeed'])
    
    # these two make RPC calls:
    nfiles = getfilecount(server,gid)
    filename = getname(server,job_status,gid)
    
    return "%4s  %8s  %5.1f%%  %s % 4dkB/s % 4dkB/s  %d     %s" % (gid, status, percent, totsize, dlspeed, ulspeed, nfiles, filename)

def b2kb(sz):
    return int(sz)/1024
    
def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)
    
def getname(server, job_status, gid):
    try:
        filename = job_status['bittorrent']['info']['name']
    except:
        filename = os.path.basename(top_file_name(server, gid))
    
    return filename


def percentage(job_status):
    length = float(job_status['totalLength'])
    completed = float(job_status['completedLength'])
    if length > 0:
        return (completed * 100) / length
    return 0

def top_file_name(server, gid):
    return server.aria2.getFiles(secret,gid)[0]['path']

def getfilecount(server, gid):
    files = server.aria2.getFiles(secret,gid)
    #pprint(files)
    return len(files)

def get_options():
    """Get options for the script."""
    parser = argparse.ArgumentParser(
            description="view the aria2 queue on localhost:6800",
             )
    # parser.add_argument() calls here
    options = parser.parse_args()
    # extra processing of options here
    return options

if __name__ == "__main__":
    main(get_options())
