-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
299 lines (267 loc) · 10.8 KB
/
index.js
File metadata and controls
299 lines (267 loc) · 10.8 KB
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
const jwt = require('jsonwebtoken');
const nconf = require.main.require('nconf');
const winston = require.main.require('winston');
const api = require.main.require('./src/api');
const meta = require.main.require('./src/meta');
const user = require.main.require('./src/user');
const db = require.main.require('./src/database');
const search = require.main.require('./src/search');
const topics = require.main.require('./src/topics');
const messaging = require.main.require('./src/messaging');
const categories = require.main.require('./src/categories');
const middleware = require.main.require('./src/middleware');
const helpers = require.main.require('./src/controllers/helpers');
const routeHelpers = require.main.require('./src/routes/helpers');
//const shouts = require('../nodebb-plugin-shoutbox/lib/shouts');
//const socketPlugins = require.main.require('./src/socket.io/plugins');
const MFF_USER_UID = 1;
const MFFDiscordBridge = {
token: "changeMe",
discordWebHook: "changeMe",
jwtSecret: "changeMe",
registrationCallback: "changeMe",
tutorialCategoryId: 0,
supportCategoryId: 0,
// Init the plugin
async init(params) {
const { router } = params;
// Discord bridge api
router.get('/discordapi/tutorial', getTutorial);
router.get('/discordapi/solvedthread', getSolvedThread);
//app.post('/discordapi/sendshout', checkToken, sendShout);
// Discord link account page
routeHelpers.setupPageRoute(router, '/discord', [middleware.ensureLoggedIn], showLinkAccountPage);
router.post('/discord', middleware.ensureLoggedIn, linkDiscordAccount);
// Admin panel
routeHelpers.setupAdminPageRoute(router, '/admin/plugins/mff-discord', renderAdmin);
try {
const options = await meta.settings.get('mffdiscordbridge');
if (options.hasOwnProperty("token")) {
MFFDiscordBridge.token = options["token"];
}
if (options.hasOwnProperty("webhook")) {
MFFDiscordBridge.discordWebHook = options["webhook"];
}
if (options.hasOwnProperty("jwtSecret")) {
MFFDiscordBridge.jwtSecret = options["jwtSecret"];
}
if (options.hasOwnProperty("registrationCallback")) {
MFFDiscordBridge.registrationCallback = options["registrationCallback"];
}
if (options.hasOwnProperty("tutorialCategoryId")) {
MFFDiscordBridge.tutorialCategoryId = options["tutorialCategoryId"];
}
if (options.hasOwnProperty("supportCategoryId")) {
MFFDiscordBridge.supportCategoryId = options["supportCategoryId"];
}
}
catch (err) {
console.log(`[plugin/mffdiscordbridge] Unable to retrieve settings, will keep defaults: ${err.message}`);
}
// let originSend = socketPlugins.shoutbox.send;
// socketPlugins.shoutbox.send = (socket, data, callback) => {
// originSend(socket, data, callback); // call send from nodebb-plugin-shoutbox
// if (socket.uid && data && data.message) {
// user.getUsersWithFields([socket.uid], ['username', 'picture'], socket.uid, (err, userData) => {
// if (!err && userData && userData[0]) {
// let avatarUrl = userData[0].picture.startsWith("http") ? userData[0].picture : (nconf.get('url') + userData[0].picture);
// request.post(MFFDiscordBridge.discordWebHook, {
// json: {
// username: userData[0].username,
// avatar_url: avatarUrl,
// content: data.message.replace(/\@(here|everyone)/gi, "$1")
// }
// }, (error, response, body) => {
// if (error) {
// console.log(error);
// }
// });
// }
// });
// }
// };
},
async addToAdminNav(header) {
header.plugins.push({
route: '/plugins/mff-discord',
name: 'MFF Discord bridge',
});
return header;
}
};
function showLinkAccountPage(req, res) {
const jwtToken = req.query.token;
try {
const decoded = jwt.verify(jwtToken, MFFDiscordBridge.jwtSecret);
return res.render('discord-link', {
breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[mff-discord:link.discord]]' }]),
title: '[[mff-discord:link.discord]]',
id: decoded.id,
displayName: decoded.displayName,
avatarUrl: decoded.avatarUrl
});
}
catch (err) {
winston.error('Fail to decode token', err);
return res.render('500', {
title: '[[mff-discord:link.discord]]',
error: '[[mff-discord:link.error]]',
});
}
}
async function linkDiscordAccount(req, res) {
const jwtToken = req.query.token;
try {
const decoded = jwt.verify(jwtToken, MFFDiscordBridge.jwtSecret);
// Re-encode the token with the uid of the user on the forum
const newToken = jwt.sign({ ...decoded, forumUid: req.user.uid }, MFFDiscordBridge.jwtSecret);
try {
const response = await fetch(MFFDiscordBridge.registrationCallback, {
method: 'POST',
headers: {
'User-Agent': 'MFF Discord Bridge',
'Content-Type': 'application/json',
},
body: JSON.stringify({
token: newToken,
}),
});
const data = await response.json();
res.status(response.status).json(data);
}
catch (reqErr) {
return res.status(500).json({ error: '[[mff-discord:request.error]]' });
}
}
catch (jwtErr) {
return res.status(500).json({ error: '[[mff-discord:link.error]]' });
}
}
// check token middleware
function checkToken(req, res, next) {
let token = req.body.token || req.query.token || "";
if (token === MFFDiscordBridge.token) {
next();
} else {
res.status(403).json({ message: "Invalid token!" });
}
}
function getTutorial(req, res) {
return searchInPost(req, res, [MFFDiscordBridge.tutorialCategoryId]);
}
function getSolvedThread(req, res) {
return searchInPost(req, res, [MFFDiscordBridge.supportCategoryId]);
}
async function searchInPost(req, res, categories) {
const data = {
query: req.query.term,
searchIn: 'titles',
matchWords: 'all',
categories: categories,
searchChildren: true,
hasTags: req.query.hasTags,
sortBy: '',
qs: req.query
};
try {
const results = await search.search(data);
const topicIds = results.posts.map(post => post && post.tid);
try {
const postTags = await topics.getTopicsTags(topicIds);
if (results.posts.length === 0) {
return res.status(200).json({ data: [] });
}
let response = {};
if (!req.query.hasTags) { // only add none tag if there is not tags filter in the request
response['none'] = [];
}
for (const tags of postTags) {
for (const tag of tags) {
if (isTagInFilter(tag, req.query.hasTags)) {
response[tag] = [];
}
}
}
for (const i in results.posts) {
let post = {
title: results.posts[i].topic.title,
url: nconf.get('url') + '/topic/' + results.posts[i].topic.slug
};
if (postTags[i].length === 0) {
response['none'].push(post);
} else {
for (const tag of postTags[i]) {
// avoid duplicate if topic has multiple tags
if (isTagInFilter(tag, req.query.hasTags)) {
response[tag].push(post);
}
}
}
}
return res.status(200).json({ data: response });
}
catch (err2) {
winston.error(err2);
return res.status(500).json({ message: 'Error while getting topic tags' });
}
}
catch (err) {
winston.error(err);
return res.status(500).json({ message: 'Error while performing the search' });
}
}
function isTagInFilter(tag, tagsFilter) {
return !tagsFilter || (tagsFilter && tagsFilter.indexOf(tag) >= 0);
}
// function sendShout(req, res) {
// if (req.body.senderId && req.body.message && req.body.mentions) {
// user.exists(req.body.senderId, (isExist) => {
// user.getUsernamesByUids(req.body.mentions, (err, usernames) => {
// if (err) {
// console.error(`Couldn't find the name for an user : ${err}`);
// return res.status(500).json({error: "Couldn't retrieve an user from given id"});
// }
// if (usernames.indexOf(0) !== -1) {
// return res.status(500).json({error: "User not found"});
// }
// let index = 0;
// const message = req.body.message.replace(/<@![0-9]+>/g, function () {
// return '@' + usernames[index++];
// });
// shouts.addShout(req.body.senderId, message, function (err, shout) {
// if (err) {
// return res.status(500).json({error: "Failed to send shout"});
// }
// shout.fromBot = true;
// socketIndex.server.sockets.emit('event:shoutbox.receive', shout);
// return res.status(200).json({success: "true"});
// });
// });
// if (isExist)
// return res.status(500).json({error: "User not found"});
// });
// } else {
// res.status(400).json({error: "Missing arguments"});
// }
// }
async function renderAdmin(req, res) {
const cids = await db.getSortedSetRange('categories:cid', 0, -1);
const cats = await categories.getCategoriesFields(cids, ['cid', 'name']);
res.render('admin/plugins/mff-discord', {
title: 'MFF Discord integration',
categories: cats
});
}
function randomizeNumber() {
let number = "";
for (let i = 0; i < 6; i++) {
number += getRandomIntInclusive(0, 9);
}
return number;
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
module.exports = MFFDiscordBridge;