From 7a8790a8f0a7803be732b26eea34ae92e8ba92f5 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 29 Dec 2014 20:41:47 -0800 Subject: [PATCH] New API: Add file.getURL() Fixes #217 --- README.md | 27 +++++++++++++++++++++++++++ lib/storage.js | 19 ++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f4ceed1f..31713ffc 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,14 @@ Seed ratio for all torrents in the client. ### torrent api +#### `torrent.infoHash` + +Get the info hash of the torrent. + +#### `torrent.magnetURI` + +Get the magnet URI of the torrent. + #### `torrent.files[...]` An array of all files in the torrent. See the file section for more info on what methods @@ -415,6 +423,25 @@ You can pass `opts` to stream only a slice of a file. Both `start` and `end` are inclusive. +#### `file.getBlobURL(function callback (err, url) {})` + +Get a url which can be used in the browser to refer to the file. + +The file will be fetched from the network with highest priority, and `callback` will be +called when it is ready. `callback` must be specified and may be called with a an `Error` +or the blob url (`String`) when the file data is available and ready to be used. + +```js +file.getBlobURL(function (err, url) { + if (err) throw err + var a = document.createElement('a') + a.download = file.name + a.href = url + a.textContent = 'Download ' + file.name + body.appendChild(a) +}) +``` + ### Modules Most of the active development is happening inside of small npm modules which are used by WebTorrent. diff --git a/lib/storage.js b/lib/storage.js index bb621ab8..5454a380 100644 --- a/lib/storage.js +++ b/lib/storage.js @@ -240,7 +240,6 @@ File.prototype.deselect = function () { */ File.prototype.createReadStream = function (opts) { var self = this - debug('createReadStream') opts = extend({ pieceLength: self.pieceLength }, opts) @@ -254,6 +253,24 @@ File.prototype.createReadStream = function (opts) { return stream } +/** + * TODO: detect errors and call callback with error + * @param {function} cb + */ +File.prototype.getBlobURL = function (cb) { + var self = this + var chunks = [] + self.createReadStream() + .on('data', function (chunk) { + chunks.push(chunk) + }) + .on('end', function () { + var buf = Buffer.concat(chunks) + var url = URL.createObjectURL(new Blob([ buf ])) + cb(null, url) + }) +} + File.prototype._checkDone = function () { var self = this self.done = self.pieces.every(function (piece) {