app.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. const express = require('express');
  2. const app = express()
  3. const cors = require("cors");
  4. const http = require('http'); //create new http
  5. const mongoose = require('mongoose');
  6. const socket = require("socket.io");
  7. const User = require('./db/models/User');
  8. const Message = require('./db/models/Message');
  9. const PrivateMessage = require('./db/models/PrivateMessage')
  10. const jwt = require('jsonwebtoken');
  11. const bcrypt = require('bcrypt');
  12. require('dotenv').config(); // add dotnv for config
  13. const Uuid = require('uuid'); //lib for unic id generate
  14. const fileupload = require('express-fileupload');
  15. const fs = require('fs');
  16. const ORIGIN_URL = process.env.REACT_APP_BASE_URL
  17. const server = http.createServer(app);
  18. app.use(cors());
  19. app.use(express.json());
  20. app.use(fileupload())
  21. app.use(express.static('avatars')); //folder for static files
  22. const io = require("socket.io")(server, {
  23. cors: ORIGIN_URL
  24. });
  25. const PORT = process.env.PORT || 5000;
  26. const TOKEN_KEY = process.env.TOKEN_KEY || 'rGH4r@3DKOg06hgj';
  27. const HASH_KEY = 7;
  28. const STATIC_PATH = process.env. STATIC_PATH || 'avatars';
  29. const generateToken = (id, userName, isAdmin) => {
  30. const payload = {
  31. id,
  32. userName,
  33. isAdmin
  34. }
  35. return jwt.sign(payload, TOKEN_KEY);
  36. }
  37. const isValidUserName = (userName) => {
  38. const nameRegex = /[^A-Za-z0-9]/ ;
  39. return (!nameRegex.test(userName) && userName.trim().length > 2);
  40. }
  41. const getAllDbUsers = async (socket) => {
  42. const usersDb = await User.find({})
  43. socket.emit('allDbUsers', usersDb)
  44. }
  45. const getOneUser = async (userName) => {
  46. const userInDb = await User.findOne({userName});
  47. return userInDb;
  48. }
  49. app.post('/login', async (req, res) => {
  50. try {
  51. const {userName,password} = req.body;
  52. if (!isValidUserName(userName)){
  53. return res.status(400).json({message: 'Invalid username'})
  54. }
  55. const dbUser = await getOneUser(userName)
  56. if (dbUser?.isBanned){
  57. return res.status(401).json({message: 'Your account has been banned!!!'})
  58. }
  59. const hashPassword = await bcrypt.hash(password, HASH_KEY);
  60. if (!dbUser) {
  61. const user = new User({
  62. userName,
  63. hashPassword,
  64. isAdmin: !await User.count().exec(),
  65. isBanned: false,
  66. isMutted: false,
  67. avatar: '',
  68. messages: []
  69. });
  70. await user.save()
  71. return res.json({
  72. token: generateToken(user.id, user.userName, user.isAdmin)
  73. });
  74. }
  75. if (dbUser && !bcrypt.compareSync(password, dbUser.hashPassword)){
  76. return res.status(400).json({message: 'Invalid credantials'})
  77. }
  78. res.json({
  79. token: generateToken(dbUser.id, dbUser.userName, dbUser.isAdmin),
  80. })
  81. } catch (e) {
  82. console.log(e);
  83. res.status(500).json({message: `Error ${e}`});
  84. }
  85. })
  86. app.post('/avatar', async (req, res) => {
  87. if (!req.files || Object.keys(req.files).length === 0) {
  88. return res.status(400).json('No files were uploaded.');
  89. }
  90. try {
  91. const file = req.files.file;
  92. const user = jwt.verify(req.body.token, TOKEN_KEY);
  93. const avatarFileName = Uuid.v4() + '.jpeg';
  94. file.mv(STATIC_PATH + '\/' + avatarFileName)
  95. const userFromDb = await getOneUser(user.userName);
  96. if(userFromDb.avatar){
  97. const oldAvatar = userFromDb.avatar;
  98. fs.unlinkSync(STATIC_PATH + '\/' + oldAvatar)
  99. }
  100. await User.findOneAndUpdate({userName: user.userName},{ $set: {'avatar': avatarFileName}}, {
  101. new: true
  102. });
  103. return res.json({ message:'Avatar was uploud succesfully...', avatarUrl: avatarFileName})
  104. } catch (error) {
  105. res.status(500).json({message: `Error uppload file to serverp: ${error}`});
  106. }
  107. })
  108. app.post('/files', async (req, res) => {
  109. if (!req.files || Object.keys(req.files).length === 0) {
  110. return res.status(400).json('No files were uploaded.');
  111. }
  112. const user = jwt.verify(req.body.token, TOKEN_KEY);
  113. const oneUser = await getOneUser(user.userName);
  114. if(oneUser.isMutted){
  115. return;
  116. }
  117. const files = req.files.files;
  118. if (files.length) {
  119. for (let i = 0; i < files.length; i++) {
  120. let file = files[i]
  121. file.mv(STATIC_PATH + '\/' + file.name)
  122. const message = new Message({
  123. text: file.name,
  124. userName: user.userName,
  125. createDate: Date.now(),
  126. user: oneUser.id, //add link to other collection by id
  127. file: file.name,
  128. fileType: file.mimetype
  129. });
  130. try {
  131. await message.save();
  132. if(!oneUser.messages){
  133. await oneUser.update({ $set: {'messages': []}});
  134. }
  135. await oneUser.messages.push(message)
  136. await oneUser.save()
  137. }
  138. catch (error) {
  139. console.log('Message save to db error', error);
  140. }
  141. const newMessages = await message.populate( {path:'user'})
  142. io.emit('newmessage', newMessages);
  143. }}
  144. else {
  145. if (files.name == 'blob') {
  146. files.name = Uuid.v4() + '.jpeg'
  147. }
  148. files.mv(STATIC_PATH + '\/' + files.name); //for one file
  149. const message = new Message({
  150. text: files.name,
  151. userName: user.userName,
  152. createDate: Date.now(),
  153. user: oneUser.id, //add link to other collection by id
  154. file: files.name,
  155. fileType: files.mimetype
  156. });
  157. try {
  158. await message.save();
  159. if(!oneUser.messages){
  160. await oneUser.update({ $set: {'messages': []}});
  161. }
  162. await oneUser.messages.push(message)
  163. await oneUser.save()
  164. }
  165. catch (error) {
  166. console.log('Message save to db error', error);
  167. }
  168. const newMessages = await message.populate( {path:'user'})
  169. io.emit('newmessage', newMessages);
  170. }
  171. return res.json({ message:'File was uploud succesfully...'})
  172. })
  173. io.use( async (socket, next) => {
  174. const token = socket.handshake.auth.token;
  175. const sockets = await io.fetchSockets();
  176. if(!token) {
  177. console.log('socket disconnect')
  178. socket.disconnect();
  179. return;
  180. }
  181. const usersOnline = [];
  182. sockets.map(sock => usersOnline.push(sock.user))
  183. try {
  184. const user = jwt.verify(token, TOKEN_KEY);
  185. const userName = user.userName;
  186. const dbUser = await getOneUser(userName);
  187. if(dbUser && dbUser.isBanned){
  188. socket.disconnect();
  189. return;
  190. }
  191. socket.user = user;
  192. const exist = sockets.find(current => current.user.userName == socket.user.userName)
  193. // console.log('exist ' , exist)
  194. if(exist) { //&& !user.isAdmin - add for two or more admins
  195. console.log(exist.user.userName, 'exist twice entering...')
  196. exist.disconnect();
  197. }
  198. } catch(e) {
  199. console.log(e);
  200. socket.disconnect();
  201. }
  202. next();
  203. });
  204. io.on("connection", async (socket) => {
  205. const userName = socket.user.userName;
  206. const sockets = await io.fetchSockets();
  207. const dbUser = await getOneUser(userName);
  208. const allUsers = await getAllDbUsers(socket) // send allUsers from DB to socket user
  209. //need to use this ID to socket privat messges
  210. const users = [];
  211. for (let [id, socket] of io.of("/").sockets) {
  212. const dbUser = await getOneUser(socket.user.userName)
  213. users.push({...dbUser._doc,socketId: id });
  214. }
  215. // const onUser = []
  216. // const usersOnlineID = usersOnline.map(users => Object.values(users)[0])
  217. // const userSet = new Set(usersOnlineID)
  218. // for (let id of userSet) {
  219. // const userFromDb = await User.findById(id)
  220. // onUser.push(userFromDb)
  221. // }
  222. //tasks
  223. // find private chats and send to users
  224. // if(socket.user){
  225. // const siPrivate = await PrivateMessage.find({toUser: socket.user.id})
  226. // console.log(!!siPrivate)
  227. // }
  228. io.emit('usersOnline', users); // send array online users
  229. //send private chats for user
  230. const privateChats = await PrivateMessage.find( {$or:[ {toUser: dbUser._id}, {fromUser: dbUser._id }],foreignField: '_id'}).populate( ['fromUser','toUser'])//need to optimal way found
  231. const myChats = []
  232. // privateChats.map((item, i) => {
  233. // console.log(item)
  234. // })
  235. ///
  236. // console.log(myChats)
  237. //console.log(privateChats)
  238. socket.emit('my chats', privateChats)
  239. socket.emit('connected', dbUser); //socket.user
  240. if(socket.user.isAdmin){
  241. getAllDbUsers(socket);
  242. }//sent all users from db to admin
  243. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});
  244. socket.emit('allmessages', messagesToShow.reverse());
  245. socket.on("message", async (data) => {
  246. const dateNow = Date.now(); // for correct working latest post
  247. const post = await Message.findOne({userName}).sort({ 'createDate': -1 })
  248. const oneUser = await getOneUser(userName);
  249. if(oneUser.isMutted){ //(oneUser.isMutted || !post)
  250. return;
  251. }
  252. if(((Date.now() - Date.parse(post?.createDate)) < 1500)){
  253. console.log((Date.now() - Date.parse(post?.createDate)))// can use to show timer near by button
  254. return;
  255. }
  256. // if(!oneUser.isMutted && post){
  257. // if(((Date.now() - Date.parse(post.createDate)) > 150)){//change later 15000
  258. const message = new Message({
  259. text: data.message,
  260. userName: userName,
  261. createDate: Date.now(),
  262. user: oneUser.id, //add link to other collection by id
  263. });
  264. try {
  265. await message.save();
  266. if(!oneUser.messages){
  267. await oneUser.update({ $set: {'messages': []}});
  268. }
  269. await oneUser.messages.push(message)
  270. await oneUser.save()
  271. } catch (error) {
  272. console.log('Message save to db error', error);
  273. }
  274. const newMessages = await message.populate( {path:'user'})
  275. io.emit('newmessage', newMessages);
  276. // }
  277. // }
  278. });
  279. try {
  280. socket.on("disconnect", async () => {
  281. const exist = sockets.find(current => current.user.userName == socket.user.userName)
  282. const usersOnline = sockets.map(sock => sock.user)
  283. const filteredUsersOnline = usersOnline.filter(user => exist.user.id !== user.id)
  284. io.emit('usersOnline', filteredUsersOnline);
  285. // const sockets = await io.fetchSockets();
  286. // io.emit('usersOnline', sockets.map(sock => sock.user));
  287. console.log(`user :${socket.user.userName} , disconnected to socket`);
  288. });
  289. console.log(`user :${socket.user.userName} , connected to socket`);
  290. socket.on("muteUser",async (data) => {
  291. if(!socket.user.isAdmin){
  292. return;
  293. }
  294. // if(socket.user.isAdmin){
  295. const {user, prevStatus} = data;
  296. const sockets = await io.fetchSockets();
  297. const mute = await User.updateOne({userName : user}, {$set: {isMutted :!prevStatus}});
  298. getAllDbUsers(socket);
  299. const exist = sockets.find( current => current.user.userName == user)
  300. const dbUser = await getOneUser(user);
  301. if(exist){
  302. exist.emit('connected', dbUser);
  303. }
  304. // }
  305. });
  306. socket.on("private message", async ({ fromUser, from, message, toUser , to}) => {
  307. //create message and save to DB
  308. const privateMessage = new PrivateMessage({
  309. text: message,
  310. createDate: Date.now(),
  311. fromUser,
  312. toUser
  313. });
  314. await privateMessage.save()
  315. //emit event
  316. socket.to(to).emit("private message", privateMessage);
  317. // //send new messages array to user
  318. // const privateMessagesToUser = await PrivateMessage.find({toUser: {$in:[fromUser._id, toUser._id]}, fromUser: {$in:[fromUser._id, toUser._id]}}).sort({ 'createDate': 1 })
  319. // socket.emit('send privat messages', {privateMessagesToUser, fromUser})
  320. });
  321. socket.on('privat chat', async (data) => {
  322. //find user to in Db
  323. const privateMessagesToUser = await PrivateMessage.find({toUser: {$in:[data.user._id, data.toUser._id]}, fromUser: {$in:[data.user._id, data.toUser._id]}}).sort({ 'createDate': 1 })
  324. //find user from in db
  325. //compare users and if messages is - send
  326. socket.emit('send privat messages', privateMessagesToUser)
  327. })
  328. socket.on("banUser",async (data) => {
  329. if(!socket.user.isAdmin){
  330. return;
  331. }
  332. // if(socket.user.isAdmin) {
  333. const {user, prevStatus} = data;
  334. const sockets = await io.fetchSockets();
  335. const ban = await User.updateOne({userName : user}, {$set: {isBanned:!prevStatus}});
  336. getAllDbUsers(socket)
  337. const exist = sockets.find( current => current.user.userName == user)
  338. if(exist){
  339. exist.emit('ban', "dbUser")
  340. exist.disconnect();
  341. }
  342. // }
  343. });
  344. socket.on('userWriting', async () => {
  345. let isTyping = true;
  346. io.emit('writing', {userName, isTyping})
  347. })
  348. socket.on('editmessage', async (data) => {
  349. console.log(data.messageNewText)
  350. const user = jwt.verify(data.token, TOKEN_KEY)
  351. if(!user){
  352. return
  353. }
  354. try {
  355. await Message.findByIdAndUpdate(data.messageId, {text:data.messageNewText})
  356. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});
  357. io.emit('allmessages', messagesToShow.reverse())
  358. } catch (error) {
  359. console.log(error)
  360. }
  361. })
  362. socket.on('deleteMessage', async (data) => {
  363. const user = jwt.verify(data.token, TOKEN_KEY)
  364. console.log(data.messageId)
  365. if(!user){
  366. return
  367. }
  368. try {
  369. await Message.findByIdAndDelete(data.messageId)
  370. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});
  371. io.emit('allmessages', messagesToShow.reverse())
  372. } catch (error) {
  373. console.log(error)
  374. }
  375. })
  376. } catch (e) {
  377. console.log(e);
  378. }
  379. });
  380. //server and database start
  381. const start = async () => {
  382. try {
  383. await mongoose.connect('mongodb://localhost:27017/chat')
  384. .then(() => console.log(`DB started`))
  385. // await mongoose
  386. // .connect('mongodb+srv://serg1557733:1557733@cluster0.p9ltitx.mongodb.net/?retryWrites=true&w=majority')
  387. // .then(() => console.log(`DB started`))
  388. server.listen(PORT, () => {
  389. console.log(`Server started. Port: ${PORT}`);
  390. })
  391. } catch (e) {
  392. console.log(e);
  393. }
  394. }
  395. start();