messages.js 12 KB

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