From 959344080ee467010b5c954d452cb8e8be33c64f Mon Sep 17 00:00:00 2001 From: Alexey Kasyanchuk Date: Fri, 20 Apr 2018 05:08:51 +0300 Subject: [PATCH] feat(vote): replicate torrent on voting --- src/background/api.js | 32 +++++++++++++++++++++++++++++--- src/background/store.js | 15 +++++++++++++-- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/background/api.js b/src/background/api.js index c2659bd..d78500d 100644 --- a/src/background/api.js +++ b/src/background/api.js @@ -141,6 +141,15 @@ module.exports = ({ onTorrent(hash, options, (data) => callback(data)) }) + const getTorrent = async (hash) => { + let torrent = await sphinx.query(`SELECT * FROM torrents WHERE hash = '${hash}'`) + if(torrent && torrent.length > 0) + { + torrent[0].filesList = (await sphinx.query(`SELECT * FROM files WHERE hash = '${hash}'`)) || [] + return torrent[0] + } + } + if(config.p2pReplication) { console.log('p2p replication enabled') @@ -657,6 +666,20 @@ module.exports = ({ return {good, bad, selfVote} } + p2pStore.on('store', (value) => { + if(!value.temp) + return + + if(!value.temp.torrent) + return + + if(value.myself) + return + + console.log('replicate torrent from store record', value.temp.torrent.hash) + insertTorrentToDB(value.temp.torrent) + }) + recive('vote', async (hash, isGood, callback) => { if(hash.length != 40) @@ -672,12 +695,15 @@ module.exports = ({ if(!selfVote) { - p2pStore.store({ + setTimeout(async () => p2pStore.store({ type: 'vote', torrentHash: hash, vote: action, - _index: `vote:${hash}` - }) + _index: `vote:${hash}`, + _temp: { + torrent: await getTorrent(hash) + } + }), 0) good += isGood ? 1 : 0 bad += !isGood ? 1 : 0 } diff --git a/src/background/store.js b/src/background/store.js index f0d3570..312cc45 100644 --- a/src/background/store.js +++ b/src/background/store.js @@ -1,8 +1,10 @@ const objectHash = require('object-hash'); +const EventEmitter = require('events'); -module.exports = class P2PStore { +module.exports = class P2PStore extends EventEmitter { constructor(p2p, sphinx) { + super() this.id = 0 console.log('connect p2p store...') @@ -91,6 +93,9 @@ module.exports = class P2PStore { return } + // set myself to false + record.myself = false + // push to db console.log('sync peerdb record', record.id) this._pushToDb(record) @@ -99,6 +104,7 @@ module.exports = class P2PStore { _pushToDb(value, callback) { + this.emit('store', value) const data = this.sphinx.escape(JSON.stringify(value.data)) this.sphinx.query( `insert into store(id, hash, peerId, data` + (value.index || value.data._index ? ', storeIndex' : '') + `) @@ -122,8 +128,13 @@ module.exports = class P2PStore { hash: objectHash(obj), data: obj, index: obj._index, - peerId: this.p2p.peerId + peerId: this.p2p.peerId, + myself: true, + temp: obj._temp } + if(obj._temp) + delete obj._temp + console.log('store object', value.id) this._pushToDb(value, () => {