Given a .torrent file how do I generate a magnet link in python?

Sebastian Sixx picture Sebastian Sixx · Sep 18, 2012 · Viewed 15.3k times · Source

I need a way to convert .torrents into magnet links. Would like a way to do so in python. Are there any libraries that already do this?

Answer

jterrace picture jterrace · Sep 18, 2012

You can do this with the bencode module, extracted from BitTorrent.

To show you an example, I downloaded a torrent ISO of Ubuntu from here:

http://releases.ubuntu.com/12.04/ubuntu-12.04.1-desktop-i386.iso.torrent

Then, you can parse it in Python like this:

>>> import bencode
>>> torrent = open('ubuntu-12.04.1-desktop-i386.iso.torrent', 'r').read()
>>> metadata = bencode.bdecode(torrent)

A magnet hash is calculated from only the "info" section of the torrent metadata and then encoded in base32, like this:

>>> hashcontents = bencode.bencode(metadata['info'])
>>> import hashlib
>>> digest = hashlib.sha1(hashcontents).digest()
>>> import base64
>>> b32hash = base64.b32encode(digest)
>>> b32hash
'CT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6'

You can verify that this is correct by looking here and you will see the magnet link is:

magnet:?xt=urn:btih:CT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6

If you want to fill in some extra parameters to the magnet URI:

>>> params = {'xt': 'urn:btih:%s' % b32hash,
...           'dn': metadata['info']['name'],
...           'tr': metadata['announce'],
...           'xl': metadata['info']['length']}
>>> import urllib
>>> paramstr = urllib.urlencode(params)
>>> magneturi = 'magnet:?%s' % paramstr
>>> magneturi
'magnet:?dn=ubuntu-12.04.1-desktop-i386.iso&tr=http%3A%2F%2Ftorrent.ubuntu.com%3A6969%2Fannounce&xl=729067520&xt=urn%3Abtih%3ACT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6'