messages.js 12 KB

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