-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
521 lines (486 loc) · 14.6 KB
/
index.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
'use strict';
/**
* NodeBB provider module
* @module sockbot.providers.nodebb
* @author Accalia
* @license MIT
*/
const debug = require('debug')('sockbot:provider:nodebb');
const EventEmitter = require('events').EventEmitter;
const io = require('socket.io-client'),
request = require('request');
const utils = require('../../lib/utils'),
postModule = require('./post'),
topicModule = require('./topic'),
categoryModule = require('./category'),
userModule = require('./user'),
notifications = require('./notification'),
chatModule = require('./chat'),
formatters = require('./format');
/**
* Forum connector
*
* Connects to a NodeBB forum
*/
class Forum extends EventEmitter {
/**
* Get announced compatibilities string for the provider
*/
static get compatibilities() {
return '(nodebb/compatible) (wtdwtf/compatible)';
}
/**
* Create a forum connector instance
*
* @public
* @class
*
* @param {object} config Bot configuration data
* @param {string} useragent Useragent to use for all requests
*/
constructor(config, useragent) {
super();
utils.mapSet(this, {
config: config,
useragent: useragent
});
this.Post = postModule.bindPost(this);
this.Topic = topicModule.bindTopic(this);
this.Category = categoryModule.bindCategory(this);
this.User = userModule.bindUser(this);
this.Notification = notifications.bindNotification(this);
this.PrivateMessage = chatModule.bindChat(this);
this.Chat = this.PrivateMessage;
this.Format = formatters;
this._plugins = [];
}
/**
* Bot instance configuration
*
* @public
*
* @type {object}
*/
get config() {
return JSON.parse(JSON.stringify(utils.mapGet(this, 'config')));
}
/**
* Useragent used by the instance
*
* @public
*
* @type {string}
*/
get useragent() {
return utils.mapGet(this, 'useragent');
}
/**
* Base URL for the forum
*
* @public
*
* @type {string}
*/
get url() {
return this.config.core.forum;
}
/**
* Username bot will log in as
*
* @public
*
* @type{string}
*/
get username() {
return this.config.core.username;
}
/**
* Logged in Bot Username
*
* @public
*
* @type {User}
*/
get user() {
return utils.mapGet(this, 'user');
}
/**
* Bot instance Owner user
*
* @public
*
* @type {User}
*/
get owner() {
return utils.mapGet(this, 'owner');
}
/**
* Get Commands object bound to this instance
*
* @public
*
* @type {Commands}
*/
get Commands() {
return utils.mapGet(this, 'commands');
}
/**
* Store Commands object bound to this instance
*
* @private
*
* @param {Commands} commands commands Instance
*/
set Commands(commands) {
utils.mapSet(this, 'commands', commands);
}
/**
* Verify that cookiejar is set properly
*
* @private
*/
_verifyCookies() {
const jar = this._cookiejar || request.jar();
this._cookiejar = jar;
}
/**
* Get forum configuration for CSRF token
*
* @private
*
* @returns {Promise} Resolves after config is retrieved
*/
_getConfig() {
this._verifyCookies();
this._config = {};
return new Promise((resolve, reject) => {
debug('begin configuration fetch for CSRF token');
request.get({
url: `${this.url}/api/config`,
jar: this._cookiejar,
headers: {
'User-Agent': this.useragent
}
}, (err, _, data) => {
if (err) {
debug('failed configuration fetch for CSRF token');
if (!(err instanceof Error)) {
err = new Error(err);
}
return reject(err);
}
try {
debug('completed configuration fetch for CSRF token');
this._config = JSON.parse(data);
return resolve(this._config);
} catch (jsonErr) {
debug('parse of retrieved configuration data failed');
return reject(jsonErr);
}
});
});
}
/**
* Login to forum instance
*
* @returns {Promise<Forum>} Resolves to logged in forum
*
* @promise
* @fulfill {Forum} Logged in forum
*/
login() {
const errorify = (err) => {
if (!(err instanceof Error)) {
err = new Error(err);
}
return err;
};
return this._getConfig()
.then((config) => new Promise((resolve, reject) => {
this._verifyCookies();
debug('begin post login data');
request.post({
url: `${this.url}/login`,
jar: this._cookiejar,
headers: {
'User-Agent': this.useragent,
'x-csrf-token': config.csrf_token
},
form: {
username: this.config.core.username,
password: this.config.core.password,
remember: 'off',
returnTo: this.url
}
}, (loginError, response, reason) => {
if (loginError) {
debug(`Login failed for reason: ${loginError}`);
return reject(errorify(loginError));
}
if (response.statusCode >= 400) {
debug(`Login failed for reason: ${reason}`);
return reject(errorify(reason));
}
debug('complete post login data');
return resolve();
});
}))
.then(() => this);
}
/**
* Connect to remote websocket
*
* @public
*
* @returns {Promise<Forum>} Resolves to connected forum
*
* @promise
* @resolves {Forum} Connected forum
*/
connectWebsocket() {
if (this.socket) {
return Promise.resolve(this);
}
const promisefn = (resolve, reject) => {
this._verifyCookies();
const cookies = this._cookiejar.getCookieString(this.url);
this.socket = Forum.io(this.url, {
extraHeaders: {
'Origin': this.url,
'User-Agent': this.useragent,
'Cookie': cookies
}
});
this.socket.on('pong', (data) => this.emit('log', `Ping exchanged with ${data}ms latency`));
this.socket.on('connect', () => this.emit('connect'));
this.socket.on('disconnect', () => this.emit('disconnect'));
this.socket.once('connect', () => resolve());
this.socket.once('error', (err) => reject(err));
};
return new Promise(promisefn)
.then(() => this);
}
/**
* Plugin Generator Function
*
* @typedef {PluginFn}
* @function
*
* @param {Forum} forum Forum provider instance
* @param {object} config Plugin configuration
* @returns {Plugin} Generated plugin
*
*/
/**
* Plugin Generator Object
*
* @typedef {PluginGenerator}
*
* @property {PluginFn} plugin Plugin generating function
*
*/
/**
* Promising Function
*
* @typedef {promiseFunction}
* @function
*
* @returns {Promise} Resolves when function is complete
*
*/
/**
* Plugin Object
*
* @typedef {Plugin}
*
* @property {promiseFunction} activate Activates plugin
* @property {promiseFunction} deactivate Deactivates plugin
*
*/
/**
* Add a plugin to this forum instance
*
* @public
*
* @param {PluginFn|PluginGenerator} fnPlugin Plugin Generator
* @param {object} pluginConfig Plugin configuration
* @returns {Promise} Resolves on completion
*
* @promise
* @fulfill {*} Plugin addedd successfully
* @reject {Error} Generated plugin is invalid
*/
addPlugin(fnPlugin, pluginConfig) {
return new Promise((resolve, reject) => {
let fn = fnPlugin;
if (typeof fn !== 'function') {
fn = fn.plugin;
}
const plugin = fn(this, pluginConfig);
if (typeof plugin !== 'object') {
return reject(new Error('[[invalid_plugin:no_plugin_object]]'));
}
if (typeof plugin.activate !== 'function') {
return reject(new Error('[[invalid_plugin:no_activate_function]]'));
}
if (typeof plugin.deactivate !== 'function') {
return reject(new Error('[[invalid_plugin:no_deactivate_function]]'));
}
this._plugins.push(plugin);
return resolve();
});
}
/**
* Activate forum and plugins
*
* @returns {Promise} Resolves when all plugins have been enabled
*/
activate() {
return this.connectWebsocket()
.then(() => Promise.all([
this.User.getByName(this.config.core.username),
this.User.getByName(this.config.core.owner)
]))
.then((data) => {
utils.mapSet(this, 'user', data[0]);
utils.mapSet(this, 'owner', data[1]);
})
.then(() => {
this.Notification.activate();
this.Chat.activate();
return Promise.all(this._plugins.map((plugin) => plugin.activate()));
})
.then(() => this);
}
/**
* Deactivate forum and plugins
*
* @returns {Promise} Resolves when all plugins have been disabled
*/
deactivate() {
const promiser = (resolve, reject) => {
this.Notification.deactivate();
this.Chat.deactivate();
return Promise.all(this._plugins.map((plugin) => plugin.deactivate()))
.then(resolve)
.catch(reject);
};
return new Promise(promiser)
.then(() => this);
}
/**
* Supports: does the provider support a given feature?
*
* @param {string|strng[]} supportString The feature string.
* Feature strings consist of one or more features connected by dots.
* May also be an array of such strings
* @returns {boolean} True if all levels of feature supplied are supported,
* false if not. In the case of an array, will only be true if all
* strings are supported
*/
supports(supportString) {
const supported = [
'PrivateMessage',
'Users', 'Users.Avatars', 'Users.AvatarUpload', 'Users.Follow', 'Users.URL', 'Users.Seen',
'Users.PostCount',
'Posts', 'Posts.Edit', 'Posts.Vote', 'Posts.Delete', 'Posts.Bookmark', 'Posts.URL',
'Topics', 'Topics.URL', 'Topics.Watch', 'Topics.Mute', 'Topics.Lock',
'Categories',
'Notifications', 'Notifications.URL',
'Formatting', 'Formatting.Markup', 'Formatting.Markup.Markdown',
'Formatting.Multiline', 'Formatting.Links', 'Formatting.Images', 'Formatting.Spoilers',
'Formatting.Preformat', 'Formatting.Strikethrough', 'Formatting.List'
];
let support = false;
if (Array.isArray(supportString)) {
support = supportString.reduce((value, item) => {
return value && this.supports(item);
}, true);
return support;
}
if (supported.indexOf(supportString) > -1) {
support = true;
}
return support;
}
/**
* Emit a websocket event
*
* @private
*
* @param {string} event Event to emit
* @param {*} args... Event arguments
* @returns {Promise<*>} Resolves to result of websocket event
*
* @promise
* @fulfill {*} Resilt of websocket call
*/
_emit() {
const args = Array.prototype.slice.call(arguments);
return new Promise((resolve, reject) => {
args.push(function continuation(err) {
if (err) {
if (!(err instanceof Error)) {
if (typeof err !== 'string' && typeof err.message === 'string') {
err = err.message;
}
err = new Error(err);
}
return reject(err);
}
const results = Array.prototype.slice.call(arguments);
results.shift(); // Shift off the `err` argument
if (results.length < 2) {
return resolve(results[0]);
}
return resolve(results);
});
this.socket.emit.apply(this.socket, args);
});
}
_emitWithRetry(delay) {
let trials = 5;
const args = Array.prototype.slice.call(arguments);
args.shift(); // remove the delay parameter
const fn = () => new Promise((resolve, reject) => {
this._emit.apply(this, args).then(resolve, (err) => {
if (trials > 1 && err.message.indexOf('[[error:too-many-') === 0){
trials -= 1;
setTimeout(() => {
fn().then(resolve, reject);
}, delay);
} else {
reject(err);
}
});
});
return fn();
}
/**
* Parser function
*
* @typedef {ParserFunction}
* @function
*
* @param {*} data Data to Parse
* @returns {T} Parsed object
*/
/**
* Retrieve and parse an object
*
* @public
*
* @param {string} func Websocket function to retrieve object from
* @param {*} id Id parameter to websocket function
* @param {ParserFunction<T>} parser Parse function to apply to retrieved data
* @returns {Promise<T>} Resolves to retrieved and parsed object
*
* @promise
* @fullfil {T} Retrieved and parsed object
*/
fetchObject(func, id, parser) {
return this._emit(func, id).then((data) => parser(data));
}
}
Forum.io = io;
module.exports = Forum;