From 1fe5076f63e0d3b291c4b9a2295220713f982f91 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 5 Feb 2016 19:41:22 +0100 Subject: Move the creation of requests in lib instead of model for poolrequests --- lib/friends.js | 5 ++--- lib/poolRequests.js | 42 +++++++++++++++++++++++++++++++++++++----- 2 files changed, 39 insertions(+), 8 deletions(-) (limited to 'lib') diff --git a/lib/friends.js b/lib/friends.js index badf09c7d..c05ccedb1 100644 --- a/lib/friends.js +++ b/lib/friends.js @@ -10,7 +10,6 @@ var logger = require('../helpers/logger') var peertubeCrypto = require('../helpers/peertubeCrypto') var Pods = require('../models/pods') - var PoolRequests = require('../models/poolRequests') var poolRequests = require('../lib/poolRequests') var requests = require('../helpers/requests') var Videos = require('../models/videos') @@ -32,7 +31,7 @@ var id = video.name + video.magnetUri // ensure namePath is null video.namePath = null - PoolRequests.addRequest(id, 'add', video) + poolRequests.addRequest(id, 'add', video) } function hasFriends (callback) { @@ -204,7 +203,7 @@ function removeVideoToFriends (video) { // To avoid duplicates var id = video.name + video.magnetUri - PoolRequests.addRequest(id, 'remove', video) + poolRequests.addRequest(id, 'remove', video) } // --------------------------------------------------------------------------- diff --git a/lib/poolRequests.js b/lib/poolRequests.js index ccc3489ab..5b7d5489d 100644 --- a/lib/poolRequests.js +++ b/lib/poolRequests.js @@ -15,10 +15,47 @@ var poolRequests = { activate: activate, + addRequest: addRequest, deactivate: deactivate, forceSend: forceSend } + function activate () { + logger.info('Pool requests activated.') + timer = setInterval(makePoolRequests, constants.INTERVAL) + } + + function addRequest (id, type, request) { + logger.debug('Add request to the pool requests.', { id: id, type: type, request: request }) + + PoolRequests.findById(id, function (err, entity) { + if (err) { + logger.error('Cannot find one pool request.', { error: err }) + return // Abort + } + + if (entity) { + if (entity.type === type) { + logger.error('Cannot insert two same requests.') + return // Abort + } + + // Remove the request of the other type + PoolRequests.removeById(id, function (err) { + if (err) { + logger.error('Cannot remove a pool request.', { error: err }) + return // Abort + } + }) + } else { + PoolRequests.create(id, type, request, function (err) { + logger.error('Cannot create a pool request.', { error: err }) + return // Abort + }) + } + }) + } + function deactivate () { logger.info('Pool requests deactivated.') clearInterval(timer) @@ -29,11 +66,6 @@ makePoolRequests() } - function activate () { - logger.info('Pool requests activated.') - timer = setInterval(makePoolRequests, constants.INTERVAL) - } - // --------------------------------------------------------------------------- module.exports = poolRequests -- cgit v1.2.3