-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlibrary.js
More file actions
520 lines (449 loc) · 15.3 KB
/
library.js
File metadata and controls
520 lines (449 loc) · 15.3 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
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
(function(module) {
"use strict";
require('./lib/nodebb.js');
var Telegram = {};
var db = require.main.require('./src/database'),
meta = require.main.require('./src/meta'),
user = require.main.require('./src/user'),
posts = require.main.require('./src/posts'),
Topics = require.main.require('./src/topics'),
Categories = require.main.require('./src/categories'),
messaging = require.main.require('./src/messaging'),
SocketPlugins = require.main.require('./src/socket.io/plugins'),
winston = require.main.require('winston'),
nconf = require.main.require('nconf'),
async = require.main.require('async'),
S = require.main.require('string'),
cache = require('lru-cache'),
lang_cache,
translator = require.main.require('./public/src/modules/translator'),
moment = require('./lib/moment.min.js'),
pubsub = require.main.require('./src/pubsub'),
privileges = require.main.require('./src/privileges'),
Settings = require('./lib/userSettings.js')(Telegram),
// SocketAdmins = require.main.require('./socket.io/admin');
TelegramBot = require('node-telegram-bot-api');
var bot = null;
var token = null;
var message = null;
var messageQueue = {};
var plugin = {
config: {
telegramid: '',
chatid:'',
roomId:'',
maxLength: '',
postCategories: '',
topicsOnly: '',
messageContent: ''
}
};
Telegram.init = function(params, callback) {
var middleware = params.middleware,
controllers = params.controllers;
// Prepare templates
controllers.getTelegramBotAdmin = function (req, res, next) {
// Renders template (*Renderiza la plantilla)
res.render('admin/plugins/telegrambot', {});
};
// prepare parameter and start the bot
controllers.getTelegramBotSettings = function (req, res, next) {
// Renders template (*Renderiza la plantilla)
pubsub.on('telegram:me', function(me){
res.render('user/settings', {botname:me.username});
});
pubsub.publish('telegram:getMe');
};
// Create urls
params.router.get('/admin/telegrambot', middleware.buildHeader, controllers.getTelegramBotAdmin);
params.router.get('/api/admin/telegrambot', controllers.getTelegramBotAdmin);
params.router.get('/telegram/settings', Telegram.isLoggedIn, middleware.buildHeader, controllers.getTelegramBotSettings);
params.router.get('/api/telegram/settings', Telegram.isLoggedIn, controllers.getTelegramBotSettings);
// User language cache
db.getObjectField('global', 'userCount', function(err, numUsers) {
var cacheOpts = {
max: 50,
maxAge: 1000 * 60 * 60 * 24
};
if (!err && numUsers > 0) {
cacheOpts.max = Math.floor(numUsers / 20);
}
lang_cache = cache(cacheOpts);
});
// get settings
meta.settings.get('telegram-notification', function(err, settings) {
for (var prop in plugin.config) {
if (settings.hasOwnProperty(prop)) {
plugin.config[prop] = settings[prop];
}
}
token = plugin.config['telegramid'];
// Start the bot only on the primary instance and if a bot token is configured
if(nconf.get('isPrimary') && !nconf.get('jobsDisabled') && token)
{
console.log("trying to start Telegram Bot")
startBot();
if (bot) {
console.log("Telegram Bot started\n")
}
}
//else
{ // at least get token in all instances to prepare&show menus
db.getObject('telegrambot-token', function(err, t)
{
if(err || !t)
{
return;
}
message = plugin.config['messagecontent'];
});
}
});
callback();
};
function startBot()
{
// Prepare bot
messageQueue = {};
console.log("\n\n\nToken; "+token+"\n\n\n");
// Setup polling way
bot = global.telegram = new TelegramBot(token,{polling: true});
bot.on('text', function (msg) {
var chatId = msg.chat.id;
var userId = msg.from.id;
var username = msg.from.username;
var text = msg.text;
if (plugin.config['chatid'] == '')
{
plugin.config['chatid'] = chatId;
}
if(!message)
{
message = "\n Hello this is the ForumBot\n\n"+
"I am your interface to your "+
"NodeBB Forum\n\n"+
"Your Telegram ID: {userid}\n"+
"ID of this chat:<b> "+msg.chat.id+ "</b>\n"+
"Open a chat with me and type /bothelp to see, what I can do for you\n"+
"You even may enter commands here: like '/<command> <parameters>@forumbot', "+
"but I always ill answer in private chat only";
}
if (text.toLowerCase().indexOf("@forumbot") >=3)
{
var text2 = text.split("@forumbot"); //remove the @forumbot, that should be at the end of the command
text = text2.join(" "); //recover the command
}
else
{
// if (msg.text == "@ForumBot")
if (text.toLowerCase() == "@forumbot")
{
var messageToSend = message.replace("{userid}", msg.from.id);
bot.sendMessage(msg.chat.id, messageToSend);
}
else
{
if(text.indexOf("/") == 0)
{
parseCommands(userId, text);
}
}
}
});
// Notification observer.
pubsub.on('telegram:notification', function(data){
bot.sendMessage(data.telegramId, data.message).catch(function(){});
});
// Settings observer.
pubsub.on('telegram:getMe', function(){
bot.getMe().then(function(me){
pubsub.publish('telegram:me', me);
}).catch(function(){});
});
} // function startbot
var parseCommands = function(telegramId, mesg)
{
function respond(response) {
pubsub.publish('telegram:notification', {telegramId: telegramId, message: response});
}
function respondWithTranslation(uid, response) {
Telegram.getUserLanguage(uid, function(lang){
translator.translate(response, lang, function(translated) {
respond(translated);
});
});
}
if(mesg.indexOf("/") == 0)
{
db.sortedSetScore('telegramid:uid', telegramId, function(err, uid){
if(err || !uid)
{
return respond("UserID not found.. Put your TelegramID again in the telegram settings of the forum. :(");
}
var command = mesg.split(" "); // Split command
if(command[0].toLowerCase() == "/reply" && command.length >= 2)
{ // It's a reply to a topic!
var data = {};
data.uid = uid;
data.tid = command[1];
command.splice(0, 2); // Delete /reply and topic id, only keep the message
data.content = command.join(" "); // recover the message
if(messageQueue[data.uid]){
// check queue to avoid race conditions and flood with many posts
// Get user language to send the error
respondWithTranslation(uid, "[[error:too-many-messages]]");
return;
}
// update queue
messageQueue[data.uid] = true;
Topics.reply(data, function(err, postData){
delete messageQueue[data.uid];
if(err){
// Get user language to send the error
respondWithTranslation(uid, err.message);
return;
}
respondWithTranslation(uid, "[[success:topic-post]]");
return;
});
}
/* chat command kills nodebb, so disable it until it's fixed
*
else if(command[0].toLowerCase() == "/chat" && command.length >= 3)
{ // It's a reply to a topic!
var data = {};
user.getUidByUserslug(command[1], function(err, touid){
if(err || !touid)
{
return respond("Error: UserID "+command[1]+" not found);
}
data.fromuid = uid;
command.splice(0, 2); // Delete /chat and username, only keep the message
data.content = command.join(" "); // recover the message
messaging.addMessage(uid, touid, data.content, function(err, r){
if(err)
{
respond("Error..");
}
else
{
respondWithTranslation(uid, "[[success:success]]");
}
});
});
}
*/
else if(command[0].toLowerCase() == "/recent")
{
var data = {};
var numtopics = command[1] || 10;
numtopics = Math.min(30, numtopics);
Topics.getTopicsFromSet('topics:recent', uid, 0, Math.max(1, numtopics), function(err, topics) {
if (err)
{
return respond("[[error:no-recent-topics]]");
}
var response = "";
topics = topics.topics;
for(var i in topics)
{
var title = topics[i].title;
var tid = topics[i].tid;
var user = topics[i].user.username;
var time = moment.unix(topics[i].lastposttime / 1000).fromNow();
var url = nconf.get("url") + "/topic/" + tid;
response += title + " " + time + " by " + user + "\n" + url + "\n\n";
}
respond(response);
});
}
else if(command[0].toLowerCase() == "/read" && command.length >= 2)
{
var data = {};
var tid = command[1];
privileges.topics.get(tid, uid, function(err, data){
var canRead = data['topics:read'];
if(!canRead)
{
return respondWithTranslation(uid, "[[error:no-privileges]]");;
}
Topics.getPids(tid, function(err, pids){
posts.getPostsByPids(pids, uid, function(err, posts){
if (err)
{
return respond("[[error:no-posts-for-topic]]");
}
var postsuids = [];
for(var i in posts)
{
postsuids.push(posts[i].uid);
}
user.getUsersFields(postsuids, ["username"], function(err, usernames){
var response = "";
var numPosts = 10;
var start = posts.length-numPosts > 0 ? posts.length-numPosts : 0;
for(var i=start; i<posts.length;i++)
{
var username = usernames[i].username;
var content = posts[i].content;
content = content.replace(/\<[^\>]*\>/gi, "");
var tid = posts[i].tid;
var time = moment.unix(posts[i].timestamp / 1000).fromNow();
response = content + " \n " + time + " by " + username + "\n\n";
respond(response);
}
});
});
});
});
}
else if (command[0].toLowerCase() == "/bothelp")
{
var response = "I understand the following commands:\n"+
"/recent [<number>]\t- list recent <number> posts. (Default = 10)\n"+
"/reply \t\t\t<TopicId> \t- respond to forum topic <TopicId>\n"+
"/read \t\t <TopicId> \t- read latest posts form Topic <TopicId>\n";
respond(response);
}
else respond ("[[Sorry, I don't understand]] "+command+" [[try again]]");
});
}
};
Telegram.postSave = function(post) {
post = post.post;
var roomId= -plugin.config['roomId'];
var topicsOnly = plugin.config['topicsOnly'] || 'off';
if (topicsOnly === 'off' || (topicsOnly === 'on' && post.isMain)) {
var content = post.content;
async.parallel({
user: function(callback) {
user.getUserFields(post.uid, ['username', 'picture'], callback);
},
topic: function(callback) {
Topics.getTopicFields(post.tid, ['title', 'slug'], callback);
},
category: function(callback) {
Categories.getCategoryFields(post.cid, ['name', 'bgColor'], callback);
}
}, function(err, data) {
var categories = JSON.parse(plugin.config['postCategories']);
if (!categories || categories.indexOf(String(post.cid)) >= 0) {
// Trim long posts:
var maxQuoteLength = plugin.config['maxLength'] || 1024;
if (content.length > maxQuoteLength) {
content = content.substring(0, maxQuoteLength) + '...';
}
// Ensure absolute thumbnail URL:
var thumbnail = data.user.picture.match(/^\//) ? forumURL + data.user.picture : data.user.picture;
// Add custom message:
var messageContent = plugin.config['messageContent']+"\n"+content;
messageContent += "\n\n"+nconf.get('url')+'/topic/'+data.topic.slug+"/";
// messageContent = S(messageContent).unescapeHTML().stripTags().unescapeHTML().s
/*
// Make the rich embed:
var embed = new Discord.RichEmbed()
.setColor(data.category.bgColor)
.setURL(forumURL + '/topic/' + data.topic.slug)
.setTitle(data.category.name + ': ' + data.topic.title)
.setDescription(content)
.setFooter(data.user.username, thumbnail)
.setTimestamp();
*/
// Send notification:
if (bot) {
bot.sendMessage(roomId,messageContent).catch(console.error);
}
else console.log ("Telegram: No bot found:");
}
});
}
},
Telegram.getUserLanguage = function(uid, callback) {
if (lang_cache && lang_cache.has(uid)) {
callback(null, lang_cache.get(uid));
} else {
user.getSettings(uid, function(err, settings) {
var language = settings.language || meta.config.defaultLang || 'en_GB';
callback(null, language);
lang_cache.set(uid, language);
});
}
};
/* changed notification mechanism
* Users need to join the configured Telegram room now in order to be notified,
* as there may be non- forum members on telegram.
* the method below can be enabled again to provide additional notifications to
* forum users with configured telegram ID
*/
Telegram.pushNotification = function(data) {
var notifObj = data.notification;
var uids = data.uids;
console.log('pushNotification:\n',notifObj);
if (!Array.isArray(uids) || !uids.length || !notifObj)
{
return;
}
if(notifObj.nid && notifObj.nid.indexOf("post_flag") > -1)
{ // Disable notifications from flags.
return;
}
// Send notification for each user.
user.getUsersFields(uids, ["telegramid"], function(err, usersData){
async.eachSeries(usersData, function iterator(user, cb){
var telegramId = user.telegramid;
var uid = user.uid;
async.waterfall([
function(next){
// Get user language
Telegram.getUserLanguage(uid, next);
},
function(lang, next) {
// Prepare notification with the user language
notifObj.bodyLong = notifObj.bodyLong || '';
notifObj.bodyLong = S(notifObj.bodyLong).unescapeHTML().stripTags().unescapeHTML().s;
async.parallel({
title: function(next) {
translator.translate(notifObj.bodyShort, lang, function(translated) {
next(undefined, S(translated).stripTags().s);
});
},
postIndex: async.apply(posts.getPidIndex, notifObj.pid, notifObj.tid, ''),
topicSlug: async.apply(Topics.getTopicFieldByPid, 'slug', notifObj.pid)
}, next);
},
function(data, next) {
// Send notification
var title = data.title;
var url = nconf.get('url') + notifObj.path;
var body = title + "\n\n" + notifObj.bodyLong + "\n\n" + url;
winston.verbose('[plugins/telegram] Sending notification to uid ' + uid);
pubsub.publish('telegram:notification', {telegramId: telegramId, message: body});
cb(); // Go next user in array (async.eachSeries)
}
]);
});
});
};
/**/
Telegram.addNavigation = function(custom_header, callback) {
// Adding to admin menu access to see logs (*Añadimos al menu de admin el acceso a ver los registros)
custom_header.plugins.push({
route: '/telegrambot',
icon: '',
name: 'Telegram Notifications'
});
callback(null, custom_header);
}
Telegram.isLoggedIn = function(req, res, next) {
// Check if user is logged in (for middleware)
if (req.user && parseInt(req.user.uid, 10) > 0)
{
next();
}
else
{
res.redirect('403');
}
}
module.exports = Telegram;
}(module));