-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary.js
More file actions
395 lines (346 loc) · 10.3 KB
/
library.js
File metadata and controls
395 lines (346 loc) · 10.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
"use strict";
var db = module.parent.require('./database'),
meta = module.parent.require('./meta'),
user = module.parent.require('./user'),
posts = module.parent.require('./posts'),
topics = module.parent.require('./topics'),
messaging = module.parent.require('./messaging'),
SocketPlugins = module.parent.require('./socket.io/plugins'),
winston = module.parent.require('winston'),
nconf = module.parent.require('nconf'),
async = module.parent.require('async'),
S = module.parent.require('string'),
cache = require('lru-cache'),
lang_cache,
translator = module.parent.require('../public/src/modules/translator'),
moment = require('./lib/moment.min.js'),
pubsub = module.parent.require('./pubsub'),
Telegram = {};
var SocketAdmins = module.parent.require('./socket.io/admin');
var TelegramBot = require('node-telegram-bot-api');
var token = null;
var message = null;
Telegram.init = function(params, callback) {
var middleware = params.middleware,
controllers = params.controllers;
// Prepare templates
controllers.getTelegramBotAdmin = function (req, res, next) {
// Renderiza la plantilla
res.render('admin/plugins/telegrambot', {});
};
controllers.getTelegramBotSettings = function (req, res, next) {
// Renderiza la plantilla
pubsub.once('telegram:me', function(me){
res.render('telegrambot/telegramusersettings', {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', middleware.buildHeader, controllers.getTelegramBotSettings);
params.router.get('/api/telegram/settings', 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);
});
// Start the bot only on the primary instance.
if(nconf.get('isPrimary') === 'true' && !nconf.get('jobsDisabled') && !global.telegram) startBot();
callback();
};
function startBot()
{
// Prepare bot
db.getObject('telegrambot-token', function(err, t){
if(err || !t)
{
return;
}
token = t.token;
message = t.msg;
// Setup polling way
var 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(!message)
{
message = "Your Telegram ID: {userid}";
}
if(text.indexOf("/") == 0)
{
parseCommands(userId, text);
}
else
{
var messageToSend = message.replace("{userid}", msg.from.id);
bot.sendMessage(msg.chat.id, messageToSend);
}
});
// Notification observer.
pubsub.on('telegram:notification', function(data){
bot.sendMessage(data.telegramId, data.message);
});
// Settings observer.
pubsub.on('telegram:getMe', function(){
bot.getMe().then(function(me){
pubsub.publish('telegram:me', me);
});
});
});
}
var parseCommands = function(telegramId, mesg)
{
function respond(response) {
pubsub.publish('telegram:notification', {telegramId: telegramId, message: response});
}
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() == "/r" && command.length >= 3)
{ // It's a reply to a topic!
var data = {};
data.uid = uid;
data.tid = command[1];
command.splice(0, 2); // Delete /r and topic id, only keep the message
data.content = command.join(" "); // recover the message
topics.getTopicData(data.tid, function(err, topicData){
if(err || !topicData)
{
return respond("Error.. invalid topic..");
}
var cid = topicData.cid;
user.isReadyToPost(uid, cid, function(err){
if(!err)
{
posts.create(data, function(err, r){
if(err)
{
respond("Error..");
}
else
{
respond("OK!");
}
});
}
else
{
respond("Error..");
}
});
});
}
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..");
}
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
{
respond("OK!");
}
});
});
}
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..");
}
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];
topics.getPids(tid, function(err, pids){
posts.getPostsByPids(pids, uid, function(err, posts){
if (err)
{
return respond("Error..");
}
var postsuids = [];
for(var i in posts)
{
postsuids.push(posts[i].uid);
}
user.getMultipleUserFields(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);
});
});
});
}
});
}
};
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);
});
}
};
Telegram.pushNotification = function(data) {
var notifObj = data.notification;
var uids = data.uids;
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.getMultipleUserFields(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 = notifObj.path || (nconf.get('url') + '/topic/' + data.topicSlug + '/' + data.postIndex);
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)
}
]);
});
});
};
// Add button in profile
Telegram.addProfileItem = function(links, callback) {
if (token) {
links.push({
id: 'telegram',
route: '../../telegram/settings',
icon: 'fa-mobile',
name: 'Telegram',
public: false
});
}
callback(null, links);
};
Telegram.addNavigation = function(custom_header, callback) {
// 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);
}
// Sockets
SocketAdmins.setTelegramToken = function (socket, data, callback)
{
var t = {token:data.token, msg:data.msg};
db.setObject('telegrambot-token', data, callback);
}
SocketAdmins.getTelegramToken = function (socket, data, callback)
{
db.getObject('telegrambot-token', callback);
}
SocketPlugins.setTelegramID = function (socket, data, callback)
{
user.getUserField(socket.uid, "telegramid", function(err, telid){
if(telid)
{
db.sortedSetRemove("telegramid:uid", telid); // Remove previus index
}
user.setUserField(socket.uid, "telegramid", data, function(err){
if(data && data != "")
{
var obj = { value: data, score:socket.uid };
db.sortedSetAdd("telegramid:uid", socket.uid, data, callback); // Index to get uid from telegramid
}
else
{
callback(null, "");
}
});
});
}
SocketPlugins.getTelegramID = function (socket, data, callback)
{
user.getUserField(socket.uid, "telegramid", callback);
}
module.exports = Telegram;