messages.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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 editMessage = async (req, res, next) => {
  39. try {
  40. const userId = req.user.id;
  41. const { id, message, caption } = req.body;
  42. const userMessage = await MessageModel.getById(id, userId);
  43. await MessageModel.updateMessage(id, userId, {
  44. message: userMessage.fullType === null ? message : userMessage.message,
  45. caption,
  46. edited: true,
  47. });
  48. await MessageModel.findByFieldsAndUpdateMany(
  49. {
  50. oldId: userMessage._id,
  51. },
  52. {
  53. forwardMessage:
  54. userMessage.fullType === null ? message : userMessage.forwardMessage,
  55. forwardCaption: caption,
  56. replyMessage:
  57. userMessage.fullType === null ? message : userMessage.replyMessage,
  58. replyCaption: caption,
  59. edited: true,
  60. }
  61. );
  62. const companionMessage = await MessageModel.findByFields(
  63. userId,
  64. userMessage.idTime,
  65. userMessage.companionId
  66. );
  67. await MessageModel.findByFieldsAndUpdate(
  68. userId,
  69. userMessage.idTime,
  70. userMessage.companionId,
  71. {
  72. message: userMessage.fullType === null ? message : userMessage.message,
  73. caption,
  74. }
  75. );
  76. await MessageModel.findByFieldsAndUpdateMany(
  77. {
  78. oldId: companionMessage._id,
  79. },
  80. {
  81. forwardMessage:
  82. userMessage.fullType === null ? message : userMessage.forwardMessage,
  83. forwardCaption: caption,
  84. replyMessage:
  85. userMessage.fullType === null ? message : userMessage.replyMessage,
  86. replyCaption: caption,
  87. }
  88. );
  89. const isChat = await ChatModel.getByField(userMessage.companionId, userId);
  90. const isCompanionChat = await ChatModel.getByField(
  91. userId,
  92. userMessage.companionId
  93. );
  94. const updatedAt = new Date();
  95. await ChatModel.update(isChat._id, userId, {
  96. lastMessage: 'The Message was Edited',
  97. lastMessageCreatedAt: updatedAt,
  98. });
  99. await ChatModel.update(isCompanionChat._id, userMessage.companionId, {
  100. lastMessage: 'The Message was Edited',
  101. lastMessageCreatedAt: updatedAt,
  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 updateMessageEmoji = async (req, res, next) => {
  113. try {
  114. const id = req.params.id;
  115. const userId = req.user.id;
  116. const { emoji } = req.body;
  117. const userMessage = await MessageModel.updateMessage(id, userId, { emoji });
  118. await MessageModel.findByFieldsAndUpdate(
  119. userId,
  120. userMessage.idTime,
  121. userMessage.companionId,
  122. {
  123. emojiCompanion: emoji,
  124. }
  125. );
  126. return res.status(200).json({
  127. status: 'success',
  128. code: 200,
  129. data: {},
  130. });
  131. } catch (e) {
  132. next(e);
  133. }
  134. };
  135. const updateMessagePin = async (req, res, next) => {
  136. try {
  137. const id = req.params.id;
  138. const userId = req.user.id;
  139. const { pinned } = req.body;
  140. const userMessage = await MessageModel.updateMessage(id, userId, {
  141. pinned,
  142. });
  143. await MessageModel.findByFieldsAndUpdate(
  144. userId,
  145. userMessage.idTime,
  146. userMessage.companionId,
  147. {
  148. pinned,
  149. }
  150. );
  151. return res.status(200).json({
  152. status: 'success',
  153. code: 200,
  154. data: {},
  155. });
  156. } catch (e) {
  157. next(e);
  158. }
  159. };
  160. const unpinAllMessage = async (req, res, next) => {
  161. try {
  162. const userId = req.user.id;
  163. const pinnedMessages = req.body.pinnedMessages;
  164. pinnedMessages.forEach(async (id) => {
  165. const userMessage = await MessageModel.updateMessage(id, userId, {
  166. pinned: false,
  167. });
  168. await MessageModel.findByFieldsAndUpdate(
  169. userId,
  170. userMessage.idTime,
  171. userMessage.companionId,
  172. {
  173. pinned: false,
  174. }
  175. );
  176. });
  177. return res.status(200).json({
  178. status: 'success',
  179. code: 200,
  180. data: {},
  181. });
  182. } catch (e) {
  183. next(e);
  184. }
  185. };
  186. const removeMessage = async (req, res, next) => {
  187. try {
  188. const id = req.params.id;
  189. const userId = req.user.id;
  190. const userMessage = await MessageModel.remove(id, userId);
  191. await MessageModel.findByFieldsAndUpdateMany(
  192. {
  193. oldId: userMessage._id,
  194. },
  195. {
  196. replyMessage: null,
  197. replyName: null,
  198. replyLastName: null,
  199. replyCaption: null,
  200. forwardMessage: null,
  201. forwardMessage: null,
  202. forwardName: null,
  203. forwardLastName: null,
  204. forwardCaption: null,
  205. fullType: null,
  206. companionIdForwardToAndFrom: null,
  207. oldId: null,
  208. }
  209. );
  210. const companionMessage = await MessageModel.findByFields(
  211. userId,
  212. userMessage.idTime,
  213. userMessage.companionId
  214. );
  215. await MessageModel.findByFieldsAndUpdateMany(
  216. {
  217. oldId: companionMessage._id,
  218. },
  219. {
  220. replyMessage: null,
  221. replyName: null,
  222. replyLastName: null,
  223. replyCaption: null,
  224. forwardMessage: null,
  225. forwardMessage: null,
  226. forwardName: null,
  227. forwardLastName: null,
  228. forwardCaption: null,
  229. fullType: null,
  230. companionIdForwardToAndFrom: null,
  231. oldId: null,
  232. }
  233. );
  234. await MessageModel.removeByFields(
  235. userId,
  236. userMessage.idTime,
  237. userMessage.companionId
  238. );
  239. if (userMessage.type !== 'text') {
  240. const params = {
  241. Bucket: AWS_BUCKET_NAME,
  242. Key: `${userMessage.message}`,
  243. };
  244. s3.deleteObject(params, async function (err, _data) {
  245. if (err) throw err;
  246. });
  247. }
  248. const isChat = await ChatModel.getByField(userMessage.companionId, userId);
  249. const isCompanionChat = await ChatModel.getByField(
  250. userId,
  251. userMessage.companionId
  252. );
  253. const { total } = await MessageModel.getList(
  254. { owner: userId, companionId: userMessage.companionId },
  255. {}
  256. );
  257. const { total: Total } = await MessageModel.getList(
  258. { owner: userMessage.companionId, companionId: userId },
  259. {}
  260. );
  261. const seenCalculate = (seen, total) => {
  262. if (seen <= total) {
  263. return seen;
  264. } else {
  265. return total;
  266. }
  267. };
  268. const updatedAt = new Date();
  269. await ChatModel.update(isChat._id, userId, {
  270. total: total,
  271. seen: seenCalculate(isChat.seen, total),
  272. seenCompanion: seenCalculate(isChat.seenCompanion, total),
  273. lastMessage: 'The Message was Deleted',
  274. lastMessageCreatedAt: updatedAt,
  275. });
  276. await ChatModel.update(isCompanionChat._id, userMessage.companionId, {
  277. total: Total,
  278. seen: seenCalculate(isCompanionChat.seen, Total),
  279. seenCompanion: seenCalculate(isCompanionChat.seenCompanion, Total),
  280. lastMessage: 'The Message was Deleted',
  281. lastMessageCreatedAt: updatedAt,
  282. });
  283. return res.json({
  284. status: 'success',
  285. code: 200,
  286. data: {},
  287. });
  288. } catch (e) {
  289. next(e);
  290. }
  291. };
  292. const removeSelected = async (req, res, next) => {
  293. try {
  294. const userId = req.user.id;
  295. const { selectedArr, companionId } = req.body;
  296. const toDeleteMessage = async (id) => {
  297. const userMessage = await MessageModel.remove(id, userId);
  298. await MessageModel.findByFieldsAndUpdateMany(
  299. {
  300. oldId: userMessage._id,
  301. },
  302. {
  303. replyMessage: null,
  304. replyName: null,
  305. replyLastName: null,
  306. replyCaption: null,
  307. forwardMessage: null,
  308. forwardMessage: null,
  309. forwardName: null,
  310. forwardLastName: null,
  311. forwardCaption: null,
  312. fullType: null,
  313. companionIdForwardToAndFrom: null,
  314. oldId: null,
  315. }
  316. );
  317. const companionMessage = await MessageModel.findByFields(
  318. userId,
  319. userMessage.idTime,
  320. companionId
  321. );
  322. await MessageModel.findByFieldsAndUpdateMany(
  323. {
  324. oldId: companionMessage._id,
  325. },
  326. {
  327. replyMessage: null,
  328. replyName: null,
  329. replyLastName: null,
  330. replyCaption: null,
  331. forwardMessage: null,
  332. forwardMessage: null,
  333. forwardName: null,
  334. forwardLastName: null,
  335. forwardCaption: null,
  336. fullType: null,
  337. companionIdForwardToAndFrom: null,
  338. oldId: null,
  339. }
  340. );
  341. await MessageModel.removeByFields(
  342. userId,
  343. userMessage.idTime,
  344. companionId
  345. );
  346. if (userMessage.type !== 'text') {
  347. const params = {
  348. Bucket: AWS_BUCKET_NAME,
  349. Key: `${userMessage.message}`,
  350. };
  351. s3.deleteObject(params, async function (err, _data) {
  352. if (err) throw err;
  353. });
  354. }
  355. };
  356. await selectedArr.forEach(async (id) => await toDeleteMessage(id));
  357. const isChat = await ChatModel.getByField(companionId, userId);
  358. const isCompanionChat = await ChatModel.getByField(userId, companionId);
  359. const { total } = await MessageModel.getList(
  360. { owner: userId, companionId },
  361. {}
  362. );
  363. const { total: Total } = await MessageModel.getList(
  364. { owner: companionId, companionId: userId },
  365. {}
  366. );
  367. const seenCalculate = (seen, total) => {
  368. if (seen <= total) {
  369. return seen;
  370. } else {
  371. return total;
  372. }
  373. };
  374. const updatedAt = new Date();
  375. await ChatModel.update(isChat._id, userId, {
  376. total: total,
  377. seen: seenCalculate(isChat.seen, total),
  378. seenCompanion: seenCalculate(isChat.seenCompanion, total),
  379. lastMessage: 'Some Messages were Deleted',
  380. lastMessageCreatedAt: updatedAt,
  381. });
  382. await ChatModel.update(isCompanionChat._id, companionId, {
  383. total: Total,
  384. seen: seenCalculate(isCompanionChat.seen, Total),
  385. seenCompanion: seenCalculate(isCompanionChat.seenCompanion, Total),
  386. lastMessage: 'Some Messages were Deleted',
  387. lastMessageCreatedAt: updatedAt,
  388. });
  389. return res.json({
  390. status: 'success',
  391. code: 200,
  392. data: {},
  393. });
  394. } catch (e) {
  395. next(e);
  396. }
  397. };
  398. const sentMessage = async (req, res, next) => {
  399. try {
  400. const { id, message, caption } = req.body;
  401. const idTime = Math.round(Date.now() / 1000);
  402. const user = req.user;
  403. const userId = user.id;
  404. const companion = await UserModel.findById(id);
  405. const isChat = await ChatModel.getByField(id, userId);
  406. const isCompanionChat = await ChatModel.getByField(userId, id);
  407. const { name, lastName, avatarUrl, color, number } = user;
  408. if (companion && isChat && isCompanionChat) {
  409. const newMessage = await MessageModel.add({
  410. message,
  411. name,
  412. lastName,
  413. avatarUrl,
  414. color,
  415. number,
  416. type: 'text',
  417. caption,
  418. idTime,
  419. companionIdFlow: userId,
  420. companionId: id,
  421. owner: userId,
  422. });
  423. await MessageModel.add({
  424. message,
  425. name: isCompanionChat.name,
  426. lastName: isCompanionChat.lastName,
  427. avatarUrl,
  428. color,
  429. number,
  430. type: 'text',
  431. caption,
  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: message,
  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. seenCompanion: Total,
  455. lastMessage: message,
  456. lastMessageCreatedAt: newMessage.createdAt,
  457. });
  458. return res.status(201).json({
  459. status: 'success',
  460. code: 201,
  461. data: newMessage,
  462. });
  463. }
  464. } catch (e) {
  465. next(e);
  466. }
  467. };
  468. const sentMessageReply = async (req, res, next) => {
  469. try {
  470. const { id, message, caption } = req.body;
  471. const idTime = Math.round(Date.now() / 1000);
  472. const user = req.user;
  473. const userId = user.id;
  474. const userMessage = await MessageModel.getById(id, userId);
  475. const companionMessage = await MessageModel.findByFields(
  476. userId,
  477. userMessage.idTime,
  478. userMessage.companionId
  479. );
  480. const isChat = await ChatModel.getByField(userMessage.companionId, userId);
  481. const isCompanionChat = await ChatModel.getByField(
  482. userId,
  483. userMessage.companionId
  484. );
  485. if (isChat && isCompanionChat && userMessage && companionMessage) {
  486. const newMessage = await MessageModel.add({
  487. message,
  488. replyMessage: userMessage.message,
  489. name: user.name,
  490. lastName: user.lastName,
  491. replyName: userMessage.name,
  492. replyLastName: userMessage.lastName,
  493. avatarUrl: user.avatarUrl,
  494. color: user.color,
  495. number: user.number,
  496. type: 'text',
  497. fullType: userMessage.fullType,
  498. caption,
  499. replyCaption: userMessage.caption,
  500. idTime,
  501. oldId: id,
  502. companionIdFlow: userId,
  503. companionId: userMessage.companionId,
  504. owner: userId,
  505. });
  506. await MessageModel.add({
  507. message,
  508. replyMessage: companionMessage.message,
  509. name: isCompanionChat.name,
  510. lastName: isCompanionChat.lastName,
  511. replyName: companionMessage.name,
  512. replyLastName: companionMessage.lastName,
  513. avatarUrl: user.avatarUrl,
  514. color: user.color,
  515. number: user.number,
  516. type: 'text',
  517. fullType: companionMessage.fullType,
  518. caption,
  519. replyCaption: companionMessage.caption,
  520. idTime,
  521. oldId: companionMessage._id,
  522. companionIdFlow: userId,
  523. companionId: userId,
  524. owner: userMessage.companionId,
  525. });
  526. const { total } = await MessageModel.getList(
  527. { owner: userId, companionId: userMessage.companionId },
  528. {}
  529. );
  530. await ChatModel.update(isChat._id, userId, {
  531. total,
  532. seen: total,
  533. watched: false,
  534. lastMessage: message,
  535. lastMessageCreatedAt: newMessage.createdAt,
  536. });
  537. const { total: Total } = await MessageModel.getList(
  538. { owner: userMessage.companionId, companionId: userId },
  539. {}
  540. );
  541. await ChatModel.update(isCompanionChat._id, userMessage.companionId, {
  542. total: Total,
  543. seenCompanion: Total,
  544. lastMessage: message,
  545. lastMessageCreatedAt: newMessage.createdAt,
  546. });
  547. return res.status(201).json({
  548. status: 'success',
  549. code: 201,
  550. data: newMessage,
  551. });
  552. }
  553. } catch (e) {
  554. next(e);
  555. }
  556. };
  557. const sentMessageForward = async (req, res, next) => {
  558. try {
  559. const { id, companionIdForwardToAndFrom, message, caption } = req.body;
  560. const idTime = Math.round(Date.now() / 1000);
  561. const user = req.user;
  562. const userId = user.id;
  563. const userMessage = await MessageModel.getById(id, userId);
  564. const isChat = await ChatModel.getByField(
  565. companionIdForwardToAndFrom,
  566. userId
  567. );
  568. const companionMessage = await MessageModel.findByFields(
  569. userId,
  570. userMessage.idTime,
  571. userMessage.companionId
  572. );
  573. const isCompanionUser = await UserModel.findById(userMessage.companionId);
  574. const isForwardChat = await ChatModel.getByField(
  575. userId,
  576. companionIdForwardToAndFrom
  577. );
  578. if (
  579. userMessage &&
  580. isCompanionUser &&
  581. isChat &&
  582. isForwardChat &&
  583. companionMessage
  584. ) {
  585. const newMessage = await MessageModel.add({
  586. message,
  587. caption,
  588. forwardMessage: userMessage.message,
  589. forwardCaption: userMessage.caption,
  590. name: user.name,
  591. lastName: user.lastName,
  592. avatarUrl: user.avatarUrl,
  593. color: user.color,
  594. number: user.number,
  595. type: 'text',
  596. fullType: userMessage.fullType,
  597. forwardName:
  598. user.number === userMessage.number ? user.name : isCompanionUser.name,
  599. forwardLastName:
  600. user.number === userMessage.number
  601. ? user.lastName
  602. : isCompanionUser.lastName,
  603. oldId: userMessage._id,
  604. idTime,
  605. companionIdFlow: userId,
  606. companionIdForwardToAndFrom: userMessage.companionId,
  607. companionId: companionIdForwardToAndFrom,
  608. owner: userId,
  609. });
  610. await MessageModel.add({
  611. message,
  612. caption,
  613. forwardMessage: userMessage.message,
  614. forwardCaption: userMessage.caption,
  615. name: isForwardChat.name,
  616. lastName: isForwardChat.lastName,
  617. avatarUrl: user.avatarUrl,
  618. color: user.color,
  619. number: user.number,
  620. type: 'text',
  621. fullType: userMessage.fullType,
  622. forwardName:
  623. user.number === userMessage.number ? user.name : isCompanionUser.name,
  624. forwardLastName:
  625. user.number === userMessage.number
  626. ? user.lastName
  627. : isCompanionUser.lastName,
  628. oldId: companionMessage._id,
  629. idTime,
  630. companionIdFlow: userId,
  631. companionId: userId,
  632. companionIdForwardToAndFrom: userMessage.companionId,
  633. owner: companionIdForwardToAndFrom,
  634. });
  635. const { total } = await MessageModel.getList(
  636. { owner: userId, companionId: companionIdForwardToAndFrom },
  637. {}
  638. );
  639. await ChatModel.update(isChat._id, userId, {
  640. total,
  641. seen: total,
  642. watched: false,
  643. lastMessage: message,
  644. lastMessageCreatedAt: newMessage.createdAt,
  645. });
  646. const { total: Total } = await MessageModel.getList(
  647. { owner: companionIdForwardToAndFrom, companionId: userId },
  648. {}
  649. );
  650. await ChatModel.update(isForwardChat._id, companionIdForwardToAndFrom, {
  651. total: Total,
  652. seenCompanion: Total,
  653. lastMessage: message,
  654. lastMessageCreatedAt: newMessage.createdAt,
  655. });
  656. return res.status(201).json({
  657. status: 'success',
  658. code: 201,
  659. data: newMessage,
  660. });
  661. }
  662. } catch (e) {
  663. next(e);
  664. }
  665. };
  666. const imageMessage = async (req, res, next) => {
  667. try {
  668. const userId = req.user.id;
  669. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  670. const caption = rest.join(' ').slice(0, -1);
  671. const idTime = Math.round(Date.now() / 1000);
  672. const isChat = await ChatModel.getByField(id, userId);
  673. const isCompanionChat = await ChatModel.getByField(userId, id);
  674. const originalName = req.file.originalname;
  675. const pathToFile = req.file.path;
  676. const fullType = req.file.mimetype;
  677. const imgUrl = `${Math.round(Date.now() / 1000)}${userId}${originalName}`;
  678. const fileContent = await fs.readFile(pathToFile);
  679. const params = {
  680. Bucket: AWS_BUCKET_NAME,
  681. Key: `${imgUrl}`,
  682. Body: fileContent,
  683. };
  684. s3.upload(params, async (err, _data) => {
  685. if (err) throw err;
  686. fs.unlink(pathToFile);
  687. });
  688. if (isChat && isCompanionChat) {
  689. const { name, lastName, avatarUrl, color, number } = req.user;
  690. const newMessage = await MessageModel.add({
  691. message: imgUrl,
  692. name,
  693. lastName,
  694. avatarUrl,
  695. color,
  696. number,
  697. type: 'image',
  698. fullType,
  699. caption,
  700. idTime,
  701. companionIdFlow: userId,
  702. companionId: id,
  703. owner: userId,
  704. });
  705. await MessageModel.add({
  706. message: imgUrl,
  707. name: isCompanionChat.name,
  708. lastName: isCompanionChat.lastName,
  709. avatarUrl,
  710. color,
  711. number,
  712. type: 'image',
  713. fullType,
  714. caption,
  715. idTime,
  716. companionIdFlow: userId,
  717. companionId: userId,
  718. owner: id,
  719. });
  720. const { total } = await MessageModel.getList(
  721. { owner: userId, companionId: id },
  722. {}
  723. );
  724. await ChatModel.update(isChat._id, userId, {
  725. total,
  726. seen: total,
  727. watched: false,
  728. lastMessage: fullType,
  729. lastMessageCreatedAt: newMessage.createdAt,
  730. });
  731. const { total: Total } = await MessageModel.getList(
  732. { owner: id, companionId: userId },
  733. {}
  734. );
  735. await ChatModel.update(isCompanionChat._id, id, {
  736. total: Total,
  737. seenCompanion: Total,
  738. lastMessage: fullType,
  739. lastMessageCreatedAt: newMessage.createdAt,
  740. });
  741. return res.status(201).json({
  742. status: 'success',
  743. code: 201,
  744. data: newMessage,
  745. });
  746. }
  747. } catch (e) {
  748. next(e);
  749. }
  750. };
  751. const audioMessage = async (req, res, next) => {
  752. try {
  753. const userId = req.user.id;
  754. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  755. let caption = rest.join(' ');
  756. if (caption.length === 1) caption.slice(0, -1);
  757. const idTime = Math.round(Date.now() / 1000);
  758. const isChat = await ChatModel.getByField(id, userId);
  759. const isCompanionChat = await ChatModel.getByField(userId, id);
  760. const originalName = req.file.originalname;
  761. const pathToFile = req.file.path;
  762. const fullType = req.file.mimetype;
  763. const audioUrl = `${Math.round(Date.now() / 1000)}${originalName}`;
  764. const fileContent = await fs.readFile(pathToFile);
  765. const params = {
  766. Bucket: AWS_BUCKET_NAME,
  767. Key: `${audioUrl}`,
  768. Body: fileContent,
  769. };
  770. s3.upload(params, async (err, _data) => {
  771. if (err) throw err;
  772. fs.unlink(pathToFile);
  773. });
  774. if (isChat && isCompanionChat) {
  775. const { name, lastName, avatarUrl, color, number } = req.user;
  776. const newMessage = await MessageModel.add({
  777. message: audioUrl,
  778. name,
  779. lastName,
  780. avatarUrl,
  781. color,
  782. number,
  783. type: 'audio',
  784. fullType,
  785. caption,
  786. idTime,
  787. companionIdFlow: userId,
  788. companionId: id,
  789. owner: userId,
  790. });
  791. await MessageModel.add({
  792. message: audioUrl,
  793. name: isCompanionChat.name,
  794. lastName: isCompanionChat.lastName,
  795. avatarUrl,
  796. color,
  797. number,
  798. type: 'audio',
  799. fullType,
  800. caption,
  801. idTime,
  802. companionIdFlow: userId,
  803. companionId: userId,
  804. owner: id,
  805. });
  806. const { total } = await MessageModel.getList(
  807. { owner: userId, companionId: id },
  808. {}
  809. );
  810. await ChatModel.update(isChat._id, userId, {
  811. total,
  812. seen: total,
  813. watched: false,
  814. lastMessage: fullType,
  815. lastMessageCreatedAt: newMessage.createdAt,
  816. });
  817. const { total: Total } = await MessageModel.getList(
  818. { owner: id, companionId: userId },
  819. {}
  820. );
  821. await ChatModel.update(isCompanionChat._id, id, {
  822. total: Total,
  823. seenCompanion: Total,
  824. lastMessage: fullType,
  825. lastMessageCreatedAt: newMessage.createdAt,
  826. });
  827. return res.status(201).json({
  828. status: 'success',
  829. code: 201,
  830. data: newMessage,
  831. });
  832. }
  833. } catch (e) {
  834. next(e);
  835. }
  836. };
  837. const videoMessage = async (req, res, next) => {
  838. try {
  839. const userId = req.user.id;
  840. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  841. let caption = rest.join(' ');
  842. if (caption.length === 1) caption.slice(0, -1);
  843. const idTime = Math.round(Date.now() / 1000);
  844. const isChat = await ChatModel.getByField(id, userId);
  845. const isCompanionChat = await ChatModel.getByField(userId, id);
  846. const originalName = req.file.originalname;
  847. const pathToFile = req.file.path;
  848. const videoUrl = `${Math.round(Date.now() / 1000)}${originalName}`;
  849. const fullType = req.file.mimetype;
  850. const fileContent = await fs.readFile(pathToFile);
  851. const params = {
  852. Bucket: AWS_BUCKET_NAME,
  853. Key: `${videoUrl}`,
  854. Body: fileContent,
  855. };
  856. s3.upload(params, async (err, _data) => {
  857. if (err) throw err;
  858. fs.unlink(pathToFile);
  859. });
  860. if (isChat && isCompanionChat) {
  861. const { name, lastName, avatarUrl, color, number } = req.user;
  862. const newMessage = await MessageModel.add({
  863. message: videoUrl,
  864. name: isCompanionChat.name,
  865. lastName: isCompanionChat.lastName,
  866. avatarUrl,
  867. color,
  868. number,
  869. type: 'video',
  870. fullType,
  871. caption,
  872. idTime,
  873. companionIdFlow: userId,
  874. companionId: id,
  875. owner: userId,
  876. });
  877. await MessageModel.add({
  878. message: videoUrl,
  879. name,
  880. lastName,
  881. avatarUrl,
  882. color,
  883. number,
  884. type: 'video',
  885. fullType,
  886. caption,
  887. idTime,
  888. companionIdFlow: userId,
  889. companionId: userId,
  890. owner: id,
  891. });
  892. const { total } = await MessageModel.getList(
  893. { owner: userId, companionId: id },
  894. {}
  895. );
  896. await ChatModel.update(isChat._id, userId, {
  897. total,
  898. seen: total,
  899. watched: false,
  900. lastMessage: fullType,
  901. lastMessageCreatedAt: newMessage.createdAt,
  902. });
  903. const { total: Total } = await MessageModel.getList(
  904. { owner: id, companionId: userId },
  905. {}
  906. );
  907. await ChatModel.update(isCompanionChat._id, id, {
  908. total: Total,
  909. seenCompanion: Total,
  910. lastMessage: fullType,
  911. lastMessageCreatedAt: newMessage.createdAt,
  912. });
  913. return res.status(201).json({
  914. status: 'success',
  915. code: 201,
  916. data: newMessage,
  917. });
  918. }
  919. } catch (e) {
  920. next(e);
  921. }
  922. };
  923. const fileMessage = async (req, res, next) => {
  924. try {
  925. const userId = req.user.id;
  926. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  927. let caption = rest.join(' ');
  928. if (caption.length === 1) caption.slice(0, -1);
  929. const idTime = Math.round(Date.now() / 1000);
  930. const isChat = await ChatModel.getByField(id, userId);
  931. const isCompanionChat = await ChatModel.getByField(userId, id);
  932. const pathToFile = req.file.path;
  933. const fullType = req.file.mimetype;
  934. let type;
  935. switch (fullType) {
  936. case 'application/pdf':
  937. type = 'pdf';
  938. break;
  939. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  940. type = 'docx';
  941. break;
  942. case 'application/octet-stream':
  943. type = 'docx';
  944. break;
  945. default:
  946. break;
  947. }
  948. const fileUrl = `${Math.round(Date.now() / 1000)}file.${type}`;
  949. const fileContent = await fs.readFile(pathToFile);
  950. const params = {
  951. Bucket: AWS_BUCKET_NAME,
  952. Key: `${fileUrl}`,
  953. Body: fileContent,
  954. };
  955. s3.upload(params, async (err, _data) => {
  956. if (err) throw err;
  957. fs.unlink(pathToFile);
  958. });
  959. if (isChat && isCompanionChat) {
  960. const { name, lastName, avatarUrl, color, number } = req.user;
  961. const newMessage = await MessageModel.add({
  962. message: fileUrl,
  963. name,
  964. lastName,
  965. avatarUrl,
  966. color,
  967. number,
  968. type,
  969. fullType,
  970. caption,
  971. idTime,
  972. companionIdFlow: userId,
  973. companionId: id,
  974. owner: userId,
  975. });
  976. await MessageModel.add({
  977. message: fileUrl,
  978. name: isCompanionChat.name,
  979. lastName: isCompanionChat.lastName,
  980. avatarUrl,
  981. color,
  982. number,
  983. type,
  984. fullType,
  985. caption,
  986. idTime,
  987. companionIdFlow: userId,
  988. companionId: userId,
  989. owner: id,
  990. });
  991. const { total } = await MessageModel.getList(
  992. { owner: userId, companionId: id },
  993. {}
  994. );
  995. await ChatModel.update(isChat._id, userId, {
  996. total,
  997. seen: total,
  998. watched: false,
  999. lastMessage: fullType,
  1000. lastMessageCreatedAt: newMessage.createdAt,
  1001. });
  1002. const { total: Total } = await MessageModel.getList(
  1003. { owner: id, companionId: userId },
  1004. {}
  1005. );
  1006. await ChatModel.update(isCompanionChat._id, id, {
  1007. total: Total,
  1008. seenCompanion: Total,
  1009. lastMessage: fullType,
  1010. lastMessageCreatedAt: newMessage.createdAt,
  1011. });
  1012. return res.status(201).json({
  1013. status: 'success',
  1014. code: 201,
  1015. data: newMessage,
  1016. });
  1017. }
  1018. } catch (e) {
  1019. next(e);
  1020. }
  1021. };
  1022. module.exports = {
  1023. listMessages,
  1024. removeMessage,
  1025. removeSelected,
  1026. editMessage,
  1027. updateMessageEmoji,
  1028. updateMessagePin,
  1029. unpinAllMessage,
  1030. listMessagesById,
  1031. sentMessage,
  1032. sentMessageReply,
  1033. sentMessageForward,
  1034. imageMessage,
  1035. audioMessage,
  1036. videoMessage,
  1037. fileMessage,
  1038. };