2023-08-15 12:14:10 +00:00
'use strict'
2023-02-13 12:43:00 +00:00
const { initIO } = require ( "./helpers/socket" )
2023-08-15 12:14:10 +00:00
const { ObjectId } = require ( 'mongodb' )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const backup _session = require ( './helpers/backup_session' )
const restore = require ( './helpers/restore' )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const dbcloud = require ( './funcs/dbcloud.js' )
2023-04-10 14:07:53 +00:00
2023-08-15 12:14:10 +00:00
const { Client , Location , List , Buttons , LocalAuth } = require ( 'whatsapp-web.js/index' )
const qrencode = require ( 'qr-encode' )
const axios = require ( 'axios' ) . default
const bodyparser = require ( 'body-parser' )
const path = require ( 'path' )
const fs = require ( 'fs' )
const express = require ( 'express' )
const FormData = require ( 'form-data' )
2023-02-13 12:43:00 +00:00
2023-04-10 14:07:53 +00:00
// const { MessageMedia } = require('./node_modules/whatsapp-web.js/src/structures');
2023-08-15 12:14:10 +00:00
let whatsappWebGlobalPath = path . join ( process . env . NODE _PATH , 'whatsapp-web.js' , '/src/structures' )
2023-05-02 12:47:41 +00:00
whatsappWebGlobalPath = whatsappWebGlobalPath . replace ( ':' , '' )
2023-04-10 20:50:02 +00:00
console . log ( 'whatsappWebGlobalPath: ' , whatsappWebGlobalPath )
console . log ( 'process.env.NODE_PATH: ' , process . env . NODE _PATH )
2023-08-15 12:14:10 +00:00
const { MessageMedia } = require ( whatsappWebGlobalPath )
2023-04-10 14:07:53 +00:00
2023-02-13 12:43:00 +00:00
const logger = require ( 'logger' )
2023-08-15 12:14:10 +00:00
const dotenv = require ( 'dotenv' )
dotenv . config ( { path : '.env' } )
const mime = require ( 'mime' )
const qrcode = require ( 'qrcode-terminal' )
const omnihit = require ( './funcs/omnihit.js' )
const { allowedNodeEnvironmentFlags } = require ( 'process' )
const mongo = require ( './funcs/mongoConn' )
const db = mongo . db ( process . env . DB _MONGO _NAME )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
let auxCampaignMessage = ''
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
require ( "./funcs/tools.js" ) ( )
let scheduler _messages _outbound
let scheduler _monitor
let scheduler _monitor _cell
let scheduler _campaign _monitor
let client
2023-02-13 12:43:00 +00:00
// const PORT = 80;
let sendSeen = false
let unreadMessaesProcess
const { imageUpload } = require ( './helpers/image-uploader' )
2023-08-15 12:14:10 +00:00
var QRCODE = "0"
var mobileuid
var destroy
2023-02-13 12:43:00 +00:00
let asking _qrcode = false
2023-08-15 12:14:10 +00:00
const dbcc = require ( './helpers/mysql_conn.js' )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const removeDir = require ( './helpers/remove_dir' )
2023-02-13 12:43:00 +00:00
// (async()=>{
// backup_session(destroy)
// clearTimeout(destroy)
// })
// console.log('PASSOU............')
// return
// Sleep
const sleep = ( ms ) => {
2023-08-15 12:14:10 +00:00
return new Promise ( ( resolve ) => setTimeout ( resolve , ms ) )
}
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
function getRandomNumber ( min , max ) {
return Math . floor ( Math . random ( ) * ( max - min + 1 ) ) + min
}
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const app = express ( )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
app . use ( express . static ( path . join ( _ _dirname , 'public' ) ) )
2023-02-13 12:43:00 +00:00
//app.use(bodyparser.urlencoded({ extended: true }));
2023-08-15 12:14:10 +00:00
app . use ( bodyparser . json ( ) )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const sessionName = process . env . MOBILEUID
2023-02-13 12:43:00 +00:00
// console.log('DIRNAME: ', path.join(__dirname, '.wwebjs_auth', 'session-omnihit_sesssion'))
//TEST DEL
console . log ( 'process.env.CLIENT_URL: ' , process . env . CLIENT _URL )
2023-08-15 12:14:10 +00:00
console . log ( '1' )
2023-02-13 12:43:00 +00:00
// Connect to server
2023-08-15 12:14:10 +00:00
var io = require ( 'socket.io-client' )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
// const socket = initIO('http://localhost:8024')
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const socketIo = io ( process . env . CLIENT _URL , { reconnect : true , maxHttpBufferSize : 1e8 } )
2023-02-13 12:43:00 +00:00
socketIo . on ( 'connect' , async function ( ) {
2023-08-15 12:14:10 +00:00
console . log ( 'Made socket connection' , socketIo . id )
2023-02-13 12:43:00 +00:00
console . log ( 'process.env.WHATSAPP_ID: ' , process . env . WHATSAPP _ID )
2023-08-15 12:14:10 +00:00
socketIo . emit ( 'joinWhatsSession' , process . env . WHATSAPP _ID )
2023-02-13 12:43:00 +00:00
sendSeen = true
if ( mobileuid ) {
console . log ( 'Socket conectado com o cliente: ' , mobileuid )
setTimeout ( async ( ) => {
console . log ( 'Entro no syncUnreadMessages ON CONNECTED SOCKET' )
await syncUnreadMessages ( client )
2023-08-15 12:14:10 +00:00
client . sendPresenceAvailable ( )
2023-02-13 12:43:00 +00:00
} , 5000 )
}
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
socketIo . on ( 'message_from_server' , function ( ) {
2023-08-15 12:14:10 +00:00
console . log ( 'message_from_server data: ' )
} )
2023-02-13 12:43:00 +00:00
// socketIo.on('disconnect', function () {
// console.log('disconnect');
// });
2023-08-15 12:14:10 +00:00
// var count = 0
// // Send a message to the server 3 seconds after initial connection.
2023-02-13 12:43:00 +00:00
// setInterval(function () {
2023-08-15 12:14:10 +00:00
// // socketIo.emit('message_from_client', 'Sent an event from the client!');
// const data = {
// id: "64d7fa0ce984e1cb781baee0",
// sent: count
// }
// socketIo.emit("campaign_message_sent", data)
// count++
// }, 3000)
2023-02-13 12:43:00 +00:00
socketIo . on ( 'connect_error' , async function ( err ) {
2023-08-15 12:14:10 +00:00
console . log ( 'connection errror' , err )
2023-02-13 12:43:00 +00:00
sendSeen = false
if ( mobileuid ) {
client . sendPresenceUnavailable ( )
}
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
//
//NOVA OPÇÃO MD
client = new Client ( {
authStrategy : new LocalAuth ( { clientId : 'omnihit_sesssion' } ) ,
puppeteer : { args : [ '--no-sandbox' , '--disable-setuid-sandbox' ] , executablePath : process . env . CHROME _BIN || '/usr/bin/google-chrome-stable' } ,
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
client . initialize ( )
2023-02-13 12:43:00 +00:00
client . on ( "qr" , async qr => {
2023-08-15 12:14:10 +00:00
console . log ( "Session:" , sessionName )
2023-02-13 12:43:00 +00:00
// Generate and scan this code with your phone
2023-08-15 12:14:10 +00:00
QRCODE = qr
2023-02-13 12:43:00 +00:00
qrcode . generate ( qr , { small : true } )
2023-08-15 12:14:10 +00:00
console . log ( 'QR RECEIVED' , qr )
2023-02-13 12:43:00 +00:00
// omnihit.qrcode(process.env.MOBILEUID, process.env.MOBILENAME, qr);
// omnihit.monitor(process.env.MOBILEUID, process.env.MOBILENAME, "STARTUP");
2023-07-12 14:54:29 +00:00
asking _qrcode = true
2023-02-13 12:43:00 +00:00
2023-05-02 12:47:41 +00:00
await new Promise ( ( resolve , reject ) => {
2023-02-13 12:43:00 +00:00
2023-05-02 12:47:41 +00:00
dbcc . query ( "UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ? where id = ?" , [ qr , 'qrcode' , 0 , process . env . WHATSAPP _ID ] ,
2023-02-13 12:43:00 +00:00
2023-05-02 12:47:41 +00:00
function ( err , result ) {
2023-02-13 12:43:00 +00:00
2023-05-02 12:47:41 +00:00
if ( err ) {
2023-08-15 12:14:10 +00:00
console . log ( "ERROR: " + err )
2023-05-02 12:47:41 +00:00
reject ( err )
}
else {
resolve ( result )
}
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
2023-07-12 14:54:29 +00:00
} )
2023-02-13 12:43:00 +00:00
let url = process . env . CLIENT _URL + '/whatsapp/connection/qrcode'
try {
2023-08-15 12:14:10 +00:00
let response = await axios . post ( url , { whatsappId : process . env . WHATSAPP _ID } )
2023-02-13 12:43:00 +00:00
} catch ( error ) {
2023-08-15 12:14:10 +00:00
console . log ( 'There was an error on POST THE DATA TO URL: ' , url , '\n' + error )
2023-02-13 12:43:00 +00:00
}
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
client . on ( "authenticated" , async session => {
2023-08-15 12:14:10 +00:00
console . log ( ` Session: ${ sessionName } AUTHENTICATED ` )
} )
2023-02-13 12:43:00 +00:00
client . on ( "auth_failure" , async msg => {
console . log (
` Session: ${ sessionName } AUTHENTICATION FAILURE! Reason: ${ msg } `
2023-08-15 12:14:10 +00:00
)
2023-02-13 12:43:00 +00:00
2023-04-17 13:05:22 +00:00
// omnihit.monitor(process.env.MOBILEUID, process.env.MOBILENAME, "AUTHFAILURE");
2023-02-13 12:43:00 +00:00
//reject(new Error("Error starting whatsapp session."));
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
client . on ( "ready" , async ( ) => {
2023-08-15 12:14:10 +00:00
console . log ( ` Session: ${ sessionName } READY ` )
2023-02-13 12:43:00 +00:00
// console.log('>>>>>>>>>>>>>> ready client.ts MOBILE NUMBER: ', client.info["wid"]["user"])
2023-08-15 12:14:10 +00:00
mobileuid = client . info [ "wid" ] [ "user" ]
console . log ( new Date ( ) . toISOString ( ) + " >>> Mobile UID ::: " + mobileuid )
2023-02-13 12:43:00 +00:00
// logger.info(`Session: ${sessionName} READY`);
const whatsapp = await new Promise ( ( resolve , reject ) => {
dbcc . query ( "SELECT * from Whatsapps where id = ?" , [ process . env . WHATSAPP _ID ] , ( err , result ) => {
if ( err ) {
reject ( err )
}
else {
resolve ( result )
}
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
} )
if ( whatsapp [ 0 ] [ 'name' ] . includes ( client . info [ "wid" ] [ "user" ] ) ) {
console . log ( '-----------------> THIS IS THE RIGHT NUMBER' )
2023-08-15 12:14:10 +00:00
2023-02-13 12:43:00 +00:00
}
else {
console . log ( '-----------------> THIS IS THE WRONG NUMBER' )
let read _number = client . info [ "wid" ] [ "user" ]
let url = process . env . CLIENT _URL + '/whatsapp/connection/number'
try {
await client . logout ( )
2023-08-15 12:14:10 +00:00
let response = await axios . post ( url , { number : read _number } )
2023-02-13 12:43:00 +00:00
} catch ( error ) {
2023-08-15 12:14:10 +00:00
console . log ( 'There was an error on POST THE DATA TO URL: ' , url , '\n' + error )
2023-02-13 12:43:00 +00:00
}
return
}
2023-05-02 12:47:41 +00:00
await new Promise ( ( resolve , reject ) => {
dbcc . query ( "UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ?, number = ? where id = ?" , [ "" , 'CONNECTED' , 0 , client . info [ "wid" ] [ "user" ] , process . env . WHATSAPP _ID ] ,
function ( err , result ) {
if ( err ) {
2023-08-15 12:14:10 +00:00
console . log ( "ERROR: " + err )
2023-05-02 12:47:41 +00:00
reject ( err )
}
else {
resolve ( result )
}
2023-08-15 12:14:10 +00:00
} )
2023-05-02 12:47:41 +00:00
} )
2023-02-13 12:43:00 +00:00
let url = process . env . CLIENT _URL + '/whatsapp/connection/qrcode'
try {
2023-08-15 12:14:10 +00:00
let response = await axios . post ( url , { whatsappId : process . env . WHATSAPP _ID } )
2023-02-13 12:43:00 +00:00
} catch ( error ) {
2023-08-15 12:14:10 +00:00
console . log ( 'There was an error on POST THE DATA TO URL: ' , url , '\n' + error )
2023-02-13 12:43:00 +00:00
}
console . log ( 'SEND SEEN: ' , sendSeen )
await syncUnreadMessages ( client )
if ( sendSeen ) {
2023-08-15 12:14:10 +00:00
client . sendPresenceAvailable ( )
2023-02-13 12:43:00 +00:00
}
// if(asking_qrcode){
// // backup_session(destroy, 120000, true)
// }
backup _session ( destroy , 120000 , false )
asking _qrcode = false
console . log ( 'PASSOU............' )
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
async function read ( ) {
2023-08-15 12:14:10 +00:00
let chats = await client . getState ( )
console . log ( chats )
2023-02-13 12:43:00 +00:00
}
client . on ( "message_create" , async msg => {
2023-04-08 22:28:32 +00:00
// if (msg.hasMedia && msg.fromMe)
// return
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
if ( msg . fromMe && msg . type === "chat" && auxCampaignMessage . trim ( ) == msg ? . body ? . trim ( ) ) {
console . log ( 'IGNORED MESSAGE SENT CAMPAIGN' )
return
}
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
await handleMessage ( msg )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
client . on ( "media_uploaded" , async msg => {
console . log ( 'Entrou no midia upload' )
let msgContact = null
let media = null
if ( msg . fromMe ) {
2023-08-15 12:14:10 +00:00
msgContact = await client . getContactById ( msg . to )
2023-02-13 12:43:00 +00:00
}
else {
2023-08-15 12:14:10 +00:00
msgContact = await msg . getContact ( )
2023-02-13 12:43:00 +00:00
}
2023-08-15 12:14:10 +00:00
const chat = await msg . getChat ( )
2023-02-13 12:43:00 +00:00
msgContact . getProfilePicUrl = await msgContact . getProfilePicUrl ( )
2023-08-15 12:14:10 +00:00
let quotedMsg = await msg . getQuotedMessage ( )
2023-02-13 12:43:00 +00:00
if ( msg . hasMedia ) {
2023-08-15 12:14:10 +00:00
media = await msg . downloadMedia ( )
2023-02-13 12:43:00 +00:00
}
let data = {
id : process . env . WHATSAPP _ID ,
msg : msg ,
msgContact : msgContact ,
chat : chat ,
quotedMsg : quotedMsg ? quotedMsg . id . id : null ,
media : media
}
2023-08-15 12:14:10 +00:00
socketIo . emit ( "media_uploaded" , data )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
client . on ( "message_ack" , async ( msg , ack ) => {
2023-08-15 12:14:10 +00:00
const campaigSend = await db . collection ( 'campaignsends' ) . findOne ( { whatsapp _msg _id : msg . id . id } )
if ( campaigSend && ack == 3 ) {
const updateResult = await db . collection ( 'campaignsends' ) . updateOne ( { _id : ObjectId ( campaigSend . _id ) } ,
{
$set : {
read : new Date ( new Date ( ) + "UTC" ) ,
ack : ack
}
} )
// console.log('RESULT ACK UPDATE: ', updateResult)
const read = await db . collection ( 'campaignsends' ) . countDocuments ( { campaignId : ObjectId ( campaigSend . campaignId ) , ack : 3 } )
const data = {
id : ObjectId ( campaigSend . campaignId ) ,
read : read
}
console . log ( 'DATA ACK READ MESSAGE CAMPAIGN: ' , data )
socketIo . emit ( "campaign_message_sent" , data )
return
}
else if ( campaigSend && ( ack == 2 || ack == 1 ) ) {
return
}
2023-02-13 12:43:00 +00:00
let data = {
whatsappId : process . env . WHATSAPP _ID ,
id : msg . id . id ,
ack : ack
}
2023-08-15 12:14:10 +00:00
socketIo . emit ( "message_ack" , data )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
socketIo . on ( 'send_message' , async data => {
2023-05-02 12:47:41 +00:00
2023-02-13 12:43:00 +00:00
console . log ( '#' )
2023-08-15 12:14:10 +00:00
console . log ( '--------------> send_message from number: ' , mobileuid )
console . log ( '--------------> send_message to number: ' , data . msg . number )
console . log ( '--------------> send_message body: ' , data . msg . body )
console . log ( '--------------> send_message quotedMessageId: ' , data . msg . quotedMessageId )
console . log ( '--------------> send_message linkPreview: ' , data . msg . linkPreview )
2023-02-13 12:43:00 +00:00
console . log ( '#' )
2023-08-15 12:14:10 +00:00
const sentMessage = await client . sendMessage ( data . msg . number , data . msg . body , { quotedMessageId : data . msg . quotedMessageId , linkPreview : data . msg . linkPreview } )
2023-02-13 12:43:00 +00:00
// console.log('=====================> sentMessage: ', sentMessage)
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
socketIo . on ( 'send_media' , async data => {
2023-05-02 12:47:41 +00:00
2023-02-13 12:43:00 +00:00
console . log ( '#' )
2023-08-15 12:14:10 +00:00
console . log ( '--------------> send_message from number: ' , mobileuid )
console . log ( '--------------> send_message to number: ' , data . msg . number )
2023-02-13 12:43:00 +00:00
// console.log('--------------> send_message media: ', data.msg.media);
2023-08-15 12:14:10 +00:00
console . log ( '--------------> send_message sendAudioAsVoice: ' , data . msg . sendAudioAsVoice )
console . log ( '--------------> data.msg.media.mimetype: ' , data . msg . media . mimetype )
console . log ( '--------------> data.msg.media.filename: ' , data . msg . media . filename )
2023-02-13 12:43:00 +00:00
console . log ( '#' )
2023-08-15 12:14:10 +00:00
let media = new MessageMedia ( data . msg . media . mimetype , data . msg . media . data , data . msg . media . file )
2023-02-13 12:43:00 +00:00
if ( media && ! media . filename )
media . filename = data . msg . media . filename
2023-05-02 12:47:41 +00:00
2023-08-15 12:14:10 +00:00
const sentMessage = await client . sendMessage ( data . msg . number , media , { sendAudioAsVoice : data . msg . sendAudioAsVoice } )
2023-02-13 12:43:00 +00:00
// const fullFilename = process.cwd() + process.env.MEDIA_DOWNLOAD_IN + data.msg.media.filename;
// console.log('fullFIlename: ', fullFilename)
// fs.writeFileSync(fullFilename, data.msg.media.data, { encoding: 'base64' });
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
client . on ( "change_state" , async newState => {
let omnihit _url = process . env . CLIENT _URL + '/whatsapp/connection/monitor'
// logger.info(`Monitor session: ${sessionName}, ${newState}`);
console . log ( '>>>>>>>>>>>>>> change_state wbotMonitor.ts MOBILE NUMBER: ' , client . info [ "wid" ] [ "user" ] )
let data = {
action : 'change_state' ,
whatsappId : process . env . WHATSAPP _ID
2023-08-15 12:14:10 +00:00
}
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
await whatsappMonitor ( newState , omnihit _url , data )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
client . on ( "disconnected" , async reason => {
let omnihit _url = process . env . CLIENT _URL + '/whatsapp/connection/monitor'
console . log ( '>>>>>>>>>>>>>> change_state wbotMonitor.ts MOBILE NUMBER: ' , client . info [ "wid" ] [ "user" ] )
let data = {
action : 'disconnected' ,
whatsappId : process . env . WHATSAPP _ID ,
reason : reason
2023-08-15 12:14:10 +00:00
}
2023-02-13 12:43:00 +00:00
await removeDir ( path . join ( _ _dirname , '.wwebjs_auth' , 'session-omnihit_sesssion' ) )
setTimeout ( ( ) => {
process . exit ( )
} , 3000 )
2023-08-15 12:14:10 +00:00
await whatsappMonitor ( 'OPENING' , omnihit _url , data )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
app . get ( '/' , function ( req , res ) { return res . send ( 'Express + TypeScript Server' ) } )
2023-02-13 12:43:00 +00:00
app . post ( '/start' , function ( req , res ) {
2023-08-15 12:14:10 +00:00
client . initialize ( )
res . send ( "OK" )
} )
2023-02-13 12:43:00 +00:00
app . post ( '/qr' , function ( req , res ) {
2023-08-15 12:14:10 +00:00
res . send ( QRCODE )
} )
2023-02-13 12:43:00 +00:00
app . post ( '/api/getWbotMessage' , async ( req , res ) => {
const { number , messageId , limit } = req . body
console . log ( 'number: ' , number , ' | limit: ' , limit )
2023-08-15 12:14:10 +00:00
const wbotChat = await client . getChatById ( number )
2023-02-13 12:43:00 +00:00
const fetchWbotMessagesGradually = async ( ) => {
2023-08-15 12:14:10 +00:00
const chatMessages = await wbotChat . fetchMessages ( { limit } )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const msgFound = chatMessages . find ( msg => msg . id . id === messageId )
2023-02-13 12:43:00 +00:00
if ( ! msgFound && limit < 100 ) {
2023-08-15 12:14:10 +00:00
limit += 20
return fetchWbotMessagesGradually ( )
2023-02-13 12:43:00 +00:00
}
2023-08-15 12:14:10 +00:00
return msgFound
}
2023-02-13 12:43:00 +00:00
try {
2023-08-15 12:14:10 +00:00
const msgFound = await fetchWbotMessagesGradually ( )
2023-02-13 12:43:00 +00:00
if ( ! msgFound ) {
2023-08-15 12:14:10 +00:00
res . status ( 404 ) . json ( { message : "Cannot found message within 100 last messages" } )
2023-02-13 12:43:00 +00:00
return
}
2023-08-15 12:14:10 +00:00
res . status ( 200 ) . json ( { message : "ok" , data : msgFound } )
2023-02-13 12:43:00 +00:00
} catch ( err ) {
console . log ( 'ERR_FETCH_WAPP_MSG: ' , err )
2023-08-15 12:14:10 +00:00
res . status ( 404 ) . json ( { message : "ERR_FETCH_WAPP_MSG" } )
2023-02-13 12:43:00 +00:00
}
} )
app . post ( '/api/disconnect' , async ( req , res ) => {
try {
console . log ( 'Restaring the session.........' )
await removeDir ( path . join ( _ _dirname , '.wwebjs_auth' , 'session-omnihit_sesssion' ) )
2023-08-15 12:14:10 +00:00
await client . logout ( )
2023-02-13 12:43:00 +00:00
setTimeout ( ( ) => {
process . exit ( )
} , 3000 )
} catch ( error ) {
console . log ( 'There was an error on try disconnect the whatsapp: ' , error )
}
2023-08-15 12:14:10 +00:00
res . status ( 200 ) . json ( { message : "ok" } )
2023-02-13 12:43:00 +00:00
} )
app . post ( '/api/DeleteWhatsAppMessage' , async ( req , res ) => {
const { number , messageId , limit } = req . body
console . log ( 'number: ' , number , ' | messageId: ' , messageId , ' | limit: ' , limit )
try {
const messageToDelete = await getWbotMessage ( messageId , number , limit )
2023-08-15 12:14:10 +00:00
await messageToDelete . delete ( true )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
res . status ( 200 ) . json ( { message : "ok" , data : messageToDelete } )
2023-02-13 12:43:00 +00:00
return
} catch ( error ) {
2023-04-24 17:15:07 +00:00
console . log ( 'There was an error on try delete the massage: ' , error )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
res . status ( 500 ) . json ( { message : "There was an error on trying delete the message" } )
2023-02-13 12:43:00 +00:00
return
}
} )
app . post ( '/api/GetProfilePicUrl' , async ( req , res ) => {
const { number } = req . body
console . log ( 'THE NUMBER: ' , number )
2023-08-15 12:14:10 +00:00
const profilePicUrl = await client . getProfilePicUrl ( ` ${ number } @c.us ` )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
res . status ( 200 ) . json ( { message : "ok" , data : profilePicUrl } )
2023-02-13 12:43:00 +00:00
} )
app . post ( '/api/restore' , async ( req , res ) => {
await restore ( client )
2023-08-15 12:14:10 +00:00
res . status ( 200 ) . json ( { message : "ok" } )
2023-02-13 12:43:00 +00:00
} )
2023-07-12 14:54:29 +00:00
app . post ( '/api/sendSeen' , async ( req , res ) => {
let stat
2023-08-15 12:14:10 +00:00
const { number } = req . body
2023-07-12 14:54:29 +00:00
try {
2023-08-15 12:14:10 +00:00
stat = await client . getState ( )
2023-07-12 14:54:29 +00:00
// await syncUnreadMessages(client)
2023-08-15 12:14:10 +00:00
const wbotChat = await client . getChatById ( number )
2023-07-12 14:54:29 +00:00
2023-08-15 12:14:10 +00:00
wbotChat . sendSeen ( )
2023-07-12 14:54:29 +00:00
// const chatMessages = await wbotChat.fetchMessages({ limit: 100 });
// console.log('=============> wbotChat: ', chatMessages)
} catch ( err ) {
2023-08-15 12:14:10 +00:00
let terr = err . message
2023-07-12 14:54:29 +00:00
stat = ( terr . search ( 'Session closed' ) > - 1 ? 'SESSIONCLOSED' : 'UNKNOWN' )
}
2023-08-15 12:14:10 +00:00
res . status ( 200 ) . json ( { message : "ok" } )
2023-07-12 14:54:29 +00:00
} )
2023-02-13 12:43:00 +00:00
app . get ( '/api/connection/status' , async ( req , res ) => {
let stat
try {
2023-08-15 12:14:10 +00:00
stat = await client . getState ( )
2023-02-13 12:43:00 +00:00
} catch ( err ) {
2023-08-15 12:14:10 +00:00
let terr = err . message
2023-02-13 12:43:00 +00:00
stat = ( terr . search ( 'Session closed' ) > - 1 ? 'SESSIONCLOSED' : 'UNKNOWN' )
}
2023-08-15 12:14:10 +00:00
res . status ( 200 ) . json ( { message : "ok" , data : stat } )
2023-02-13 12:43:00 +00:00
} )
const syncUnreadMessages = async ( wbot ) => {
console . log ( 'ENTROU NO UNREAD MESSAGES +++++++++++++=' )
2023-08-15 12:14:10 +00:00
const chats = await wbot . getChats ( )
2023-02-13 12:43:00 +00:00
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-await-in-loop */
for ( const chat of chats ) {
2023-07-12 14:54:29 +00:00
// console.log('chat: ', chat)
2023-02-13 12:43:00 +00:00
if ( chat . unreadCount > 0 ) {
const unreadMessages = await chat . fetchMessages ( {
limit : chat . unreadCount
2023-08-15 12:14:10 +00:00
} )
2023-02-13 12:43:00 +00:00
for ( const msg of unreadMessages ) {
// console.log('--BACKEND MSG: ', msg)
if ( ! sendSeen ) {
return
}
2023-08-15 12:14:10 +00:00
await handleMessage ( msg , wbot )
2023-02-13 12:43:00 +00:00
}
console . log ( ':::::::::::::::::::::::::::::PASSOU' )
2023-08-15 12:14:10 +00:00
await chat . sendSeen ( )
2023-02-13 12:43:00 +00:00
}
}
2023-08-15 12:14:10 +00:00
}
2023-02-13 12:43:00 +00:00
const getWbotMessage = async ( messageId , number , limit , ) => {
2023-08-15 12:14:10 +00:00
const wbotChat = await client . getChatById ( number )
2023-02-13 12:43:00 +00:00
const fetchWbotMessagesGradually = async ( ) => {
2023-08-15 12:14:10 +00:00
const chatMessages = await wbotChat . fetchMessages ( { limit } )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
const msgFound = chatMessages . find ( msg => msg . id . id === messageId )
2023-02-13 12:43:00 +00:00
if ( ! msgFound && limit < 100 ) {
2023-08-15 12:14:10 +00:00
limit += 20
return fetchWbotMessagesGradually ( )
2023-02-13 12:43:00 +00:00
}
2023-08-15 12:14:10 +00:00
return msgFound
}
2023-02-13 12:43:00 +00:00
try {
2023-08-15 12:14:10 +00:00
const msgFound = await fetchWbotMessagesGradually ( )
2023-02-13 12:43:00 +00:00
if ( ! msgFound ) {
return null
}
return msgFound
} catch ( err ) {
console . log ( 'ERR_FETCH_WAPP_MSG: ' , err )
}
return null
}
2023-07-12 14:54:29 +00:00
async function whatsappMonitor ( newState , omnihit _url , data ) {
2023-02-13 12:43:00 +00:00
2023-05-02 12:47:41 +00:00
const whatsapp = await whatsappUpdateStatus ( newState )
2023-02-13 12:43:00 +00:00
2023-05-02 12:47:41 +00:00
if ( whatsapp && whatsapp . affectedRows ) {
console . log ( 'whatsapp status update affectedRows: ' , whatsapp . affectedRows )
}
// console.log(' whatsappwhatsappwhatsappwhatsapp: ', whatsapp)
2023-02-13 12:43:00 +00:00
try {
2023-08-15 12:14:10 +00:00
let response = await axios . post ( omnihit _url , data )
2023-02-13 12:43:00 +00:00
} catch ( error ) {
2023-08-15 12:14:10 +00:00
console . log ( 'There was an error on POST THE DATA TO URL: ' , omnihit _url , '\n' + error )
2023-02-13 12:43:00 +00:00
}
}
2023-05-02 12:47:41 +00:00
async function whatsappUpdateStatus ( newState ) {
return await new Promise ( ( resolve , reject ) => {
dbcc . query ( "UPDATE Whatsapps SET status = ? where id = ?" , [ newState , process . env . WHATSAPP _ID ] ,
function ( err , result ) {
if ( err ) {
2023-08-15 12:14:10 +00:00
console . log ( "ERROR: " + err )
reject ( err )
2023-05-02 12:47:41 +00:00
}
else {
2023-08-15 12:14:10 +00:00
resolve ( result )
2023-05-02 12:47:41 +00:00
}
2023-08-15 12:14:10 +00:00
} )
2023-05-02 12:47:41 +00:00
2023-08-15 12:14:10 +00:00
} )
2023-05-02 12:47:41 +00:00
}
2023-02-13 12:43:00 +00:00
async function handleMessage ( msg ) {
2023-08-15 12:14:10 +00:00
console . log ( 'Entrou no message_create' )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
let msgContact = null
let media = null
2023-02-13 12:43:00 +00:00
2023-05-02 12:47:41 +00:00
if ( msg . fromMe ) {
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
msgContact = await client . getContactById ( msg . to )
2023-02-13 12:43:00 +00:00
}
else {
console . log ( '################# RECEIVING MESSAGE FROM: ' , msg . from , ' to ' , msg . to )
2023-08-15 12:14:10 +00:00
msgContact = await msg . getContact ( )
2023-02-13 12:43:00 +00:00
}
2023-08-15 12:14:10 +00:00
const chat = await msg . getChat ( )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
msgContact . getProfilePicUrl = await msgContact . getProfilePicUrl ( )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
let quotedMsg = await msg . getQuotedMessage ( )
2023-02-13 12:43:00 +00:00
if ( msg . hasMedia ) {
2023-08-15 12:14:10 +00:00
media = await msg . downloadMedia ( )
2023-02-13 12:43:00 +00:00
}
let data = {
id : process . env . WHATSAPP _ID ,
msg : msg ,
msgContact : msgContact ,
chat : chat ,
quotedMsg : quotedMsg ? quotedMsg . id . id : null ,
media : media
2023-08-15 12:14:10 +00:00
}
2023-05-02 12:47:41 +00:00
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
socketIo . emit ( "message_create" , data )
2023-02-13 12:43:00 +00:00
}
async function getlabels ( ) {
2023-08-15 12:14:10 +00:00
var ret = await client . getContactById ( '551721379544-1625752306@g.us' )
2023-02-13 12:43:00 +00:00
//createGroup('The books', ['551100000000@c.us']);
2023-08-15 12:14:10 +00:00
console . log ( "-- Chats --------------------------------" )
console . log ( ret )
return ret
2023-02-13 12:43:00 +00:00
}
function base64 _encode ( file ) {
// read binary data
2023-08-15 12:14:10 +00:00
var bitmap = fs . readFileSync ( file )
2023-02-13 12:43:00 +00:00
// convert binary data to base64 encoded string
2023-08-15 12:14:10 +00:00
return new Buffer ( bitmap ) . toString ( 'base64' )
2023-02-13 12:43:00 +00:00
}
function getBase64 ( url ) {
return axios
. get ( url , {
responseType : 'arraybuffer'
} )
. then ( response => Buffer . from ( response . data , 'binary' ) . toString ( 'base64' ) )
}
function downloadMedia ( url ) {
2023-08-15 12:14:10 +00:00
let base64 = axios . get ( url , { response : "arraybuffer" } ) . toString ( "base64" )
console . log ( "-- BASE64 -------------------------------" )
console . log ( base64 )
return base64
2023-02-13 12:43:00 +00:00
}
async function validate ( mobile , cb ) {
// let ret = await client.isRegisteredUser(mobile);
2023-08-15 12:14:10 +00:00
let ret = await client . isRegisteredUser ( ` ${ mobile } @c.us ` )
2023-02-13 12:43:00 +00:00
// ///////////////////////////////////////////////////// 5571992888229 casaes
let _validNumber = null
console . log ( '******** mobile: ' , mobile )
try {
2023-08-15 12:14:10 +00:00
_validNumber = ( await client . getNumberId ( ` ${ mobile } @c.us ` ) ) . user
2023-02-13 12:43:00 +00:00
} catch ( err ) {
console . log ( ` Error number: ${ err } ` )
}
console . log ( '_validNumber: ' , _validNumber )
////////////////////////////////////////////////////////////////////
2023-08-15 12:14:10 +00:00
cb ( { isValid : ret , number : _validNumber } )
2023-02-13 12:43:00 +00:00
// cb(ret)
}
app . post ( '/api/validate' , ( req , res ) => {
console . log ( 'ENTROU' )
2023-08-15 12:14:10 +00:00
let mobile = req . body [ 'mobile' ]
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
console . log ( new Date ( ) + " >>> Validating Registration Number ::: " + mobile + " on WhatsApp ..." )
2023-02-13 12:43:00 +00:00
validate ( mobile , function ( e ) {
2023-08-15 12:14:10 +00:00
res . send ( e )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
} )
} )
2023-02-13 12:43:00 +00:00
app . post ( '/api/chat' , ( req , res ) => {
2023-08-15 12:14:10 +00:00
let mobile = req . body [ 'mobile' ]
let message = req . body [ 'message' ]
console . log ( new Date ( ) + " >>> Send Message ::: " + mobile + " ..." )
client . sendMessage ( mobile , message )
res . send ( 'OK' )
} )
2023-02-13 12:43:00 +00:00
app . post ( '/group' , function ( req , res ) {
//var ret = client.createGroup("Prueba", ["55@c.us"]);
var ret = getlabels ( )
2023-08-15 12:14:10 +00:00
res . send ( ret )
} )
2023-02-13 12:43:00 +00:00
app . post ( '/stop' , function ( req , res ) {
2023-08-15 12:14:10 +00:00
client . destroy ( )
res . send ( "OK" )
} )
2023-02-13 12:43:00 +00:00
app . post ( '/api/status' , function ( req , res ) {
2023-08-15 12:14:10 +00:00
res . send ( "OK" )
} )
2023-02-13 12:43:00 +00:00
async function monitor ( ) {
2023-08-15 12:14:10 +00:00
let _nextime = 0
2023-02-13 12:43:00 +00:00
try {
2023-08-15 12:14:10 +00:00
clearInterval ( scheduler _monitor )
let stat
2023-02-13 12:43:00 +00:00
if ( mobileuid != undefined ) {
try {
2023-08-15 12:14:10 +00:00
stat = await client . getState ( )
2023-02-13 12:43:00 +00:00
} catch ( err ) {
2023-08-15 12:14:10 +00:00
let terr = err . message
2023-02-13 12:43:00 +00:00
stat = ( terr . search ( 'Session closed' ) > - 1 ? 'SESSIONCLOSED' : 'UNKNOWN' )
}
// omnihit.monitor(process.env.MOBILEUID, process.env.MOBILENAME, stat);
2023-08-15 12:14:10 +00:00
_nextime = 30000
2023-02-13 12:43:00 +00:00
} else {
2023-08-15 12:14:10 +00:00
_nextime = 10000
2023-02-13 12:43:00 +00:00
}
console . log ( ` WHATSAPP_ID: ${ process . env . WHATSAPP _ID } | CLIENT MOBILEUID: ${ mobileuid } | NAME: ${ process . env . MOBILENAME } | ENV MOBILEUID: ${ process . env . MOBILEUID } | STATUS: ${ stat } ` )
2023-05-02 12:47:41 +00:00
if ( stat && stat === 'CONNECTED' ) {
2023-08-15 12:14:10 +00:00
2023-05-02 12:47:41 +00:00
const result = await whatsappUpdateStatus ( 'CONNECTED' )
if ( result )
console . log ( ` Update status to CONNECTED WHATSAPP_ID: ${ process . env . WHATSAPP _ID } => result.affectedRows: ${ result . affectedRows } ` )
}
2023-02-13 12:43:00 +00:00
} catch ( error ) {
//new Date(new Date() + 'UTC')
// console.log(new Date().toISOString() + " >>> ", error);
2023-08-15 12:14:10 +00:00
console . log ( new Date ( new Date ( ) + 'UTC' ) + " >>> " , error )
2023-02-13 12:43:00 +00:00
} finally {
2023-08-15 12:14:10 +00:00
scheduler _monitor = setInterval ( monitor , _nextime )
}
}
const sendCampaignMessage = async ( ) => {
try {
clearInterval ( scheduler _campaign _monitor )
if ( mobileuid != undefined ) {
auxCampaignMessage = ''
const campaign = await db . collection ( 'campaigns' ) . findOne ( { 'campaign.whatsapp_sender' : process . env . MOBILEUID , 'app.status' : 'running' } )
if ( ! campaign )
return
const campaigSend = await db . collection ( 'campaignsends' ) . findOne ( { campaignId : ObjectId ( campaign . _id ) , ack : 1 } )
if ( ! campaigSend ) {
const countCampaignSend = await db . collection ( 'campaignsends' ) . countDocuments ( )
if ( countCampaignSend && countCampaignSend > 0 ) {
await db . collection ( 'campaigns' ) . updateOne ( { _id : ObjectId ( campaign . _id ) } ,
{
$set : {
'app.status' : 'success'
}
} )
const data = {
id : ObjectId ( campaign . _id ) ,
status : 'success'
}
socketIo . emit ( "campaign_message_sent" , data )
}
return
}
if ( campaign . campaign ? . textToSeconds &&
campaign . campaign ? . message &&
campaign . campaign . message . trim ( ) . length > 0 ) {
let msgMs = Math . round ( ( campaign . campaign . message . trim ( ) . length * 0.1 ) * 1000 )
console . log ( 'AWAITING MESSAGE TEXT LENGTH TO MILISECONDS: ' , msgMs )
await sleep ( msgMs )
}
if ( campaign . campaign ? . secondStart && campaign . campaign ? . secondEnd ) {
let randomTime = getRandomNumber ( campaign . campaign . secondStart , campaign . campaign . secondEnd ) * 1000
console . log ( 'AWAITING RANDOM TIME TO SEND CAMPAIGN MESSAGE: ' , randomTime )
await sleep ( randomTime )
}
auxCampaignMessage = campaign . campaign . message
const sentMessage = await client . sendMessage ( ` ${ campaigSend . number } @c.us ` , campaign . campaign . message )
if ( sentMessage ) {
const updateResult = await db . collection ( 'campaignsends' ) . updateOne ( { _id : ObjectId ( campaigSend . _id ) } ,
{
$set : {
whatsapp _msg _id : sentMessage . id . id ,
sender : process . env . MOBILEUID ,
delivered : new Date ( new Date ( ) + "UTC" ) ,
ack : 2
}
} )
// console.log('RESULT: ', updateResult)
const sent = await db . collection ( 'campaignsends' ) . countDocuments ( { campaignId : ObjectId ( campaign . _id ) , $or : [ { ack : 2 } , { ack : 3 } ] } )
const data = {
id : ObjectId ( campaign . _id ) ,
sent
}
socketIo . emit ( "campaign_message_sent" , data )
}
}
} catch ( error ) {
console . log ( 'error on sendCampaignMessage: ' , error )
}
finally {
scheduler _campaign _monitor = setInterval ( sendCampaignMessage , 3000 )
2023-02-13 12:43:00 +00:00
}
}
async function monitorCell ( ) {
try {
2023-08-15 12:14:10 +00:00
clearInterval ( scheduler _monitor _cell )
2023-02-13 12:43:00 +00:00
// let _contact_mobile = "5511954803572@c.us";
2023-08-15 12:14:10 +00:00
let _message = new Date ( new Date ( ) + 'UTC' )
2023-02-13 12:43:00 +00:00
if ( client . info && client . info [ "wid" ] [ "user" ] ) {
2023-08-15 12:14:10 +00:00
client . sendMessage ( ` ${ process . env . MONITOR _NUMBER } @c.us ` , _message )
2023-02-13 12:43:00 +00:00
}
} catch ( error ) {
2023-08-15 12:14:10 +00:00
console . log ( ` Error on send monitor message to number ${ process . env . MONITOR _NUMBER } from monitorCell function: ${ error } ` )
2023-02-13 12:43:00 +00:00
} finally {
2023-08-15 12:14:10 +00:00
scheduler _monitor _cell = setInterval ( monitorCell , 1800000 )
2023-02-13 12:43:00 +00:00
}
}
function comercialBuss ( until _hour ) {
const _hour = new Date ( ) . getHours ( )
console . log ( ' _hour: ' , _hour )
// const _minute = new Date().getMinutes()
// const _second = new Date().getSeconds()
if ( _hour >= until _hour ) {
console . log ( 'Trying send message into comercial buss!' )
return
}
}
2023-08-15 12:14:10 +00:00
scheduler _monitor = setInterval ( monitor , 10000 )
2023-02-13 12:43:00 +00:00
2023-08-15 12:14:10 +00:00
scheduler _campaign _monitor = setInterval ( sendCampaignMessage , 3000 )
2023-02-13 12:43:00 +00:00
app . listen ( process . env . PORT || 8003 , function ( ) {
2023-08-15 12:14:10 +00:00
console . log ( "\u26A1[server]: Server is running at Port ::: " + process . env . PORT || 8003 )
} )
2023-02-13 12:43:00 +00:00
process . on ( 'uncaughtException' , function ( err ) {
2023-08-15 12:14:10 +00:00
console . error ( ' ' )
2023-02-13 12:43:00 +00:00
console . error ( '----- ' + ( new Date ) . toUTCString ( ) + ' ----------------------------------' )
console . error ( 'Erro uncaughtException: ' , err . message )
console . error ( err . stack )
2023-08-15 12:14:10 +00:00
console . error ( ' ' )
2023-02-13 12:43:00 +00:00
return
} ) ;
2023-08-15 12:14:10 +00:00