From 5abeec313f897bbb1f1f39c3849675ec9a77d506 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Sat, 1 Oct 2016 15:33:27 +0200 Subject: [PATCH] Server: fix remaining milli seconds before the next requests feature --- server/controllers/api/v1/requests.js | 4 +--- server/models/request.js | 21 ++++++++++++++++++--- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/server/controllers/api/v1/requests.js b/server/controllers/api/v1/requests.js index 17aca8af0..9610e5cd6 100644 --- a/server/controllers/api/v1/requests.js +++ b/server/controllers/api/v1/requests.js @@ -28,11 +28,9 @@ function getStatsRequests (req, res, next) { Request.list(function (err, requests) { if (err) return next(err) - const remainingMilliSeconds = constants.REQUESTS_INTERVAL - (Date.now() % constants.REQUESTS_INTERVAL) - return res.json({ requests: requests, - remainingMilliSeconds: remainingMilliSeconds, + remainingMilliSeconds: Request.remainingMilliSeconds(), milliSecondsInterval: constants.REQUESTS_INTERVAL }) }) diff --git a/server/models/request.js b/server/models/request.js index 73b17dc8c..2d50d94e0 100644 --- a/server/models/request.js +++ b/server/models/request.js @@ -14,6 +14,7 @@ const Pod = mongoose.model('Pod') const Video = mongoose.model('Video') let timer = null +let lastRequestTimestamp = 0 // --------------------------------------------------------------------------- @@ -27,7 +28,8 @@ RequestSchema.statics = { deactivate, flush, forceSend, - list + list, + remainingMilliSeconds } RequestSchema.pre('save', function (next) { @@ -54,12 +56,19 @@ mongoose.model('Request', RequestSchema) function activate () { logger.info('Requests scheduler activated.') - timer = setInterval(makeRequests.bind(this), constants.REQUESTS_INTERVAL) + lastRequestTimestamp = Date.now() + + const self = this + timer = setInterval(function () { + lastRequestTimestamp = Date.now() + makeRequests.call(self) + }, constants.REQUESTS_INTERVAL) } function deactivate () { logger.info('Requests scheduler deactivated.') clearInterval(timer) + timer = null } function flush () { @@ -77,6 +86,12 @@ function list (callback) { this.find({ }, callback) } +function remainingMilliSeconds () { + if (timer === null) return -1 + + return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp) +} + // --------------------------------------------------------------------------- // Make a requests to friends of a certain type @@ -159,7 +174,7 @@ function makeRequests () { return callbackEach() } - // Maybe the pod is not our friend anymore so simply remove them + // Maybe the pod is not our friend anymore so simply remove it if (!toPod) { removePodOf.call(self, requestToMake.ids, toPodId) return callbackEach()