messages.js 12 KB

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