繁体   English   中英

我如何从底层 bencode 数据中提取给定 .torrent 将创建的目录的名称?

[英]How can i extract the name of the directory a given `.torrent` would create from the underlying bencode data?

解析 python 中的 bencode 以获取.torrent文件生成的目录名称的最简单方法是什么?

.torrent文件名和它们生成的目录名很少相同。 我正在开发一个将.torrent文件移交给服务器并在完成后检索它的应用程序。 我需要知道.torrent文件创建的文件的名称,而无需实际启动下载。 我无法在服务器端执行任何操作。

之前,我通过相当庞大的完整 torrent 客户端 (libtorrent) 的依赖实现了这一点。 这已经行不通了。 遗憾的是,我不够聪明,无法理解 libtorrent 是如何解决这个问题的,但是获取文件名的命令是:

import libtorrent as lt

TORRENT = <direntry item that is a .torrent file>


def getFileNamefromTorrent(torrent):
    """must be a direntry item. Gets the name of the torrent's finished folder from the .torrent file."""
    torrent_info = lt.torrent_info(torrent.path)
    return torrent_info.name()

print(getFileNameFromTorrent(TORRENT)

我的第一次尝试是解析 bencode,我可以从中获取文件名:

import bencode
import itertools

TORRENT = "path to .torrent file"

def getTorrentFilenames(filename):
    with open(filename, "rb") as fin:
        torrent = bencode.bdecode(fin.read())
        
    return itertools.chain(*(f["path"] for f in torrent["info"]["files"]))

for file in getTorrentFilenames(TORRENT) 

这给了我 torrent 中的文件,但没有提供将它们放入的目录的名称。

我尝试访问字典中的不同元素(比如name而不是files ,但会产生typeError

Traceback (most recent call last):
  File "torrent_management.py", line 65, in <module>
    test = listTorrent(TESTTORRENT)
  File "torrent_management.py", line 63, in listTorrent
    return itertools.chain(*(f["path"] for f in torrent["info"]["name"]))
  File "torrent_management.py", line 63, in <genexpr>
    return itertools.chain(*(f["path"] for f in torrent["info"]["name"]))
TypeError: string indices must be integers

如果我忽略了一些非常明显的事情,我深表歉意。 BitTorrent.torrent 元信息文件结构提到字典中有一个“名称”。

我在上面的代码部分提供了一个在 python 中运行的最小工作示例。字典应该提供用 bencode 编码的 torrent 的名称,但它不是有效的字典项。

我发现我哪里出错了。

正确的最小解决方案如下:(如果您在使用 bencode 库时遇到问题,请确保使用bencode.py而不是bencode

import bencode

def getTorrentName(filename):
    """List name of a torrent from the corresponding .torrent file."""
    with open(filename, "rb") as fin:
        torrent = bencode.bdecode(fin.read())
    
    return torrent["info"]["name"]

torrent = <location of .torrent>

torrentName = getTorrentName(torrent)

此外,显然“名称”键是严格建议性的。 我不确定“名称”键是否用于生成相应的目录,或者它只是与之相关。 很想知道!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM