Skip to content

Commit

Permalink
added more endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
ookamiiixd committed Sep 9, 2021
1 parent b40a653 commit 62a5119
Show file tree
Hide file tree
Showing 9 changed files with 190 additions and 29 deletions.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@
"@adiwajshing/baileys": "^3.5.2",
"express": "^4.17.1",
"express-validator": "^6.12.1",
"lodash.clonedeep": "^4.5.0",
"qrcode": "^1.4.4",
"socket.io": "^4.2.0"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}
39 changes: 20 additions & 19 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
const app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http),
bodyParser = require('body-parser'),
{ response } = require('./response'),
whatsapp = require('./whatsapp'),
routes = require('./routes')

whatsapp.init()
{ listen } = require('./socket'),
chats = require('./routes/chatsRouter'),
groups = require('./routes/groupsRouter')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.use('/', routes)

io.on('connection', socket => {
socket.emit('init', whatsapp.getActiveSessions())
app.use('/chats', chats)
app.use('/groups', groups)

socket.on('add', session => {
if(whatsapp.checkSession(session)) return socket.emit('message', 'Session already exists.')
app.get('/', (req, res) => {
res.sendFile('./index.html', {root: __dirname})
})

whatsapp.createSession(socket, session)
.catch(err => {
console.log('unexpected error: ' + err)
socket.emit('message', 'An error occured during creating session.')
})
})
app.all('*', (req, res) => {
response(res, 404, {success: false, message: 'The requested url cannot be found.'})
})

http.listen(8000, () => console.log('listening on http://localhost:8000/'))
whatsapp.init()

http.listen(8000, () => {
listen(io, whatsapp)

console.log('Server listening on http://localhost:8000/')
})
39 changes: 39 additions & 0 deletions src/controllers/chatsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const { response } = require('./../response'),
{ validationResult } = require('express-validator'),
whatsapp = require('./../whatsapp'),
{ MessageType } = require('@adiwajshing/baileys')

const getChats = (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()) return response(res, 400, {success: false, message: 'Please fill out all required inputs.'})

const session = whatsapp.getSession(req.query.session)
if(!session) return response(res, 404, {success: false, message: 'The requested session cannot be found.'})

response(res, 200, {success: true, data: whatsapp.getChats(session, 'single')})
}

const sendMessage = (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()) return response(res, 400, {success: false, message: 'Please fill out all required inputs.'})

const receiver = whatsapp.formatPhone(req.body.receiver)
const message = req.body.message
const session = whatsapp.getSession(req.body.sender)

if(!session) return response(res, 404, {success: false, message: 'The requested session cannot be found.'})

session.isOnWhatsApp(receiver)
.then(exists => {
if(!exists) return response(res, 404, {success: false, message: 'The receiver number cannot be found.'})

session.sendMessage(receiver, message, MessageType.text)
.then(() => response(res, 200, {success: true, message: 'The message has been sent successfully.'}))
.catch(err => response(res, 500, {sucess: false, message: 'An error occured during sending the message.'}))
})
}

module.exports = {
getChats: getChats,
sendMessage: sendMessage
}
34 changes: 34 additions & 0 deletions src/controllers/groupsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const { response } = require('./../response'),
{ validationResult } = require('express-validator'),
whatsapp = require('./../whatsapp'),
{ MessageType } = require('@adiwajshing/baileys')

const getChats = (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()) return response(res, 400, {success: false, message: 'Please fill out all required inputs.'})

const session = whatsapp.getSession(req.query.session)
if(!session) return response(res, 404, {success: false, message: 'The requested session cannot be found.'})

response(res, 200, {success: true, data: whatsapp.getChats(session, 'group')})
}

const sendMessage = (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()) return response(res, 400, {success: false, message: 'Please fill out all required inputs.'})

const receiver = whatsapp.formatGroup(req.body.receiver)
const message = req.body.message
const session = whatsapp.getSession(req.body.sender)

if(!session) return response(res, 404, {success: false, message: 'The requested session cannot be found.'})

session.sendMessage(receiver, message, MessageType.text)
.then(() => response(res, 200, {success: true, message: 'The message has been sent successfully.'}))
.catch(err => response(res, 500, {sucess: false, message: 'An error occured during sending the message.'}))
}

module.exports = {
getChats: getChats,
sendMessage: sendMessage
}
7 changes: 7 additions & 0 deletions src/response.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const response = (res, code, data) => {
res.status(code)
res.json(data)
res.end()
}

exports.response = response
19 changes: 19 additions & 0 deletions src/routes/chatsRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const router = require('express').Router(),
{ query, body } = require('express-validator'),
controller = require('./../controllers/chatsController')

router.get(
'/get',
query('session').notEmpty(),
controller.getChats
)

router.post(
'/send',
body('sender').notEmpty(),
body('receiver').notEmpty(),
body('message').notEmpty(),
controller.sendMessage
)

module.exports = router
19 changes: 19 additions & 0 deletions src/routes/groupsRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const router = require('express').Router(),
{ query, body } = require('express-validator'),
controller = require('./../controllers/groupsController')

router.get(
'/get',
query('session').notEmpty(),
controller.getChats
)

router.post(
'/send',
body('sender').notEmpty(),
body('receiver').notEmpty(),
body('message').notEmpty(),
controller.sendMessage
)

module.exports = router
17 changes: 17 additions & 0 deletions src/socket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const listen = (io, whatsapp) => {
io.on('connection', socket => {
socket.emit('init', whatsapp.getActiveSessions())

socket.on('add', session => {
if(whatsapp.checkSession(session)) return socket.emit('message', 'Session already exists.')

whatsapp.createSession(socket, session)
.catch(err => {
console.log('unexpected error: ' + err)
socket.emit('message', 'An error occured during creating session.')
})
})
})
}

exports.listen = listen
41 changes: 31 additions & 10 deletions src/whatsapp.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
const fs = require('fs'),
path = require('path'),
qrcode = require('qrcode'),
clone = require('lodash.clonedeep'),
{ WAConnection } = require('@adiwajshing/baileys')

let sessions = [],
connections = {}

const getChats = (session, type) => {
let chats = clone(
session.chats.filter((item => type == 'group' ? item.jid.includes('@g.us') : item.jid.includes('@s.whatsapp.net'))).all()
)

return chats.map(chat => {
if('messages' in chat) delete chat['messages']

return chat
})
}

const createExistedSession = async session => {
let wa = new WAConnection()

wa.browserDescription = ['Windows', 'Chrome', '10']
wa.loadAuthInfo(path.join(__dirname, '..', 'sessions', `${session}.json`))
wa.loadAuthInfo(path.join(__dirname, 'sessions', `${session}.json`))

wa.on('open', () => {
let authInfo = wa.base64EncodedAuthInfo()
fs.writeFileSync(path.join(__dirname, '..', 'sessions', `${session}.json`), JSON.stringify(authInfo, null, '\t'))
const authInfo = wa.base64EncodedAuthInfo()
fs.writeFileSync(path.join(__dirname, 'sessions', `${session}.json`), JSON.stringify(authInfo, null, '\t'))

sessions.push(session)
connections[session] = wa
Expand All @@ -24,7 +37,7 @@ const createExistedSession = async session => {
wa.on('close', () => deleteSession(session))

await wa.connect()
.catch(err => console.log('unexpected error: ' + err))
.catch(err => console.log('Unexpected error: ' + err))
}

const createSession = async (socket, session) => {
Expand All @@ -45,8 +58,8 @@ const createSession = async (socket, session) => {
})

wa.on('open', () => {
let authInfo = wa.base64EncodedAuthInfo()
fs.writeFileSync(path.join(__dirname, '..', 'sessions', `${session}.json`), JSON.stringify(authInfo, null, '\t'))
const authInfo = wa.base64EncodedAuthInfo()
fs.writeFileSync(path.join(__dirname, 'sessions', `${session}.json`), JSON.stringify(authInfo, null, '\t'))

sessions.push(session)
connections[session] = wa
Expand All @@ -61,12 +74,12 @@ const createSession = async (socket, session) => {

socket.emit('deleted', session)
})

return await wa.connect()
}

const deleteSession = session => {
if(fs.existsSync(path.join(__dirname, '..', 'sessions', `${session}.json`))) fs.unlinkSync(path.join(__dirname, '..', 'sessions', `${session}.json`))
if(fs.existsSync(path.join(__dirname, 'sessions', `${session}.json`))) fs.unlinkSync(path.join(__dirname, 'sessions', `${session}.json`))

delete connections[session]

Expand Down Expand Up @@ -98,8 +111,14 @@ const formatPhone = phone => {
return formatted += '@s.whatsapp.net'
}

const formatGroup = group => {
let formatted = group.replace(/[^\d\-]/g, '')

return formatted += '@g.us'
}

const init = () => {
fs.readdir(path.join(__dirname, '..', 'sessions'), (err, files) => {
fs.readdir(path.join(__dirname, 'sessions'), (err, files) => {
if(err) throw err

files.forEach(file => {
Expand All @@ -111,9 +130,11 @@ const init = () => {
module.exports = {
init: init,
formatPhone: formatPhone,
formatGroup: formatGroup,
getSession: getSession,
getActiveSessions: getActiveSessions,
checkSession: checkSession,
createSession: createSession,
deleteSession: deleteSession
deleteSession: deleteSession,
getChats: getChats
}

0 comments on commit 62a5119

Please sign in to comment.