簡體   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