messages.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 s3 = require('../helpers/aws');
  6. const AWS_BUCKET_NAME = process.env.AWS_BUCKET_NAME;
  7. require('dotenv').config();
  8. const listMessages = async (req, res, next) => {
  9. try {
  10. const userId = req.user.id;
  11. const messages = await MessageModel.getList({ owner: userId }, req.query);
  12. return res.json({
  13. status: 'success',
  14. code: 200,
  15. data: messages,
  16. });
  17. } catch (e) {
  18. next(e);
  19. }
  20. };
  21. const listMessagesById = async (req, res, next) => {
  22. try {
  23. const userId = req.user.id;
  24. const companionId = req.params.companionId;
  25. const messages = await MessageModel.getList(
  26. { owner: userId, companionId },
  27. {}
  28. );
  29. return res.json({
  30. status: 'success',
  31. code: 200,
  32. data: messages,
  33. });
  34. } catch (e) {
  35. next(e);
  36. }
  37. };
  38. const updateMessageEmoji = async (req, res, next) => {
  39. try {
  40. const id = req.params.id;
  41. const userId = req.user.id;
  42. const { emoji } = req.body;
  43. const userMessage = await MessageModel.updateMessage(id, userId, { emoji });
  44. await MessageModel.findByFieldsAndUpdate(
  45. userId,
  46. userMessage.idTime,
  47. userMessage.companionId,
  48. {
  49. emojiCompanion: emoji,
  50. }
  51. );
  52. return res.status(200).json({
  53. status: 'success',
  54. code: 200,
  55. data: {},
  56. });
  57. } catch (e) {
  58. next(e);
  59. }
  60. };
  61. const updateMessagePin = async (req, res, next) => {
  62. try {
  63. const id = req.params.id;
  64. const userId = req.user.id;
  65. const { pinned } = req.body;
  66. const userMessage = await MessageModel.updateMessage(id, userId, {
  67. pinned,
  68. });
  69. await MessageModel.findByFieldsAndUpdate(
  70. userId,
  71. userMessage.idTime,
  72. userMessage.companionId,
  73. {
  74. pinned,
  75. }
  76. );
  77. return res.status(200).json({
  78. status: 'success',
  79. code: 200,
  80. data: {},
  81. });
  82. } catch (e) {
  83. next(e);
  84. }
  85. };
  86. const unpinAllMessage = async (req, res, next) => {
  87. try {
  88. const userId = req.user.id;
  89. const pinnedMessages = req.body.pinnedMessages;
  90. pinnedMessages.forEach(async (id) => {
  91. const userMessage = await MessageModel.updateMessage(id, userId, {
  92. pinned: false,
  93. });
  94. await MessageModel.findByFieldsAndUpdate(
  95. userId,
  96. userMessage.idTime,
  97. userMessage.companionId,
  98. {
  99. pinned: false,
  100. }
  101. );
  102. });
  103. return res.status(200).json({
  104. status: 'success',
  105. code: 200,
  106. data: {},
  107. });
  108. } catch (e) {
  109. next(e);
  110. }
  111. };
  112. const removeMessage = async (req, res, next) => {
  113. try {
  114. const id = req.params.id;
  115. const userId = req.user.id;
  116. const userMessage = await MessageModel.remove(id, userId);
  117. await MessageModel.removeByFields(
  118. userId,
  119. userMessage.idTime,
  120. userMessage.companionId
  121. );
  122. if (userMessage.type !== 'text') {
  123. const params = {
  124. Bucket: AWS_BUCKET_NAME,
  125. Key: `${userMessage.message}`,
  126. };
  127. s3.deleteObject(params, async function (err, _data) {
  128. if (err) throw err;
  129. });
  130. }
  131. const isChat = await ChatModel.getByField(userMessage.companionId, userId);
  132. const isCompanionChat = await ChatModel.getByField(
  133. userId,
  134. userMessage.companionId
  135. );
  136. const { total } = await MessageModel.getList(
  137. { owner: userId, companionId: userMessage.companionId },
  138. {}
  139. );
  140. const { total: Total } = await MessageModel.getList(
  141. { owner: userMessage.companionId, companionId: userId },
  142. {}
  143. );
  144. await ChatModel.update(isChat._id, userId, {
  145. total: total,
  146. seen: total - isChat.seen > 0 ? isChat.seen : total,
  147. watched: false,
  148. });
  149. await ChatModel.update(isCompanionChat._id, userMessage.companionId, {
  150. total: Total,
  151. seen: Total - isCompanionChat.seen > 0 ? isCompanionChat.seen : Total,
  152. watched: true,
  153. });
  154. return res.json({
  155. status: 'success',
  156. code: 200,
  157. data: {},
  158. });
  159. } catch (e) {
  160. next(e);
  161. }
  162. };
  163. const removeSelected = async (req, res, next) => {
  164. try {
  165. const userId = req.user.id;
  166. const { selectedArr, companionId } = req.body;
  167. const totalDeleted = selectedArr.length;
  168. const toDeleteMessage = async (id) => {
  169. const userMessage = await MessageModel.remove(id, userId);
  170. await MessageModel.removeByFields(
  171. userId,
  172. userMessage.idTime,
  173. companionId
  174. );
  175. if (userMessage.type !== 'text') {
  176. const params = {
  177. Bucket: AWS_BUCKET_NAME,
  178. Key: `${userMessage.message}`,
  179. };
  180. s3.deleteObject(params, async function (err, _data) {
  181. if (err) throw err;
  182. });
  183. }
  184. };
  185. await selectedArr.forEach(async (id) => await toDeleteMessage(id));
  186. const isChat = await ChatModel.getByField(companionId, userId);
  187. const isCompanionChat = await ChatModel.getByField(userId, companionId);
  188. const { total } = await MessageModel.getList(
  189. { owner: userId, companionId },
  190. {}
  191. );
  192. const { total: Total } = await MessageModel.getList(
  193. { owner: companionId, companionId: userId },
  194. {}
  195. );
  196. await ChatModel.update(isChat._id, userId, {
  197. total: total,
  198. seen: isChat.seen - totalDeleted > 0 ? isChat.seen - totalDeleted : 0,
  199. watched: false,
  200. });
  201. await ChatModel.update(isCompanionChat._id, companionId, {
  202. total: Total,
  203. seen:
  204. isCompanionChat.seen - totalDeleted > 0
  205. ? isCompanionChat.seen - totalDeleted
  206. : 0,
  207. watched: true,
  208. });
  209. return res.json({
  210. status: 'success',
  211. code: 200,
  212. data: {},
  213. });
  214. } catch (e) {
  215. next(e);
  216. }
  217. };
  218. const sentMessage = async (req, res, next) => {
  219. try {
  220. const { id, message, caption } = req.body;
  221. const idTime = Math.round(Date.now() / 1000);
  222. const user = req.user;
  223. const userId = user.id;
  224. const companion = await UserModel.findById(id);
  225. const isChat = await ChatModel.getByField(id, userId);
  226. const isCompanionChat = await ChatModel.getByField(userId, id);
  227. const { name, lastName, avatarUrl, color, number } = user;
  228. if (companion && isChat && isCompanionChat) {
  229. const newMessage = await MessageModel.add({
  230. message,
  231. name,
  232. lastName,
  233. avatarUrl,
  234. color,
  235. number,
  236. type: 'text',
  237. caption,
  238. idTime,
  239. companionIdFlow: userId,
  240. companionId: id,
  241. owner: userId,
  242. });
  243. await MessageModel.add({
  244. message,
  245. name,
  246. lastName,
  247. avatarUrl,
  248. color,
  249. number,
  250. type: 'text',
  251. caption,
  252. idTime,
  253. companionIdFlow: userId,
  254. companionId: userId,
  255. owner: id,
  256. });
  257. const { total } = await MessageModel.getList(
  258. { owner: userId, companionId: id },
  259. {}
  260. );
  261. await ChatModel.update(isChat._id, userId, {
  262. total,
  263. seen: total,
  264. watched: false,
  265. lastMessage: message,
  266. lastMessageCreatedAt: newMessage.createdAt,
  267. });
  268. const { total: Total } = await MessageModel.getList(
  269. { owner: id, companionId: userId },
  270. {}
  271. );
  272. await ChatModel.update(isCompanionChat._id, id, {
  273. total: Total,
  274. lastMessage: message,
  275. lastMessageCreatedAt: newMessage.createdAt,
  276. });
  277. return res.status(201).json({
  278. status: 'success',
  279. code: 201,
  280. data: newMessage,
  281. });
  282. }
  283. } catch (e) {
  284. next(e);
  285. }
  286. };
  287. const imageMessage = async (req, res, next) => {
  288. try {
  289. const userId = req.user.id;
  290. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  291. const caption = rest.join(' ').slice(0, -1);
  292. const idTime = Math.round(Date.now() / 1000);
  293. const isChat = await ChatModel.getByField(id, userId);
  294. const isCompanionChat = await ChatModel.getByField(userId, id);
  295. const originalName = req.file.originalname;
  296. const pathToFile = req.file.path;
  297. const fullType = req.file.mimetype;
  298. const imgUrl = `${Math.round(Date.now() / 1000)}${userId}${originalName}`;
  299. const fileContent = await fs.readFile(pathToFile);
  300. const params = {
  301. Bucket: AWS_BUCKET_NAME,
  302. Key: `${imgUrl}`,
  303. Body: fileContent,
  304. };
  305. s3.upload(params, async (err, _data) => {
  306. if (err) throw err;
  307. fs.unlink(pathToFile);
  308. });
  309. if (isChat && isCompanionChat) {
  310. const { name, lastName, avatarUrl, color, number } = req.user;
  311. const newMessage = await MessageModel.add({
  312. message: imgUrl,
  313. name,
  314. lastName,
  315. avatarUrl,
  316. color,
  317. number,
  318. type: 'image',
  319. fullType,
  320. caption,
  321. idTime,
  322. companionIdFlow: userId,
  323. companionId: id,
  324. owner: userId,
  325. });
  326. await MessageModel.add({
  327. message: imgUrl,
  328. name,
  329. lastName,
  330. avatarUrl,
  331. color,
  332. number,
  333. type: 'image',
  334. fullType,
  335. caption,
  336. idTime,
  337. companionIdFlow: userId,
  338. companionId: userId,
  339. owner: id,
  340. });
  341. const { total } = await MessageModel.getList(
  342. { owner: userId, companionId: id },
  343. {}
  344. );
  345. await ChatModel.update(isChat._id, userId, {
  346. total,
  347. seen: total,
  348. watched: false,
  349. lastMessage: imgUrl,
  350. lastMessageCreatedAt: newMessage.createdAt,
  351. });
  352. const { total: Total } = await MessageModel.getList(
  353. { owner: id, companionId: userId },
  354. {}
  355. );
  356. await ChatModel.update(isCompanionChat._id, id, {
  357. total: Total,
  358. lastMessage: imgUrl,
  359. lastMessageCreatedAt: newMessage.createdAt,
  360. });
  361. return res.status(201).json({
  362. status: 'success',
  363. code: 201,
  364. data: newMessage,
  365. });
  366. }
  367. } catch (e) {
  368. next(e);
  369. }
  370. };
  371. const audioMessage = async (req, res, next) => {
  372. try {
  373. const userId = req.user.id;
  374. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  375. let caption = rest.join(' ');
  376. if (caption.length === 1) caption.slice(0, -1);
  377. const idTime = Math.round(Date.now() / 1000);
  378. const isChat = await ChatModel.getByField(id, userId);
  379. const isCompanionChat = await ChatModel.getByField(userId, id);
  380. const originalName = req.file.originalname;
  381. const pathToFile = req.file.path;
  382. const fullType = req.file.mimetype;
  383. const audioUrl = `${Math.round(Date.now() / 1000)}${originalName}`;
  384. const fileContent = await fs.readFile(pathToFile);
  385. const params = {
  386. Bucket: AWS_BUCKET_NAME,
  387. Key: `${audioUrl}`,
  388. Body: fileContent,
  389. };
  390. s3.upload(params, async (err, _data) => {
  391. if (err) throw err;
  392. fs.unlink(pathToFile);
  393. });
  394. if (isChat && isCompanionChat) {
  395. const { name, lastName, avatarUrl, color, number } = req.user;
  396. const newMessage = await MessageModel.add({
  397. message: audioUrl,
  398. name,
  399. lastName,
  400. avatarUrl,
  401. color,
  402. number,
  403. type: 'audio',
  404. fullType,
  405. caption,
  406. idTime,
  407. companionIdFlow: userId,
  408. companionId: id,
  409. owner: userId,
  410. });
  411. await MessageModel.add({
  412. message: audioUrl,
  413. name,
  414. lastName,
  415. avatarUrl,
  416. color,
  417. number,
  418. type: 'audio',
  419. fullType,
  420. caption,
  421. idTime,
  422. companionIdFlow: userId,
  423. companionId: userId,
  424. owner: id,
  425. });
  426. const { total } = await MessageModel.getList(
  427. { owner: userId, companionId: id },
  428. {}
  429. );
  430. await ChatModel.update(isChat._id, userId, {
  431. total,
  432. seen: total,
  433. watched: false,
  434. lastMessage: audioUrl,
  435. lastMessageCreatedAt: newMessage.createdAt,
  436. });
  437. const { total: Total } = await MessageModel.getList(
  438. { owner: id, companionId: userId },
  439. {}
  440. );
  441. await ChatModel.update(isCompanionChat._id, id, {
  442. total: Total,
  443. lastMessage: audioUrl,
  444. lastMessageCreatedAt: newMessage.createdAt,
  445. });
  446. return res.status(201).json({
  447. status: 'success',
  448. code: 201,
  449. data: newMessage,
  450. });
  451. }
  452. } catch (e) {
  453. next(e);
  454. }
  455. };
  456. const videoMessage = async (req, res, next) => {
  457. try {
  458. const userId = req.user.id;
  459. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  460. let caption = rest.join(' ');
  461. if (caption.length === 1) caption.slice(0, -1);
  462. const idTime = Math.round(Date.now() / 1000);
  463. const isChat = await ChatModel.getByField(id, userId);
  464. const isCompanionChat = await ChatModel.getByField(userId, id);
  465. const originalName = req.file.originalname;
  466. const pathToFile = req.file.path;
  467. const videoUrl = `${Math.round(Date.now() / 1000)}${originalName}`;
  468. const fullType = req.file.mimetype;
  469. const fileContent = await fs.readFile(pathToFile);
  470. const params = {
  471. Bucket: AWS_BUCKET_NAME,
  472. Key: `${videoUrl}`,
  473. Body: fileContent,
  474. };
  475. s3.upload(params, async (err, _data) => {
  476. if (err) throw err;
  477. fs.unlink(pathToFile);
  478. });
  479. if (isChat && isCompanionChat) {
  480. const { name, lastName, avatarUrl, color, number } = req.user;
  481. const newMessage = await MessageModel.add({
  482. message: videoUrl,
  483. name,
  484. lastName,
  485. avatarUrl,
  486. color,
  487. number,
  488. type: 'video',
  489. fullType,
  490. caption,
  491. idTime,
  492. companionIdFlow: userId,
  493. companionId: id,
  494. owner: userId,
  495. });
  496. await MessageModel.add({
  497. message: videoUrl,
  498. name,
  499. lastName,
  500. avatarUrl,
  501. color,
  502. number,
  503. type: 'video',
  504. fullType,
  505. caption,
  506. idTime,
  507. companionIdFlow: userId,
  508. companionId: userId,
  509. owner: id,
  510. });
  511. const { total } = await MessageModel.getList(
  512. { owner: userId, companionId: id },
  513. {}
  514. );
  515. await ChatModel.update(isChat._id, userId, {
  516. total,
  517. seen: total,
  518. watched: false,
  519. lastMessage: videoUrl,
  520. lastMessageCreatedAt: newMessage.createdAt,
  521. });
  522. const { total: Total } = await MessageModel.getList(
  523. { owner: id, companionId: userId },
  524. {}
  525. );
  526. await ChatModel.update(isCompanionChat._id, id, {
  527. total: Total,
  528. lastMessage: videoUrl,
  529. lastMessageCreatedAt: newMessage.createdAt,
  530. });
  531. return res.status(201).json({
  532. status: 'success',
  533. code: 201,
  534. data: newMessage,
  535. });
  536. }
  537. } catch (e) {
  538. next(e);
  539. }
  540. };
  541. const fileMessage = async (req, res, next) => {
  542. try {
  543. const userId = req.user.id;
  544. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  545. let caption = rest.join(' ');
  546. if (caption.length === 1) caption.slice(0, -1);
  547. const idTime = Math.round(Date.now() / 1000);
  548. const isChat = await ChatModel.getByField(id, userId);
  549. const isCompanionChat = await ChatModel.getByField(userId, id);
  550. const pathToFile = req.file.path;
  551. const fullType = req.file.mimetype;
  552. let type;
  553. switch (fullType) {
  554. case 'application/pdf':
  555. type = 'pdf';
  556. break;
  557. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  558. type = 'docx';
  559. break;
  560. case 'application/octet-stream':
  561. type = 'docx';
  562. break;
  563. default:
  564. break;
  565. }
  566. const fileUrl = `${Math.round(Date.now() / 1000)}file.${type}`;
  567. const fileContent = await fs.readFile(pathToFile);
  568. const params = {
  569. Bucket: AWS_BUCKET_NAME,
  570. Key: `${fileUrl}`,
  571. Body: fileContent,
  572. };
  573. s3.upload(params, async (err, _data) => {
  574. if (err) throw err;
  575. fs.unlink(pathToFile);
  576. });
  577. if (isChat && isCompanionChat) {
  578. const { name, lastName, avatarUrl, color, number } = req.user;
  579. const newMessage = await MessageModel.add({
  580. message: fileUrl,
  581. name,
  582. lastName,
  583. avatarUrl,
  584. color,
  585. number,
  586. type,
  587. fullType,
  588. caption,
  589. idTime,
  590. companionIdFlow: userId,
  591. companionId: id,
  592. owner: userId,
  593. });
  594. await MessageModel.add({
  595. message: fileUrl,
  596. name,
  597. lastName,
  598. avatarUrl,
  599. color,
  600. number,
  601. type,
  602. fullType,
  603. caption,
  604. idTime,
  605. companionIdFlow: userId,
  606. companionId: userId,
  607. owner: id,
  608. });
  609. const { total } = await MessageModel.getList(
  610. { owner: userId, companionId: id },
  611. {}
  612. );
  613. await ChatModel.update(isChat._id, userId, {
  614. total,
  615. seen: total,
  616. watched: false,
  617. lastMessage: fileUrl,
  618. lastMessageCreatedAt: newMessage.createdAt,
  619. });
  620. const { total: Total } = await MessageModel.getList(
  621. { owner: id, companionId: userId },
  622. {}
  623. );
  624. await ChatModel.update(isCompanionChat._id, id, {
  625. total: Total,
  626. lastMessage: fileUrl,
  627. lastMessageCreatedAt: newMessage.createdAt,
  628. });
  629. return res.status(201).json({
  630. status: 'success',
  631. code: 201,
  632. data: newMessage,
  633. });
  634. }
  635. } catch (e) {
  636. next(e);
  637. }
  638. };
  639. module.exports = {
  640. listMessages,
  641. removeMessage,
  642. removeSelected,
  643. updateMessageEmoji,
  644. updateMessagePin,
  645. unpinAllMessage,
  646. listMessagesById,
  647. sentMessage,
  648. imageMessage,
  649. audioMessage,
  650. videoMessage,
  651. fileMessage,
  652. };