messages.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. const MessageModel = require('../model/message');
  2. const UserModel = require('../model/user');
  3. const ChatModel = require('../model/chat');
  4. const Jimp = require('jimp');
  5. const fs = require('fs').promises;
  6. const path = require('path');
  7. const createFolderIsExist = require('../helpers/create-directory');
  8. require('dotenv').config();
  9. const listMessages = async (req, res, next) => {
  10. try {
  11. const userId = req.user.id;
  12. const messages = await MessageModel.getList({ owner: userId }, req.query);
  13. return res.json({
  14. status: 'success',
  15. code: 200,
  16. data: messages,
  17. });
  18. } catch (e) {
  19. next(e);
  20. }
  21. };
  22. const removeMessage = async (req, res, next) => {
  23. try {
  24. const id = req.params.id;
  25. const userId = req.user.id;
  26. const DIR_IMAGES = process.env.DIR_IMAGES;
  27. const DIR_AUDIOS = process.env.DIR_AUDIOS;
  28. const DIR_VIDEOS = process.env.DIR_VIDEOS;
  29. const DIR_FILES = process.env.DIR_FILES;
  30. const userMessage = await MessageModel.remove(id, userId);
  31. const companionMessage = await MessageModel.removeByFields(
  32. userId,
  33. userMessage.idTime,
  34. userMessage.companionId
  35. );
  36. if (userMessage.type !== 'text') {
  37. switch (userMessage.type) {
  38. case 'image':
  39. await fs.unlink(path.join(DIR_IMAGES, userMessage.message));
  40. break;
  41. case 'audio':
  42. await fs.unlink(path.join(DIR_AUDIOS, userMessage.message));
  43. break;
  44. case 'video':
  45. await fs.unlink(path.join(DIR_VIDEOS, userMessage.message));
  46. break;
  47. default:
  48. await fs.unlink(path.join(DIR_FILES, userMessage.message));
  49. break;
  50. }
  51. }
  52. if (userMessage && companionMessage) {
  53. return res.json({
  54. status: 'success',
  55. code: 200,
  56. data: {},
  57. });
  58. } else {
  59. return res.status(404).json({
  60. status: 'error',
  61. code: 404,
  62. data: 'Not Found',
  63. });
  64. }
  65. } catch (e) {
  66. next(e);
  67. }
  68. };
  69. const listMessagesById = async (req, res, next) => {
  70. try {
  71. const userId = req.user.id;
  72. const companionId = req.params.companionId;
  73. const messages = await MessageModel.getList(
  74. { owner: userId, companionId },
  75. {}
  76. );
  77. return res.json({
  78. status: 'success',
  79. code: 200,
  80. data: messages,
  81. });
  82. } catch (e) {
  83. next(e);
  84. }
  85. };
  86. const sentMessage = async (req, res, next) => {
  87. try {
  88. const { id, message } = req.body;
  89. const idTime = Math.round(Date.now() / 1000);
  90. const user = req.user;
  91. const userId = user.id;
  92. const companion = await UserModel.findById(id);
  93. const isChat = await ChatModel.getByField(id, userId);
  94. const isCompanionChat = await ChatModel.getByField(userId, id);
  95. const { name, lastName, avatarUrl, color, number } = user;
  96. if (companion && isChat && isCompanionChat) {
  97. const newMessage = await MessageModel.add({
  98. message,
  99. name,
  100. lastName,
  101. avatarUrl,
  102. color,
  103. number,
  104. type: 'text',
  105. idTime,
  106. companionIdFlow: userId,
  107. companionId: id,
  108. owner: userId,
  109. });
  110. await MessageModel.add({
  111. message,
  112. name,
  113. lastName,
  114. avatarUrl,
  115. color,
  116. number,
  117. type: 'text',
  118. idTime,
  119. companionIdFlow: userId,
  120. companionId: userId,
  121. owner: id,
  122. });
  123. const { total } = await MessageModel.getList(
  124. { owner: userId, companionId: id },
  125. {}
  126. );
  127. await ChatModel.update(isChat._id, userId, {
  128. total,
  129. seen: total,
  130. watched: false,
  131. lastMessage: message,
  132. lastMessageCreatedAt: newMessage.createdAt,
  133. });
  134. const { total: Total } = await MessageModel.getList(
  135. { owner: id, companionId: userId },
  136. {}
  137. );
  138. await ChatModel.update(isCompanionChat._id, id, {
  139. total: Total,
  140. lastMessage: message,
  141. lastMessageCreatedAt: newMessage.createdAt,
  142. });
  143. return res.status(201).json({
  144. status: 'success',
  145. code: 201,
  146. data: newMessage,
  147. });
  148. }
  149. } catch (e) {
  150. next(e);
  151. }
  152. };
  153. const imageMessage = async (req, res, next) => {
  154. try {
  155. const userId = req.user.id;
  156. const id = req.params.companionId;
  157. const idTime = Math.round(Date.now() / 1000);
  158. const isChat = await ChatModel.getByField(id, userId);
  159. const isCompanionChat = await ChatModel.getByField(userId, id);
  160. const DIR_IMAGES = process.env.DIR_IMAGES;
  161. const pathToFile = req.file.path;
  162. const originalName = req.file.originalname;
  163. const newNameImg = `${Math.round(Date.now() / 1000)}${originalName}`;
  164. const fullType = req.file.mimetype;
  165. await Jimp.read(pathToFile);
  166. await createFolderIsExist(path.join(DIR_IMAGES, userId));
  167. await fs.rename(pathToFile, path.join(DIR_IMAGES, userId, newNameImg));
  168. const imgUrl = path.normalize(path.join(userId, newNameImg));
  169. if (isChat && isCompanionChat && imgUrl) {
  170. const { name, lastName, avatarUrl, color, number } = req.user;
  171. const newMessage = await MessageModel.add({
  172. message: imgUrl,
  173. name,
  174. lastName,
  175. avatarUrl,
  176. color,
  177. number,
  178. type: 'image',
  179. fullType,
  180. idTime,
  181. companionIdFlow: userId,
  182. companionId: id,
  183. owner: userId,
  184. });
  185. await MessageModel.add({
  186. message: imgUrl,
  187. name,
  188. lastName,
  189. avatarUrl,
  190. color,
  191. number,
  192. type: 'image',
  193. fullType,
  194. idTime,
  195. companionIdFlow: userId,
  196. companionId: userId,
  197. owner: id,
  198. });
  199. const { total } = await MessageModel.getList(
  200. { owner: userId, companionId: id },
  201. {}
  202. );
  203. await ChatModel.update(isChat._id, userId, {
  204. total,
  205. seen: total,
  206. watched: false,
  207. lastMessage: imgUrl,
  208. lastMessageCreatedAt: newMessage.createdAt,
  209. });
  210. const { total: Total } = await MessageModel.getList(
  211. { owner: id, companionId: userId },
  212. {}
  213. );
  214. await ChatModel.update(isCompanionChat._id, id, {
  215. total: Total,
  216. lastMessage: imgUrl,
  217. lastMessageCreatedAt: newMessage.createdAt,
  218. });
  219. return res.status(201).json({
  220. status: 'success',
  221. code: 201,
  222. data: newMessage,
  223. });
  224. }
  225. } catch (e) {
  226. next(e);
  227. }
  228. };
  229. const audioMessage = async (req, res, next) => {
  230. try {
  231. const userId = req.user.id;
  232. const id = req.params.companionId;
  233. const idTime = Math.round(Date.now() / 1000);
  234. const isChat = await ChatModel.getByField(id, userId);
  235. const isCompanionChat = await ChatModel.getByField(userId, id);
  236. const DIR_AUDIOS = process.env.DIR_AUDIOS;
  237. const pathToFile = req.file.path;
  238. const originalName = req.file.originalname;
  239. const newNameAudio = `${Math.round(Date.now() / 1000)}${originalName}`;
  240. const fullType = req.file.mimetype;
  241. await createFolderIsExist(path.join(DIR_AUDIOS, userId));
  242. await fs.rename(pathToFile, path.join(DIR_AUDIOS, userId, newNameAudio));
  243. const audioUrl = path.normalize(path.join(userId, newNameAudio));
  244. if (isChat && isCompanionChat && audioUrl) {
  245. const { name, lastName, avatarUrl, color, number } = req.user;
  246. const newMessage = await MessageModel.add({
  247. message: audioUrl,
  248. name,
  249. lastName,
  250. avatarUrl,
  251. color,
  252. number,
  253. type: 'audio',
  254. fullType,
  255. idTime,
  256. companionIdFlow: userId,
  257. companionId: id,
  258. owner: userId,
  259. });
  260. await MessageModel.add({
  261. message: audioUrl,
  262. name,
  263. lastName,
  264. avatarUrl,
  265. color,
  266. number,
  267. type: 'audio',
  268. fullType,
  269. idTime,
  270. companionIdFlow: userId,
  271. companionId: userId,
  272. owner: id,
  273. });
  274. const { total } = await MessageModel.getList(
  275. { owner: userId, companionId: id },
  276. {}
  277. );
  278. await ChatModel.update(isChat._id, userId, {
  279. total,
  280. seen: total,
  281. watched: false,
  282. lastMessage: audioUrl,
  283. lastMessageCreatedAt: newMessage.createdAt,
  284. });
  285. const { total: Total } = await MessageModel.getList(
  286. { owner: id, companionId: userId },
  287. {}
  288. );
  289. await ChatModel.update(isCompanionChat._id, id, {
  290. total: Total,
  291. lastMessage: audioUrl,
  292. lastMessageCreatedAt: newMessage.createdAt,
  293. });
  294. return res.status(201).json({
  295. status: 'success',
  296. code: 201,
  297. data: newMessage,
  298. });
  299. }
  300. } catch (e) {
  301. next(e);
  302. }
  303. };
  304. const videoMessage = async (req, res, next) => {
  305. try {
  306. const userId = req.user.id;
  307. const id = req.params.companionId;
  308. const idTime = Math.round(Date.now() / 1000);
  309. const isChat = await ChatModel.getByField(id, userId);
  310. const isCompanionChat = await ChatModel.getByField(userId, id);
  311. const DIR_VIDEOS = process.env.DIR_VIDEOS;
  312. const pathToFile = req.file.path;
  313. const originalName = req.file.originalname;
  314. const newNameVideo = `${Math.round(Date.now() / 1000)}${originalName}`;
  315. const fullType = req.file.mimetype;
  316. await createFolderIsExist(path.join(DIR_VIDEOS, userId));
  317. await fs.rename(pathToFile, path.join(DIR_VIDEOS, userId, newNameVideo));
  318. const videoUrl = path.normalize(path.join(userId, newNameVideo));
  319. if (isChat && isCompanionChat && videoUrl) {
  320. const { name, lastName, avatarUrl, color, number } = req.user;
  321. const newMessage = await MessageModel.add({
  322. message: videoUrl,
  323. name,
  324. lastName,
  325. avatarUrl,
  326. color,
  327. number,
  328. type: 'video',
  329. fullType,
  330. idTime,
  331. companionIdFlow: userId,
  332. companionId: id,
  333. owner: userId,
  334. });
  335. await MessageModel.add({
  336. message: videoUrl,
  337. name,
  338. lastName,
  339. avatarUrl,
  340. color,
  341. number,
  342. type: 'video',
  343. fullType,
  344. idTime,
  345. companionIdFlow: userId,
  346. companionId: userId,
  347. owner: id,
  348. });
  349. const { total } = await MessageModel.getList(
  350. { owner: userId, companionId: id },
  351. {}
  352. );
  353. await ChatModel.update(isChat._id, userId, {
  354. total,
  355. seen: total,
  356. watched: false,
  357. lastMessage: videoUrl,
  358. lastMessageCreatedAt: newMessage.createdAt,
  359. });
  360. const { total: Total } = await MessageModel.getList(
  361. { owner: id, companionId: userId },
  362. {}
  363. );
  364. await ChatModel.update(isCompanionChat._id, id, {
  365. total: Total,
  366. lastMessage: videoUrl,
  367. lastMessageCreatedAt: newMessage.createdAt,
  368. });
  369. return res.status(201).json({
  370. status: 'success',
  371. code: 201,
  372. data: newMessage,
  373. });
  374. }
  375. } catch (e) {
  376. next(e);
  377. }
  378. };
  379. const fileMessage = async (req, res, next) => {
  380. try {
  381. const userId = req.user.id;
  382. const id = req.params.companionId;
  383. const idTime = Math.round(Date.now() / 1000);
  384. const isChat = await ChatModel.getByField(id, userId);
  385. const isCompanionChat = await ChatModel.getByField(userId, id);
  386. const DIR_FILES = process.env.DIR_FILES;
  387. const pathToFile = req.file.path;
  388. const fullType = req.file.mimetype;
  389. let type;
  390. switch (fullType) {
  391. case 'application/pdf':
  392. type = 'pdf';
  393. break;
  394. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  395. type = 'docx';
  396. break;
  397. case 'application/octet-stream':
  398. type = 'docx';
  399. break;
  400. default:
  401. break;
  402. }
  403. const newNameFile = `${Math.round(Date.now() / 1000)}file.${type}`;
  404. await createFolderIsExist(path.join(DIR_FILES, userId));
  405. await fs.rename(pathToFile, path.join(DIR_FILES, userId, newNameFile));
  406. const fileUrl = path.normalize(path.join(userId, newNameFile));
  407. if (isChat && isCompanionChat && fileUrl) {
  408. const { name, lastName, avatarUrl, color, number } = req.user;
  409. const newMessage = await MessageModel.add({
  410. message: fileUrl,
  411. name,
  412. lastName,
  413. avatarUrl,
  414. color,
  415. number,
  416. type,
  417. fullType,
  418. idTime,
  419. companionIdFlow: userId,
  420. companionId: id,
  421. owner: userId,
  422. });
  423. await MessageModel.add({
  424. message: fileUrl,
  425. name,
  426. lastName,
  427. avatarUrl,
  428. color,
  429. number,
  430. type,
  431. fullType,
  432. idTime,
  433. companionIdFlow: userId,
  434. companionId: userId,
  435. owner: id,
  436. });
  437. const { total } = await MessageModel.getList(
  438. { owner: userId, companionId: id },
  439. {}
  440. );
  441. await ChatModel.update(isChat._id, userId, {
  442. total,
  443. seen: total,
  444. watched: false,
  445. lastMessage: fileUrl,
  446. lastMessageCreatedAt: newMessage.createdAt,
  447. });
  448. const { total: Total } = await MessageModel.getList(
  449. { owner: id, companionId: userId },
  450. {}
  451. );
  452. await ChatModel.update(isCompanionChat._id, id, {
  453. total: Total,
  454. lastMessage: fileUrl,
  455. lastMessageCreatedAt: newMessage.createdAt,
  456. });
  457. return res.status(201).json({
  458. status: 'success',
  459. code: 201,
  460. data: newMessage,
  461. });
  462. }
  463. } catch (e) {
  464. next(e);
  465. }
  466. };
  467. module.exports = {
  468. listMessages,
  469. removeMessage,
  470. listMessagesById,
  471. sentMessage,
  472. imageMessage,
  473. audioMessage,
  474. videoMessage,
  475. fileMessage,
  476. };