BT種子文件相對磁力鏈來說存儲不方便,而且在網站上存放BT文件容易引起版權糾紛,而磁力鏈相對來說則風險小一些。而且很多論壇或者網站限制了文件上傳的類型,分享一個BT種子還需要改文件后綴或者壓縮一次,其他人需要下載時候還要額外多一步下載種子的操作。
所以將BT種子轉換為占用空間更小,分享更方便的磁力鏈還是有挺大好處的。
首先一個方案是使用bencode這個插件,通過pip方式安裝或者自行下載源文件https://pypi.python.org/pypi/bencode/1.0通過python setup.py install方式安裝均可。
相應的將BT種子轉換為磁力鏈代碼為:
import bencode, hashlib, base64, urllib
torrent = open('ubuntu-12.04.2-server-amd64.iso.torrent', 'rb').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'],
'tr': metadata['announce'],
'xl': metadata['info']['length']}
paramstr = urllib.urlencode(params)
magneturi = 'magnet:?%s' % paramstr
print magneturi
還有另外一個效率相對較高,而且更方便的方案是安裝libtorrent,在Debian只需要
apt-get install python-libtorrent即可
對應轉換磁力鏈的代碼為:
import libtorrent as bt
info = bt.torrent_info('test.torrent')
print "magnet:?xt=urn:btih:%s&dn=%s" % (info.info_hash(), info.name())