Given a .torrent file how do I generate a magnet l

2019-01-13 10:53发布

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?

1条回答
放我归山
2楼-- · 2019-01-13 11:33

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'
查看更多
登录 后发表回答