messages.js 13 KB

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