messages.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 removeMessage = async (req, res, next) => {
  62. try {
  63. const id = req.params.id;
  64. const userId = req.user.id;
  65. const userMessage = await MessageModel.remove(id, userId);
  66. await MessageModel.removeByFields(
  67. userId,
  68. userMessage.idTime,
  69. userMessage.companionId
  70. );
  71. if (userMessage.type !== 'text') {
  72. const params = {
  73. Bucket: AWS_BUCKET_NAME,
  74. Key: `${userMessage.message}`,
  75. };
  76. s3.deleteObject(params, async function (err, _data) {
  77. if (err) throw err;
  78. });
  79. }
  80. const isChat = await ChatModel.getByField(userMessage.companionId, userId);
  81. const isCompanionChat = await ChatModel.getByField(
  82. userId,
  83. userMessage.companionId
  84. );
  85. const { total } = await MessageModel.getList(
  86. { owner: userId, companionId: userMessage.companionId },
  87. {}
  88. );
  89. const { total: Total } = await MessageModel.getList(
  90. { owner: userMessage.companionId, companionId: userId },
  91. {}
  92. );
  93. await ChatModel.update(isChat._id, userId, {
  94. total: total,
  95. seen: total - isChat.seen > 0 ? isChat.seen : total,
  96. watched: false,
  97. });
  98. await ChatModel.update(isCompanionChat._id, userMessage.companionId, {
  99. total: Total,
  100. seen: Total - isCompanionChat.seen > 0 ? isCompanionChat.seen : Total,
  101. watched: true,
  102. });
  103. return res.json({
  104. status: 'success',
  105. code: 200,
  106. data: {},
  107. });
  108. } catch (e) {
  109. next(e);
  110. }
  111. };
  112. const sentMessage = async (req, res, next) => {
  113. try {
  114. const { id, message, caption } = req.body;
  115. const idTime = Math.round(Date.now() / 1000);
  116. const user = req.user;
  117. const userId = user.id;
  118. const companion = await UserModel.findById(id);
  119. const isChat = await ChatModel.getByField(id, userId);
  120. const isCompanionChat = await ChatModel.getByField(userId, id);
  121. const { name, lastName, avatarUrl, color, number } = user;
  122. if (companion && isChat && isCompanionChat) {
  123. const newMessage = await MessageModel.add({
  124. message,
  125. name,
  126. lastName,
  127. avatarUrl,
  128. color,
  129. number,
  130. type: 'text',
  131. caption,
  132. idTime,
  133. companionIdFlow: userId,
  134. companionId: id,
  135. owner: userId,
  136. });
  137. await MessageModel.add({
  138. message,
  139. name,
  140. lastName,
  141. avatarUrl,
  142. color,
  143. number,
  144. type: 'text',
  145. caption,
  146. idTime,
  147. companionIdFlow: userId,
  148. companionId: userId,
  149. owner: id,
  150. });
  151. const { total } = await MessageModel.getList(
  152. { owner: userId, companionId: id },
  153. {}
  154. );
  155. await ChatModel.update(isChat._id, userId, {
  156. total,
  157. seen: total,
  158. watched: false,
  159. lastMessage: message,
  160. lastMessageCreatedAt: newMessage.createdAt,
  161. });
  162. const { total: Total } = await MessageModel.getList(
  163. { owner: id, companionId: userId },
  164. {}
  165. );
  166. await ChatModel.update(isCompanionChat._id, id, {
  167. total: Total,
  168. lastMessage: message,
  169. lastMessageCreatedAt: newMessage.createdAt,
  170. });
  171. return res.status(201).json({
  172. status: 'success',
  173. code: 201,
  174. data: newMessage,
  175. });
  176. }
  177. } catch (e) {
  178. next(e);
  179. }
  180. };
  181. const imageMessage = async (req, res, next) => {
  182. try {
  183. const userId = req.user.id;
  184. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  185. const caption = rest.join(' ').slice(0, -1);
  186. const idTime = Math.round(Date.now() / 1000);
  187. const isChat = await ChatModel.getByField(id, userId);
  188. const isCompanionChat = await ChatModel.getByField(userId, id);
  189. const originalName = req.file.originalname;
  190. const pathToFile = req.file.path;
  191. const fullType = req.file.mimetype;
  192. const imgUrl = `${Math.round(Date.now() / 1000)}${userId}${originalName}`;
  193. const fileContent = await fs.readFile(pathToFile);
  194. const params = {
  195. Bucket: AWS_BUCKET_NAME,
  196. Key: `${imgUrl}`,
  197. Body: fileContent,
  198. };
  199. s3.upload(params, async (err, _data) => {
  200. if (err) throw err;
  201. fs.unlink(pathToFile);
  202. });
  203. if (isChat && isCompanionChat) {
  204. const { name, lastName, avatarUrl, color, number } = req.user;
  205. const newMessage = await MessageModel.add({
  206. message: imgUrl,
  207. name,
  208. lastName,
  209. avatarUrl,
  210. color,
  211. number,
  212. type: 'image',
  213. fullType,
  214. caption,
  215. idTime,
  216. companionIdFlow: userId,
  217. companionId: id,
  218. owner: userId,
  219. });
  220. await MessageModel.add({
  221. message: imgUrl,
  222. name,
  223. lastName,
  224. avatarUrl,
  225. color,
  226. number,
  227. type: 'image',
  228. fullType,
  229. caption,
  230. idTime,
  231. companionIdFlow: userId,
  232. companionId: userId,
  233. owner: id,
  234. });
  235. const { total } = await MessageModel.getList(
  236. { owner: userId, companionId: id },
  237. {}
  238. );
  239. await ChatModel.update(isChat._id, userId, {
  240. total,
  241. seen: total,
  242. watched: false,
  243. lastMessage: imgUrl,
  244. lastMessageCreatedAt: newMessage.createdAt,
  245. });
  246. const { total: Total } = await MessageModel.getList(
  247. { owner: id, companionId: userId },
  248. {}
  249. );
  250. await ChatModel.update(isCompanionChat._id, id, {
  251. total: Total,
  252. lastMessage: imgUrl,
  253. lastMessageCreatedAt: newMessage.createdAt,
  254. });
  255. return res.status(201).json({
  256. status: 'success',
  257. code: 201,
  258. data: newMessage,
  259. });
  260. }
  261. } catch (e) {
  262. next(e);
  263. }
  264. };
  265. const audioMessage = async (req, res, next) => {
  266. try {
  267. const userId = req.user.id;
  268. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  269. let caption = rest.join(' ');
  270. if (caption.length === 1) caption.slice(0, -1);
  271. const idTime = Math.round(Date.now() / 1000);
  272. const isChat = await ChatModel.getByField(id, userId);
  273. const isCompanionChat = await ChatModel.getByField(userId, id);
  274. const originalName = req.file.originalname;
  275. const pathToFile = req.file.path;
  276. const fullType = req.file.mimetype;
  277. const audioUrl = `${Math.round(Date.now() / 1000)}${originalName}`;
  278. const fileContent = await fs.readFile(pathToFile);
  279. const params = {
  280. Bucket: AWS_BUCKET_NAME,
  281. Key: `${audioUrl}`,
  282. Body: fileContent,
  283. };
  284. s3.upload(params, async (err, _data) => {
  285. if (err) throw err;
  286. fs.unlink(pathToFile);
  287. });
  288. if (isChat && isCompanionChat) {
  289. const { name, lastName, avatarUrl, color, number } = req.user;
  290. const newMessage = await MessageModel.add({
  291. message: audioUrl,
  292. name,
  293. lastName,
  294. avatarUrl,
  295. color,
  296. number,
  297. type: 'audio',
  298. fullType,
  299. caption,
  300. idTime,
  301. companionIdFlow: userId,
  302. companionId: id,
  303. owner: userId,
  304. });
  305. await MessageModel.add({
  306. message: audioUrl,
  307. name,
  308. lastName,
  309. avatarUrl,
  310. color,
  311. number,
  312. type: 'audio',
  313. fullType,
  314. caption,
  315. idTime,
  316. companionIdFlow: userId,
  317. companionId: userId,
  318. owner: id,
  319. });
  320. const { total } = await MessageModel.getList(
  321. { owner: userId, companionId: id },
  322. {}
  323. );
  324. await ChatModel.update(isChat._id, userId, {
  325. total,
  326. seen: total,
  327. watched: false,
  328. lastMessage: audioUrl,
  329. lastMessageCreatedAt: newMessage.createdAt,
  330. });
  331. const { total: Total } = await MessageModel.getList(
  332. { owner: id, companionId: userId },
  333. {}
  334. );
  335. await ChatModel.update(isCompanionChat._id, id, {
  336. total: Total,
  337. lastMessage: audioUrl,
  338. lastMessageCreatedAt: newMessage.createdAt,
  339. });
  340. return res.status(201).json({
  341. status: 'success',
  342. code: 201,
  343. data: newMessage,
  344. });
  345. }
  346. } catch (e) {
  347. next(e);
  348. }
  349. };
  350. const videoMessage = async (req, res, next) => {
  351. try {
  352. const userId = req.user.id;
  353. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  354. let caption = rest.join(' ');
  355. if (caption.length === 1) caption.slice(0, -1);
  356. const idTime = Math.round(Date.now() / 1000);
  357. const isChat = await ChatModel.getByField(id, userId);
  358. const isCompanionChat = await ChatModel.getByField(userId, id);
  359. const originalName = req.file.originalname;
  360. const pathToFile = req.file.path;
  361. const videoUrl = `${Math.round(Date.now() / 1000)}${originalName}`;
  362. const fullType = req.file.mimetype;
  363. const fileContent = await fs.readFile(pathToFile);
  364. const params = {
  365. Bucket: AWS_BUCKET_NAME,
  366. Key: `${videoUrl}`,
  367. Body: fileContent,
  368. };
  369. s3.upload(params, async (err, _data) => {
  370. if (err) throw err;
  371. fs.unlink(pathToFile);
  372. });
  373. if (isChat && isCompanionChat) {
  374. const { name, lastName, avatarUrl, color, number } = req.user;
  375. const newMessage = await MessageModel.add({
  376. message: videoUrl,
  377. name,
  378. lastName,
  379. avatarUrl,
  380. color,
  381. number,
  382. type: 'video',
  383. fullType,
  384. caption,
  385. idTime,
  386. companionIdFlow: userId,
  387. companionId: id,
  388. owner: userId,
  389. });
  390. await MessageModel.add({
  391. message: videoUrl,
  392. name,
  393. lastName,
  394. avatarUrl,
  395. color,
  396. number,
  397. type: 'video',
  398. fullType,
  399. caption,
  400. idTime,
  401. companionIdFlow: userId,
  402. companionId: userId,
  403. owner: id,
  404. });
  405. const { total } = await MessageModel.getList(
  406. { owner: userId, companionId: id },
  407. {}
  408. );
  409. await ChatModel.update(isChat._id, userId, {
  410. total,
  411. seen: total,
  412. watched: false,
  413. lastMessage: videoUrl,
  414. lastMessageCreatedAt: newMessage.createdAt,
  415. });
  416. const { total: Total } = await MessageModel.getList(
  417. { owner: id, companionId: userId },
  418. {}
  419. );
  420. await ChatModel.update(isCompanionChat._id, id, {
  421. total: Total,
  422. lastMessage: videoUrl,
  423. lastMessageCreatedAt: newMessage.createdAt,
  424. });
  425. return res.status(201).json({
  426. status: 'success',
  427. code: 201,
  428. data: newMessage,
  429. });
  430. }
  431. } catch (e) {
  432. next(e);
  433. }
  434. };
  435. const fileMessage = async (req, res, next) => {
  436. try {
  437. const userId = req.user.id;
  438. const [id, ...rest] = req.params.companionIdAndCaption.split(' ');
  439. let caption = rest.join(' ');
  440. if (caption.length === 1) caption.slice(0, -1);
  441. const idTime = Math.round(Date.now() / 1000);
  442. const isChat = await ChatModel.getByField(id, userId);
  443. const isCompanionChat = await ChatModel.getByField(userId, id);
  444. const pathToFile = req.file.path;
  445. const fullType = req.file.mimetype;
  446. let type;
  447. switch (fullType) {
  448. case 'application/pdf':
  449. type = 'pdf';
  450. break;
  451. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  452. type = 'docx';
  453. break;
  454. case 'application/octet-stream':
  455. type = 'docx';
  456. break;
  457. default:
  458. break;
  459. }
  460. const fileUrl = `${Math.round(Date.now() / 1000)}file.${type}`;
  461. const fileContent = await fs.readFile(pathToFile);
  462. const params = {
  463. Bucket: AWS_BUCKET_NAME,
  464. Key: `${fileUrl}`,
  465. Body: fileContent,
  466. };
  467. s3.upload(params, async (err, _data) => {
  468. if (err) throw err;
  469. fs.unlink(pathToFile);
  470. });
  471. if (isChat && isCompanionChat) {
  472. const { name, lastName, avatarUrl, color, number } = req.user;
  473. const newMessage = await MessageModel.add({
  474. message: fileUrl,
  475. name,
  476. lastName,
  477. avatarUrl,
  478. color,
  479. number,
  480. type,
  481. fullType,
  482. caption,
  483. idTime,
  484. companionIdFlow: userId,
  485. companionId: id,
  486. owner: userId,
  487. });
  488. await MessageModel.add({
  489. message: fileUrl,
  490. name,
  491. lastName,
  492. avatarUrl,
  493. color,
  494. number,
  495. type,
  496. fullType,
  497. caption,
  498. idTime,
  499. companionIdFlow: userId,
  500. companionId: userId,
  501. owner: id,
  502. });
  503. const { total } = await MessageModel.getList(
  504. { owner: userId, companionId: id },
  505. {}
  506. );
  507. await ChatModel.update(isChat._id, userId, {
  508. total,
  509. seen: total,
  510. watched: false,
  511. lastMessage: fileUrl,
  512. lastMessageCreatedAt: newMessage.createdAt,
  513. });
  514. const { total: Total } = await MessageModel.getList(
  515. { owner: id, companionId: userId },
  516. {}
  517. );
  518. await ChatModel.update(isCompanionChat._id, id, {
  519. total: Total,
  520. lastMessage: fileUrl,
  521. lastMessageCreatedAt: newMessage.createdAt,
  522. });
  523. return res.status(201).json({
  524. status: 'success',
  525. code: 201,
  526. data: newMessage,
  527. });
  528. }
  529. } catch (e) {
  530. next(e);
  531. }
  532. };
  533. module.exports = {
  534. listMessages,
  535. removeMessage,
  536. updateMessageEmoji,
  537. listMessagesById,
  538. sentMessage,
  539. imageMessage,
  540. audioMessage,
  541. videoMessage,
  542. fileMessage,
  543. };