Skip to main content
 首页 » 编程设计

c#之使用 Libtorrent save_state() 保存单个种子

2024年02月06日23artech

我目前正在使用 Ragnar这是一个 CLI Libtorrent 包装器。

我碰壁了。也许这是我正在使用的包装器的实现缺陷,或者我只是误解了 Libtorrent API 文档,但我无法弄清楚如何正确保存/加载当前 session 状态数据。

我目前的目标,正如我能最好地说明的那样,是在当前 session 中保存所有 torrent_handles,这样当我下次运行我正在处理的 torrent 客户端时,我可以自动加载它们启动并恢复下载/播种。

我仍然不确定是否应该通过保存 session 状态来执行此操作。根据 API documentation's措辞:

The flags arguments passed in to save_state can be used to filter which parts of the session state to save. By default, all state is saved (except for the individual torrents).

但是我看不到属于个人种子的标志:

enum save_state_flags_t 
{ 
        save_settings =     0x001, 
        save_dht_settings = 0x002, 
        save_dht_state =    0x004, 
        save_proxy =        0x008, 
        save_i2p_proxy =    0x010, 
        save_encryption_settings = 0x020, 
        save_as_map =       0x040, 
        save_feeds =        0x080 
}; 

此外,包装器目前被硬编码为不接受这些标志:

cli::array<byte>^ Session::SaveState() 
{ 
    libtorrent::entry entry; 
    this->_session->save_state(entry); 
 
    return Utils::GetByteArrayFromLibtorrentEntry(entry); 
} 

这应该很容易修复,但我是否遗漏了什么?我是否试图通过错误的机制进行保存?

请您参考如下方法:

libtorrent 不提供保存 torrent 列表的机制。期望您(客户端)将 .torrent 文件保存在磁盘上(因为它们是不可变的)并在再次启动时首先重新添加它们。

唯一的异常(exception)是添加磁力链接时,您需要能够将 torrent_handle 转换为实际的 .torrent 文件。这是一个片段:

boost::intrusive_ptr<torrent_info const> ti = h.torrent_file(); 
create_torrent new_torrent(*ti); 
std::vector<char> out; 
bencode(std::back_inserter(out), new_torrent.generate()); 
save_file("mytorrent.torrent", out); 

然而,也许更好的选择是将 .torrent 文件(或信息字典)保存为简历数据的一部分。调用save_resume_data()时, 如果你传入 save_info_dict标志,恢复数据将包含重新启动 torrent 所需的一切。即 .torrent 文件的实际副本将保存在简历文件中。

libtorrent 附带的示例只是将 .torrent 文件保存在一个目录中,并在启动时(并定期)扫描该目录,因此文件系统存储了 torrent 列表。一种更有效的方法是将实际的 .torrent 文件与简历数据一起存储在数据库(例如,sqlite)中。

这是一个将与 .torrent 文件捆绑在一起的简历数据保存在 sqlite 数据库中的示例。

save_resume.cpp , save_resume.hpp

在加载所有数据库时,数据库可以提高启动效率。将简历数据与 torrent 捆绑在一起还可以为您加载的每个 torrent 节省一次磁盘搜索)。