messages.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 newNameAudio = `${Math.round(Date.now() / 1000)}${originalName}`;
  253. const fullType = req.file.mimetype;
  254. await createFolderIsExist(path.join(DIR_IMAGES, userId));
  255. await fs.rename(
  256. path.join(DIR_UPLOAD, originalName),
  257. path.join(DIR_IMAGES, userId, newNameAudio)
  258. );
  259. const audioUrl = path.normalize(path.join(userId, newNameAudio));
  260. if (isChat && isCompanionChat && audioUrl) {
  261. const { name, lastName, avatarUrl, color, number } = req.user;
  262. const newMessage = await MessageModel.add({
  263. message: audioUrl,
  264. name,
  265. lastName,
  266. avatarUrl,
  267. color,
  268. number,
  269. type: 'audio',
  270. fullType,
  271. idTime,
  272. companionIdFlow: userId,
  273. companionId: id,
  274. owner: userId,
  275. });
  276. await MessageModel.add({
  277. message: audioUrl,
  278. name,
  279. lastName,
  280. avatarUrl,
  281. color,
  282. number,
  283. type: 'audio',
  284. fullType,
  285. idTime,
  286. companionIdFlow: userId,
  287. companionId: userId,
  288. owner: id,
  289. });
  290. const { total } = await MessageModel.getList(
  291. { owner: userId, companionId: id },
  292. {}
  293. );
  294. await ChatModel.update(isChat._id, userId, {
  295. total,
  296. seen: total,
  297. watched: false,
  298. lastMessage: audioUrl,
  299. lastMessageCreatedAt: newMessage.createdAt,
  300. });
  301. const { total: Total } = await MessageModel.getList(
  302. { owner: id, companionId: userId },
  303. {}
  304. );
  305. await ChatModel.update(isCompanionChat._id, id, {
  306. total: Total,
  307. lastMessage: audioUrl,
  308. lastMessageCreatedAt: newMessage.createdAt,
  309. });
  310. return res.status(201).json({
  311. status: 'success',
  312. code: 201,
  313. data: newMessage,
  314. });
  315. }
  316. } catch (e) {
  317. next(e);
  318. }
  319. };
  320. const videoMessage = async (req, res, next) => {
  321. try {
  322. const userId = req.user.id;
  323. const id = req.params.companionId;
  324. const idTime = Math.round(Date.now() / 1000);
  325. const isChat = await ChatModel.getByField(id, userId);
  326. const isCompanionChat = await ChatModel.getByField(userId, id);
  327. const originalName = req.file.originalname;
  328. const newNameVideo = `${Math.round(Date.now() / 1000)}${originalName}`;
  329. const fullType = req.file.mimetype;
  330. await createFolderIsExist(path.join(DIR_VIDEOS, userId));
  331. await fs.rename(
  332. path.join(DIR_UPLOAD, originalName),
  333. path.join(DIR_VIDEOS, userId, newNameVideo)
  334. );
  335. const videoUrl = path.normalize(path.join(userId, newNameVideo));
  336. if (isChat && isCompanionChat && videoUrl) {
  337. const { name, lastName, avatarUrl, color, number } = req.user;
  338. const newMessage = await MessageModel.add({
  339. message: videoUrl,
  340. name,
  341. lastName,
  342. avatarUrl,
  343. color,
  344. number,
  345. type: 'video',
  346. fullType,
  347. idTime,
  348. companionIdFlow: userId,
  349. companionId: id,
  350. owner: userId,
  351. });
  352. await MessageModel.add({
  353. message: videoUrl,
  354. name,
  355. lastName,
  356. avatarUrl,
  357. color,
  358. number,
  359. type: 'video',
  360. fullType,
  361. idTime,
  362. companionIdFlow: userId,
  363. companionId: userId,
  364. owner: id,
  365. });
  366. const { total } = await MessageModel.getList(
  367. { owner: userId, companionId: id },
  368. {}
  369. );
  370. await ChatModel.update(isChat._id, userId, {
  371. total,
  372. seen: total,
  373. watched: false,
  374. lastMessage: videoUrl,
  375. lastMessageCreatedAt: newMessage.createdAt,
  376. });
  377. const { total: Total } = await MessageModel.getList(
  378. { owner: id, companionId: userId },
  379. {}
  380. );
  381. await ChatModel.update(isCompanionChat._id, id, {
  382. total: Total,
  383. lastMessage: videoUrl,
  384. lastMessageCreatedAt: newMessage.createdAt,
  385. });
  386. return res.status(201).json({
  387. status: 'success',
  388. code: 201,
  389. data: newMessage,
  390. });
  391. }
  392. } catch (e) {
  393. next(e);
  394. }
  395. };
  396. const fileMessage = async (req, res, next) => {
  397. try {
  398. const userId = req.user.id;
  399. const id = req.params.companionId;
  400. const idTime = Math.round(Date.now() / 1000);
  401. const isChat = await ChatModel.getByField(id, userId);
  402. const isCompanionChat = await ChatModel.getByField(userId, id);
  403. const originalName = req.file.originalname;
  404. const fullType = req.file.mimetype;
  405. let type;
  406. switch (fullType) {
  407. case 'application/pdf':
  408. type = 'pdf';
  409. break;
  410. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  411. type = 'docx';
  412. break;
  413. case 'application/octet-stream':
  414. type = 'docx';
  415. break;
  416. default:
  417. break;
  418. }
  419. const newNameFile = `${Math.round(Date.now() / 1000)}file.${type}`;
  420. await createFolderIsExist(path.join(DIR_FILES, userId));
  421. await fs.rename(
  422. path.join(DIR_UPLOAD, originalName),
  423. path.join(DIR_FILES, userId, newNameFile)
  424. );
  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. };