messages.js 12 KB

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