2
votes

Recently, I'm doing things related to magnet link. What I want to do is to convert a torrent file to magnet link.

I've tried given-a-torrent-file-how-do-i-generate-a-magnet-link-in-python, but get an error when issuing command metadata = bencode.bdecode(torrent):

"bencode.BTL.BTFailure: not a valid bencoded string"

Then I tried installing python-libtorrent, but failed to finish the installation.

Is there a way to do it in Java? If not, how can this be easily done in Python, Thanks a lot!

1
Did you try multiple torrents, maybe the one you're using is corrupted or something...ThinkChaos
you can use the frostwire project library with the git links is as below : github.com/frostwire/frostwire-jlibtorrentArian

1 Answers

0
votes

I didn't check if this works but it's a reference to start, follow this link for a example in python using the bencode library.

#!/usr/bin/python

import sys
import urllib
import bencode
import hashlib
import base64

if len(sys.argv) == 0:
print("Usage: file")
exit()

torrent = open(sys.argv[1], 'r').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']}

announcestr = ''
for announce in metadata['announce-list']:
announcestr += '&' + urllib.urlencode({'tr':announce[0]})

paramstr = urllib.urlencode(params) + announcestr
magneturi = 'magnet:?%s' % paramstr

print(magneturi)