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

旧时模样 提交于 2019-12-28 05:10:52

问题


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:


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'


来源:https://stackoverflow.com/questions/12479570/given-a-torrent-file-how-do-i-generate-a-magnet-link-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!