messages.js 25 KB

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