File: uTorrent.py

#!/usr/bin/env python

#
# uTorrent interface
# SegPhault (Ryan Paul) - 01/17/2007
#

import base64, httplib

class Torrent(object):
  def __init__(self, **kwargs):
    self.data = kwargs

  @classmethod
  def parse_dict(cls, data):
    d = dict((name, data[column]) for column, name in enumerate([
      "hash", "state", "name", "total", "unknown", "received", "sent", "ratio",
      "upload_speed", "speed", "eta", "label", "connected_peers", "peers",
      "connected_seeds", "seeds", "available", "queue", "remaining"]))
    
    d.update(
      hours_remaining = round(float(d["eta"] / 60 / 60), 2),
      percent = round(float(d["received"]) / d["total"] * 100, 2),
      speed_kb = round(float(d["speed"]) / 1024, 2))

    return Torrent(**d)

  def __getattr__(self, attr):
    if attr in self.data.keys(): return self.data[attr]

class uTorrent:
  def __init__(self, host="localhost", port=8080, usrn="admin", passw=""):
    self.auth = {"Authorization": "Basic %s" %
        base64.encodestring("%s:%s" % (usrn, passw)).strip()}

    self.connection = httplib.HTTPConnection(host, port)

  def request(self, url):
    self.connection.request("GET", url, headers = self.auth)
    response = self.connection.getresponse()

    if response.status == 200: return response.read()
    else: raise "uTorrent Access Error", response.status

  def __iter__(self):
    for x in eval(self.request("/gui/?list=1"))["torrents"]:
      yield Torrent.parse_dict(x)

  torrents = property(list)

if __name__ == "__main__":
  ut = uTorrent()

  for t in ut:
    print "%-20.20s | %5.2f kb/s | %3.0f hours | %5.2f%%" % (
      t.name, t.speed_kb, t.hours_remaining, t.percent)

  print "\n", "Total download speed: %s kb/s" % sum(t.speed_kb for t in ut)

File: g15torrent.py

#!/usr/bin/env python

import uTorrent, time, sys

while True:
  torrents = [t for t in uTorrent.uTorrent() if t.speed]
  total_speed = sum(t.speed_kb for t in torrents)
  text = "%(name)-20.20s %(speed_kb)3d %(hours_remaining)3d %(percent)3d"
  headings = "%-20.20s %3s %3s %3s" % ("Name", "k/s", "eta", "%")

  sys.stdout = f = open(sys.argv[1], "a")

  print "PC 0"
  print "TM \"%s\"" % headings
  print "TO 0 10 1 0 \"%s\"" % '" "'.join(text % t.data for t in torrents)
  print "TO 0 35 2 0 \"uTorrent %0.2f Kb/s\"" % total_speed

  for x in [101, 121, 141]: print "DL %d 0 %d 32 1" % (x, x)
  for x in [8, 32]: print "DL 0 %d 500 %d 1" % (x, x)
  
  f.flush()
  time.sleep(1)