如何从 magnet link 或 infohash 创建 torrent 文件

How to create torrent files from magnet link or infohash

我正在尝试创建一个 Torrent 搜索引擎。但是我找到了一种从 DHT 网络收集 torrent infohashes 的方法。我的问题是如何从中提取 .torrent 文件? 我有一个 MongoDB 集合包含 1M-1.5M(Growing Very Quickly) 种子信息哈希。

我自己解决了这个问题。 我使用了 webtorrent npm 包,还创建了一个算法来遍历整个数据库,并在下载任务中添加了磁铁 link。一旦客户端获得元数据,我就将其保存到 torrent 文件并取消下载。

好吧,代码还没有完全准备好生产。之后我将 Post 代码片段放在这里。谢谢!

更新:我正在使用这个 class 从磁铁下载 Torrent 文件

const Discovery = require('torrent-discovery');
const Protocol = require('bittorrent-protocol');
const ut_metadata = require('ut_metadata');
const addrToIPPort = require('addr-to-ip-port');
const net = require('net');

class TorrentDownloader {
  constructor(port, trackers, timeout) {
    this.SELF_HASH = '4290a5ff50130a90f1de64b1d9cc7822799affd5';
    this.port = port | 6881;
    this.trackers = trackers;
    this.timeout = timeout | 80000;
  }

  downloadTorrent(infoHash) {
    let self = this;
    return new Promise((resolve, reject) => {
      let dis = new Discovery({infoHash: infoHash, peerId: this.SELF_HASH, port: this.port, dht: true, announce: this.trackers})
          .on('peer', function (peer) {
            const peerAddress = {address: addrToIPPort(peer)[0], port: addrToIPPort(peer)[1]};
            // console.log(`download metadata from peer ${peerAddress.address}:${peerAddress.port}`);
            self.getMetadata(peerAddress, infoHash, resolve);
          });
      setTimeout(() => {
        dis.destroy();
        reject(new Error("Torrent Timeout"))
      }, this.timeout)
    })
  }

  getMetadata(peerAddress, infoHash, resolve) {
    const socket = new net.Socket();
    socket.setTimeout(this.timeout);
    socket.connect(peerAddress.port, peerAddress.address, () => {
      const wire = new Protocol();

      socket.pipe(wire).pipe(socket);
      wire.use(ut_metadata());
      wire.handshake(infoHash, this.SELF_HASH, {dht: true});
      wire.on('handshake', function (infoHash, peerId) {
        wire.ut_metadata.fetch();
      });
      wire.ut_metadata.on('metadata', function (rawMetadata) {
        resolve(rawMetadata);
        wire.destroy();
        socket.destroy()
      })
    });
    socket.on('error', err => {
      socket.destroy();
    });
  }
}

module.exports = TorrentDownloader;

仅给出一个信息哈希,例如:

  • 463e408429535139a0bbb5dd676db10d5963bf05

您可以使用:

BEP: 9 - Extension for Peers to Send Metadata Files

The purpose of this extension is to allow clients to join a swarm and complete a download without the need of downloading a .torrent file first. This extension instead allows clients to download the metadata from peers. It makes it possible to support magnet links, a link on a web page only containing enough information to join the swarm (the info hash).

您使用 DHT 查找分布式跟踪器。
然后你使用分布式跟踪器找到拥有种子的同行。
然后你就可以从同行那里下载种子元数据

您将编码后的元数据请求发送给对等方:

{ 
   "msg_type": 0,      ; 0==>request
   "piece": 0
}