-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
324 lines (300 loc) · 10.6 KB
/
server.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
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server,{ wsEngine: 'ws' });
var mysql = require('mysql');
var port = process.env.PORT || 3000;
var googleTranslate = require('google-translate')('AIzaSyDrn4uhUxn2Jk8HopmbtBsDe4q3ILC5LgE');
var con = mysql.createConnection({
host: "remotemysql.com",
user: "TggTikyCK7",
password: "JgoDz9XiW2",
database: "TggTikyCK7"
});
var CryptoJS = require("crypto-js");
var pass_encrypt = "baguvix-wanrltw";
var users_online = {};
con.connect(function(err) {
console.log("Connected Mysql!");
});
app.use(express.static(__dirname));
app.get('/index', function(req, res){
res.sendFile(__dirname + '/index.html');
});
server.listen(port, () => {
console.log("Listening on port " + port);
});
io.on('connection', (socket) => {
socket.on('signin',(data)=>{
//console.log('signin',data)
var sql = "SELECT * FROM users WHERE email='"+data.email+"'";
con.query(sql, function (err, result) {
if (err) throw err;
if(result.length == 0){
var sql2 = "INSERT INTO users (name,email,image,lang) VALUES ('"+data.name+"','"+data.email+"','"+ data.image+"','"+ data.lang+"')";
con.query(sql2, function (err2, result2) {
if (err2) throw err2;
socket.id_user = result2.insertId
socket.emit('user_is_signin',{"id_user":result2.insertId})
})
}else{
socket.emit('user_is_signin',{"id_user":result[0].id})
}
})
})
socket.on('client_load_dialog',(data)=>{
console.log('client_load_dialog',data)
if(data.id_user != null){
chat.addUsersToListOnline(data.id_user)
//users_online[data.id_user] = {'status':'online','socket':socket.id}
//socket.join(data.url_chat);
chat.addUsersToListOnline(data.id_user,data.url_chat)
//var sql = "SELECT * FROM users WHERE id="+data.id_user;
//con.query(sql, function (err3, result3) {
//if (err3) throw err3;
var _url_chat = data.url_chat != null?" room='"+data.url_chat+"' AND":'';
var _url_chat_union = data.url_chat != null?" UNION SELECT * FROM users_chat WHERE room="+data.url_chat:'';
var sql_get = "SELECT * FROM `users_chat` WHERE"+_url_chat+" id_user="+data.id_user+" "+_url_chat_union;
// console.log(sql_get)
con.query(sql_get, (err2, result2)=>{
if (err2) throw err2;
var curr_user = [],
count_users = 0
for(var k in result2){
if(result2[k]['id_user'] == data.id_user){
curr_user.push(result2[k])
}
if(result2[k]['id_user'] != data.id_user){
count_users++;
}
}
if(curr_user.length == 0 && count_users < 2 && data.url_chat != null){
var sql_new_chat = "INSERT INTO users_chat (id_user,room,lang) VALUES ("+data.id_user+",'"+data.url_chat+"','"+data.lang+"')"
con.query(sql_new_chat, (err3, result3)=>{
chat.reloadUsersListDialog(data.url_chat,'all')
})
}else{
chat.reloadUsersListDialog(data.url_chat,'one')
}
});
//})
}
})
socket.on('client_create_new_dialog',(data)=>{
console.log('create new dialog',data)
var url_chat = new Date().getTime();
socket.join(url_chat);
chat.addUsersToListOnline(data.id_user,url_chat)
var sql_new_chat = "INSERT INTO users_chat (id_user,room,lang) VALUES ("+data.id_user+",'"+url_chat+"','"+data.lang+"')"
con.query(sql_new_chat, (err, res)=>{
if(err) throw err;
chat.reloadUsersListDialog(url_chat,'all')
})
})
socket.on('client_load_list_dialog',(data)=>{
console.log('reload list dialog')
var sql = "SELECT * FROM users_chat WHERE id_user ="+data.id_user;
con.query(sql,(err,res)=>{
if (err) throw err;
var chats = [];
for(var k in res){
socket.join(res[k]['room'])
chat.addUsersToListOnline(data.id_user,res[k]['room'])
chats.push(res[k]['room'])
}
if(chats.length > 0){
chats = '('+chats.join(",")+')';
var sql2 = "SELECT * FROM users_chat WHERE room IN "+chats;
con.query(sql2, function (err2, res2) {
if (err2) throw err2;
var all_unread_msg = "SELECT * FROM message WHERE view=0 AND chat_id IN "+chats;
con.query(all_unread_msg, function (err4, res4) {
if (err4) throw err4;
var id_users = []
var unread_msg = {}
for(var l in res2){
id_users.indexOf(res2[l]['id_user']) == -1?id_users.push(res2[l]['id_user']):''
}
for(var k in res){
res[k]['unread'] = 0;
for(y in res4){
if(res4[y]['chat_id'] == res[k]['room'] && res4[y]['msg_from'] != data.id_user){
res[k]['unread'] +=1;
}
}
}
id_users = '('+id_users.join(",")+')';
var sql3 = "SELECT * FROM users WHERE id IN "+id_users;
//console.log(id_users,sql3)
con.query(sql3, function (err3, res3) {
if (err) throw err;
var objUser = [];
for(var k in res2){
for(var y in res3){
if(res2[k]['id_user'] == res3[y]['id']){
res3[y]['room'] = res2[k]['room']
res3[y]['lang'] = res2[k]['lang']
res3[y]['online'] = users_online[res2[k]['id_user']]?'online':'';
}
}
}
socket.emit('server_load_list_dialog',{'users':res3,'chats':res})
})
})
})
}else{
socket.emit('server_load_list_dialog',{'users':[],'chats':[]})
}
})
})
socket.on('client_change_lang',(data)=>{
console.log('client_change_lang',data)
if(data.id_user != 'undefined'){
var sql_update = "UPDATE users_chat SET lang = '"+data.lang+"' WHERE id_user ="+data.id_user+" AND room='"+data.chat_url+"'";
con.query(sql_update, function (err2, result2) {
if (err2) throw err2;
console.log(result2,sql_update)
});
}
})
socket.on('client_load_chat_msg',(data)=>{
console.log('client_load_chat_msg',data)
if(data.url_chat != 'undefined'){
var sql = "SELECT * FROM message WHERE chat_id='"+data.url_chat+"' ORDER BY id ";
con.query(sql, function (err, result) {
if (err) throw err;
var sql2 = "SELECT users_chat.lang AS 'lang',users.id AS 'id',users.name AS 'user_name', users.image AS 'user_image' FROM users_chat JOIN users ON users.id=users_chat.id_user WHERE users_chat.room='"+data.url_chat+"'";
for(var k in result){
result[k]['msg'] = CryptoJS.AES.decrypt(result[k]['msg'],pass_encrypt);
result[k]['msg'] = result[k]['msg'].toString(CryptoJS.enc.Utf8)
}
con.query(sql2, function (err2, result2) {
if(err2) throw err2;
var id_other_user = result2.length > 1?result2[0]['id'] != data.id_user?result2[0]['id']:result2[1]['id']:''
console.log(id_other_user)
chat.setReadStatus(data.url_chat,id_other_user)
socket.emit('server_get_chat_msg',{'messages':result,'chat_users':result2})
})
});
}
})
socket.on('client_send_new_msg',(data)=>{
console.log('client_send_new_msg',data)
data.msg = data.msg.trim()
var sql = "SELECT * FROM users_chat WHERE room ='"+data.url_chat+"'";
con.query(sql, function (err, result) {
if (err) throw err;
if(result.length > 0){
var pr = new Promise(function (resolve, reject) {
var objMsg = {'original':data.msg};
if(data.type != 'msg'){
objMsg['file_name'] = data.file_name
resolve(objMsg)
return false;
}
var count = 1;
for (var k in result) {
const lang = result[k]['lang'] !=undefined?result[k]['lang']:'en';
googleTranslate.translate(data.msg, lang, function(err, translation){
if (err) throw reject(err);
objMsg[lang] = translation.translatedText;
//objMsg[lang] = data.msg;
if(count == result.length ){
resolve(objMsg)
}
count++;
})
}
});
pr.then(function(obj){
var msg_encrypt = CryptoJS.AES.encrypt(JSON.stringify(obj), pass_encrypt);
/*var decrypted = CryptoJS.AES.decrypt(encrypted, myPassword);
console.log(decrypted.toString(CryptoJS.enc.Utf8))*/
io.sockets.in(data.url_chat).emit('server_new_msg',{"time":data.time,"msg_from":data.id_user,"msg":obj,'url_chat':data.url_chat,'type':data.type});
var sql = "INSERT INTO message (chat_id,msg_from,msg,time,type,date) VALUES ('"+data.url_chat+"','"+data.id_user+"','"+msg_encrypt+"','"+data.time+"','"+data.type+"','"+data.date+"')";
con.query(sql, function (err, result) {
if (err) throw err;
});
}).catch(function (err) {
console.log(err);
});
}
});
})
socket.on('delete_chat',(data)=>{
if(data['id_user'] && data['url_chat'] && data['conf']){
var find_chat = "SELECT * FROM `users_chat` WHERE room='"+data['url_chat']+"'"
con.query(find_chat,(err,res)=>{
if(err){
throw err
}else{
console.log(res)
if(res.length > 0){
for(var k in res){
if(res[k]['id_user'] == data['id_user']){
var delet = "DELETE FROM `users_chat` WHERE id_user="+data['id_user']+" AND room='"+data['url_chat']+"'"
console.log(delet)
con.query(delet,(err2,res2)=>{
if(err2){
throw err2
}else{
if(res.length == 1){
var delet_msg = "DELETE FROM `message` WHERE chat_id='"+data['url_chat']+"'"
con.query(delet_msg,(err3,res3)=>{
if(err3) throw err3
})
}
}
})
}
}
}
}
})
}
})
socket.on('disconnect',(data)=>{
console.log('disconect')
for(var k in users_online){
if(users_online[k]['socket'] == socket.id){
for(var y in users_online[k]['room']){
var url_chat = users_online[k]['room'][y],
id_user = users_online[k]['id_user'];
io.sockets.in(url_chat).emit('online_status',{'id_user':id_user,'status':''})
}
console.log('disconnect')
delete users_online[k];
}
}
})
var chat = {
reloadUsersListDialog: (url_chat,type)=>{
if(type == 'all'){
io.sockets.in(url_chat).emit('reloadInf',{'type':'list-dialog','url_chat':url_chat})
}else if(type == 'one'){
socket.emit('reloadInf',{'type':'list-dialog'})
}
},
addUsersToListOnline(id_user,room = false){
if(users_online[id_user]){
if(room != false){
socket.join(room)
io.sockets.in(room).emit('online_status',{'id_user':id_user,'status':'online'})
users_online[id_user]['room'] = users_online[id_user]['room']?users_online[id_user]['room']:[];
users_online[id_user]['room'].indexOf(room) == -1?users_online[id_user]['room'].push(room):''
}
}else{
users_online[id_user] = {'status':'online','id_user':id_user,'room':[],'socket':socket.id}
users_online[id_user]['room'].push(room)
}
},
setReadStatus: (chat_id,id_user)=>{
var sql = "UPDATE `message` SET `view`=1 WHERE chat_id ='"+chat_id+"' AND msg_from='"+id_user+"'"
con.query(sql,(err,res)=>{
if(err) throw err;
console.log('update read status',id_user)
})
}
}
});