torrent2magnet.py 736 B

12345678910111213141516171819202122232425262728
  1. #!/usr/bin/env python3
  2. # adapted from https://github.com/DanySK/torrent2magnet
  3. import sys
  4. import hashlib
  5. import base64
  6. from fastbencode import bencode, bdecode
  7. def make_magnet_from_file(file):
  8. with open(file, "rb") as f:
  9. data = f.read()
  10. metadata = bdecode(data)
  11. subj = metadata[b'info']
  12. hashcontents = bencode(subj)
  13. digest = hashlib.sha1(hashcontents).digest()
  14. b32hash = base64.b32encode(digest).decode()
  15. return 'magnet:?'\
  16. + 'xt=urn:btih:' + b32hash\
  17. + '&dn=' + metadata[b'info'][b'name'].decode()\
  18. + '&tr=' + metadata[b'announce'].decode()\
  19. + '&xl=' + str(metadata[b'info'][b'length'])
  20. if __name__ == "__main__":
  21. magnet = make_magnet_from_file(sys.argv[1])
  22. print(magnet)