messages.js 18 KB

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