import libtorrent, os, time
def magnet_to_torrent(magnet_uri, dst):
"""
Args:
magnet_uri (str): magnet link to convert to torrent file
dst (str): path to the destination folder where the torrent will be saved
"""
# Parse magnet URI parameters
params = libtorrent.parse_magnet_uri(magnet_uri)
# Download torrent info
session = libtorrent.session()
handle = session.add_torrent(params)
print "Downloading metadata..."
while not handle.has_metadata():
time.sleep(0.1)
# Create torrent and save to file
torrent_info = handle.get_torrent_info()
torrent_file = libtorrent.create_torrent(torrent_info)
torrent_path = os.path.join(dst, torrent_info.name() + ".torrent")
with open(torrent_path, "wb") as f:
f.write(libtorrent.bencode(torrent_file.generate()))
print "Torrent saved to %s" % torrent_path
if handle.has_metadata():
torinfo = handle.get_torrent_info()
fs = libtorrent.file_storage()
for file in torinfo.files():
fs.add_file(file)
torfile = libtorrent.create_torrent(fs)
torfile.set_comment(torinfo.comment())
torfile.set_creator(torinfo.creator())
for i in xrange(0, torinfo.num_pieces()):
hash = torinfo.hash_for_piece(i)
torfile.set_hash(i, hash)
for url_seed in torinfo.url_seeds():
torfile.add_url_seed(url_seed)
for http_seed in torinfo.http_seeds():
torfile.add_http_seed(http_seed)
for node in torinfo.nodes():
torfile.add_node(node)
for tracker in torinfo.trackers():
torfile.add_tracker(tracker)
torfile.set_priv(torinfo.priv())
f = open(magnet_torrent, "wb")
f.write(libtorrent.bencode(torfile.generate()))
f.close()
如果保存resume data不起作用,则可以使用现有连接中的信息生成新的torrent文件。
我怀疑它会使恢复比专门为此目的构建的函数更快。
只想提供一个使用现代libtorrent Python包的快速更新:libtorrent现在有了
parse_magnet_uri
方法,您可以使用该方法生成一个torrent句柄:此处找到的解决方案:
http://code.google.com/p/libtorrent/issues/detail?id=165#c5
请参见创建torrent:
http://www.rasterbar.com/products/libtorrent/make_torrent.html
修改第一行:
对此:
“handle”来自这里:
另外,在创建torrent之前,您必须确保元数据已下载,通过调用
handle.has_metadata()
来执行此操作。更新
似乎libtorrent python api缺少从磁铁创建torrent所需的一些重要c++api,上面的示例在python中不起作用,因为
create_torrent
python类不接受torrent_info作为参数(c++有它可用)。所以我尝试了另一种方法,但也遇到了一堵砖墙,这使得它不可能,下面是代码:
这一行出现错误:
它期望哈希为
const char*
,但torrent_info.hash_for_piece(int)
返回类big_number
,该类没有将其转换回const char*的api。当我找到一段时间后,我将向libtorrent开发人员报告这个丢失的api错误,因为在使用python绑定时,目前不可能从magnet uri创建.torrent文件。
python绑定中也缺少
torrent_info.orig_files()
,我不确定torrent_info.files()
是否足够。更新2
我在这个问题上提出了一个问题,请看这里: http://code.google.com/p/libtorrent/issues/detail?id=294
启动它,让他们尽快修复它。
更新3
现在已经修复了,有一个0.16.0版本。windows的二进制文件也可用。
相关问题 更多 >
编程相关推荐