Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 485
Sebastian Sixx Avatar asked Sep 18 '12 14:09

Sebastian Sixx


People also ask

How do I turn a file into a magnet link?

Solution 1: Convert Magnet to Torrent by Magnet2Torrent Step 1: Open your browser and enter Magnet2Torrent website. Step 2: Copy and paste your magnet link to the orange line. Then the magnet link will be automatically converted into torrent files and stored in the folder of your browser.

How do I get magnet links to open automatically?

Click on the “Content Settings” button. Find the “Handlers” option that says “allow sites to ask to become default handlers for protocols.” Click on it. Ensure that this setting's toggle is in the ON position. Your Chrome browser should now be able to download your magnet link.

How do I copy and paste a magnet link?

Just right-click the magnet link and copy the link address. When you copy and paste the link, click OK to confirm.


1 Answers

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'
like image 140
jterrace Avatar answered Sep 18 '22 09:09

jterrace