Wednesday, July 26, 2017

convert magnet to torrent





*** gettorrent.py

import sys
import libtorrent as lt
import tempfile
from time import sleep
import shutil
import os.path as pt


tempdir = tempfile.mkdtemp()

ses = lt.session()
magnet = sys.argv[1]

params = {
    'save_path': tempdir,
    'storage_mode': lt.storage_mode_t(2),
    'paused': False,
    'auto_managed': True,
    'duplicate_is_error': True
}
handle = lt.add_magnet_uri(ses, magnet, params)
print("Downloading Metadata")
while (not handle.has_metadata()):
        try:
            sleep(1)
        except KeyboardInterrupt:
            print("Aborting...")
            ses.pause()
            print("Cleanup dir " + tempdir)
            shutil.rmtree(tempdir)
            sys.exit(0)
ses.pause()
print("Done")

torinfo = handle.get_torrent_info()
torfile = lt.create_torrent(torinfo)

output = pt.abspath(torinfo.name() + ".torrent")

output_name = torinfo.name() + ".torrent"
output = pt.abspath(output_name)
torcontent = lt.bencode(torfile.generate())
f = open(output, "wb")
f.write(lt.bencode(torfile.generate()))
f.close()
# print("Saved! Cleaning up dir: " + tempdir)
ses.remove_torrent(handle)
shutil.rmtree(tempdir)




** usage
$ ./gettorrent.py magnet

No comments:

Post a Comment