diff --git a/config.js b/config.js index 8095b556..f8c65135 100644 --- a/config.js +++ b/config.js @@ -7,6 +7,7 @@ module.exports = { CONFIG_PATH: applicationConfigPath('WebTorrent'), CONFIG_POSTER_PATH: path.join(applicationConfigPath('WebTorrent'), 'Posters'), + CONFIG_TORRENT_PATH: path.join(applicationConfigPath('WebTorrent'), 'Torrents'), INDEX: 'file://' + path.join(__dirname, 'renderer', 'index.html'), diff --git a/renderer/index.js b/renderer/index.js index 9989eb75..693ff244 100644 --- a/renderer/index.js +++ b/renderer/index.js @@ -405,12 +405,14 @@ function addTorrentToList (torrent) { // Starts downloading and/or seeding a given torrent, torrentSummary or magnet URI function startTorrenting (infoHash) { - var torrent = state.client.add(infoHash, { - // Use downloads folder - path: state.saved.downloadPath + checkIfTorrentFileExists(infoHash, function (torrentPath, exists) { + var torrentID = exists ? torrentPath : infoHash + var torrent = state.client.add(torrentID, { + path: state.saved.downloadPath // Use downloads folder + }) + addTorrentEvents(torrent) + return torrent }) - addTorrentEvents(torrent) - return torrent } // Stops downloading and/or seeding. See startTorrenting @@ -439,6 +441,8 @@ function addTorrentEvents (torrent) { torrentSummary.name = torrentSummary.displayName || torrent.name torrentSummary.infoHash = torrent.infoHash + saveTorrentFile(torrentSummary, torrent) + if (!torrentSummary.posterURL) { generateTorrentPoster(torrent, torrentSummary) } @@ -475,6 +479,38 @@ function generateTorrentPoster (torrent, torrentSummary) { }) } +// Every time we resolve a magnet URI, save the torrent file so that we never +// have to download it again. Never ask the DHT the same question twice. +function saveTorrentFile (torrentSummary, torrent) { + checkIfTorrentFileExists(torrentSummary.infoHash, function (torrentPath, exists) { + if (exists) { + // We've already saved the file + torrentSummary.torrentPath = torrentPath + saveState() + return + } + + // Otherwise, save the .torrent file, under the app config folder + fs.mkdir(config.CONFIG_TORRENT_PATH, function (_) { + fs.writeFile(torrentPath, torrent.torrentFile, function (err) { + if (err) return console.log('Error saving torrent file %s: %o', torrentPath, err) + console.log('Saved torrent file %s', torrentPath) + torrentSummary.torrentPath = torrentPath + saveState() + }) + }) + }) +} + +// Checks whether we've already resolved a given infohash to a torrent file +// Calls back with (torrentPath, exists). Logs, does not call back on error +function checkIfTorrentFileExists (infoHash, cb) { + var torrentPath = path.join(config.CONFIG_TORRENT_PATH, infoHash + '.torrent') + fs.exists(torrentPath, function (exists) { + cb(torrentPath, exists) + }) +} + function startServer (infoHash, index, cb) { if (state.server) return cb() @@ -489,7 +525,7 @@ function startServerFromReadyTorrent (torrent, index, cb) { if (!index) { // filter out file formats that the