messages.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. const MessageModel = require('../model/message');
  2. const UserModel = require('../model/user');
  3. const ChatModel = require('../model/chat');
  4. const fs = require('fs').promises;
  5. const path = require('path');
  6. const createFolderIsExist = require('../helpers/create-directory');
  7. const DIR_UPLOAD = process.env.DIR_UPLOAD;
  8. const DIR_IMAGES = process.env.DIR_IMAGES;
  9. const DIR_AUDIOS = process.env.DIR_AUDIOS;
  10. const DIR_VIDEOS = process.env.DIR_VIDEOS;
  11. const DIR_FILES = process.env.DIR_FILES;
  12. require('dotenv').config();
  13. const listMessages = async (req, res, next) => {
  14. try {
  15. const userId = req.user.id;
  16. const messages = await MessageModel.getList({ owner: userId }, req.query);
  17. return res.json({
  18. status: 'success',
  19. code: 200,
  20. data: messages,
  21. });
  22. } catch (e) {
  23. next(e);
  24. }
  25. };
  26. const removeMessage = async (req, res, next) => {
  27. try {
  28. const id = req.params.id;
  29. const userId = req.user.id;
  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 originalName = req.file.originalname;
  176. const newNameImg = `${Math.round(Date.now() / 1000)}${originalName}`;
  177. const fullType = req.file.mimetype;
  178. await createFolderIsExist(path.join(DIR_IMAGES, userId));
  179. await fs.rename(
  180. path.join(DIR_UPLOAD, originalName),
  181. path.join(DIR_IMAGES, userId, newNameImg)
  182. );
  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 originalName = req.file.originalname;
  252. const fileName = req.file.fileName;
  253. const newNameAudio = `${Math.round(Date.now() / 1000)}${originalName}`;
  254. const fullType = req.file.mimetype;
  255. await createFolderIsExist(path.join(DIR_IMAGES, userId));
  256. await fs.rename(
  257. path.join(DIR_UPLOAD, fileName),
  258. path.join(DIR_IMAGES, userId, newNameAudio)
  259. );
  260. const audioUrl = path.normalize(path.join(userId, newNameAudio));
  261. if (isChat && isCompanionChat && audioUrl) {
  262. const { name, lastName, avatarUrl, color, number } = req.user;
  263. const newMessage = await MessageModel.add({
  264. message: audioUrl,
  265. name,
  266. lastName,
  267. avatarUrl,
  268. color,
  269. number,
  270. type: 'audio',
  271. fullType,
  272. idTime,
  273. companionIdFlow: userId,
  274. companionId: id,
  275. owner: userId,
  276. });
  277. await MessageModel.add({
  278. message: audioUrl,
  279. name,
  280. lastName,
  281. avatarUrl,
  282. color,
  283. number,
  284. type: 'audio',
  285. fullType,
  286. idTime,
  287. companionIdFlow: userId,
  288. companionId: userId,
  289. owner: id,
  290. });
  291. const { total } = await MessageModel.getList(
  292. { owner: userId, companionId: id },
  293. {}
  294. );
  295. await ChatModel.update(isChat._id, userId, {
  296. total,
  297. seen: total,
  298. watched: false,
  299. lastMessage: audioUrl,
  300. lastMessageCreatedAt: newMessage.createdAt,
  301. });
  302. const { total: Total } = await MessageModel.getList(
  303. { owner: id, companionId: userId },
  304. {}
  305. );
  306. await ChatModel.update(isCompanionChat._id, id, {
  307. total: Total,
  308. lastMessage: audioUrl,
  309. lastMessageCreatedAt: newMessage.createdAt,
  310. });
  311. return res.status(201).json({
  312. status: 'success',
  313. code: 201,
  314. data: newMessage,
  315. });
  316. }
  317. } catch (e) {
  318. next(e);
  319. }
  320. };
  321. const videoMessage = async (req, res, next) => {
  322. try {
  323. const userId = req.user.id;
  324. const id = req.params.companionId;
  325. const idTime = Math.round(Date.now() / 1000);
  326. const isChat = await ChatModel.getByField(id, userId);
  327. const isCompanionChat = await ChatModel.getByField(userId, id);
  328. const originalName = req.file.originalname;
  329. const newNameVideo = `${Math.round(Date.now() / 1000)}${originalName}`;
  330. const fullType = req.file.mimetype;
  331. await createFolderIsExist(path.join(DIR_VIDEOS, userId));
  332. await fs.rename(
  333. path.join(DIR_UPLOAD, originalName),
  334. path.join(DIR_VIDEOS, userId, newNameVideo)
  335. );
  336. const videoUrl = path.normalize(path.join(userId, newNameVideo));
  337. if (isChat && isCompanionChat && videoUrl) {
  338. const { name, lastName, avatarUrl, color, number } = req.user;
  339. const newMessage = await MessageModel.add({
  340. message: videoUrl,
  341. name,
  342. lastName,
  343. avatarUrl,
  344. color,
  345. number,
  346. type: 'video',
  347. fullType,
  348. idTime,
  349. companionIdFlow: userId,
  350. companionId: id,
  351. owner: userId,
  352. });
  353. await MessageModel.add({
  354. message: videoUrl,
  355. name,
  356. lastName,
  357. avatarUrl,
  358. color,
  359. number,
  360. type: 'video',
  361. fullType,
  362. idTime,
  363. companionIdFlow: userId,
  364. companionId: userId,
  365. owner: id,
  366. });
  367. const { total } = await MessageModel.getList(
  368. { owner: userId, companionId: id },
  369. {}
  370. );
  371. await ChatModel.update(isChat._id, userId, {
  372. total,
  373. seen: total,
  374. watched: false,
  375. lastMessage: videoUrl,
  376. lastMessageCreatedAt: newMessage.createdAt,
  377. });
  378. const { total: Total } = await MessageModel.getList(
  379. { owner: id, companionId: userId },
  380. {}
  381. );
  382. await ChatModel.update(isCompanionChat._id, id, {
  383. total: Total,
  384. lastMessage: videoUrl,
  385. lastMessageCreatedAt: newMessage.createdAt,
  386. });
  387. return res.status(201).json({
  388. status: 'success',
  389. code: 201,
  390. data: newMessage,
  391. });
  392. }
  393. } catch (e) {
  394. next(e);
  395. }
  396. };
  397. const fileMessage = async (req, res, next) => {
  398. try {
  399. const userId = req.user.id;
  400. const id = req.params.companionId;
  401. const idTime = Math.round(Date.now() / 1000);
  402. const isChat = await ChatModel.getByField(id, userId);
  403. const isCompanionChat = await ChatModel.getByField(userId, id);
  404. const originalName = req.file.originalname;
  405. const fullType = req.file.mimetype;
  406. let type;
  407. switch (fullType) {
  408. case 'application/pdf':
  409. type = 'pdf';
  410. break;
  411. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  412. type = 'docx';
  413. break;
  414. case 'application/octet-stream':
  415. type = 'docx';
  416. break;
  417. default:
  418. break;
  419. }
  420. const newNameFile = `${Math.round(Date.now() / 1000)}file.${type}`;
  421. await createFolderIsExist(path.join(DIR_FILES, userId));
  422. await fs.rename(
  423. path.join(DIR_UPLOAD, originalName),
  424. path.join(DIR_FILES, userId, newNameFile)
  425. );
  426. const fileUrl = path.normalize(path.join(userId, newNameFile));
  427. if (isChat && isCompanionChat && fileUrl) {
  428. const { name, lastName, avatarUrl, color, number } = req.user;
  429. const newMessage = await MessageModel.add({
  430. message: fileUrl,
  431. name,
  432. lastName,
  433. avatarUrl,
  434. color,
  435. number,
  436. type,
  437. fullType,
  438. idTime,
  439. companionIdFlow: userId,
  440. companionId: id,
  441. owner: userId,
  442. });
  443. await MessageModel.add({
  444. message: fileUrl,
  445. name,
  446. lastName,
  447. avatarUrl,
  448. color,
  449. number,
  450. type,
  451. fullType,
  452. idTime,
  453. companionIdFlow: userId,
  454. companionId: userId,
  455. owner: id,
  456. });
  457. const { total } = await MessageModel.getList(
  458. { owner: userId, companionId: id },
  459. {}
  460. );
  461. await ChatModel.update(isChat._id, userId, {
  462. total,
  463. seen: total,
  464. watched: false,
  465. lastMessage: fileUrl,
  466. lastMessageCreatedAt: newMessage.createdAt,
  467. });
  468. const { total: Total } = await MessageModel.getList(
  469. { owner: id, companionId: userId },
  470. {}
  471. );
  472. await ChatModel.update(isCompanionChat._id, id, {
  473. total: Total,
  474. lastMessage: fileUrl,
  475. lastMessageCreatedAt: newMessage.createdAt,
  476. });
  477. return res.status(201).json({
  478. status: 'success',
  479. code: 201,
  480. data: newMessage,
  481. });
  482. }
  483. } catch (e) {
  484. next(e);
  485. }
  486. };
  487. module.exports = {
  488. listMessages,
  489. removeMessage,
  490. listMessagesById,
  491. sentMessage,
  492. imageMessage,
  493. audioMessage,
  494. videoMessage,
  495. fileMessage,
  496. };