app.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 jwt = require('jsonwebtoken');
  10. const bcrypt = require('bcrypt');
  11. require('dotenv').config(); // add dotnv for config
  12. const Uuid = require('uuid'); //lib for unic id generate
  13. const fileupload = require('express-fileupload');
  14. const fs = require('fs');
  15. const server = http.createServer(app);
  16. app.use(cors());
  17. app.use(express.json());
  18. app.use(fileupload())
  19. app.use(express.static('avatars')); //folder for static files
  20. const io = require("socket.io")(server, {
  21. cors: {
  22. origin: "http://192.168.0.107:3000" //client endpoint and port
  23. }
  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.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. io.emit('usersOnline', sockets.map(sock => sock.user)); // send array online users
  209. socket.emit('connected', dbUser); //socket.user
  210. if(socket.user.isAdmin){
  211. getAllDbUsers(socket);
  212. }//sent all users from db to admin
  213. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});
  214. socket.emit('allmessages', messagesToShow.reverse());
  215. socket.on("message", async (data) => {
  216. const dateNow = Date.now(); // for correct working latest post
  217. const post = await Message.findOne({userName}).sort({ 'createDate': -1 })
  218. const oneUser = await getOneUser(userName);
  219. if(oneUser.isMutted){ //(oneUser.isMutted || !post)
  220. return;
  221. }
  222. if(((Date.now() - Date.parse(post?.createDate)) < 1500)){
  223. console.log((Date.now() - Date.parse(post?.createDate)))// can use to show timer near by button
  224. return;
  225. }
  226. // if(!oneUser.isMutted && post){
  227. // if(((Date.now() - Date.parse(post.createDate)) > 150)){//change later 15000
  228. const message = new Message({
  229. text: data.message,
  230. userName: userName,
  231. createDate: Date.now(),
  232. user: oneUser.id, //add link to other collection by id
  233. });
  234. try {
  235. await message.save();
  236. if(!oneUser.messages){
  237. await oneUser.update({ $set: {'messages': []}});
  238. }
  239. await oneUser.messages.push(message)
  240. await oneUser.save()
  241. } catch (error) {
  242. console.log('Message save to db error', error);
  243. }
  244. const newMessages = await message.populate( {path:'user'})
  245. io.emit('newmessage', newMessages);
  246. // }
  247. // }
  248. });
  249. try {
  250. socket.on("disconnect", async () => {
  251. const sockets = await io.fetchSockets();
  252. io.emit('usersOnline', sockets.map(sock => sock.user));
  253. console.log(`user :${socket.user.userName} , disconnected to socket`);
  254. });
  255. console.log(`user :${socket.user.userName} , connected to socket`);
  256. socket.on("muteUser",async (data) => {
  257. if(!socket.user.isAdmin){
  258. return;
  259. }
  260. // if(socket.user.isAdmin){
  261. const {user, prevStatus} = data;
  262. const sockets = await io.fetchSockets();
  263. const mute = await User.updateOne({userName : user}, {$set: {isMutted :!prevStatus}});
  264. getAllDbUsers(socket);
  265. const exist = sockets.find( current => current.user.userName == user)
  266. const dbUser = await getOneUser(user);
  267. if(exist){
  268. exist.emit('connected', dbUser);
  269. }
  270. // }
  271. });
  272. socket.on("banUser",async (data) => {
  273. if(!socket.user.isAdmin){
  274. return;
  275. }
  276. // if(socket.user.isAdmin) {
  277. const {user, prevStatus} = data;
  278. const sockets = await io.fetchSockets();
  279. const ban = await User.updateOne({userName : user}, {$set: {isBanned:!prevStatus}});
  280. getAllDbUsers(socket)
  281. const exist = sockets.find( current => current.user.userName == user)
  282. if(exist){
  283. exist.emit('ban', "dbUser")
  284. exist.disconnect();
  285. }
  286. // }
  287. });
  288. socket.on('userWriting', async () => {
  289. let isTyping = true;
  290. io.emit('writing', {userName, isTyping})
  291. })
  292. socket.on('editmessage', async (data) => {
  293. console.log(data.messageNewText)
  294. const user = jwt.verify(data.token, TOKEN_KEY)
  295. if(!user){
  296. return
  297. }
  298. try {
  299. await Message.findByIdAndUpdate(data.messageId, {text:data.messageNewText})
  300. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});
  301. io.emit('allmessages', messagesToShow.reverse())
  302. } catch (error) {
  303. console.log(error)
  304. }
  305. })
  306. socket.on('deleteMessage', async (data) => {
  307. const user = jwt.verify(data.token, TOKEN_KEY)
  308. console.log(data.messageId)
  309. if(!user){
  310. return
  311. }
  312. try {
  313. await Message.findByIdAndDelete(data.messageId)
  314. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});
  315. io.emit('allmessages', messagesToShow.reverse())
  316. } catch (error) {
  317. console.log(error)
  318. }
  319. })
  320. } catch (e) {
  321. console.log(e);
  322. }
  323. });
  324. //server and database start
  325. const start = async () => {
  326. try {
  327. await mongoose.connect('mongodb://localhost:27017/chat')
  328. .then(() => console.log(`DB started`))
  329. server.listen(PORT, () => {
  330. console.log(`Server started. Port: ${PORT}`);
  331. })
  332. } catch (e) {
  333. console.log(e);
  334. }
  335. }
  336. start();