forked from calzoneman/sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
549 lines (476 loc) · 17.3 KB
/
server.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
const VERSION = require("../package.json").version;
var singleton = null;
var Config = require("./config");
var Promise = require("bluebird");
import * as ChannelStore from './channel-storage/channelstore';
import { EventEmitter } from 'events';
const LOGGER = require('@calzoneman/jsli')('server');
module.exports = {
init: function () {
LOGGER.info("Starting CyTube v%s", VERSION);
var chanlogpath = path.join(__dirname, "../chanlogs");
fs.exists(chanlogpath, function (exists) {
exists || fs.mkdirSync(chanlogpath);
});
var chandumppath = path.join(__dirname, "../chandump");
fs.exists(chandumppath, function (exists) {
exists || fs.mkdirSync(chandumppath);
});
var gdvttpath = path.join(__dirname, "../google-drive-subtitles");
fs.exists(gdvttpath, function (exists) {
exists || fs.mkdirSync(gdvttpath);
});
singleton = new Server();
return singleton;
},
getServer: function () {
return singleton;
}
};
var path = require("path");
var fs = require("fs");
var https = require("https");
var express = require("express");
var Channel = require("./channel/channel");
var db = require("./database");
var Flags = require("./flags");
var sio = require("socket.io");
import LocalChannelIndex from './web/localchannelindex';
import { PartitionChannelIndex } from './partition/partitionchannelindex';
import IOConfiguration from './configuration/ioconfig';
import WebConfiguration from './configuration/webconfig';
import session from './session';
import { LegacyModule } from './legacymodule';
import { PartitionModule } from './partition/partitionmodule';
import { Gauge } from 'prom-client';
import { AccountDB } from './db/account';
import { ChannelDB } from './db/channel';
import { AccountController } from './controller/account';
import { EmailController } from './controller/email';
var Server = function () {
var self = this;
self.channels = [],
self.express = null;
self.db = null;
self.api = null;
self.announcement = null;
self.infogetter = null;
self.servers = {};
self.chanPath = Config.get('channel-path');
var initModule;
if (Config.get('enable-partition')) {
initModule = this.initModule = new PartitionModule();
self.partitionDecider = initModule.getPartitionDecider();
} else {
initModule = this.initModule = new LegacyModule();
}
const globalMessageBus = this.initModule.getGlobalMessageBus();
globalMessageBus.on('UserProfileChanged', this.handleUserProfileChange.bind(this));
globalMessageBus.on('ChannelDeleted', this.handleChannelDelete.bind(this));
globalMessageBus.on('ChannelRegistered', this.handleChannelRegister.bind(this));
// database init ------------------------------------------------------
var Database = require("./database");
self.db = Database;
self.db.init();
ChannelStore.init();
const accountDB = new AccountDB(db.getDB());
const channelDB = new ChannelDB(db.getDB());
// controllers
const accountController = new AccountController(accountDB, globalMessageBus);
let emailTransport;
if (Config.getEmailConfig().getPasswordReset().isEnabled()) {
const smtpConfig = Config.getEmailConfig().getSmtp();
emailTransport = require("nodemailer").createTransport({
host: smtpConfig.getHost(),
port: smtpConfig.getPort(),
secure: smtpConfig.isSecure(),
auth: {
user: smtpConfig.getUser(),
pass: smtpConfig.getPassword()
}
});
} else {
emailTransport = {
sendMail() {
throw new Error('Email is not enabled on this server');
}
};
}
const emailController = new EmailController(
emailTransport,
Config.getEmailConfig()
);
// webserver init -----------------------------------------------------
const ioConfig = IOConfiguration.fromOldConfig(Config);
const webConfig = WebConfiguration.fromOldConfig(Config);
const clusterClient = initModule.getClusterClient();
var channelIndex;
if (Config.get("enable-partition")) {
channelIndex = new PartitionChannelIndex(
initModule.getRedisClientProvider().get()
);
} else {
channelIndex = new LocalChannelIndex();
}
self.express = express();
require("./web/webserver").init(
self.express,
webConfig,
ioConfig,
clusterClient,
channelIndex,
session,
globalMessageBus,
accountController,
channelDB,
Config.getEmailConfig(),
emailController
);
// http/https/sio server init -----------------------------------------
var key = "", cert = "", ca = undefined;
if (Config.get("https.enabled")) {
const certData = self.loadCertificateData();
key = certData.key;
cert = certData.cert;
ca = certData.ca;
}
var opts = {
key: key,
cert: cert,
passphrase: Config.get("https.passphrase"),
ca: ca,
ciphers: Config.get("https.ciphers"),
honorCipherOrder: true
};
Config.get("listen").forEach(function (bind) {
var id = bind.ip + ":" + bind.port;
if (id in self.servers) {
LOGGER.warn("Ignoring duplicate listen address %s", id);
return;
}
if (bind.https && Config.get("https.enabled")) {
self.servers[id] = https.createServer(opts, self.express)
.listen(bind.port, bind.ip);
self.servers[id].on("clientError", function (err, socket) {
try {
socket.destroy();
} catch (e) {
// Ignore
}
});
} else if (bind.http) {
self.servers[id] = self.express.listen(bind.port, bind.ip);
self.servers[id].on("clientError", function (err, socket) {
try {
socket.destroy();
} catch (e) {
// Ignore
}
});
}
});
require("./io/ioserver").init(self, webConfig);
// background tasks init ----------------------------------------------
require("./bgtask")(self);
// prometheus server
const prometheusConfig = Config.getPrometheusConfig();
if (prometheusConfig.isEnabled()) {
require("./prometheus-server").init(prometheusConfig);
}
// setuid
require("./setuid");
initModule.onReady();
};
Server.prototype = Object.create(EventEmitter.prototype);
Server.prototype.loadCertificateData = function loadCertificateData() {
const data = {
key: fs.readFileSync(path.resolve(__dirname, "..",
Config.get("https.keyfile"))),
cert: fs.readFileSync(path.resolve(__dirname, "..",
Config.get("https.certfile")))
};
if (Config.get("https.cafile")) {
data.ca = fs.readFileSync(path.resolve(__dirname, "..",
Config.get("https.cafile")));
}
return data;
};
Server.prototype.reloadCertificateData = function reloadCertificateData() {
const certData = this.loadCertificateData();
Object.keys(this.servers).forEach(key => {
const server = this.servers[key];
// TODO: Replace with actual node API
// once https://github.com/nodejs/node/issues/4464 is implemented.
if (server._sharedCreds) {
try {
server._sharedCreds.context.setCert(certData.cert);
server._sharedCreds.context.setKey(certData.key, Config.get("https.passphrase"));
LOGGER.info('Reloaded certificate data for %s', key);
} catch (error) {
LOGGER.error('Failed to reload certificate data for %s: %s', key, error.stack);
}
}
});
};
Server.prototype.isChannelLoaded = function (name) {
name = name.toLowerCase();
for (var i = 0; i < this.channels.length; i++) {
if (this.channels[i].uniqueName == name)
return true;
}
return false;
};
const promActiveChannels = new Gauge({
name: 'cytube_channels_num_active',
help: 'Number of channels currently active'
});
Server.prototype.getChannel = function (name) {
var cname = name.toLowerCase();
if (this.partitionDecider &&
!this.partitionDecider.isChannelOnThisPartition(cname)) {
const error = new Error(`Channel '${cname}' is mapped to a different partition`);
error.code = 'EWRONGPART';
throw error;
}
var self = this;
for (var i = 0; i < self.channels.length; i++) {
if (self.channels[i].uniqueName === cname)
return self.channels[i];
}
var c = new Channel(name);
promActiveChannels.inc();
c.on("empty", function () {
self.unloadChannel(c);
});
c.waitFlag(Flags.C_ERROR, () => {
self.unloadChannel(c, { skipSave: true });
});
self.channels.push(c);
return c;
};
Server.prototype.unloadChannel = function (chan, options) {
var self = this;
if (chan.dead || chan.dying) {
return;
}
chan.dying = true;
if (!options) {
options = {};
}
if (!options.skipSave) {
chan.saveState().catch(error => {
LOGGER.error(`Failed to save /${this.chanPath}/${chan.name} for unload: ${error.stack}`);
}).then(finishUnloading);
} else {
finishUnloading();
}
function finishUnloading() {
chan.logger.log("[init] Channel shutting down");
chan.logger.close();
chan.notifyModules("unload", []);
Object.keys(chan.modules).forEach(function (k) {
chan.modules[k].dead = true;
/*
* Automatically clean up any timeouts/intervals assigned
* to properties of channel modules. Prevents a memory leak
* in case of forgetting to clear the timer on the "unload"
* module event.
*/
Object.keys(chan.modules[k]).forEach(function (prop) {
if (chan.modules[k][prop] && chan.modules[k][prop]._onTimeout) {
LOGGER.warn("Detected non-null timer when unloading " +
"module " + k + ": " + prop);
try {
clearTimeout(chan.modules[k][prop]);
clearInterval(chan.modules[k][prop]);
} catch (error) {
LOGGER.error(error.stack);
}
}
});
});
for (var i = 0; i < self.channels.length; i++) {
if (self.channels[i].uniqueName === chan.uniqueName) {
self.channels.splice(i, 1);
i--;
}
}
LOGGER.info("Unloaded channel " + chan.name);
chan.broadcastUsercount.cancel();
// Empty all outward references from the channel
Object.keys(chan).forEach(key => {
if (key !== "refCounter") {
delete chan[key];
}
});
chan.dead = true;
promActiveChannels.dec();
}
};
Server.prototype.packChannelList = function (publicOnly, isAdmin) {
var channels = this.channels.filter(function (c) {
if (!publicOnly) {
return true;
}
return c.modules.options && c.modules.options.get("show_public");
});
return channels.map(function (c) {
return c.packInfo(isAdmin);
});
};
Server.prototype.announce = function (data) {
this.setAnnouncement(data);
if (data == null) {
db.clearAnnouncement();
} else {
db.setAnnouncement(data);
}
this.emit("announcement", data);
};
Server.prototype.setAnnouncement = function (data) {
if (data == null) {
this.announcement = null;
} else {
this.announcement = data;
sio.instance.emit("announcement", data);
}
};
Server.prototype.forceSave = function () {
Promise.map(this.channels, channel => {
try {
return channel.saveState().tap(() => {
LOGGER.info(`Saved /${this.chanPath}/${channel.name}`);
}).catch(err => {
LOGGER.error(`Failed to save /${this.chanPath}/${channel.name}: ${err.stack}`);
});
} catch (error) {
LOGGER.error(`Failed to save channel: ${error.stack}`);
}
}, { concurrency: 5 }).then(() => {
LOGGER.info('Finished save');
});
};
Server.prototype.shutdown = function () {
LOGGER.info("Unloading channels");
Promise.map(this.channels, channel => {
try {
return channel.saveState().tap(() => {
LOGGER.info(`Saved /${this.chanPath}/${channel.name}`);
}).catch(err => {
LOGGER.error(`Failed to save /${this.chanPath}/${channel.name}: ${err.stack}`);
});
} catch (error) {
LOGGER.error(`Failed to save channel: ${error.stack}`);
}
}, { concurrency: 5 }).then(() => {
LOGGER.info("Goodbye");
process.exit(0);
}).catch(err => {
LOGGER.error(`Caught error while saving channels: ${err.stack}`);
process.exit(1);
});
};
Server.prototype.handlePartitionMapChange = function () {
const channels = Array.prototype.slice.call(this.channels);
Promise.map(channels, channel => {
if (channel.dead) {
return;
}
if (!this.partitionDecider.isChannelOnThisPartition(channel.uniqueName)) {
LOGGER.info("Partition changed for " + channel.uniqueName);
return channel.saveState().then(() => {
channel.broadcastAll("partitionChange",
this.partitionDecider.getPartitionForChannel(channel.uniqueName));
const users = Array.prototype.slice.call(channel.users);
users.forEach(u => {
try {
u.socket.disconnect();
} catch (error) {
// Ignore
}
});
this.unloadChannel(channel, { skipSave: true });
}).catch(error => {
LOGGER.error(`Failed to unload /${this.chanPath}/${channel.name} for ` +
`partition map flip: ${error.stack}`);
});
}
}, { concurrency: 5 }).then(() => {
LOGGER.info("Partition reload complete");
});
};
Server.prototype.reloadPartitionMap = function () {
if (!Config.get("enable-partition")) {
return;
}
this.initModule.getPartitionMapReloader().reload();
};
Server.prototype.handleUserProfileChange = function (event) {
try {
const lname = event.user.toLowerCase();
// Probably not the most efficient thing in the world, but w/e
// profile changes are not high volume
this.channels.forEach(channel => {
if (channel.dead) return;
channel.users.forEach(user => {
if (user.getLowerName() === lname && user.account.user) {
user.account.user.profile = {
image: event.profile.image,
text: event.profile.text
};
user.account.update();
channel.sendUserProfile(channel.users, user);
LOGGER.info(
'Updated profile for user %s in channel %s',
lname,
channel.name
);
}
});
});
} catch (error) {
LOGGER.error('handleUserProfileChange failed: %s', error);
}
};
Server.prototype.handleChannelDelete = function (event) {
try {
const lname = event.channel.toLowerCase();
this.channels.forEach(channel => {
if (channel.dead) return;
if (channel.uniqueName === lname) {
channel.clearFlag(Flags.C_REGISTERED);
const users = Array.prototype.slice.call(channel.users);
users.forEach(u => {
u.kick('Channel deleted');
});
if (!channel.dead && !channel.dying) {
channel.emit('empty');
}
LOGGER.info('Processed deleted channel %s', lname);
}
});
} catch (error) {
LOGGER.error('handleChannelDelete failed: %s', error);
}
};
Server.prototype.handleChannelRegister = function (event) {
try {
const lname = event.channel.toLowerCase();
this.channels.forEach(channel => {
if (channel.dead) return;
if (channel.uniqueName === lname) {
channel.clearFlag(Flags.C_REGISTERED);
const users = Array.prototype.slice.call(channel.users);
users.forEach(u => {
u.kick('Channel reloading');
});
if (!channel.dead && !channel.dying) {
channel.emit('empty');
}
LOGGER.info('Processed registered channel %s', lname);
}
});
} catch (error) {
LOGGER.error('handleChannelRegister failed: %s', error);
}
};