-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
index.js
367 lines (311 loc) · 10.5 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
'use strict';
const fs = require('fs');
const path = require('path');
const async = require('async');
const winston = require('winston');
const semver = require('semver');
const nconf = require('nconf');
const request = require('request-promise-native');
const user = require('../user');
const posts = require('../posts');
const utils = require('../utils');
const { pluginNamePattern, themeNamePattern, paths } = require('../constants');
var app;
var middleware;
const Plugins = module.exports;
require('./install')(Plugins);
require('./load')(Plugins);
require('./hooks')(Plugins);
require('./usage')(Plugins);
Plugins.data = require('./data');
Plugins.getPluginPaths = Plugins.data.getPluginPaths;
Plugins.loadPluginInfo = Plugins.data.loadPluginInfo;
Plugins.pluginsData = {};
Plugins.libraries = {};
Plugins.loadedHooks = {};
Plugins.staticDirs = {};
Plugins.cssFiles = [];
Plugins.lessFiles = [];
Plugins.acpLessFiles = [];
Plugins.clientScripts = [];
Plugins.acpScripts = [];
Plugins.libraryPaths = [];
Plugins.versionWarning = [];
Plugins.languageData = {};
Plugins.loadedPlugins = [];
Plugins.initialized = false;
Plugins.requireLibrary = function (pluginData) {
let libraryPath;
// attempt to load a plugin directly with `require("nodebb-plugin-*")`
// Plugins should define their entry point in the standard `main` property of `package.json`
try {
libraryPath = pluginData.path;
Plugins.libraries[pluginData.id] = require(libraryPath);
} catch (e) {
// DEPRECATED: @1.15.0, remove in version >=1.17
// for backwards compatibility
// if that fails, fall back to `pluginData.library`
if (pluginData.library) {
winston.warn(` [plugins/${pluginData.id}] The plugin.json field "library" is deprecated. Please use the package.json field "main" instead.`);
winston.verbose(`[plugins/${pluginData.id}] See https://github.com/NodeBB/NodeBB/issues/8686`);
libraryPath = path.join(pluginData.path, pluginData.library);
Plugins.libraries[pluginData.id] = require(libraryPath);
} else {
throw e;
}
}
Plugins.libraryPaths.push(libraryPath);
};
Plugins.init = async function (nbbApp, nbbMiddleware) {
if (Plugins.initialized) {
return;
}
if (nbbApp) {
app = nbbApp;
middleware = nbbMiddleware;
}
if (global.env === 'development') {
winston.verbose('[plugins] Initializing plugins system');
}
await Plugins.reload();
if (global.env === 'development') {
winston.info('[plugins] Plugins OK');
}
Plugins.initialized = true;
};
Plugins.reload = async function () {
// Resetting all local plugin data
Plugins.libraries = {};
Plugins.loadedHooks = {};
Plugins.staticDirs = {};
Plugins.versionWarning = [];
Plugins.cssFiles.length = 0;
Plugins.lessFiles.length = 0;
Plugins.acpLessFiles.length = 0;
Plugins.clientScripts.length = 0;
Plugins.acpScripts.length = 0;
Plugins.libraryPaths.length = 0;
Plugins.loadedPlugins.length = 0;
await user.addInterstitials();
const paths = await Plugins.getPluginPaths();
for (const path of paths) {
/* eslint-disable no-await-in-loop */
await Plugins.loadPlugin(path);
}
// If some plugins are incompatible, throw the warning here
if (Plugins.versionWarning.length && nconf.get('isPrimary')) {
console.log('');
winston.warn('[plugins/load] The following plugins may not be compatible with your version of NodeBB. This may cause unintended behaviour or crashing. In the event of an unresponsive NodeBB caused by this plugin, run `./nodebb reset -p PLUGINNAME` to disable it.');
for (var x = 0, numPlugins = Plugins.versionWarning.length; x < numPlugins; x += 1) {
console.log(' * '.yellow + Plugins.versionWarning[x]);
}
console.log('');
}
// Possibly put these in a different file...
Plugins.registerHook('core', {
hook: 'filter:parse.post',
method: async (data) => {
data.postData.content = posts.sanitize(data.postData.content);
return data;
},
});
Plugins.registerHook('core', {
hook: 'filter:parse.raw',
method: async content => posts.sanitize(content),
});
Plugins.registerHook('core', {
hook: 'filter:parse.aboutme',
method: async content => posts.sanitize(content),
});
Plugins.registerHook('core', {
hook: 'filter:parse.signature',
method: async (data) => {
data.userData.signature = posts.sanitize(data.userData.signature);
return data;
},
});
Plugins.registerHook('core', {
hook: 'filter:settings.set',
method: async ({ plugin, settings, quiet }) => {
if (plugin === 'core.api' && Array.isArray(settings.tokens)) {
// Generate tokens if not present already
settings.tokens.forEach((set) => {
if (set.token === '') {
set.token = utils.generateUUID();
}
if (isNaN(parseInt(set.uid, 10))) {
set.uid = 0;
}
});
}
return { plugin, settings, quiet };
},
});
// Lower priority runs earlier
Object.keys(Plugins.loadedHooks).forEach(function (hook) {
Plugins.loadedHooks[hook].sort((a, b) => a.priority - b.priority);
});
// Post-reload actions
await posts.configureSanitize();
};
Plugins.reloadRoutes = async function (params) {
var controllers = require('../controllers');
await Plugins.fireHook('static:app.load', { app: app, router: params.router, middleware: middleware, controllers: controllers });
winston.verbose('[plugins] All plugins reloaded and rerouted');
};
Plugins.get = async function (id) {
const url = (nconf.get('registry') || 'https://packages.nodebb.org') + '/api/v1/plugins/' + id;
const body = await request(url, {
json: true,
});
let normalised = await Plugins.normalise([body ? body.payload : {}]);
normalised = normalised.filter(plugin => plugin.id === id);
return normalised.length ? normalised[0] : undefined;
};
Plugins.list = async function (matching) {
if (matching === undefined) {
matching = true;
}
const version = require(paths.currentPackage).version;
const url = (nconf.get('registry') || 'https://packages.nodebb.org') + '/api/v1/plugins' + (matching !== false ? '?version=' + version : '');
try {
const body = await request(url, {
json: true,
});
return await Plugins.normalise(body);
} catch (err) {
winston.error('Error loading ' + url, err);
return await Plugins.normalise([]);
}
};
Plugins.listTrending = async () => {
const url = `${nconf.get('registry') || 'https://packages.nodebb.org'}/api/v1/analytics/top/week`;
return await request(url, {
json: true,
});
};
Plugins.normalise = async function (apiReturn) {
const pluginMap = {};
const dependencies = require(paths.currentPackage).dependencies;
apiReturn = Array.isArray(apiReturn) ? apiReturn : [];
apiReturn.forEach(function (packageData) {
packageData.id = packageData.name;
packageData.installed = false;
packageData.active = false;
packageData.url = packageData.url || (packageData.repository ? packageData.repository.url : '');
pluginMap[packageData.name] = packageData;
});
let installedPlugins = await Plugins.showInstalled();
installedPlugins = installedPlugins.filter(plugin => plugin && !plugin.system);
installedPlugins.forEach(function (plugin) {
// If it errored out because a package.json or plugin.json couldn't be read, no need to do this stuff
if (plugin.error) {
pluginMap[plugin.id] = pluginMap[plugin.id] || {};
pluginMap[plugin.id].installed = true;
pluginMap[plugin.id].error = true;
return;
}
pluginMap[plugin.id] = pluginMap[plugin.id] || {};
pluginMap[plugin.id].id = pluginMap[plugin.id].id || plugin.id;
pluginMap[plugin.id].name = plugin.name || pluginMap[plugin.id].name;
pluginMap[plugin.id].description = plugin.description;
pluginMap[plugin.id].url = pluginMap[plugin.id].url || plugin.url;
pluginMap[plugin.id].installed = true;
pluginMap[plugin.id].isTheme = themeNamePattern.test(plugin.id);
pluginMap[plugin.id].error = plugin.error || false;
pluginMap[plugin.id].active = plugin.active;
pluginMap[plugin.id].version = plugin.version;
pluginMap[plugin.id].settingsRoute = plugin.settingsRoute;
pluginMap[plugin.id].license = plugin.license;
// If package.json defines a version to use, stick to that
if (dependencies.hasOwnProperty(plugin.id) && semver.valid(dependencies[plugin.id])) {
pluginMap[plugin.id].latest = dependencies[plugin.id];
} else {
pluginMap[plugin.id].latest = pluginMap[plugin.id].latest || plugin.version;
}
pluginMap[plugin.id].outdated = semver.gt(pluginMap[plugin.id].latest, pluginMap[plugin.id].version);
});
const pluginArray = [];
for (var key in pluginMap) {
if (pluginMap.hasOwnProperty(key)) {
pluginArray.push(pluginMap[key]);
}
}
pluginArray.sort(function (a, b) {
if (a.name > b.name) {
return 1;
} else if (a.name < b.name) {
return -1;
}
return 0;
});
return pluginArray;
};
Plugins.nodeModulesPath = paths.nodeModules;
Plugins.showInstalled = async function () {
const dirs = await fs.promises.readdir(Plugins.nodeModulesPath);
let pluginPaths = await findNodeBBModules(dirs);
pluginPaths = pluginPaths.map(dir => path.join(Plugins.nodeModulesPath, dir));
async function load(file) {
try {
const pluginData = await Plugins.loadPluginInfo(file);
const isActive = await Plugins.isActive(pluginData.name);
delete pluginData.hooks;
delete pluginData.library;
pluginData.active = isActive;
pluginData.installed = true;
pluginData.error = false;
return pluginData;
} catch (err) {
winston.error(err.stack);
}
}
const plugins = await Promise.all(pluginPaths.map(file => load(file)));
return plugins.filter(Boolean);
};
async function findNodeBBModules(dirs) {
const pluginPaths = [];
await async.each(dirs, function (dirname, next) {
var dirPath = path.join(Plugins.nodeModulesPath, dirname);
async.waterfall([
function (cb) {
fs.stat(dirPath, function (err, stats) {
if (err && err.code !== 'ENOENT') {
return cb(err);
}
if (err || !stats.isDirectory()) {
return next();
}
if (pluginNamePattern.test(dirname)) {
pluginPaths.push(dirname);
return next();
}
if (dirname[0] !== '@') {
return next();
}
fs.readdir(dirPath, cb);
});
},
function (subdirs, cb) {
async.each(subdirs, function (subdir, next) {
if (!pluginNamePattern.test(subdir)) {
return next();
}
var subdirPath = path.join(dirPath, subdir);
fs.stat(subdirPath, function (err, stats) {
if (err && err.code !== 'ENOENT') {
return next(err);
}
if (err || !stats.isDirectory()) {
return next();
}
pluginPaths.push(dirname + '/' + subdir);
next();
});
}, cb);
},
], next);
});
return pluginPaths;
}
require('../promisify')(Plugins);