Browse Source

add uploads images into chat

unknown 2 years ago
parent
commit
995bf95886

+ 61 - 1
controllers/messages.js

@@ -1,6 +1,11 @@
 const MessageModel = require('../model/message');
 const UserModel = require('../model/user');
 const ChatModel = require('../model/chat');
+const Jimp = require('jimp');
+const fs = require('fs').promises;
+const path = require('path');
+const createFolderIsExist = require('../helpers/create-directory');
+require('dotenv').config();
 
 const listMessages = async (req, res, next) => {
 	try {
@@ -51,6 +56,7 @@ const sentMessage = async (req, res, next) => {
 				avatarUrl,
 				color,
 				number,
+				type: 'text',
 				companionId: id,
 				owner: userId,
 			});
@@ -61,6 +67,59 @@ const sentMessage = async (req, res, next) => {
 				avatarUrl,
 				color,
 				number,
+				type: 'text',
+				companionId: userId,
+				owner: id,
+			});
+			const { total } = await MessageModel.getList(userId, {});
+			await ChatModel.update(isChat._id, { total, seen: total });
+			const { total: Total } = await MessageModel.getList(id, {});
+			await ChatModel.update(isCompanionChat._id, { total: Total });
+			return res.status(201).json({
+				status: 'success',
+				code: 201,
+				data: newMessage,
+			});
+		}
+	} catch (e) {
+		next(e);
+	}
+};
+
+const imgMessage = async (req, res, next) => {
+	try {
+		const userId = req.user.id;
+		const id = req.params.companionId;
+		const isChat = await ChatModel.getByField(id, userId);
+		const isCompanionChat = await ChatModel.getByField(userId, id);
+		const DIR_IMAGES = process.env.DIR_IMAGES;
+		const pathToFile = req.file.path;
+		const newNameImg = req.file.originalname;
+		await Jimp.read(pathToFile);
+		await createFolderIsExist(path.join(DIR_IMAGES, userId));
+		await fs.rename(pathToFile, path.join(DIR_IMAGES, userId, newNameImg));
+		const imgUrl = path.normalize(path.join(userId, newNameImg));
+		if (isChat && isCompanionChat && imgUrl) {
+			const { name, lastName, avatarUrl, color, number } = req.user;
+			const newMessage = await MessageModel.add({
+				message: imgUrl,
+				name,
+				lastName,
+				avatarUrl,
+				color,
+				number,
+				type: 'image',
+				companionId: id,
+				owner: userId,
+			});
+			await MessageModel.add({
+				message: imgUrl,
+				name,
+				lastName,
+				avatarUrl,
+				color,
+				number,
+				type: 'image',
 				companionId: userId,
 				owner: id,
 			});
@@ -81,6 +140,7 @@ const sentMessage = async (req, res, next) => {
 
 module.exports = {
 	listMessages,
-	sentMessage,
 	listMessagesById,
+	sentMessage,
+	imgMessage,
 };

+ 1 - 2
controllers/user.js

@@ -16,8 +16,7 @@ const createNewUser = async (req, res, next) => {
 		const { number, country } = req.body;
 		const isExist = await UserModel.findByNumber(number);
 		if (isExist) {
-			const id = isExist._id;
-			await UserModel.updateCode(id, code);
+			await UserModel.updateCode(isExist._id, code);
 		} else {
 			await UserModel.createUser({ number, country, color, code });
 		}

+ 18 - 17
helpers/upload.js

@@ -1,24 +1,25 @@
-const multer = require("multer");
-const path = require("path");
-require("dotenv").config();
+const multer = require('multer');
+const path = require('path');
+require('dotenv').config();
 const DIR_UPLOAD = path.join(process.cwd(), process.env.DIR_UPLOAD);
 
 const storage = multer.diskStorage({
-  destination: function (_req, _file, cb) {
-    cb(null, DIR_UPLOAD);
-  },
-  filename: function (_req, file, cb) {
-    cb(null, file.originalname);
-  },
+	destination: function (_req, _file, cb) {
+		cb(null, DIR_UPLOAD);
+	},
+	filename: function (_req, file, cb) {
+		cb(null, file.originalname);
+	},
 });
 
-const upload = multer({
-  storage: storage,
-  limits: { fileSize: 2000000 },
-  fileFilter: (_req, file, cb) => {
-    if (file.mimetype.includes("image")) return cb(null, true);
-    cb(null, false);
-  },
+const uploadImg = multer({
+	storage: storage,
+	limits: { fileSize: 2000000 },
+	fileFilter: (_req, file, cb) => {
+		if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg')
+			return cb(null, true);
+		cb(null, false);
+	},
 });
 
-module.exports = upload;
+module.exports = { uploadImg };

BIN
images/62275dbc1f60894d30cce0c9/monkey.png


+ 4 - 0
model/schemas/message.js

@@ -34,6 +34,10 @@ const messageSchema = new Schema(
 			type: String,
 			default: null,
 		},
+		type: {
+			type: String,
+			default: null,
+		},
 		owner: {
 			type: SchemaTypes.ObjectId,
 			ref: 'user',

+ 3 - 3
routes/chats.js

@@ -8,8 +8,8 @@ router
 	.get('/', guard, controllers.listChats)
 	.get('/:companionId', guard, controllers.chatById)
 	.post('/', guard, validation.startChat, controllers.startChat)
-	.post('/mute/', guard, controllers.muteChat)
-	.post('/seen/', guard, controllers.seenChat)
-	.post('/typing/', guard, controllers.typingChat);
+	.patch('/mute/', guard, controllers.muteChat)
+	.patch('/seen/', guard, controllers.seenChat)
+	.patch('/typing/', guard, validation.typingChat, controllers.typingChat);
 
 module.exports = router;

+ 7 - 1
routes/messages.js

@@ -3,10 +3,16 @@ const router = express.Router();
 const guard = require('../helpers/guard');
 const controllers = require('../controllers/messages');
 const validation = require('../validation/message');
+const upload = require('../helpers/upload');
 
 router
 	.get('/', guard, controllers.listMessages)
-	.post('/', guard, validation.sentMessage, controllers.sentMessage);
+	.post('/', guard, validation.sentMessage, controllers.sentMessage)
+	.post(
+		'/img/:companionId',
+		[guard, upload.uploadImg.single('img'), validation.validateUploadFile],
+		controllers.imgMessage
+	);
 
 router.get('/:companionId', guard, controllers.listMessagesById);
 

+ 4 - 4
routes/user.js

@@ -7,9 +7,9 @@ const upload = require('../helpers/upload');
 
 router
 	.post('/auth/register', validation.registration, controllers.createNewUser)
-	.post('/auth/login', validation.logIn, controllers.logIn)
-	.post('/auth/logout', guard, controllers.logOut)
-	.post('/auth/online', guard, controllers.online)
+	.patch('/auth/login', validation.logIn, controllers.logIn)
+	.patch('/auth/logout', guard, controllers.logOut)
+	.patch('/auth/online', guard, controllers.online)
 	.patch(
 		'/users/current',
 		[guard, validation.updateUser],
@@ -18,7 +18,7 @@ router
 	.get('/users/current', guard, controllers.getCurrent)
 	.patch(
 		'/users/avatars',
-		[guard, upload.single('avatar'), validation.validateUploadFile],
+		[guard, upload.uploadImg.single('avatar'), validation.validateUploadFile],
 		controllers.updateAvatar
 	);
 module.exports = router;

+ 7 - 0
validation/chat.js

@@ -5,6 +5,13 @@ const validate = require('./validate');
 const schemaStartChat = Joi.object({
 	id: Joi.string().required(),
 });
+const schemaTypingChat = Joi.object({
+	id: Joi.string().required(),
+	typing: Joi.boolean().required(),
+});
 module.exports.startChat = (req, _res, next) => {
 	return validate(schemaStartChat, req.body, next);
 };
+module.exports.typingChat = (req, _res, next) => {
+	return validate(schemaTypingChat, req.body, next);
+};

+ 12 - 0
validation/message.js

@@ -6,6 +6,18 @@ const schemaSentMessage = Joi.object({
 	id: Joi.string().required(),
 	message: Joi.string().min(1).max(1400).required(),
 });
+
 module.exports.sentMessage = (req, _res, next) => {
 	return validate(schemaSentMessage, req.body, next);
 };
+
+module.exports.validateUploadFile = (req, res, next) => {
+	if (!req.file)
+		return res.status(400).json({
+			status: 'error',
+			code: 400,
+			data: 'Bad request',
+			message: 'File not found',
+		});
+	next();
+};