messages.js 12 KB

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