Skip to content

chinanf-boy/webtorrent-zh

Repository files navigation

webtorrent/webtorrent explain translate-svg

「 来自 webtorrent/webtorrent (js) 的 播种技术,让我们开始在浏览器上播种吧。」

这里’播种‘的意思,就是把内容当作'种子',供给大家下载的行为。

中文 | english


校对 ✅

翻译的原文 与日期 最新更新 更多
commit ⏰ 2018.11.13 last 中文翻译

文档来自 webtorrent/webtorrent/blob/master/docs

贡献

欢迎 👏 勘误/校对/更新贡献 😊 具体贡献请看

生活

help me live , live need money 💰


目录

开始使用 WebTorrent

WebTorrent是第一个在浏览器工作的 torrent 客户端。它很容易上手!

torrent有连发,急流的中文意思,虽不是常说的’种子‘那意思,但统称为种子,更符合中文化。所以 torrent == 种子。之前我们常用BT(BitTorrent)种子来描述,不可描述的东西,现在WT(WebTorrent)种子,看来,也已经快啦。 一切,都可播种。

安装

要开始使用 WebTorrent,只需在你的页面中,包含webtorrent.min.js脚本。

<script src="webtorrent.min.js"></script>

这给window对象中,提供了一个WebTorrent函数。

Browserify

WebTorrent 也与browserify很搭,让你使用node.jsrequire()样式,组织您的浏览器代码,并加载npm安装的软件包。

npm install webtorrent

然后,像这样用WebTorrent

var WebTorrent = require('webtorrent');

快例子

下载一个 torrent (在浏览器)

var WebTorrent = require('webtorrent');

var client = new WebTorrent();

// Sintel, 一部免费,好的电影
var torrentId =
  'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent';

client.add(torrentId, function(torrent) {
  // Torrents 可以包含许多文件(files). 让我们使用 .mp4 文件
  var file = torrent.files.find(function(file) {
    return file.name.endsWith('.mp4');
  });

  // 通过添加到 DOM , 展示该文件。
  // 支持 video, audio, image 文件, 还有更多!
  file.appendTo('body');
});

这支持视频,音频,图像,PDF,Markdown,和更多,开箱即用。还有其他方法,可以直接访问文件内容,包括 node-样式的 Stream,Buffer 或 Blob URL。

视频和音频内容可以流式传输,即在下载完整文件之前,开始播放。播种工作也是如此 - WebTorrent 根据需要,从网络中,动态获取所需的 torrent 片段。

创建一个 torrent(种子) 和 播种 (在浏览器)

var dragDrop = require('drag-drop');
var WebTorrent = require('webtorrent');

var client = new WebTorrent();

// 当用户把文件,拖到浏览器,会创建一个新的 torrent 并开始播种!
dragDrop('body', function(files) {
  client.seed(files, function(torrent) {
    console.log('Client is seeding ' + torrent.magnetURI);
  });
});

这个例子使用了drag-drop包,让 HTML5 拖放(Drag 和 Drop) API 更容易使用。

**注意:**如果您不使用 browserify,请使用独立文件dragdrop.min.js。这导出一个DragDrop函数,到window

下载和保存 一个 torrent (Node.js)

var WebTorrent = require('webtorrent');

var client = new WebTorrent();

var magnetURI = 'magnet: ...';

client.add(magnetURI, {path: '/path/to/folder'}, function(torrent) {
  torrent.on('done', function() {
    console.log('torrent download finished');
  });
});

完整的网页示例

寻找更完整的例子?不用到处找啦!此 HTML 示例具有表单输入,用户可以粘贴,磁力链接,并通过 WebTorrent 开始下载。

最重要的是,它是一个单独的 HTML 页面,低于 70 行!

如果 torrent 包含图像,视频,音频或其他可播放文件(使用支持的编解码器),则即使在下载完整内容之前,它们也能添加到 DOM ,并进行流式传输。

[x] index.html 示例源码

<!DOCTYPE html>
<html>
  <body>
    <h1>
      使用 WebTorrent 协议 (BitTorrent ^ WebRTC) 下载文件.
    </h1>

    <form>
      <label for="torrentId">磁力链接下载 </label>
      <input
        name="torrentId"
        ,
        placeholder="magnet:"
        value="magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent"
      />
      <button type="submit">下载</button>
    </form>

    <h2>记录</h2>
    <div class="log"></div>

    <!-- Include the latest version of WebTorrent -->
    <script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>

    <script>
      var client = new WebTorrent();

      client.on('error', function(err) {
        console.error('ERROR: ' + err.message);
      });

      document.querySelector('form').addEventListener('submit', function(e) {
        e.preventDefault(); // 阻止网页刷新

        var torrentId = document.querySelector('form input[name=torrentId]')
          .value;
        log('Adding ' + torrentId);
        client.add(torrentId, onTorrent);
      });

      function onTorrent(torrent) {
        log('获得 torrent 元信息!');
        log(
          'Torrent info hash: ' +
            torrent.infoHash +
            ' ' +
            '<a href="' +
            torrent.magnetURI +
            '" target="_blank">[Magnet URI]</a> ' +
            '<a href="' +
            torrent.torrentFileBlobURL +
            '" target="_blank" download="' +
            torrent.name +
            '.torrent">[Download .torrent]</a>'
        );

        // 每5秒,打印下载进度
        var interval = setInterval(function() {
          log('Progress: ' + (torrent.progress * 100).toFixed(1) + '%');
        }, 5000);

        torrent.on('done', function() {
          log('Progress: 100%');
          clearInterval(interval);
        });

        // 把所有文件,渲染进 DOM
        torrent.files.forEach(function(file) {
          file.appendTo('.log');
          log(
            '(Blob URLs 从服务器加载完成后,才能工作. "http//localhost" 可以. "file://" 不行.)'
          );
          file.getBlobURL(function(err, url) {
            if (err) return log(err.message);
            log('File 完成.');
            log(
              '<a href="' + url + '">下载完整的文件: ' + file.name + '</a>'
            );
          });
        });
      }

      function log(str) {
        var p = document.createElement('p');
        p.innerHTML = str;
        document.querySelector('.log').appendChild(p);
      }
    </script>
  </body>
</html>

HTML 示例:状态显示 UI

这个完整的 HTML 示例,模仿了webtorrent.io主页的UI。它下载了sintel.torrent文件,在浏览器中,流式传输并向用户输出一些统计信息(对端(可供给的网点),进度,剩余时间,速度...)。

你现在可以在CodePen试试,看看它的样子,玩玩它!

随意更换torrentId,换成其他 torrent 文件,或磁力链接,但请记住,浏览器只能下载,由 WebRTC 对端(web 对端)播种的种子。使用WebTorrent Desktop要么Instant.io,将种子(torrent),播种到 WebTorrent 网络。

[x] stream.html 示例源码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>WebTorrent 视频播放器</title>
    <style>
      #output video {
        width: 100%;
      }
      #progressBar {
        height: 5px;
        width: 0%;
        background-color: #35b44f;
        transition: width 0.4s ease-in-out;
      }
      body.is-seed .show-seed {
        display: inline;
      }
      body.is-seed .show-leech {
        display: none;
      }
      .show-seed {
        display: none;
      }
      #status code {
        font-size: 90%;
        font-weight: 700;
        margin-left: 3px;
        margin-right: 3px;
        border-bottom: 1px dashed rgba(255, 255, 255, 0.3);
      }

      .is-seed #hero {
        background-color: #154820;
        transition: 0.5s 0.5s background-color ease-in-out;
      }
      #hero {
        background-color: #2a3749;
      }
      #status {
        color: #fff;
        font-size: 17px;
        padding: 5px;
      }
      a:link,
      a:visited {
        color: #30a247;
        text-decoration: none;
      }
    </style>
  </head>
  <body>
    <div id="hero">
      <div id="output">
        <div id="progressBar"></div>
        <!-- The video player will be added here -->
      </div>
      <!-- Statistics -->
      <div id="status">
        <div>
          <span class="show-leech">下载中 </span>
          <span class="show-seed">播种中 </span>
          <code>
            <!-- Informative link to the torrent file -->
            <a id="torrentLink" href="https://webtorrent.io/torrents/sintel.torrent"
              >sintel.torrent</a
            >
          </code>
          <span class="show-leech"></span>
          <span class="show-seed"></span>
          <code id="numPeers">0 对端</code>.
        </div>
        <div>
          <code id="downloaded"></code>
          of <code id="total"></code><span id="remaining"></span><br />
          &#x2198;<code id="downloadSpeed">0 b/s</code> / &#x2197;<code
            id="uploadSpeed"
            >0 b/s</code
          >
        </div>
      </div>
    </div>
    <!-- Include the latest version of WebTorrent -->
    <script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>

    <!-- Moment is used to show a human-readable remaining time -->
    <script src="http://momentjs.com/downloads/moment.min.js"></script>

    <script>
      var torrentId = 'https://webtorrent.io/torrents/sintel.torrent';

      var client = new WebTorrent();

      // HTML elements
      var $body = document.body;
      var $progressBar = document.querySelector('#progressBar');
      var $numPeers = document.querySelector('#numPeers');
      var $downloaded = document.querySelector('#downloaded');
      var $total = document.querySelector('#total');
      var $remaining = document.querySelector('#remaining');
      var $uploadSpeed = document.querySelector('#uploadSpeed');
      var $downloadSpeed = document.querySelector('#downloadSpeed');

      // 下载种子
      client.add(torrentId, function(torrent) {
        // Torrents 可以包含许多文件(files). 让我们使用 .mp4 文件
        var file = torrent.files.find(function(file) {
          return file.name.endsWith('.mp4');
        });

        // 在浏览器,流式播放文件
        file.appendTo('#output');

        // 触发 统计 刷新
        torrent.on('done', onDone);
        setInterval(onProgress, 500);
        onProgress();

        // 统计
        function onProgress() {
          // Peers
          $numPeers.innerHTML =
            torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers');

          // 进度
          var percent = Math.round(torrent.progress * 100 * 100) / 100;
          $progressBar.style.width = percent + '%';
          $downloaded.innerHTML = prettyBytes(torrent.downloaded);
          $total.innerHTML = prettyBytes(torrent.length);

          // 剩余时间
          var remaining;
          if (torrent.done) {
            remaining = 'Done.';
          } else {
            remaining = moment
              .duration(torrent.timeRemaining / 1000, 'seconds')
              .humanize();
            remaining =
              remaining[0].toUpperCase() +
              remaining.substring(1) +
              ' 还需时间.';
          }
          $remaining.innerHTML = remaining;

          // Speed rates
          $downloadSpeed.innerHTML = prettyBytes(torrent.downloadSpeed) + '/s';
          $uploadSpeed.innerHTML = prettyBytes(torrent.uploadSpeed) + '/s';
        }
        function onDone() {
          $body.className += ' is-seed';
          onProgress();
        }
      });

      // 人类可读字节工具
      function prettyBytes(num) {
        var exponent,
          unit,
          neg = num < 0,
          units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        if (neg) num = -num;
        if (num < 1) return (neg ? '-' : '') + num + ' B';
        exponent = Math.min(
          Math.floor(Math.log(num) / Math.log(1000)),
          units.length - 1
        );
        num = Number((num / Math.pow(1000, exponent)).toFixed(2));
        unit = units[exponent];
        return (neg ? '-' : '') + num + ' ' + unit;
      }
    </script>
  </body>
</html>

更多文档

看看API 文档FAQ,里面有更多细节。

About

中文翻译:<webtorrent/webtorrent> 播种技术,让我们开始在浏览器上播种吧 ❤️ 校对 ✅

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published