feat(downloading): save download session support

This commit is contained in:
Alexey Kasyanchuk 2018-06-27 04:47:22 +03:00
parent 27b46d15cc
commit 0d81364ca8
3 changed files with 56 additions and 5 deletions

View File

@ -576,7 +576,7 @@ module.exports = async ({
callback(true)
});
recive('download', (torrentObject) =>
torrentClient._add = (torrentObject, savePath) =>
{
const magnet = `magnet:?xt=urn:btih:${torrentObject.hash}`
console.log('download', magnet)
@ -585,12 +585,12 @@ module.exports = async ({
return
}
const torrent = torrentClient.add(magnet, {path: config.client.downloadPath})
const torrent = torrentClient.add(magnet, {path: savePath || config.client.downloadPath})
torrentClientHashMap[torrent.infoHash] = magnet
torrent.torrentObject = torrentObject
torrent.on('ready', () => {
console.log('start downloading', torrent.infoHash)
console.log('start downloading', torrent.infoHash, 'to', torrent.path)
send('downloading', torrent.infoHash)
})
@ -614,7 +614,9 @@ module.exports = async ({
timeRemaining: torrent.timeRemaining
})
})
});
}
recive('download', torrentClient._add);
recive('downloadCancel', (hash, callback) =>
{

View File

@ -771,12 +771,20 @@ setInterval(() => {
quotaDebug('disk quota enabled');
}
// load torrents sessions
console.log('restore downloading sessions')
torrentClient.loadSession(dataDirectory + '/downloads.json')
this.stop = async (callback) => {
this.closing = true
console.log('spider closing...')
if(upnp)
upnp.ratsUnmap()
// save torrents sessions
console.log('save torrents downloads sessions')
torrentClient.saveSession(dataDirectory + '/downloads.json')
// save feed
await feed.save()

View File

@ -1,3 +1,44 @@
const WebTorrent = require('webtorrent')
let torrentClient = new WebTorrent({webSeeds: false})
const fs = require('fs')
const torrentClient = new WebTorrent({webSeeds: false})
torrentClient.saveSession = (sessionFile) => {
fs.writeFileSync(sessionFile, JSON.stringify({
torrents: torrentClient.torrents.map(torrent => ({
infoHash: torrent.infoHash,
path: torrent.path,
torrent: torrent.torrentObject
}))
}, null, 4), 'utf8');
}
torrentClient.loadSession = (sessionFile) => {
if(!fs.existsSync(sessionFile))
{
console.log('no download sessions - ignore')
return
}
const data = fs.readFileSync(sessionFile, 'utf8')
const obj = JSON.parse(data);
if(!obj.torrents)
{
console.log('no torrents list for loading session')
return
}
if(!torrentClient._add)
{
console.log('no overriden _add() method')
return
}
const {torrents} = obj
torrents.forEach(({torrent, infoHash, path}) => {
if(!torrent || !infoHash || !path)
{
console.log('no info for starting download this torrent')
return
}
console.log('restore download session:', torrent.name)
torrentClient._add(torrent, path)
})
}
module.exports = torrentClient