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?
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.
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.
Just right-click the magnet link and copy the link address. When you copy and paste the link, click OK to confirm.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With