2022-01-06 01:26:15 +00:00
import qrCode from "qrcode-terminal" ;
2022-06-27 06:21:04 +00:00
import { Client , LocalAuth } from "whatsapp-web.js" ;
2022-01-06 01:26:15 +00:00
import { getIO } from "./socket" ;
import Whatsapp from "../models/Whatsapp" ;
import AppError from "../errors/AppError" ;
import { logger } from "../utils/logger" ;
import { handleMessage } from "../services/WbotServices/wbotMessageListener" ;
2022-02-07 13:58:27 +00:00
const fs = require ( 'fs' )
2022-01-06 01:26:15 +00:00
2022-06-27 06:21:04 +00:00
import { copyFolder } from "../helpers/CopyFolder" ;
import path from "path" ;
import { number } from "yup" ;
2022-07-12 12:37:34 +00:00
import { removeDir } from "../helpers/DeleteDirectory" ;
2022-06-27 06:21:04 +00:00
2022-01-06 01:26:15 +00:00
interface Session extends Client {
id? : number ;
}
const sessions : Session [ ] = [ ] ;
2022-06-27 06:21:04 +00:00
let backupSession : any [ ] = [ ]
2022-11-17 14:40:37 +00:00
import { insertOrUpeateWhatsCache } from "../helpers/WhatsCache" ;
2022-12-11 07:47:32 +00:00
import { json } from "sequelize/types" ;
import { restartWhatsSession } from "../helpers/RestartWhatsSession" ;
2022-06-27 06:21:04 +00:00
2022-01-06 01:26:15 +00:00
const syncUnreadMessages = async ( wbot : Session ) = > {
const chats = await wbot . getChats ( ) ;
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-await-in-loop */
for ( const chat of chats ) {
if ( chat . unreadCount > 0 ) {
const unreadMessages = await chat . fetchMessages ( {
limit : chat.unreadCount
} ) ;
for ( const msg of unreadMessages ) {
2022-11-14 14:21:58 +00:00
2022-07-20 15:34:12 +00:00
// console.log('--BACKEND MSG: ', msg)
2022-11-14 14:21:58 +00:00
2022-01-06 01:26:15 +00:00
await handleMessage ( msg , wbot ) ;
}
await chat . sendSeen ( ) ;
}
}
} ;
2022-07-12 12:37:34 +00:00
export const initWbot = async ( whatsapp : Whatsapp , backupSessionRestore : boolean = false ) : Promise < Session > = > {
2022-01-06 01:26:15 +00:00
return new Promise ( ( resolve , reject ) = > {
try {
2022-04-11 11:04:49 +00:00
2022-06-27 06:21:04 +00:00
2022-02-15 10:42:35 +00:00
const io = getIO ( ) ;
const sessionName = whatsapp . name ;
let sessionCfg ;
2022-02-07 13:58:27 +00:00
2022-02-15 10:42:35 +00:00
if ( whatsapp && whatsapp . session ) {
sessionCfg = JSON . parse ( whatsapp . session ) ;
}
2022-02-07 13:58:27 +00:00
2022-06-27 06:21:04 +00:00
2022-04-11 11:04:49 +00:00
//NOVA OPÇÃO MD
2022-07-20 15:34:12 +00:00
// const wbot: Session = new Client({
// session: sessionCfg, authStrategy: new LocalAuth({ clientId: 'bd_' + whatsapp.id }),
// puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined },
// });
// usando instancia do chrome
2022-06-27 06:21:04 +00:00
const wbot : Session = new Client ( {
session : sessionCfg , authStrategy : new LocalAuth ( { clientId : 'bd_' + whatsapp . id } ) ,
2022-07-20 15:34:12 +00:00
puppeteer : { args : [ '--no-sandbox' , '--disable-setuid-sandbox' ] , executablePath : process.env.CHROME_BIN || '/usr/bin/google-chrome-stable' } ,
2022-02-15 10:42:35 +00:00
} ) ;
2022-02-07 13:58:27 +00:00
2022-04-11 11:04:49 +00:00
2022-01-06 01:26:15 +00:00
wbot . initialize ( ) ;
wbot . on ( "qr" , async qr = > {
2022-02-14 01:39:33 +00:00
2022-07-12 12:37:34 +00:00
2022-06-27 06:21:04 +00:00
if ( ! backupSession . includes ( whatsapp . id ) ) {
backupSession . push ( whatsapp . id )
}
console . log ( '************** QRCODE whatsapp.id: ' , whatsapp . id , ' | backupSession: ' , backupSession )
2022-02-14 01:39:33 +00:00
2022-01-06 01:26:15 +00:00
logger . info ( "Session:" , sessionName ) ;
qrCode . generate ( qr , { small : true } ) ;
await whatsapp . update ( { qrcode : qr , status : "qrcode" , retries : 0 } ) ;
2022-11-17 14:40:37 +00:00
await insertOrUpeateWhatsCache ( ` whatsapp: ${ whatsapp . id } ` , { qrcode : qr , status : "qrcode" , retries : 0 } )
2022-01-06 01:26:15 +00:00
const sessionIndex = sessions . findIndex ( s = > s . id === whatsapp . id ) ;
if ( sessionIndex === - 1 ) {
wbot . id = whatsapp . id ;
sessions . push ( wbot ) ;
}
io . emit ( "whatsappSession" , {
action : "update" ,
session : whatsapp
} ) ;
} ) ;
wbot . on ( "authenticated" , async session = > {
logger . info ( ` Session: ${ sessionName } AUTHENTICATED ` ) ;
2022-06-27 06:21:04 +00:00
2022-01-06 01:26:15 +00:00
} ) ;
wbot . on ( "auth_failure" , async msg = > {
console . error (
` Session: ${ sessionName } AUTHENTICATION FAILURE! Reason: ${ msg } `
) ;
if ( whatsapp . retries > 1 ) {
await whatsapp . update ( { session : "" , retries : 0 } ) ;
2022-11-17 14:40:37 +00:00
await insertOrUpeateWhatsCache ( ` whatsapp: ${ whatsapp . id } ` , { session : "" , retries : 0 } )
2022-01-06 01:26:15 +00:00
}
const retry = whatsapp . retries ;
await whatsapp . update ( {
status : "DISCONNECTED" ,
retries : retry + 1
} ) ;
2022-11-17 14:40:37 +00:00
await insertOrUpeateWhatsCache ( ` whatsapp: ${ whatsapp . id } ` , {
status : "DISCONNECTED" ,
retries : retry + 1
} )
2022-01-06 01:26:15 +00:00
io . emit ( "whatsappSession" , {
action : "update" ,
session : whatsapp
} ) ;
reject ( new Error ( "Error starting whatsapp session." ) ) ;
} ) ;
wbot . on ( "ready" , async ( ) = > {
2022-12-12 16:02:18 +00:00
logger . info ( ` Session: ${ sessionName } READY ` ) ;
2022-12-11 07:47:32 +00:00
if ( whatsapp . name . includes ( wbot . info [ "wid" ] [ "user" ] ) ) {
console . log ( '-----------------> THIS IS THE RIGHT NUMBER' )
}
else {
console . log ( '-----------------> THIS IS THE WRONG NUMBER' )
let read_number = wbot . info [ "wid" ] [ "user" ]
await wbot . logout ( )
io . emit ( "whatsappSession" , {
action : "error" ,
msg : ` Numero lido: ${ read_number } \ nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido! `
} ) ;
// restartWhatsSession(whatsapp)
return
}
2022-04-01 20:11:12 +00:00
2022-01-06 01:26:15 +00:00
await whatsapp . update ( {
status : "CONNECTED" ,
qrcode : "" ,
2022-11-14 14:21:58 +00:00
retries : 0 ,
number : wbot . info [ "wid" ] [ "user" ]
2022-11-17 14:40:37 +00:00
} ) ;
await insertOrUpeateWhatsCache ( ` whatsapp: ${ whatsapp . id } ` , whatsapp )
2022-01-06 01:26:15 +00:00
io . emit ( "whatsappSession" , {
action : "update" ,
session : whatsapp
} ) ;
const sessionIndex = sessions . findIndex ( s = > s . id === whatsapp . id ) ;
if ( sessionIndex === - 1 ) {
2022-06-27 06:21:04 +00:00
console . log ( 'WBOT ADD ID: ' , whatsapp . id )
2022-01-06 01:26:15 +00:00
wbot . id = whatsapp . id ;
sessions . push ( wbot ) ;
}
wbot . sendPresenceAvailable ( ) ;
await syncUnreadMessages ( wbot ) ;
resolve ( wbot ) ;
2022-07-12 12:37:34 +00:00
2022-06-27 06:21:04 +00:00
2022-11-16 13:23:14 +00:00
console . log ( ` >>>>>>>>>>>>>>>>>>>>>>>>> BACKUP SESSION whatsapp.id ${ whatsapp . id } | backupSession: ${ backupSession } ` )
2022-06-27 06:21:04 +00:00
2022-07-12 12:37:34 +00:00
const whatsIndex = backupSession . findIndex ( ( id : number ) = > id === + whatsapp . id ) ;
2022-06-27 06:21:04 +00:00
console . log ( ' whatsIndex: ' , whatsIndex )
2022-07-12 12:37:34 +00:00
if ( whatsIndex !== - 1 || backupSessionRestore ) {
if ( whatsIndex !== - 1 ) {
backupSession . splice ( whatsIndex , 1 ) ;
}
2022-06-27 06:21:04 +00:00
setTimeout ( async ( ) = > {
const sourcePath = path . join ( __dirname , ` ../../.wwebjs_auth/ ` , ` session-bd_ ${ whatsapp . id } ` )
const destPath = path . join ( __dirname , ` ../../.wwebjs_auth/sessions ` , ` session-bd_ ${ whatsapp . id } ` )
if ( fs . existsSync ( path . join ( __dirname , ` ../../.wwebjs_auth/sessions ` ) ) ) {
2022-07-12 12:37:34 +00:00
await removeDir ( destPath )
2022-06-27 06:21:04 +00:00
// copy the good session for backup dir
copyFolder ( sourcePath , destPath )
}
else {
console . log ( 'Directory not found to copy: ' , destPath )
}
console . log ( ` COPIOU backup whatsapp.id ----------------------------------> ${ whatsapp . id } ` )
2022-11-16 13:23:14 +00:00
} , 90000 ) ;
2022-06-27 06:21:04 +00:00
2022-07-12 12:37:34 +00:00
console . log ( ' PASSOU NO TIMEOUT whatsapp.id: ' , whatsapp . id )
2022-06-27 06:21:04 +00:00
}
2022-01-06 01:26:15 +00:00
} ) ;
} catch ( err ) {
2022-02-22 20:36:11 +00:00
logger . error ( ` ${ err } ` ) ;
2022-01-06 01:26:15 +00:00
}
} ) ;
} ;
export const getWbot = ( whatsappId : number ) : Session = > {
const sessionIndex = sessions . findIndex ( s = > s . id === whatsappId ) ;
2022-11-16 18:29:20 +00:00
// console.log('----------> sessionIndex: ', sessionIndex, ' | whatasappId: ', whatsappId)
// console.log('----------> sessions: ',sessions.map(s => s.id))
2022-11-16 13:23:14 +00:00
2022-01-06 01:26:15 +00:00
if ( sessionIndex === - 1 ) {
throw new AppError ( "ERR_WAPP_NOT_INITIALIZED" ) ;
}
return sessions [ sessionIndex ] ;
} ;
export const removeWbot = ( whatsappId : number ) : void = > {
try {
const sessionIndex = sessions . findIndex ( s = > s . id === whatsappId ) ;
if ( sessionIndex !== - 1 ) {
2022-06-27 06:21:04 +00:00
console . log ( 'WBOT REMOVED ID: ' , whatsappId )
2022-01-06 01:26:15 +00:00
sessions [ sessionIndex ] . destroy ( ) ;
sessions . splice ( sessionIndex , 1 ) ;
}
} catch ( err ) {
2022-02-22 20:36:11 +00:00
logger . error ( ` ${ err } ` ) ;
2022-01-06 01:26:15 +00:00
}
} ;