Skip to content

Commit

Permalink
Merge pull request #852 from binhodev/dev
Browse files Browse the repository at this point in the history
Dev - IdleState
  • Loading branch information
leifermendez authored Sep 30, 2023
2 parents 5e66d60 + 894edde commit cae433b
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 15 deletions.
51 changes: 51 additions & 0 deletions packages/bot/context/idleState.class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const { EventEmitter } = require('node:events')

class IdleState extends EventEmitter {
timer = null
startTime = 0
endTime = 0

setIdleTime = (timeInSeconds) => {
this.startTime = timeInSeconds
return this.reset()
}

startTimer = () => {
this.timer = setInterval(() => {
const currentTime = new Date().getTime()

if (currentTime > this.endTime) {
this.stop()
this.emit('idle')
} else {
this.debugTime()
}
}, 1000)
}

start = () => {
if (!this.timer) {
this.reset()
this.startTimer()
}
}

reset = () => {
const currentTime = new Date().getTime()
this.endTime = currentTime + this.startTime * 1000
}

stop = () => {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
}

debugTime = () => {
const currentTime = new Date().getTime()
return `Tiempo restante: ${((this.endTime - currentTime) / 1000).toFixed(0)} segundos`
}
}

module.exports = IdleState
3 changes: 3 additions & 0 deletions packages/bot/core/core.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const { LIST_REGEX } = require('../io/events')
const SingleState = require('../context/state.class')
const GlobalState = require('../context/globalState.class')
const { generateTime } = require('../utils/hash')
const IdleState = require('../context/idleState.class')

const logger = new Console({
stdout: createWriteStream(`${process.cwd()}/core.class.log`),
Expand All @@ -19,6 +20,7 @@ const loggerQueue = new Console({

const StateHandler = new SingleState()
const GlobalStateHandler = new GlobalState()
const idle = new IdleState()

/**
* [ ] Escuchar eventos del provider asegurarte que los provider emitan eventos
Expand Down Expand Up @@ -325,6 +327,7 @@ class CoreClass {
state,
globalState,
extensions,
idleState: idle,
fallBack: fallBack(flags),
flowDynamic: flowDynamic(flags),
endFlow: endFlow(flags),
Expand Down
20 changes: 11 additions & 9 deletions packages/database/src/mysql/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,27 @@ class MyslAdapter {
})
}

getPrevByNumber = (from) =>
new Promise((resolve, reject) => {
const sql = `SELECT * FROM history WHERE phone='${from}' ORDER BY id DESC`
getPrevByNumber = async (from) => {
if (this.db._closing) await this.init()
return await new Promise((resolve, reject) => {
const sql = `SELECT * FROM history WHERE phone='${from}' ORDER BY id DESC`;
this.db.query(sql, (error, rows) => {
if (error) {
reject(error)
reject(error);
}

if (rows.length) {
const [row] = rows
row.options = JSON.parse(row.options)
resolve(row)
const [row] = rows;
row.options = JSON.parse(row.options);
resolve(row);
}

if (!rows.length) {
resolve(null)
resolve(null);
}
})
});
})
}

save = (ctx) => {
const values = [
Expand Down
2 changes: 1 addition & 1 deletion packages/provider/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bot-whatsapp/provider",
"version": "0.0.124-alpha.0",
"version": "0.0.132-alpha.0",
"description": "Esto es el conector a Twilio, Meta, etc...",
"main": "./lib/mock/index.cjs",
"keywords": [],
Expand Down
6 changes: 3 additions & 3 deletions packages/provider/src/meta/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class MetaWebHookServer extends EventEmitter {
}

if (message.type === 'image') {
const body = generateRefprovider('_event_image_')
const body = generateRefprovider('_event_media_')
const idUrl = message.image?.id
const resolvedUrl = await getMediaUrl(this.version, idUrl, this.numberId, this.jwtToken)
const responseObj = {
Expand Down Expand Up @@ -91,7 +91,7 @@ class MetaWebHookServer extends EventEmitter {
}

if (message.type === 'video') {
const body = generateRefprovider('_event_video_')
const body = generateRefprovider('_event_media_')
const idUrl = message.video?.id

const resolvedUrl = await getMediaUrl(this.version, idUrl, this.numberId, this.jwtToken)
Expand Down Expand Up @@ -138,7 +138,7 @@ class MetaWebHookServer extends EventEmitter {
}

if (message.type === 'sticker') {
const body = generateRefprovider('_event_sticker_')
const body = generateRefprovider('_event_media_')

const responseObj = {
type: message.type,
Expand Down
23 changes: 22 additions & 1 deletion packages/provider/src/twilio/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ class TwilioProvider extends ProviderClass {
twilioHook
vendor
vendorNumber
constructor({ accountSid, authToken, vendorNumber, port = PORT }) {
publicUrl
constructor({ accountSid, authToken, vendorNumber, port = PORT, publicUrl = '' }) {
super()
this.publicUrl = publicUrl
this.vendor = new twilio(accountSid, authToken)
this.twilioHook = new TwilioWebHookServer(port)
this.vendorNumber = parseNumber(vendorNumber)
Expand Down Expand Up @@ -66,6 +68,25 @@ class TwilioProvider extends ProviderClass {
*/
sendMedia = async (number, message, mediaInput = null) => {
if (!mediaInput) throw new Error(`MEDIA_INPUT_NULL_: ${mediaInput}`)
const urlEncode = `${this.publicUrl}/tmp?path=${encodeURIComponent(mediaInput)}`
const regexUrl = /^(?!https?:\/\/)[^\s]+$/

const urlNotice = [
`[NOTA]: Estas intentando enviar una fichero que esta en local.`,
`[NOTA]: Para que esto funcione con Twilio necesitas que el fichero este en una URL publica`,
`[NOTA]: más informacion aqui https://bot-whatsapp.netlify.app/docs/provider-twilio/`,
].join('\n')

if (
mediaInput.includes('localhost') ||
mediaInput.includes('127.0.0.1') ||
mediaInput.includes('0.0.0.0') ||
regexUrl.test(mediaInput)
) {
console.log(urlNotice)
mediaInput = urlEncode
}

number = parseNumber(number)
return this.vendor.messages.create({
mediaUrl: [`${mediaInput}`],
Expand Down
25 changes: 24 additions & 1 deletion packages/provider/src/twilio/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const { EventEmitter } = require('node:events')
const { existsSync, createReadStream } = require('node:fs')
const mime = require('mime-types')
const polka = require('polka')
const { urlencoded } = require('body-parser')
const { urlencoded, json } = require('body-parser')
const { parseNumber } = require('./utils')

/**
Expand Down Expand Up @@ -33,14 +35,35 @@ class TwilioWebHookServer extends EventEmitter {
res.end(json)
}

/**
* Manejar los local media como
* C\\Projects\\bot-restaurante\\tmp\\menu.png
* para que puedas ser llevar a una url online
* @param {*} req
* @param {*} res
*/
handlerLocalMedia = (req, res) => {
const { query } = req
const file = query?.path
if (!file) return res.end(`path: invalid`)
const decodeFile = decodeURIComponent(file)
if (!existsSync(decodeFile)) return res.end(`not exits: ${decodeFile}`)
const fileStream = createReadStream(decodeFile)
const mimeType = mime.lookup(decodeFile)
res.writeHead(200, { 'Content-Type': mimeType })
fileStream.pipe(res)
}

/**
* Contruir HTTP Server
* @returns
*/
buildHTTPServer = () => {
return polka()
.use(urlencoded({ extended: true }))
.use(json())
.post('/twilio-hook', this.incomingMsg)
.get('/tmp', this.handlerLocalMedia)
}

/**
Expand Down

0 comments on commit cae433b

Please sign in to comment.