messages.js 13 KB

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