forked from calzoneman/sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbgtask.js
81 lines (69 loc) · 2.39 KB
/
bgtask.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
bgtask.js
Registers background jobs to run periodically while the server is
running.
*/
var Config = require("./config");
var db = require("./database");
var Promise = require("bluebird");
const LOGGER = require('@calzoneman/jsli')('bgtask');
var init = null;
/* Alias cleanup */
function initAliasCleanup(_Server) {
var CLEAN_INTERVAL = parseInt(Config.get("aliases.purge-interval"));
var CLEAN_EXPIRE = parseInt(Config.get("aliases.max-age"));
setInterval(function () {
db.cleanOldAliases(CLEAN_EXPIRE, function (err) {
LOGGER.info("Cleaned old aliases");
if (err)
LOGGER.error(err);
});
}, CLEAN_INTERVAL);
}
/* Password reset cleanup */
function initPasswordResetCleanup(_Server) {
var CLEAN_INTERVAL = 8*60*60*1000;
setInterval(function () {
db.cleanOldPasswordResets(function (err) {
if (err)
LOGGER.error(err);
});
}, CLEAN_INTERVAL);
}
function initChannelDumper(Server) {
const chanPath = Config.get('channel-path');
var CHANNEL_SAVE_INTERVAL = parseInt(Config.get("channel-save-interval"))
* 60000;
setInterval(function () {
if (Server.channels.length === 0) {
return;
}
var wait = CHANNEL_SAVE_INTERVAL / Server.channels.length;
LOGGER.info(`Saving channels with delay ${wait}`);
Promise.reduce(Server.channels, (_, chan) => {
return Promise.delay(wait).then(() => {
if (!chan.dead && chan.users && chan.users.length > 0) {
return chan.saveState().tap(() => {
LOGGER.info(`Saved /${chanPath}/${chan.name}`);
}).catch(err => {
LOGGER.error(`Failed to save /${chanPath}/${chan.name}: ${err.stack}`);
});
}
}).catch(error => {
LOGGER.error(`Failed to save channel: ${error.stack}`);
});
}, 0).catch(error => {
LOGGER.error(`Failed to save channels: ${error.stack}`);
});
}, CHANNEL_SAVE_INTERVAL);
}
module.exports = function (Server) {
if (init === Server) {
LOGGER.warn("Attempted to re-init background tasks");
return;
}
init = Server;
initAliasCleanup(Server);
initChannelDumper(Server);
initPasswordResetCleanup(Server);
};