-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
1365 lines (1245 loc) · 39.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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Andrea Sponziello - (c) Tiledesk.com
*/
require('dotenv').config();
var url = require('url');
const express = require("express");
const bodyParser = require("body-parser")
const jwt = require("jsonwebtoken")
const { uuid } = require('uuidv4');
var cors = require('cors');
var mongodb = require("mongodb");
const { ChatDB } = require('./chatdb/index.js');
const { Chat21Api } = require('./chat21Api/index.js');
const { Chat21Push } = require('./sendpush/index.js');
let logger = require('./tiledesk-logger').logger;
console.log("Logger level:", logger.logLevel);
const axios = require('axios'); // ONLY FOR TEMP PUSH WEBHOOK ENDPOINT
const https = require('https'); // ONLY FOR TEMP PUSH WEBHOOK ENDPOINT
const { TdCache } = require('./TdCache.js');
const { Contacts } = require('./Contacts.js');
let tdcache = null;
const jwtKey = process.env.JWT_KEY || "tokenKey";
const BASEURL = process.env.BASEURL || '/api';
let chatdb = null;
let chatapi = null;
let chatpush = null;
const app = express()
app.use(bodyParser.json())
// use it before all route definitions
// app.use(cors({origin: 'http://localhost:8100'}));
app.use(cors());
// app.use(cors({origin: 'http://tdchatserver.herokuapp.com'}));
// app.use(express.static('public'))
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); //qui dice cequens attento
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-XSRF-Token");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
next();
});
app.use(function (req, res, next) {
var urlobj = url.parse(req.originalUrl);
if (urlobj.pathname === '/' || urlobj.pathname === '/test' || urlobj.pathname.includes("/push/webhook/endpoint/") ) {
next();
return;
}
const jwt = decodejwt(req)
if (jwt) {
// adds "user" to req
req['user'] = {
uid: jwt.sub,
appId: jwt.app_id,
roles: {
"user": true
}
}
if (jwt.tiledesk_api_roles) { // TODO get multiple roles splitting tiledesk_api_roles on ","
req['user'].roles[jwt.tiledesk_api_roles] = true
}
else {
req['user'].roles["user"] = true
}
// adds "jwt" to req
req['jwt'] = jwt
next();
} else {
logger.error('Unauthorized.');
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
});
app.get("/", (req, res) => {
res.status(200).send("Chat21 Http Server v. 0.1.2")
})
// http://localhost:8004/test?projectid=646c838d55f7620013e4ab92&mqtt_endpoint=wss%3A%2F%2Feu.rtmv3.tiledesk.com%2Fmqws%2Fws&api_endpoint=https%3A%2F%2Fapi.tiledesk.com%2Fv3&chatapi_endpoint=https%3A%2F%2Feu.rtmv3.tiledesk.com%2Fchatapi%2Fapi
const { Chat21Client } = require('./mqttclient/chat21client.js');
app.get("/test", (req, res) => {
let TILEDESK_PROJECT_ID = "" || req.query.projectid;
// if (process.env && process.env.PERFORMANCE_TEST_TILEDESK_PROJECT_ID) {
// TILEDESK_PROJECT_ID = process.env.PERFORMANCE_TEST_TILEDESK_PROJECT_ID
// // console.log("TILEDESK_PROJECT_ID:", TILEDESK_PROJECT_ID);
// }
// else {
// throw new Error(".env.PERFORMANCE_TEST_TILEDESK_PROJECT_ID is mandatory");
// }
// console.log("process.env.PERFORMANCE_TEST_MQTT_ENDPOINT:", process.env.PERFORMANCE_TEST_MQTT_ENDPOINT);
let MQTT_ENDPOINT = "" || req.query.mqtt_endpoint;
// if (process.env && process.env.PERFORMANCE_TEST_MQTT_ENDPOINT) {
// MQTT_ENDPOINT = process.env.PERFORMANCE_TEST_MQTT_ENDPOINT
// // console.log("MQTT_ENDPOINT:", MQTT_ENDPOINT);
// }
// else {
// throw new Error(".env.PERFORMANCE_TEST_MQTT_ENDPOINT is mandatory");
// }
let API_ENDPOINT = "" || req.query.api_endpoint;
// if (process.env && process.env.PERFORMANCE_TEST_API_ENDPOINT) {
// API_ENDPOINT = process.env.PERFORMANCE_TEST_API_ENDPOINT
// // console.log("API_ENDPOINT:", API_ENDPOINT);
// }
// else {
// throw new Error(".env.PERFORMANCE_TEST_API_ENDPOINT is mandatory");
// }
let CHAT_API_ENDPOINT = "" || req.query.chatapi_endpoint;
// if (process.env && process.env.PERFORMANCE_TEST_CHAT_API_ENDPOINT) {
// CHAT_API_ENDPOINT = process.env.PERFORMANCE_TEST_CHAT_API_ENDPOINT
// // console.log("CHAT_API_ENDPOINT:", CHAT_API_ENDPOINT);
// }
// else {
// throw new Error(".env.PERFORMANCE_TEST_CHAT_API_ENDPOINT is mandatory");
// }
let config = {
MQTT_ENDPOINT: MQTT_ENDPOINT,
CHAT_API_ENDPOINT: CHAT_API_ENDPOINT,
APPID: 'tilechat',
TILEDESK_PROJECT_ID: TILEDESK_PROJECT_ID,
MESSAGE_PREFIX: "Performance-test",
}
let user1 = {
fullname: 'User 1',
firstname: 'User',
lastname: '1',
};
let chatClient1 = new Chat21Client(
{
appId: config.APPID,
MQTTendpoint: config.MQTT_ENDPOINT,
APIendpoint: config.CHAT_API_ENDPOINT,
log: false
});
(async () => {
let userdata;
try {
userdata = await createAnonymousUser(TILEDESK_PROJECT_ID, API_ENDPOINT);
}
catch(error) {
console.log("An error occurred during anonym auth:", error);
process.exit(0);
}
user1.userid = userdata.userid;
user1.token = userdata.token;
let group_id;
let group_name;
console.log("Message delay check.");
console.log("MQTT endpoint:", config.MQTT_ENDPOINT);
console.log("API endpoint:", config.CHAT_API_ENDPOINT);
console.log("Tiledesk Project Id:", config.TILEDESK_PROJECT_ID);
console.log("Connecting...")
chatClient1.connect(user1.userid, user1.token, () => {
console.log("chatClient1 connected and subscribed.");
group_id = "support-group-" + "64690469599137001a6dc6f5-" + uuid().replace(/-+/g, "");
group_name = "benchmarks group => " + group_id;
send(group_id, group_name, chatClient1, config, user1, function(delay) {
chatClient1.close()
res.json({delay: delay});
// process.exit(0);
});
});
})();
// res.status(200).send("Chat21 Http Server v. 0.1.2")
})
async function send(group_id, group_name, chatClient, config, user, callback) {
console.log("\n\n***********************************************");
console.log("********* Single message delay script *********");
console.log("***********************************************\n\n");
let time_sent = Date.now();
let handler = chatClient.onMessageAdded((message, topic) => {
console.log("> Incoming message [sender:" + message.sender_fullname + "]: " + message.text);
if (
message &&
message.text.startsWith(config.MESSAGE_PREFIX) &&
(message.sender_fullname !== "User 1" && message.sender_fullname !== "System") && // bot is the sender
message.recipient === group_id
) {
console.log("> Incoming message (sender is the chatbot) used for computing ok.");
let text = message.text.trim();
let time_received = Date.now();
let delay = time_received - time_sent;
console.log("Total delay:" + delay + "ms");
callback(delay);
}
else {
console.log("Message not computed:", message.text);
}
});
console.log("Sending test message...");
let recipient_id = group_id;
let recipient_fullname = group_name;
let message_UUID = uuid().replace(/-+/g, "");
sendMessage(message_UUID, recipient_id, recipient_fullname, async (latency) => {
console.log("Sent ok:", message_UUID);
}, chatClient, config, user);
}
function sendMessage(message_UUID, recipient_id, recipient_fullname, callback, chatClient, config, user) {
const sent_message = config.MESSAGE_PREFIX + "/"+ message_UUID;
console.log("Sending message with text:", sent_message);
chatClient.sendMessage(
sent_message,
'text',
recipient_id,
recipient_fullname,
user.fullname,
{projectId: config.TILEDESK_PROJECT_ID},
null, // no metadata
'group',
(err, msg) => {
if (err) {
console.error("Error send:", err);
}
console.log("Message Sent ok:", msg);
}
);
}
async function createAnonymousUser(tiledeskProjectId,API_ENDPOINT) {
ANONYMOUS_TOKEN_URL = API_ENDPOINT + '/auth/signinAnonymously';
console.log("Getting ANONYMOUS_TOKEN_URL:", ANONYMOUS_TOKEN_URL);
return new Promise((resolve, reject) => {
let data = JSON.stringify({
"id_project": tiledeskProjectId
});
let axios_config = {
method: 'post',
url: ANONYMOUS_TOKEN_URL, //'https://api.tiledesk.com/v3/auth/signinAnonymously',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios.request(axios_config)
.then((response) => {
console.log("Got Anonymous Token:", JSON.stringify(response.data.token));
CHAT21_TOKEN_URL = API_ENDPOINT + '/chat21/native/auth/createCustomToken';
let config = {
method: 'post',
maxBodyLength: Infinity,
url: CHAT21_TOKEN_URL,
headers: {
'Authorization': response.data.token
}
};
axios.request(config)
.then((response) => {
// console.log(response);
const mqtt_token = response.data.token;
const chat21_userid = response.data.userid;
resolve({
userid: chat21_userid,
token: mqtt_token
});
})
.catch((error) => {
console.log(error);
reject(error);
});
})
.catch((error) => {
console.log(error);
reject(error)
});
});
}
app.get("/verify", (req, res) => {
const decoded = decodejwt(req)
res.status(200).send(decoded)
})
app.get(BASEURL + "/:appid/:userid/conversations", (req, res) => {
logger.debug("HTTP: getting /:appid/:userid/conversations")
if (!authorize(req, res)) {
logger.debug("Unauthorized!")
return
}
logger.debug("Go with conversations!")
conversations(req, false, function(err, docs) {
logger.debug("Got conversations.");
if (err) {
logger.error("Error getting conversations", err);
const reply = {
success: false,
err: err.message()
}
res.status(200).send(reply)
}
else {
const reply = {
success: true,
result: docs
}
res.status(200).json(reply)
}
})
})
app.get(BASEURL + "/:appid/:userid/conversations/archived", (req, res) => {
logger.debug("HTTP: getting /:appid/:userid/archived_conversations")
if (!authorize(req, res)) {
logger.debug("Unauthorized!")
return
}
conversations(req, true, function(err, docs) {
logger.debug("got archived conversations", docs, err)
if (err) {
const reply = {
success: false,
err: err.message()
}
res.status(200).send(reply)
}
else {
const reply = {
success: true,
result: docs
}
res.status(200).json(reply)
}
});
});
app.get(BASEURL + "/:appid/getInfo", (req, res) => {
res.status(200).send({"v": "0.2.34.2"})
});
/** Delete all conversations from all timelines belonging to a group */
app.delete(BASEURL + '/:app_id/:group_id/conversations/timelines', async (req, res) => {
// app.delete('/groups/:group_id/members/:member_id', (req, res) => {
logger.debug('HTTP: Delete all conversations from all timelines belonging to a group');
if (!req.params.group_id) {
res.status(405).send('group_id is mandatory');
return
}
else if (!req.params.app_id) {
res.status(405).send('app_id is mandatory');
return
}
let group_id = req.params.group_id;
let app_id = req.params.app_id;
const user = req.user
logger.debug('app_id:' + app_id);
logger.debug('group_id:' + group_id);
chatapi.removeAllConversWithConversations(app_id, group_id, function(err) {
logger.debug('removeAllConversWithConversations error?', err);
if (err) {
res.status(405).send(err)
}
else {
res.status(200).send({success: true})
}
});
});
function authorize(req, res) {
const appid = req.params.appid
// const userid = req.params.userid
logger.debug("appId:", appid, "user:", JSON.stringify(req.user))
if (!req.user || (req.user.appId !== appid)) { // (req.user.uid !== userid) ||
res.status(401).end()
return false
}
return true
}
app.get(BASEURL + "/:appid/:userid/archived_conversations", (req, res) => {
logger.debug("HTTP: GET /:appid/:userid/archived_conversations")
if (!authorize(req, res)) {
return
}
conversations(req, true, function(err, docs) {
if (err) {
const reply = {
success: false,
err: err.message()
}
res.status(501).send(reply)
}
else {
const reply = {
success: true,
result: docs
}
res.status(200).json(reply)
}
})
})
app.get(BASEURL + "/:appid/:userid/conversations/:conversWith", (req, res) => {
logger.debug("HTTP: GET /:appid/:userid/conversations/:conversWith");
if (!authorize(req, res)) {
return
}
conversationDetail(req, false, function(err, docs) {
if (err) {
const reply = {
success: false,
err: err.message()
}
res.status(501).send(reply)
}
else {
const reply = {
success: true,
result: docs
}
res.status(200).json(reply)
}
})
})
app.get(BASEURL + "/:appid/:userid/archived_conversations/:conversWith", (req, res) => {
logger.debug("HTTP: GET /:appid/:userid/conversations/:conversWith");
if (!authorize(req, res)) {
return
}
conversationDetail(req, true, function(err, docs) {
if (err) {
const reply = {
success: false,
err: err.message()
}
res.status(501).send(reply)
}
else {
const reply = {
success: true,
result: docs
}
res.status(200).json(reply)
}
})
})
function conversationDetail(req, archived, callback) {
// logger.debug("getting /:appid/:userid/archived_conversations")
const appid = req.params.appid
const userid = req.params.userid
const conversWith = req.params.conversWith
chatdb.conversationDetail(appid, userid, conversWith, archived, function(err, docs) {
callback(err, docs);
});
}
function conversations(req, archived, callback) {
// logger.debug("getting /:appid/:userid/archived_conversations")
const appid = req.params.appid
const userid = req.params.userid
chatdb.lastConversations(appid, userid, archived, function(err, docs) {
callback(err, docs)
});
}
app.get(BASEURL + "/:appid/:userid/conversations/:convid/messages", (req, res) => {
logger.debug("HTTP: getting /:appid/:userid/messages")
const appid = req.params.appid
const userid = req.params.userid
const convid = req.params.convid
const jwt = decodejwt(req)
// logger.debug("app:", appid, "user:", userid, "convid:", convid, "token:", jwt)
if (jwt.sub !== userid || jwt.app_id !== appid) {
res.status(401).end()
return
}
chatdb.lastMessages(appid, userid, convid, -1, 200, function(err, messages) {
if (err) {
const reply = {
success: false,
err: err.message()
}
res.status(500).send(reply)
}
else {
const reply = {
success: true,
result: messages
}
// logger.debug("REPLY:", reply)
res.status(200).json(reply)
}
})
})
/** Delete (Archive) a conversation */
app.delete(BASEURL + '/:app_id/conversations/:recipient_id/', (req, res) => {
logger.debug('HTTP: delete: Conversation. req.params:', req.params, 'req.body:', req.body)
if (!req.params.recipient_id) {
res.status(405).send('recipient_id is not present!');
}
if (!req.params.app_id) {
res.status(405).send('app_id is not present!');
}
let recipient_id = req.params.recipient_id;
let app_id = req.params.app_id;
let user_id = req.user.uid;
const im_admin = req.user.roles.admin
logger.debug("im_admin?", im_admin, "roles:", req.user.roles)
if (req.body.user_id && im_admin) {
logger.debug('user_id from body:', req.body.user_id);
user_id = req.body.user_id;
}
// logger.debug('recipient_id:', recipient_id);
// logger.debug('app_id:', app_id);
logger.debug('user_id:', user_id);
chatapi.archiveConversation(app_id, user_id, recipient_id, function(err) {
if (err) {
res.status(500).send({"success":false, "err": err});
}
else {
res.status(201).send({"success":true});
}
})
// chatApi.archiveConversation(user_id, recipient_id, app_id).then(function(result) {
// logger.debug('result', result);
// res.status(204).send({"success":true});
// });
});
/**
* Sends a message.
*
* This endpoint supports CORS.
*/
app.post(BASEURL + '/:app_id/messages', (req, res) => {
logger.debug('HTTP: Sends a message:', JSON.stringify(req.body));
if (!req.body.sender_fullname) {
logger.error('Sender Fullname is mandatory');
res.status(405).send('Sender Fullname is mandatory');
return
}
else if (!req.body.recipient_id) {
logger.error('Recipient id is mandatory');
res.status(405).send('Recipient id is mandatory');
return
}
else if (!req.body.recipient_fullname) {
logger.error('Recipient Fullname is mandatory');
res.status(405).send('Recipient Fullname is mandatory');
return
}
// else if (!req.body.text) {
// logger.error('text is mandatory');
// res.status(405).send('text is mandatory');
// return
// }
logger.debug('validation ok');
let sender_id = req.user.uid;
logger.debug('sender_id' + sender_id);
im_admin = req.user.roles.admin // admin can force sender_id to someone different from current user
if (im_admin && req.body.sender_id) {
sender_id = req.body.sender_id;
}
let sender_fullname = req.body.sender_fullname;
let recipient_id = req.body.recipient_id;
let recipient_fullname = req.body.recipient_fullname;
let text = req.body.text;
let appid = req.params.app_id;
let channel_type = req.body.channel_type;
let attributes = req.body.attributes;
let type = req.body.type;
let metadata = req.body.metadata;
let timestamp = req.body.timestamp;
logger.debug('sender_id:' + sender_id);
// logger.debug('sender_fullname', sender_fullname);
logger.debug('recipient_id:' + recipient_id);
// logger.debug('recipient_fullname', recipient_fullname);
logger.debug('text:'+ text);
// logger.debug('app_id', appid);
logger.debug('channel_type:'+ channel_type);
// logger.debug('attributes', attributes);
// logger.debug('type', type);
// logger.debug('metadata', metadata);
// logger.debug('timestamp', timestamp);
chatapi.sendMessage(
appid, // mandatory
type, // optional | text
text, // mandatory
timestamp, // optional | null (=>now)
channel_type, // optional | direct
sender_id, // mandatory
sender_fullname, // mandatory
recipient_id, // mandatory
recipient_fullname, // mandatory
attributes, // optional | null
metadata, // optional | null
function(err) { // optional | null
if (err) {
logger.error("message sent with err", err)
const reply = {
success: false,
err: (err && err.message()) ? err.message() : "Not found"
}
res.status(404).send(reply)
}
else {
res.status(200).send({success: true})
}
}
)
});
// *****************************************
// **************** GROUPS *****************
// *****************************************
/** Create group */
app.post(BASEURL + '/:appid/groups', (req, res) => {
logger.debug("HTTP: Create a group /:appid/groups")
logger.debug("appId:" + req.user.appId + ", user:" + req.user.uid)
if (!req.user || !req.user.appId) {
res.status(401).end()
return
}
// cors(req, res, () => {
if (!req.body.group_name) {
res.status(405).send('group_name not present!');
return
}
if (!req.body.group_members) {
res.status(405).send('group_members not present!');
}
let group_name = req.body.group_name;
let group_id = req.body.group_id;
if (!group_id) {
group_id = newGroupId()
}
let current_user = req.user.uid;
let group_attributes = req.body.attributes;
let group_owner = current_user;
im_admin = req.user.roles.admin;
if (im_admin && req.body.group_owner) {
group_owner = req.body.group_owner;
}
let group_members = {};
if (req.body.group_members) {
group_members = req.body.group_members;
}
if (!im_admin) {
group_members[current_user] = 1;
}
let appid = req.user.appId;
logger.debug('group_name' + group_name);
logger.debug('group_id'+ group_id);
logger.debug('group_owner' + group_owner);
logger.debug('group_members' + group_members);
logger.debug('app_id' + appid);
const now = Date.now()
var group = {};
group.name = group_name;
group.uid = group_id;
group.appId = appid;
group.owner = group_owner;
group.members = group_members;
group.createdOn = now;
group.updatedOn = now;
if (group_attributes) {
group.attributes = group_attributes;
}
logger.debug("creating group " + JSON.stringify(group));
chatapi.createGroup(group, function(err) {
if (err) {
res.status(500).send({"success":false, "err": err});
}
else {
res.status(201).send({"success":true, group: group});
}
})
});
function newGroupId() {
group_id = "group-" + uuid();
return group_id
}
/** Get group data */
app.get(BASEURL + '/:appid/groups/:group_id', async (req, res) => {
logger.debug("HTTP: Get group data. getting /:appid/groups/group_id")
if (!authorize(req, res)) {
logger.debug("Unauthorized!")
return
}
const group_id = req.params.group_id
let cached_group = await groupFromCache(group_id);
console.log("cached group:", cached_group);
if (cached_group) {
im_member = cached_group.members[req.user.uid]
im_admin = req.user.roles.admin
if (im_member || im_admin) {
const reply = {
success: true,
result: cached_group
}
res.status(200).json(reply);
return;
}
else {
const reply = {
success: false,
err: "Permission denied"
}
res.status(401).send(reply)
return;
}
}
chatdb.getGroup(group_id, async (err, group) => {
if (err) {
const reply = {
success: false,
err: err.message()
}
res.status(404).send(reply)
}
else if (group) {
// logger.debug("group members", group.members)
await saveGroupInCache(group, group_id);
im_member = group.members[req.user.uid]
im_admin = req.user.roles.admin
// logger.debug("im_member:", im_member)
// logger.debug("im_admin:", im_admin)
if (im_member || im_admin) {
const reply = {
success: true,
result: group
}
res.status(200).json(reply)
}
else {
const reply = {
success: false,
err: "Permission denied"
}
res.status(401).send(reply)
}
}
else {
const reply = {
success: false,
err: "Group doesn't exist"
}
res.status(404).send(reply)
}
});
});
/** Join a group */
app.post(BASEURL + '/:appid/groups/:group_id/members', async (req, res) => {
logger.debug('HTTP: Join a group. adds a member to a group', req.body, req.params);
if (!authorize(req, res)) {
logger.debug("Unauthorized")
res.status(401).send('Unauthorized');
return
}
if (!req.body.member_id) {
res.status(405).send('member_id is mandatory!');
return
}
const joined_member_id = req.body.member_id;
const group_id = req.params.group_id;
// const app_id = req.params.appid;
console.log('joined_member_id:', joined_member_id);
console.log('join group_id:', group_id);
// logger.debug('chatapi', chatapi);
await resetGroupCache(group_id);
console.log("Got group to join to", group_id);
chatapi.addMemberToGroupAndNotifyUpdate(req.user, joined_member_id, group_id, async (err, group) => {
logger.debug("THE GROUP:", group)
if (err) {
logger.error("An error occurred while a member was joining the group", err)
const reply = {
success: false,
err: (err) ? err : "An error occurred while a member was joining the group",
http_status: 405
}
res.status(reply.http_status).send(reply)
}
else if (group) {
logger.debug("Notifying to other members and copying old group messages to new user timeline...")
const joined_member = await chatapi.getContact(joined_member_id);
let message_label = {
key: "MEMBER_JOINED_GROUP",
parameters: {
member_id: joined_member_id,
fullname: joined_member.fullname,
firstname: joined_member.firstname,
lastname: joined_member.lastname
}
};
chatapi.joinGroupMessages(joined_member_id, group, message_label, function(err) {
logger.debug("member joined. Notified to other members and copied old group messages to new user timeline");
if (err) {
logger.error("An error occurred while joining member", err);
const reply = {
success: false,
err: err,
http_status: 405
}
res.status(reply.http_status).send(reply);
}
else {
res.status(200).send({success: true});
}
});
}
else {
const reply = {
success: false,
err: "Group not found",
http_status: 405
}
logger.error("Error encountered:", reply);
res.status(reply.http_status).send(reply);
}
})
});
/** Set members of a group */
app.put(BASEURL + '/:app_id/groups/:group_id/members', async (req, res) => {
logger.debug('HTTP: Set members of a group with:', req.body);
if (!req.params.group_id) {
res.status(405).send('group_id is mandatory');
return
}
else if (!req.params.app_id) {
res.status(405).send('app_id is mandatory');
return
}
else if (!req.body.members) {
res.status(405).send('members is mandatory');
return
}
let new_members = req.body.members //{};
// req.body.members.forEach(m => {
// new_members[m] = 1
// })
// logger.debug("new_members:", new_members)
const group_id = req.params.group_id
const user = req.user
await resetGroupCache(group_id);
chatapi.setGroupMembers(user, new_members, group_id, function(err) {
if (err) {
res.status(405).send(err)
}
else {
res.status(200).send({success: true})
}
})
});
/** Leave a group */
app.delete(BASEURL + '/:app_id/groups/:group_id/members/:member_id', async (req, res) => {
// app.delete('/groups/:group_id/members/:member_id', (req, res) => {
logger.debug('HTTP: Leave group');
if (!req.params.member_id) {
res.status(405).send('member_id is mandatory');
return
}
else if (!req.params.group_id) {
res.status(405).send('group_id is mandatory');
return
}
else if (!req.params.app_id) {
res.status(405).send('app_id is mandatory');
return
}
let member_id = req.params.member_id;
let group_id = req.params.group_id;
let app_id = req.params.app_id;
const user = req.user
logger.debug('member_id:'+ member_id);
logger.debug('group_id:' + group_id);
logger.debug('app_id:' + app_id);
logger.debug('user:' + user.uid);
await resetGroupCache(group_id);
chatapi.leaveGroup(user, member_id, group_id, app_id, function(err) {
if (err) {
res.status(405).send(err)
}
else {
res.status(200).send({success: true})
}
});
});
/** Update group (just group name) */
app.put(BASEURL + '/:app_id/groups/:group_id', async (req, res) => {
logger.debug('HTTP: Update group (just group name)');
if (!req.params.group_id) {
res.status(405).send('group_id is mandatory');
return
}
else if (!req.params.app_id) {
res.status(405).send('app_id is mandatory');
return
}
else if (!req.body.group_name) {
res.status(405).send('group_name is mandatory');
return
}
const group_name = req.body.group_name;
const group_id = req.params.group_id
const user = req.user
await resetGroupCache(group_id);
chatapi.updateGroupData(user, group_name, group_id, function(err) {
if (err) {
res.status(405).send(err)
}
else {
res.status(200).send({success: true})
}
})
});
/** Update group custom attributes */
app.put(BASEURL + '/:app_id/groups/:group_id/attributes', async (req, res) => {
logger.debug('HTTP: Update group custom attributes for group:' + req.params.group_id + "body:" + JSON.stringify(req.body));
if (!req.params.group_id) {
res.status(405).send('group_id is mandatory');
return
}
else if (!req.params.app_id) {
res.status(405).send('app_id is mandatory');
return
}
else if (!req.body.attributes) {
res.status(405).send('attributes is mandatory');
return
}
const attributes = req.body.attributes;
const group_id = req.params.group_id;
const user = req.user;
await resetGroupCache(group_id);
chatapi.updateGroupAttributes(user, attributes, group_id, function(err) {
if (err) {
res.status(405).send(err)
}
else {
res.status(200).send({success: true})
}
})
});
// ********************************************************
// **************** END GROUPS MANAGEMENT *****************
// ********************************************************
// ****************************************************************
// **************** PUSH NOTIFICATIONS MANAGEMENT *****************
// ****************************************************************
/**
* Saves an App instance ID.
*