-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
165 lines (146 loc) · 4.41 KB
/
server.js
File metadata and controls
165 lines (146 loc) · 4.41 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
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);
app.use(express.static("dist", { index: "demo.html", maxage: "4h" }));
app.use(bodyParser.json());
const sessions = {};
const buffer = {};
// const historyIds = []
// handle admin Telegram messages
app.post(`/hook`, function (req, res) {
try {
const message = req.body.message || req.body.channel_post;
const chatId = process.env.TELEGRAM_CHAT_ID; // || message.chat.id;
let name = message.from.first_name || message.chat.first_name || "Support";
const text = message.text || "";
const reply = message.reply_to_message;
// console.log(JSON.stringify(req.body));
if (/(adriaan|simple)/gi.test(name)) name = "Adriaan";
if (text.startsWith("/start")) {
// console.log('/start chatId ' + chatId);
sendTelegramMessage(
chatId,
"*Welcome to Intergram* \n" +
"Your unique 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 || "";
let userId = replyText.split(":")[0];
const socketId = sessions[userId];
if (socketId) {
io.to(socketId).emit(chatId + "-" + userId, {
name,
text,
from: "admin",
});
} else {
if (!buffer[userId]) {
buffer[userId] = [];
}
console.log("client not connected buffering message");
buffer[userId].unshift({
chatId,
name,
text,
from: "admin",
adminName: name,
});
}
} else if (text) {
// io.emit(chatId, {name, text, from: 'admin'});
}
} catch (e) {
console.error("hook error", e, req.body);
}
res.statusCode = 200;
res.end();
});
// handle chat visitors websocket messages
io.on("connection", function (socket) {
socket.on("register", function (registerMsg) {
console.log("on register");
let userId = registerMsg.userId;
let chatId = registerMsg.chatId;
// let messageReceived = false;
sessions[userId] = socket.id;
// if (historyIds.indexOf(userId) > -1) {
// messageReceived = true;
// sendTelegramMessage(chatId, `${userId}: re-opened chat`, null, true);
// }
if (buffer[userId]) {
const buffered = buffer[userId];
let msg = buffered.pop();
console.log(`sending ${buffered.length} buffered messages`);
while (msg) {
const { chatId, name, text, from, adminName } = msg;
io.to(socket.id).emit(chatId + "-" + userId, {
name,
text,
from,
adminName,
});
msg = buffered.pop();
}
delete buffer[userId];
}
socket.on("message", function (msg) {
// console.log('on message', msg)
messageReceived = true;
// if (msg.from !== 'bot') io.emit(chatId + '-' + userId, msg);
if (msg.from !== "bot") io.to(socket.id).emit(chatId + "-" + userId, msg);
sendTelegramMessage(chatId, `${userId}: ${msg.text}`);
});
socket.on("disconnect", function () {
// console.log('on disconnect')
// if (historyIds.indexOf(userId) === -1) historyIds.push(userId)
// if (messageReceived) {
// sendTelegramMessage(chatId, `${userId}: has left`, null, true);
// }
delete sessions[userId];
});
});
});
function sendTelegramMessage(
chatId,
text,
parseMode,
disableNotification = false
) {
const data = {
disable_notification: disableNotification,
chat_id: chatId,
text,
};
if (parseMode) data.parse_mode = parseMode;
request
.post(
"https://api.telegram.org/bot" +
process.env.TELEGRAM_TOKEN +
"/sendMessage"
)
.form(data)
.on("error", function (err) {
console.error(err);
});
}
// app.post('/usage-start', cors(), function(req, res) {
// console.log('usage from', req.query.host);
// res.statusCode = 200;
// res.end();
// });
// // left here until the cache expires
// app.post('/usage-end', cors(), function(req, res) {
// res.statusCode = 200;
// res.end();
// });
http.listen(process.env.PORT || 3001, function () {
console.log("listening on port:" + (process.env.PORT || 3001));
});