forked from idoco/intergram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
498 lines (465 loc) · 13.2 KB
/
Copy pathserver.js
File metadata and controls
498 lines (465 loc) · 13.2 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
require("dotenv").config();
const request = require("request");
const cors = require("cors");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
const fruits = ["🍏", "🍌", "🍇", "🍈", "🍉", "🍊", "🍋", "🍍", "🥭"];
let fruitIndex = 0;
if (!process.env.TELEGRAM_TOKEN) {
console.error("TELEGRAM_TOKEN not provided");
process.exit(1);
}
const channelId = parseInt(process.env.TELEGRAM_CHANNEL_ID);
const topicId = parseInt(process.env.TOPIC_ID);
const connectedSockets = {};
const messageBuffer = {};
console.log("Connected to", channelId, `#${topicId}`);
app.use(express.static("dist", { index: "demo.html", maxage: "4h" }));
app.use(bodyParser.json());
// handle admin Telegram messages
app.post("/hook", function (req, res) {
try {
console.log("got message", `"${req.body.message.text}"`);
const message = req.body.message || req.body.channel_post;
if (!topicId || message.message_thread_id === topicId) {
const chatId = message.chat.id;
const name = message.chat.first_name || message.chat.title || "admin";
const text = message.text || "";
const reply = message.reply_to_message;
const from = message.from.username;
res.statusCode = 200;
if (text.startsWith("/start")) {
console.log("/start chatId " + chatId);
sendTelegramMessage(
"*Welcome to Intergram* \n" +
"The chat id is `" +
chatId +
"`\n" +
"Use it to link between the embedded chat and this telegram chat",
"Markdown"
);
} else if (reply) {
let replyText = reply.text || "";
// check if a reply to someone known
const userIdMatch = replyText.match(/^\[(.+)\]/);
if (userIdMatch) {
const userId = userIdMatch[1];
if (connectedSockets[userId]) {
console.log(
"client connected sending message",
`${chatId}-${userId}`
);
const sock = connectedSockets[userId];
sock.emit(chatId + "-" + userId, {
name,
text,
from: "admin",
adminName: from,
});
// check if connected, if not then buffer
appendMissiveConversationAgent({
conversationId: sock.conversationId,
email: sock.userData.email,
message: text,
});
} else {
if (!messageBuffer[userId]) {
messageBuffer[userId] = [];
}
console.log("client not connected buffering message");
messageBuffer[userId].unshift({
chatId,
name,
text,
from: "admin",
adminName: from,
});
}
} else {
console.log(
"Ignoring message as id didn't match any connected users"
);
}
}
} else {
console.log("Ignoring message in other topic");
}
} catch (e) {
console.error("hook error", e, req.body);
} finally {
res.end();
}
});
// handle chat visitors websocket messages
io.on("connection", function (client) {
const address = client.handshake.address.replace("::ffff:", "");
client.on("register", function (registerMsg) {
const {
isNewUser,
chatId,
userId,
oldId,
userData = {},
currentUrl,
} = registerMsg;
console.log("register user", userId);
userData.fruit = fruits[fruitIndex++];
if (fruitIndex >= fruits.length) {
fruitIndex = 0;
}
client.userData = userData;
connectedSockets[userId] = client;
let messageReceived = false;
// check the buffer and send anything in there
if (messageBuffer[userId]) {
const buffered = messageBuffer[userId];
let msg = buffered.pop();
console.log(`sending ${buffered.length} buffered messages`);
while (msg) {
const { chatId, name, text, from, adminName } = msg;
client.emit(chatId + "-" + userId, {
name,
text,
from,
adminName,
});
appendMissiveConversationAgent({
conversationId: client.conversationId,
email: client.userData.email,
message: text,
});
msg = buffered.pop();
}
delete messageBuffer[userId];
}
console.log("userId " + userId + " connected to chatId " + chatId);
if (oldId) {
sendMessage(
userId,
`Lead ${oldId} has logged in as ${obfuscateEmail(userData.email)}`,
"",
userData.fruit
).then(() => {
return sendStartMessage({ ...userData, currentUrl });
});
}
client.on("message", function (data) {
if (data.action === "typing") {
return setTyping(chatId);
}
const { msg } = data;
return Promise.resolve()
.then(() => {
if (isNewUser && !messageReceived) {
console.log("sending start msg");
sendStartMessage({
...userData,
currentUrl,
});
return createMissiveConversation({
email: userData.email,
message: msg.text,
});
}
return null;
})
.then((newConversationId) => {
if (newConversationId) {
client.conversationId = newConversationId;
} else {
appendMissiveConversationCustomer({
conversationId: client.conversationId,
email: userData.email,
message: msg.text,
}).then((conversationId) => {
// just in case the conversation id changes
// we try and stick with it
client.conversationId = conversationId;
});
}
messageReceived = true;
client.emit(chatId + "-" + userId, msg);
return sendMessage(
userId,
msg.text,
userData ? userData.email : "",
userData ? userData.fruit : ""
);
});
});
client.on("disconnect", function () {
if (messageReceived) {
sendTelegramMessage(userId + " has left");
}
delete connectedSockets[userId];
});
});
});
function sendStartMessage(userData = {}) {
const { id, email, currentUrl, fruit } = userData;
console.log(userData);
const isLead = !email;
let text = "";
if (isLead) {
text = `<b>New Lead ${fruit} </b>
<b>URL:</b>\t ${currentUrl || "unknown"}
`;
} else {
text = `A user has started a chat ${fruit}
<b>ID:</b>\t ${id}
<b>Email:</b>\t ${obfuscateEmail(email)}
<b>URL:</b>\t ${currentUrl || "unknown"}
<b>Admin:</b>\t https://admin.leavemealone.com/#/users/${id}
`;
}
text = `${text}`;
return sendTelegramMessage(text, "HTML");
}
function sendMessage(userId, text, email = "", fruit = "") {
return sendTelegramMessage(
`<b>[${userId}]</b> ${fruit} ${obfuscateEmail(email)}:\n${text}`,
"HTML"
);
}
app.post("/usage-start", cors(), function (req, res) {
console.log("usage from", req.query.host);
let unreadCount = 0;
if (messageBuffer[req.query.userId]) {
unreadCount = messageBuffer[req.query.userId].length;
}
res.statusCode = 200;
res.status(200).send(unreadCount.toString());
});
app.post("/unreads", cors(), function (req, res) {
let unreadCount = 0;
if (messageBuffer[req.query.userId]) {
unreadCount = messageBuffer[req.query.userId].length;
}
res.statusCode = 200;
res.status(200).send(unreadCount.toString());
});
// left here until the cache expires
app.post("/usage-end", cors(), function (req, res) {
res.statusCode = 200;
res.end();
});
http.listen(process.env.PORT || 3000, function () {
console.log("listening on port:" + (process.env.PORT || 3000));
});
app.get("/.well-known/acme-challenge/:content", (req, res) => {
res.send(process.env.CERTBOT_RESPONSE);
});
function setTyping(chatId) {
return new Promise((resolve, reject) => {
request
.post(
"https://api.telegram.org/bot" +
process.env.TELEGRAM_TOKEN +
"/sendChatAction",
function (err, resp, body) {
if (err) {
console.error(err);
return reject(err);
}
resolve(body);
}
)
.form({
chat_id: chatId,
action: "typing",
});
});
}
function sendTelegramMessage(text, parseMode = "HTML") {
let data = {
chat_id: channelId,
text: text,
parse_mode: parseMode,
};
if (topicId) {
data.message_thread_id = topicId;
}
const url =
"https://api.telegram.org/bot" +
process.env.TELEGRAM_TOKEN +
"/sendMessage";
console.log("Sending message to Telegram", JSON.stringify(data, null, 2));
return new Promise((resolve, reject) => {
request
.post(url, function (err, resp, body) {
if (err) {
console.error(err);
return reject(err);
}
resolve(body);
})
.form(data);
})
.then(() => {
console.log("Sent Telegram message");
})
.catch((err) => {
console.error("Failed to send Telegram message");
console.error(err);
});
}
process.on("uncaughtException", (error) => {
sendTelegramMessage(
`Server uncaught exception:
${error.toString()}
`
);
console.error(error);
});
process.on("unhandledRejection", (error) => {
sendTelegramMessage(
`Server unhandled rejection:
${error.toString()}
`
);
console.error(error);
});
const missiveUrl = "https://public.missiveapp.com/v1/messages";
function createMissiveConversation({ email, message }) {
if (!email) {
console.log("No email provided, skipping Missive conversation");
return Promise.resolve();
}
console.log("Creating Missive conversation", message);
const converstaionData = {
messages: {
conversation_subject: `Live Chat message from ${email}`,
account: "fc3ed25b-6e3f-4223-bf93-4e0a856be79c",
organization: "c3aa45c4-1b6a-4489-9f12-a8ee165bc6cb",
add_shared_labels: ["b4165c39-ea5d-4352-abd2-103bec50815a"],
from_field: {
address: email,
},
to_fields: [
{
address: "live-chat@leavemealone.com",
name: "Leave Me Alone Support",
},
],
body: message,
},
};
return new Promise((resolve, reject) => {
request.post(
missiveUrl,
{
json: converstaionData,
headers: {
Authorization: `Bearer ${process.env.MISSIVE_API_TOKEN}`,
},
},
function (err, resp, body) {
if (err) {
console.error(err);
return reject(err);
}
console.log(
"Missive conversation created",
JSON.stringify(body, null, 2)
);
const conversationId = body.messages.conversation;
console.log("Set missive conversation ID", conversationId);
resolve(conversationId);
}
);
});
}
function appendMissiveConversationAgent({ conversationId, email, message }) {
if (!email) {
console.log("No email provided, skipping Missive conversation");
return Promise.resolve();
}
console.log("Appending Missive conversation", conversationId, message);
const converstaionData = {
messages: {
conversation: conversationId,
account: "fc3ed25b-6e3f-4223-bf93-4e0a856be79c",
from_field: {
address: "live-chat@leavemealone.com",
name: "Leave Me Alone Support",
},
to_fields: [
{
address: email,
},
],
body: message,
},
};
return new Promise((resolve, reject) => {
request.post(
missiveUrl,
{
json: converstaionData,
headers: {
Authorization: `Bearer ${process.env.MISSIVE_API_TOKEN}`,
},
},
function (err, resp, body) {
if (err) {
console.error(err);
return reject(err);
}
console.log(
"Missive conversation updated",
JSON.stringify(body, null, 2)
);
const conversationId = body.messages.conversation;
resolve(conversationId);
}
);
});
}
function appendMissiveConversationCustomer({ conversationId, email, message }) {
console.log("Appending Missive conversation", conversationId, message);
const converstaionData = {
messages: {
conversation: conversationId,
account: "fc3ed25b-6e3f-4223-bf93-4e0a856be79c",
from_field: {
address: email,
},
to_fields: [
{
address: "live-chat@leavemealone.com",
name: "Leave Me Alone Support",
},
],
body: message,
},
};
return new Promise((resolve, reject) => {
request.post(
missiveUrl,
{
json: converstaionData,
headers: {
Authorization: `Bearer ${process.env.MISSIVE_API_TOKEN}`,
},
},
function (err, resp, body) {
if (err) {
console.error(err);
return reject(err);
}
console.log(
"Missive conversation updated",
JSON.stringify(body, null, 2)
);
const conversationId = body.messages.conversation;
resolve(conversationId);
}
);
});
}
function obfuscateEmail(email) {
return email ? email.replace(/(?<=.{2}).(?=.*@)/g, "*") : "";
}