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)

Motivation

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

wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg#md5=fe1f997bc722265116870bc7919059ea
sudo chmod 755 setuptools-0.6c11-py2.7.egg
sudo ./setuptools-0.6c11-py2.7.egg

Now it's very simple to install bencode

easy_install http://pypi.python.org/packages/2.7/b/bencode/bencode-1.0-py2.7.egg#md5=fa08025585d4cd7700bed503b6baf018

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

nano createMagnetLink.py

Put following content into it

!/usr/bin/python

import sys
import urllib
import bencode
import hashlib
import base64

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

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

print(magneturi)

Make the file executable

sudo nano 755 createMagnetLink.py

And the just call it with a torrent file

./createMagnetLink.py file.torrent

1 Kommentar: