import express, { Request, Response, NextFunction } from 'express'; import http from 'http'; // Import Node's built-in HTTP module import { Server as SocketServer } from 'socket.io'; // Import Socket.io import { query, body, validationResult } from 'express-validator'; import bodyParser from 'body-parser'; import { log } from 'console'; require('dotenv').config(); const app = express(); const server = http.createServer(app); // Create an HTTP server const io = new SocketServer(server); // Create a Socket.io server instance // app.use(bodyParser.urlencoded()); // app.use(bodyParser.json()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.post('/test', bodyParser.json(), (req: Request, res: Response) => { console.log(req.body); res.send(req.body); }); const validate = (req: Request, res: Response, next: NextFunction) => { // console.log(req.body); // console.log(JSON.stringify(req.body, null, 2)); const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } next(); }; var rules = [ body('phone_number').notEmpty(), body('telephone_id').notEmpty(), body('phone_number').isLength({ min: 11, max: 11 }).withMessage("شماره تلفن باید 11 رقم باشد.") ]; app.post('/send_notification', rules, validate, (req: Request, res: Response) => { // console.log(req.body.telephone_id); io.fetchSockets().then((sockets) => { let find = 0; sockets.map((socket) => { if (socket.handshake.auth.token === req.body.telephone_id) { find = 1; socket.timeout(2000).emit("answer", req.body.phone_number, (err: any, responses: Response) => { if (err) { console.log("#2"); console.log(err); res.end("user does not ack"); // some clients did not acknowledge the event in the given delay } else { console.log("#1"); console.log(responses); // one response per client res.end("user received notification"); } }); } // res.end("inja"); // try { // const responses = socket.timeout(2000).emitWithAck("answer"); // res.send(responses); // one response per client // } catch (e) { // res.end("ridim"); // // some clients did not acknowledge the event in the given delay // } // socket.timeout(10000).emitWithAck('new_answer', req.body.phone_number); }) if (!find) { } }) res.end("your message is received ") }); io.on('connection', (socket) => { if (socket.recovered) { console.log(socket.handshake.auth.token+':recovered'); } else { console.log(socket.handshake.auth.token+":connect"); } socket.on("disconnect", (reason) => { console.log(socket.handshake.auth.token+":"+reason); }); }); // Start the HTTP server server.listen(process.env.port, () => { console.log(`Server is running on port ${process.env.port}`); });