feat(vote): replicate torrent on voting

This commit is contained in:
Alexey Kasyanchuk 2018-04-20 05:08:51 +03:00
parent 3c6e959d49
commit 959344080e
2 changed files with 42 additions and 5 deletions

View File

@ -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
}

View File

@ -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, () => {