diff --git a/backend-manager-student/package.json b/backend-manager-student/package.json index 8329475..aac718a 100644 --- a/backend-manager-student/package.json +++ b/backend-manager-student/package.json @@ -76,8 +76,7 @@ "swagger-jsdoc": "^6.2.8", "swagger-ui-express": "^4.6.0", "ua-parser-js": "^1.0.33", - "crypto": "^1.0.1", - "node-telegram-bot-api": "^0.61.0" + "crypto": "^1.0.1" }, "devDependencies": { "jest": "^29.3.1" diff --git a/backend-manager-student/src/admin_api/app.js b/backend-manager-student/src/admin_api/app.js index 5767021..1f55b0d 100644 --- a/backend-manager-student/src/admin_api/app.js +++ b/backend-manager-student/src/admin_api/app.js @@ -44,8 +44,8 @@ app.use( saveUninitialized: CONSTANTS.DELETED_ENABLE, cookie: { secure: - CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT - ? CONSTANTS.DELETED_ENABLE + CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? + CONSTANTS.DELETED_ENABLE : CONSTANTS.DELETED_DISABLE, httpOnly: CONSTANTS.DELETED_ENABLE, maxAge: CONSTANTS._1_HOURS_S, diff --git a/backend-manager-student/src/admin_api/server.js b/backend-manager-student/src/admin_api/server.js index f1e2f72..cb08832 100644 --- a/backend-manager-student/src/admin_api/server.js +++ b/backend-manager-student/src/admin_api/server.js @@ -4,10 +4,12 @@ const dotenv = require('dotenv'); //! APP const app = require('./app'); +//! REDIS PUBSUB +const REDIS_PUB_SUB = require('../share/utils/redis_pub_sub_helper'); + //! SHARE const CONSTANTS = require('../share/configs/constants'); const MESSAGES = require('../share/configs/message'); -const { sendTelegram } = require('../share/utils/telegram'); //! USED LIBRARY dotenv.config(); @@ -27,9 +29,11 @@ console.info(`Server is listening on port:http://localhost:${PORT}`); const handleException = (err) => { console.error('Unhandled Exception:', err); - - const message = `Server Student and Admin ${PORT}:: ${err.name}: ${err.message}`; - sendTelegram(message); + const message = `Server Admin ${PORT}:: ${err.name}: ${err.message}`; + // Publish data queue Redis + return REDIS_PUB_SUB.queueMessageTelegram(CONSTANTS.QUEUE.REDIS_SERVER_ADMIN, { + message, + }); }; process.on(CONSTANTS.ERROR_REJECTION, handleException); @@ -38,6 +42,6 @@ process.on(CONSTANTS.ERROR_EXCEPTION, handleException); process.on(CONSTANTS.SIGINT, () => { server.close(() => { - console.error('Server Student and Admin::: Off '); + console.error('Server Admin::: Off '); }); }); diff --git a/backend-manager-student/src/admin_api/v1/controllers/admin.controllers/admin.controller.js b/backend-manager-student/src/admin_api/v1/controllers/admin.controllers/admin.controller.js index 5cff459..69b4fb1 100644 --- a/backend-manager-student/src/admin_api/v1/controllers/admin.controllers/admin.controller.js +++ b/backend-manager-student/src/admin_api/v1/controllers/admin.controllers/admin.controller.js @@ -122,8 +122,8 @@ const adminController = { sameSite: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, secure: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, domain: - CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT - ? req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] + CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? + req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] : CONSTANTS.HEADER_DOMAIN, maxAge: CONSTANTS._1_MONTH, }); @@ -270,8 +270,8 @@ const adminController = { sameSite: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, secure: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, domain: - CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT - ? req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] + CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? + req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] : CONSTANTS.HEADER_DOMAIN, maxAge: CONSTANTS._1_MONTH, }); @@ -442,12 +442,12 @@ const adminController = { class: student.class, email: student.email, gender: - student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING - ? CONSTANTS.GENDER_MALE + student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING ? + CONSTANTS.GENDER_MALE : CONSTANTS.GENDER_FEMALE, avatar_uri: - student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING - ? CONSTANTS.GENDER_IMAGE_MALE + student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING ? + CONSTANTS.GENDER_IMAGE_MALE : CONSTANTS.GENDER_IMAGE_FEMALE, }); } diff --git a/backend-manager-student/src/admin_api/v1/controllers/book.controllers/book.controller.js b/backend-manager-student/src/admin_api/v1/controllers/book.controllers/book.controller.js index 52cf1b3..b253191 100644 --- a/backend-manager-student/src/admin_api/v1/controllers/book.controllers/book.controller.js +++ b/backend-manager-student/src/admin_api/v1/controllers/book.controllers/book.controller.js @@ -25,8 +25,8 @@ const bookController = { * @return {Object:{Number,String}} */ createBook: async (req, res) => { - const { name, author_id, image_uri, description, page_number, bookshelf, language, quantity, public_id_image } = - req.body.input.book_input; + const { name, author_id, image_uri, description, page_number, bookshelf, language, quantity, public_id_image } + = req.body.input.book_input; // Check input if ( diff --git a/backend-manager-student/src/admin_api/v1/controllers/student.controllers/student.controller.js b/backend-manager-student/src/admin_api/v1/controllers/student.controllers/student.controller.js index e3c13f4..cbfe6c0 100644 --- a/backend-manager-student/src/admin_api/v1/controllers/student.controllers/student.controller.js +++ b/backend-manager-student/src/admin_api/v1/controllers/student.controllers/student.controller.js @@ -113,8 +113,8 @@ const StudentController = { */ updateStudent: async (req, res) => { // Input body - const { student_id, name, avatar_uri, public_id_avatar, address, dob, gender } = - req.body.input.update_student_input; + const { student_id, name, avatar_uri, public_id_avatar, address, dob, gender } + = req.body.input.update_student_input; // Check input if (!student_id || !HELPER.validateBigInt(student_id)) { diff --git a/backend-manager-student/src/share/configs/config.js b/backend-manager-student/src/share/configs/config.js index afb1e5e..dd31463 100644 --- a/backend-manager-student/src/share/configs/config.js +++ b/backend-manager-student/src/share/configs/config.js @@ -133,12 +133,4 @@ module.exports = { */ IPA_API_RATE_LIMIT_DURATION: process.env.IPA_API_RATE_LIMIT_DURATION, IPA_API_RATE_LIMIT: process.env.IPA_API_RATE_LIMIT, - - /** - * @author Nguyễn Tiến Tài - * @created_at 29/03/2023 - * @description CONNECT TELEGRAM - */ - KEY_TELEGRAM: process.env.KEY_TELEGRAM, - KEY_CHAT_ID: process.env.KEY_CHAT_ID, }; diff --git a/backend-manager-student/src/share/configs/constants.js b/backend-manager-student/src/share/configs/constants.js index 45df9c1..f5cea5a 100644 --- a/backend-manager-student/src/share/configs/constants.js +++ b/backend-manager-student/src/share/configs/constants.js @@ -436,6 +436,7 @@ module.exports = { */ // Student KEY_USER_EXIT_U: 'student_api*', + KEY_USER_EXIT_A: 'admin_api*', DELETE_KEY_CACHE_LRU: 'student_api_delete_key_lru', /** @@ -446,4 +447,13 @@ module.exports = { ERROR_REJECTION: 'unhandledRejection', ERROR_EXCEPTION: 'uncaughtException', SIGINT: 'SIGINT', + /** + * @author Nguyễn Tiến Tài + * @created_at 30/03/2023 + * @description KEY QUEUE + */ + QUEUE: { + REDIS_SERVER_ADMIN: 'admin_unErrorServer', + REDIS_SERVER_STUDENT: 'user_unErrorServer', + }, }; diff --git a/backend-manager-student/src/share/db/bot_telegram.js b/backend-manager-student/src/share/db/bot_telegram.js deleted file mode 100644 index 202ce51..0000000 --- a/backend-manager-student/src/share/db/bot_telegram.js +++ /dev/null @@ -1,18 +0,0 @@ -//! LIBRARY -const TelegramBot = require('node-telegram-bot-api'); - -//! SHARE -const CONSTANTS = require('../configs/constants'); -const CONFIGS = require('../configs/config'); - -/** - * @author Nguyễn Tiến Tài - * @created_at 29/03/2023 - * @description BOT TELEGRAM - */ -const token = CONFIGS.KEY_TELEGRAM; -const { KEY_CHAT_ID } = CONFIGS; -// Create a bot that uses 'polling' to fetch new updates -const BOT = new TelegramBot(token, { polling: CONSTANTS.DELETED_ENABLE }); - -module.exports = { BOT, KEY_CHAT_ID }; diff --git a/backend-manager-student/src/share/middleware/handle_error.js b/backend-manager-student/src/share/middleware/handle_error.js index d0e3cc4..a4edede 100644 --- a/backend-manager-student/src/share/middleware/handle_error.js +++ b/backend-manager-student/src/share/middleware/handle_error.js @@ -28,18 +28,18 @@ module.exports = { const constraint = error.constraint; let message; switch (constraint) { - case KEY_DUPLICATE.DUPLICATE_KEY_EMAIL: - message = MESSAGES.GENERAL.EXITS_EMAIL; - break; - case KEY_DUPLICATE.DUPLICATE_KEY_PHONE: - message = MESSAGES.GENERAL.EXITS_PHONE; - break; - case KEY_DUPLICATE.DUPLICATE_KEY_MSSV: - message = MESSAGES.GENERAL.EXITS_MSSV; - break; - default: - message = MESSAGES.GENERAL.ERROR_UNKNOWN; - break; + case KEY_DUPLICATE.DUPLICATE_KEY_EMAIL: + message = MESSAGES.GENERAL.EXITS_EMAIL; + break; + case KEY_DUPLICATE.DUPLICATE_KEY_PHONE: + message = MESSAGES.GENERAL.EXITS_PHONE; + break; + case KEY_DUPLICATE.DUPLICATE_KEY_MSSV: + message = MESSAGES.GENERAL.EXITS_MSSV; + break; + default: + message = MESSAGES.GENERAL.ERROR_UNKNOWN; + break; } return message; }, diff --git a/backend-manager-student/src/share/models/author.model.js b/backend-manager-student/src/share/models/author.model.js index 776a75c..6d8e652 100644 --- a/backend-manager-student/src/share/models/author.model.js +++ b/backend-manager-student/src/share/models/author.model.js @@ -10,7 +10,8 @@ module.exports = { createAuthor: (data) => new Promise((resolve, reject) => { try { - const result = knex('authors').insert(data).onConflict('author_id').merge().returning(['author_id']); + const result = knex('authors').insert(data).onConflict('author_id').merge() + .returning(['author_id']); resolve(result); } catch (error) { reject(error); diff --git a/backend-manager-student/src/share/models/book.model.js b/backend-manager-student/src/share/models/book.model.js index 026fa6f..f75dcfd 100644 --- a/backend-manager-student/src/share/models/book.model.js +++ b/backend-manager-student/src/share/models/book.model.js @@ -13,7 +13,8 @@ module.exports = { createBook: (data) => new Promise((resolve, reject) => { try { - const result = knex('books').insert(data).onConflict('book_id').merge().returning(['book_id']); + const result = knex('books').insert(data).onConflict('book_id').merge() + .returning(['book_id']); resolve(result); } catch (error) { reject(error); diff --git a/backend-manager-student/src/share/models/book_borrowed.model.js b/backend-manager-student/src/share/models/book_borrowed.model.js index c5f6ca3..13c6c1a 100644 --- a/backend-manager-student/src/share/models/book_borrowed.model.js +++ b/backend-manager-student/src/share/models/book_borrowed.model.js @@ -65,7 +65,7 @@ module.exports = { if (borrow_book_id && !user_id) { queryBuilder.where('borrowed_book_id', borrow_book_id); } - if (!borrow_book_id && !user_id) { + if (!borrow_book_id && user_id) { queryBuilder.where('user_id', user_id); } }) diff --git a/backend-manager-student/src/share/models/phone.model.js b/backend-manager-student/src/share/models/phone.model.js index c46c101..4fe56e1 100644 --- a/backend-manager-student/src/share/models/phone.model.js +++ b/backend-manager-student/src/share/models/phone.model.js @@ -10,7 +10,8 @@ module.exports = { createPhone: (data) => new Promise((resolve, reject) => { try { - const result = knex('phone').insert(data).onConflict('phone_id').merge().returning(['phone_id']); + const result = knex('phone').insert(data).onConflict('phone_id').merge() + .returning(['phone_id']); resolve(result); } catch (error) { reject(error); diff --git a/backend-manager-student/src/share/models/user.model.js b/backend-manager-student/src/share/models/user.model.js index af10110..1d81747 100644 --- a/backend-manager-student/src/share/models/user.model.js +++ b/backend-manager-student/src/share/models/user.model.js @@ -119,7 +119,8 @@ module.exports = { createStudent: (data) => new Promise((resolve, reject) => { try { - const result_student = knex('user').insert(data).onConflict('user_id').merge().returning(['user_id']); + const result_student = knex('user').insert(data).onConflict('user_id').merge() + .returning(['user_id']); resolve(result_student); } catch (error) { reject(error); diff --git a/backend-manager-student/src/share/utils/redis_pub_sub_helper.js b/backend-manager-student/src/share/utils/redis_pub_sub_helper.js index 625fa7f..83c2666 100644 --- a/backend-manager-student/src/share/utils/redis_pub_sub_helper.js +++ b/backend-manager-student/src/share/utils/redis_pub_sub_helper.js @@ -53,7 +53,19 @@ const queueMessageUserApi = async (key, value) => { console.info('Del success'); } }; +const queueMessageTelegram = async (key, value) => { + const key_convert = key; + const value_convert = JSON.stringify(value); + try { + // send email here + const publishResult = await REDIS_MASTER.publish(key_convert, value_convert); + console.info(`Published to ${publishResult} subscribers.`); + } finally { + console.info('Del success'); + } +}; module.exports = { sendEmailWithLock, queueMessageUserApi, + queueMessageTelegram, }; diff --git a/backend-manager-student/src/share/utils/telegram.js b/backend-manager-student/src/share/utils/telegram.js deleted file mode 100644 index 3cf6b7c..0000000 --- a/backend-manager-student/src/share/utils/telegram.js +++ /dev/null @@ -1,13 +0,0 @@ -const { BOT, KEY_CHAT_ID } = require('../db/bot_telegram'); - -/** - * @author Nguyễn Tiến Tài - * @created_at 29/03/2023 - * @description Send Message bot - */ -const sendTelegram = (message) => { - BOT.sendMessage(KEY_CHAT_ID, message); -}; -module.exports = { - sendTelegram, -}; diff --git a/backend-manager-student/src/user_api/server.js b/backend-manager-student/src/user_api/server.js index 31bd7e3..b7bd353 100644 --- a/backend-manager-student/src/user_api/server.js +++ b/backend-manager-student/src/user_api/server.js @@ -1,17 +1,47 @@ +//! LIBRARY const dotenv = require('dotenv'); + +//! APP const app = require('./app'); +//! REDIS PUBSUB +const REDIS_PUB_SUB = require('../share/utils/redis_pub_sub_helper'); + +//! SHARE +const CONSTANTS = require('../share/configs/constants'); +const MESSAGES = require('../share/configs/message'); + +//! USED LIBRARY dotenv.config(); app.get('/', (req, res) => { const health_check = { uptime: process.uptime(), - message: 'Server User Api', + message: MESSAGES.STUDENT.SERVER, timestamp: Date.now(), }; return res.send(health_check); }); const PORT = process.env.PORT_USER_API || 5001; -app.listen(PORT); +const server = app.listen(PORT); console.info(`Server is listening on port:http://localhost:${PORT}`); + +const handleException = (err) => { + console.error('Unhandled Exception:', err); + const message = `Server Student ${PORT}:: ${err.name}: ${err.message}`; + // Publish data queue Redis + REDIS_PUB_SUB.queueMessageTelegram(CONSTANTS.QUEUE.REDIS_SERVER_STUDENT, { + message, + }); +}; + +process.on(CONSTANTS.ERROR_REJECTION, handleException); + +process.on(CONSTANTS.ERROR_EXCEPTION, handleException); + +process.on(CONSTANTS.SIGINT, () => { + server.close(() => { + console.error('Server Student::: Off '); + }); +}); diff --git a/backend-manager-student/src/user_api/v1/controllers/borrow_book.controllers/borrow_book.controller.js b/backend-manager-student/src/user_api/v1/controllers/borrow_book.controllers/borrow_book.controller.js index 9bffa1b..d6f8bfe 100644 --- a/backend-manager-student/src/user_api/v1/controllers/borrow_book.controllers/borrow_book.controller.js +++ b/backend-manager-student/src/user_api/v1/controllers/borrow_book.controllers/borrow_book.controller.js @@ -62,15 +62,15 @@ const BorrowBookController = { if (data_borrow_book.length > 0 && data_borrow_book[0].status !== CONSTANTS.STATUS_BORROW.DONE) { let result_borrow; switch (data_borrow_book[0].status) { - case CONSTANTS.STATUS_BORROW.PENDING: - result_borrow = MESSAGES.GENERAL.ALREADY_BOOK_BORROW; - break; - case CONSTANTS.STATUS_BORROW.BORROWING: - result_borrow = MESSAGES.GENERAL.PLEASE_REFUND_BOOK; - break; - default: - result_borrow = MESSAGES.GENERAL.BORROW_FAIL; - break; + case CONSTANTS.STATUS_BORROW.PENDING: + result_borrow = MESSAGES.GENERAL.ALREADY_BOOK_BORROW; + break; + case CONSTANTS.STATUS_BORROW.BORROWING: + result_borrow = MESSAGES.GENERAL.PLEASE_REFUND_BOOK; + break; + default: + result_borrow = MESSAGES.GENERAL.BORROW_FAIL; + break; } return res.status(CONSTANTS.HTTP.STATUS_4XX_BAD_REQUEST).json({ status: CONSTANTS.HTTP.STATUS_4XX_BAD_REQUEST, diff --git a/backend-manager-student/src/user_api/v1/controllers/user.controllers/user.controller.js b/backend-manager-student/src/user_api/v1/controllers/user.controllers/user.controller.js index 6e74a44..93e2070 100644 --- a/backend-manager-student/src/user_api/v1/controllers/user.controllers/user.controller.js +++ b/backend-manager-student/src/user_api/v1/controllers/user.controllers/user.controller.js @@ -184,8 +184,8 @@ const userController = { sameSite: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, secure: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, domain: - CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT - ? req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] + CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? + req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] : CONSTANTS.HEADER_DOMAIN, maxAge: CONSTANTS._1_MONTH, }); @@ -422,8 +422,8 @@ const userController = { sameSite: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, secure: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false, domain: - CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT - ? req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] + CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? + req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0] : CONSTANTS.HEADER_DOMAIN, maxAge: CONSTANTS._1_MONTH, }); diff --git a/server-media-service/package.json b/server-media-service/package.json index 9d7c1a1..123c493 100644 --- a/server-media-service/package.json +++ b/server-media-service/package.json @@ -56,7 +56,6 @@ "pg": "^8.8.0", "ioredis": "^5.2.4", "knex": "^2.3.0", - "sharp": "^0.31.3", - "node-telegram-bot-api": "^0.61.0" + "sharp": "^0.31.3" } } diff --git a/server-media-service/src/media-service/app.js b/server-media-service/src/media-service/app.js index 67b82f9..c446e83 100644 --- a/server-media-service/src/media-service/app.js +++ b/server-media-service/src/media-service/app.js @@ -13,7 +13,7 @@ const DEVICE_MIDDLEWARE = require('../share/middlewares/device.middleware'); //! SHARE const MEDIA_API = require('./v1/routes/index.route'); -const CONSTANTS = require('../share/configs/constants') +const CONSTANTS = require('../share/configs/constants'); const OPTIONS = require('../share/configs/option'); const CONFIGS = require('../share/configs/config'); @@ -61,4 +61,6 @@ app.use(DEVICE_MIDDLEWARE); //! ROUTE app.use(MEDIA_API); +//! REDIS PUBSUB + module.exports = app; diff --git a/server-media-service/src/media-service/server.js b/server-media-service/src/media-service/server.js index 06a176f..28e818c 100644 --- a/server-media-service/src/media-service/server.js +++ b/server-media-service/src/media-service/server.js @@ -4,10 +4,12 @@ const dotenv = require('dotenv'); //! APP const app = require('./app'); +//! REDIS PUBSUB +const REDIS_PUB_SUB = require('../share/utils/redis_pub_sub_helper'); + //! SHARE const CONSTANTS = require('../share/configs/constants'); const MESSAGE = require('../share/configs/message'); -const { sendTelegram } = require('../share/utils/telegram'); dotenv.config(); @@ -27,9 +29,11 @@ const server = app.listen(PORT, () => { const handleException = (err) => { console.error('Unhandled Exception:', err); - const message = `Server Media ${PORT}:: ${err.name}: ${err.message}`; - sendTelegram(message); + // Publish data queue Redis + return REDIS_PUB_SUB.queueMessageTelegram(CONSTANTS.QUEUE.REDIS_SERVER_MEDIA, { + message, + }); }; process.on(CONSTANTS.ERROR_REJECTION, handleException); diff --git a/server-media-service/src/share/configs/config.js b/server-media-service/src/share/configs/config.js index 61959e3..5bb5e89 100644 --- a/server-media-service/src/share/configs/config.js +++ b/server-media-service/src/share/configs/config.js @@ -68,11 +68,4 @@ module.exports = { * @description MachineNo */ MACHINE_NO: process.env.MACHINE_NO, - /** - * @author Nguyễn Tiến Tài - * @created_at 29/03/2023 - * @description CONNECT TELEGRAM - */ - KEY_TELEGRAM: process.env.KEY_TELEGRAM, - KEY_CHAT_ID: process.env.KEY_CHAT_ID, }; diff --git a/server-media-service/src/share/configs/constants.js b/server-media-service/src/share/configs/constants.js index f2758c4..fa4ecdd 100644 --- a/server-media-service/src/share/configs/constants.js +++ b/server-media-service/src/share/configs/constants.js @@ -318,4 +318,12 @@ module.exports = { ERROR_REJECTION: 'unhandledRejection', ERROR_EXCEPTION: 'uncaughtException', SIGINT: 'SIGINT', + /** + * @author Nguyễn Tiến Tài + * @created_at 30/03/2023 + * @description KEY QUEUE + */ + QUEUE: { + REDIS_SERVER_MEDIA: 'media_unErrorServer', + }, }; diff --git a/server-media-service/src/share/db/bot_telegram.js b/server-media-service/src/share/db/bot_telegram.js deleted file mode 100644 index 202ce51..0000000 --- a/server-media-service/src/share/db/bot_telegram.js +++ /dev/null @@ -1,18 +0,0 @@ -//! LIBRARY -const TelegramBot = require('node-telegram-bot-api'); - -//! SHARE -const CONSTANTS = require('../configs/constants'); -const CONFIGS = require('../configs/config'); - -/** - * @author Nguyễn Tiến Tài - * @created_at 29/03/2023 - * @description BOT TELEGRAM - */ -const token = CONFIGS.KEY_TELEGRAM; -const { KEY_CHAT_ID } = CONFIGS; -// Create a bot that uses 'polling' to fetch new updates -const BOT = new TelegramBot(token, { polling: CONSTANTS.DELETED_ENABLE }); - -module.exports = { BOT, KEY_CHAT_ID }; diff --git a/server-media-service/src/share/db/init_multiple_redis.js b/server-media-service/src/share/db/init_multiple_redis.js index d5e9057..fc258e2 100644 --- a/server-media-service/src/share/db/init_multiple_redis.js +++ b/server-media-service/src/share/db/init_multiple_redis.js @@ -6,9 +6,28 @@ const CONFIGS = require('../configs/config'); /** * @author Nguyễn Tiến Tài - * @created_at 03/01/2023 - * @description Connect Cache Redis Master + * @created_at 22/01/2023 + * @updated_at 15/03/2023 + * @description Connect Cache Redis Master and Slave */ +const ConnectionRedis = (REDIS) => { + REDIS.on('connect', function() { + console.info(`Client connected to redis Push ${JSON.stringify(this.options.user)}`); + }); + REDIS.on('ready', function() { + console.info(`Client connected to redis push and ready to use ${JSON.stringify(this.options.host)}...`); + }); + REDIS.on('error', (error) => { + console.info(error); + }); + REDIS.on('end', function() { + console.info(`Client disconnected from redis push ${JSON.stringify(this.options.user)}`); + }); + REDIS.on('SIGINT', () => { + REDIS.quit(); + }); +}; + const REDIS_MASTER = new IOREDIS({ port: CONFIGS.REDIS_PORT, host: CONFIGS.REDIS_HOST, @@ -16,20 +35,8 @@ const REDIS_MASTER = new IOREDIS({ password: CONFIGS.REDIS_PASSWORD, }); -REDIS_MASTER.on("connect", () => { - console.log("Client connected to redis Push..."); -}); -REDIS_MASTER.on("ready", () => { - console.log("Client connected to redis push and ready to use..."); -}); -REDIS_MASTER.on("error", (error) => { - console.log("fail"); -}); -REDIS_MASTER.on("end", () => { - console.log("Client disconnected from redis push"); -}); -REDIS_MASTER.on("SIGINT", () => { - REDIS_MASTER.quit(); -}); +ConnectionRedis(REDIS_MASTER); -module.exports = REDIS_MASTER; +module.exports = { + REDIS_MASTER, +}; diff --git a/server-media-service/src/share/utils/redis_pub_sub_helper.js b/server-media-service/src/share/utils/redis_pub_sub_helper.js new file mode 100644 index 0000000..69e8f95 --- /dev/null +++ b/server-media-service/src/share/utils/redis_pub_sub_helper.js @@ -0,0 +1,25 @@ +//! MEMORY CACHE +const { REDIS_MASTER } = require('../db/init_multiple_redis'); +/** + * @author Nguyễn Tiến Tài + * @param {key, value, ttl} + * @created_at 30/03/2023 + * @description Redis Publish Server Send Telegram + * @returns {Object} + */ + +const queueMessageTelegram = async (key, value) => { + console.info(key, '----'); + const key_convert = key; + const value_convert = JSON.stringify(value); + try { + // send email here + const publishResult = await REDIS_MASTER.publish(key_convert, value_convert); + console.info(`Published to ${publishResult} subscribers.`); + } finally { + console.info('Del success'); + } +}; +module.exports = { + queueMessageTelegram, +}; diff --git a/server-media-service/src/share/utils/telegram.js b/server-media-service/src/share/utils/telegram.js deleted file mode 100644 index 3cf6b7c..0000000 --- a/server-media-service/src/share/utils/telegram.js +++ /dev/null @@ -1,13 +0,0 @@ -const { BOT, KEY_CHAT_ID } = require('../db/bot_telegram'); - -/** - * @author Nguyễn Tiến Tài - * @created_at 29/03/2023 - * @description Send Message bot - */ -const sendTelegram = (message) => { - BOT.sendMessage(KEY_CHAT_ID, message); -}; -module.exports = { - sendTelegram, -}; diff --git a/server-send-email-student/docker-compose-dev.yml b/server-send-email-student/docker-compose-dev.yml index 3fb59d3..9eb905f 100644 --- a/server-send-email-student/docker-compose-dev.yml +++ b/server-send-email-student/docker-compose-dev.yml @@ -12,7 +12,7 @@ services: dockerfile: Dockerfile.dev context: . environment: - NODE_ENV: development + NODE_ENV: DEVELOPER ports: - ${PORT_EMAIL}:${PORT_EMAIL} volumes: diff --git a/server-send-email-student/src/send_email_user/server.js b/server-send-email-student/src/send_email_user/server.js index c79053b..52a31fd 100644 --- a/server-send-email-student/src/send_email_user/server.js +++ b/server-send-email-student/src/send_email_user/server.js @@ -28,7 +28,7 @@ const handleException = (err) => { console.error('Unhandled Exception:', err); const message = `Server Send Email ${PORT}:: ${err.name}: ${err.message}`; - sendTelegram(message); + sendTelegram({ message }); }; process.on(CONSTANTS.ERROR_REJECTION, handleException); diff --git a/server-send-email-student/src/send_email_user/v1/redis_sub_queue.js b/server-send-email-student/src/send_email_user/v1/redis_sub_queue.js index ff861cf..cff708b 100644 --- a/server-send-email-student/src/send_email_user/v1/redis_sub_queue.js +++ b/server-send-email-student/src/send_email_user/v1/redis_sub_queue.js @@ -1,7 +1,7 @@ //! SERVICE const email_sender_user = require('./user_api/services/email_sender_users/email_sender_user'); const email_sender_admin = require('./admin_api/services/email_sender_admin/email_sender_user'); - +const telegram_sender_message = require('./telegram/services/send_message_telegram'); //! DB const { REDIS_MASTER } = require('../../share/db/redis_db'); @@ -11,26 +11,47 @@ const CONSTANTS = require('../../share/configs/constants'); /** * @author Nguyễn Tiến Tài * @created_at 19/02/2023 - * @description Setup Redis PubSub Server Send Email. + * @created_at 30/03/2023 + * @description Setup Redis PubSub Server Send Email and telegram */ //! New Map Users const userChannelHandlers = new Map(); -userChannelHandlers.set(CONSTANTS.KEY_USER_WARNING_TOKEN, email_sender_user.sendEmailUserWarningHacker); -userChannelHandlers.set(CONSTANTS.KEY_USER_LINK_RESET_PASSWORD, email_sender_user.sendEmailUserLinkResetPassword); -userChannelHandlers.set(CONSTANTS.KEY_USER_LINK_VERIFICATION, email_sender_user.sendEmailUserLinkVerification); +userChannelHandlers.set( + CONSTANTS.KEY_USER_WARNING_TOKEN, email_sender_user.sendEmailUserWarningHacker, +); +userChannelHandlers.set( + CONSTANTS.KEY_USER_LINK_RESET_PASSWORD, email_sender_user.sendEmailUserLinkResetPassword, +); +userChannelHandlers.set( + CONSTANTS.KEY_USER_LINK_VERIFICATION, email_sender_user.sendEmailUserLinkVerification, +); +userChannelHandlers.set( + CONSTANTS.KEY_SERVER.REDIS_SERVER_STUDENT, telegram_sender_message.handleException, +); //! New Map Admin const adminChannelHandlers = new Map(); -adminChannelHandlers.set(CONSTANTS.KEY_ADMIN_WARNING_TOKEN, email_sender_admin.sendEmailUser); +adminChannelHandlers.set( + CONSTANTS.KEY_ADMIN_WARNING_TOKEN, email_sender_admin.sendEmailUser, +); +adminChannelHandlers.set( + CONSTANTS.KEY_SERVER.REDIS_SERVER_ADMIN, telegram_sender_message.handleException, +); +//! New Map MEDIA +const mediaChannelHandlers = new Map(); +mediaChannelHandlers.set( + CONSTANTS.KEY_SERVER.REDIS_SERVER_MEDIA, telegram_sender_message.handleException, +); //! Start Subscribe to user and admin channels REDIS_MASTER.on('ready', async () => { try { REDIS_MASTER.psubscribe(`${CONSTANTS.KEY_USER_EXIT_U}`); REDIS_MASTER.psubscribe(`${CONSTANTS.KEY_ADMIN_EXIT_A}`); + REDIS_MASTER.psubscribe(`${CONSTANTS.KEY_MEDIA_EXIT_M}`); - console.info(`Redis subscribed to all channels starting with ${CONSTANTS.KEY_USER_EXIT_U} or ${CONSTANTS.KEY_ADMIN_EXIT_A}`); + console.info(`Redis subscribed to all channels starting with ${CONSTANTS.KEY_USER_EXIT_U} or ${CONSTANTS.KEY_ADMIN_EXIT_A} or ${CONSTANTS.KEY_MEDIA_EXIT_M} `); } catch (error) { console.error('Failed to subscribe to Redis channels:', error); } @@ -39,7 +60,9 @@ REDIS_MASTER.on('ready', async () => { //! Take queue Sub of Pub REDIS_MASTER.on('pmessage', async (pattern, channel, message) => { console.info(pattern, '::::::::pattern'); - const handler = userChannelHandlers.get(channel) || adminChannelHandlers.get(channel); + const handler = userChannelHandlers.get(channel) + || adminChannelHandlers.get(channel) + || mediaChannelHandlers.get(channel); if (handler) { try { handler(JSON.parse(message)); diff --git a/server-send-email-student/src/send_email_user/v1/telegram/services/send_message_telegram.js b/server-send-email-student/src/send_email_user/v1/telegram/services/send_message_telegram.js new file mode 100644 index 0000000..c287de0 --- /dev/null +++ b/server-send-email-student/src/send_email_user/v1/telegram/services/send_message_telegram.js @@ -0,0 +1,19 @@ +//! SHARE +const { sendTelegram } = require('../../../../share/utils/telegram'); +/** + * @author Nguyễn Tiến Tài + * @created_at 30/03/2023 + * @description Send telegram + * @function sendEmailUserWarningHacker + * @return { Object } + */ +const sendMessageTelegram = { + handleException: (message) => { + try { + return sendTelegram(message); + } catch (error) { + console.error(error); + } + }, +}; +module.exports = sendMessageTelegram; diff --git a/server-send-email-student/src/share/configs/constants.js b/server-send-email-student/src/share/configs/constants.js index 6dd9626..58233af 100644 --- a/server-send-email-student/src/share/configs/constants.js +++ b/server-send-email-student/src/share/configs/constants.js @@ -108,6 +108,16 @@ module.exports = { // Admin KEY_ADMIN_EXIT_A: 'a*', KEY_ADMIN_WARNING_TOKEN: 'admin_send_email_warning_token', + + // MEDIA + KEY_MEDIA_EXIT_M: 'm*', + + // SERVER ALL + KEY_SERVER: { + REDIS_SERVER_ADMIN: 'admin_unErrorServer', + REDIS_SERVER_STUDENT: 'user_unErrorServer', + REDIS_SERVER_MEDIA: 'media_unErrorServer', + }, /** * @author Nguyễn Tiến Tài * @created_at 19/02/2023 diff --git a/server-send-email-student/src/share/utils/telegram.js b/server-send-email-student/src/share/utils/telegram.js index 3cf6b7c..c6fc159 100644 --- a/server-send-email-student/src/share/utils/telegram.js +++ b/server-send-email-student/src/share/utils/telegram.js @@ -5,7 +5,7 @@ const { BOT, KEY_CHAT_ID } = require('../db/bot_telegram'); * @created_at 29/03/2023 * @description Send Message bot */ -const sendTelegram = (message) => { +const sendTelegram = ({ message }) => { BOT.sendMessage(KEY_CHAT_ID, message); }; module.exports = {