This blog is about Java (advanced Java topics like Reflection, Byte Code transformation, Code Generation), Maven, Web technologies, Raspberry Pi and IT in general.

Dienstag, 14. Mai 2013

Tutorial: How to generate a magnet link form a torrent file (convert torrent file to magnetic link)


It's easier to send just a link instead of a file if you want to share a torrent file.

Create the magic link

To create the magic link I used the bencode library (python). To easily install it we need first easy_install. The first thing to to is to install easy_install

sudo chmod 755 setuptools-0.6c11-py2.7.egg
sudo ./setuptools-0.6c11-py2.7.egg

Now it's very simple to install bencode


That's your preconditions. Now we can write our python script which will generate the magnic link.


Put following content into it


import sys
import urllib
import bencode
import hashlib
import base64

if len(sys.argv) == 0:
print("Usage: file")

torrent = open(sys.argv[1], 'r').read()
metadata = bencode.bdecode(torrent)

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

params = {'xt': 'urn:btih:%s' % b32hash,
'dn': metadata['info']['name']}

announcestr = ''
for announce in metadata['announce-list']:
announcestr += '&' + urllib.urlencode({'tr':announce[0]})

paramstr = urllib.urlencode(params) + announcestr
magneturi = 'magnet:?%s' % paramstr


Make the file executable

sudo nano 755

And the just call it with a torrent file

./ file.torrent

1 Kommentar: