messages.js 25 KB

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