Skip to content

Commit

Permalink
Far more efficient DB auth state handling
Browse files Browse the repository at this point in the history
Signed-off-by: Prince Mendiratta <prince.mendi@gmail.com>
  • Loading branch information
Prince-Mendiratta committed Jun 29, 2022
1 parent d3af0bc commit 83cf6cc
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 242 deletions.
45 changes: 24 additions & 21 deletions BotsApp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Boom } from '@hapi/boom'
import P, { Logger } from 'pino'
import makeWASocket, { AuthenticationCreds, AnyMessageContent, delay, DisconnectReason, fetchLatestBaileysVersion, makeInMemoryStore, useSingleFileAuthState, WASocket, GroupMetadata, proto } from '@adiwajshing/baileys'
import useRemoteFileAuthState from './core/dbAuth'
import makeWASocket, { MessageRetryMap, DisconnectReason, fetchLatestBaileysVersion, makeInMemoryStore, WASocket, proto } from '@adiwajshing/baileys'
// @ts-ignore
import useRemoteFileAuthState from './core/dbAuth.js'
import fs from 'fs'
import { join } from 'path'
import config from './config'
Expand All @@ -22,6 +23,7 @@ import { MessageType } from './sidekick/message-type'

const sequelize: Sequelize = config.DATABASE;
const GENERAL: any = STRINGS.general;
const msgRetryCounterMap: MessageRetryMap = { };
const logger: Logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` }).child({})
logger.level = 'error'

Expand Down Expand Up @@ -72,18 +74,21 @@ setInterval(() => {

let firstInit: boolean = true;

const { state, saveCreds } = await useRemoteFileAuthState(logger);

const startSock = async () => {
// @ts-ignore
const { state, saveCreds } = await useRemoteFileAuthState();
const { version, isLatest } = await fetchLatestBaileysVersion()
const sock: WASocket = makeWASocket({
version,
logger,
printQRInTerminal: true,
auth: state,
browser: ["BotsApp", "Chrome", "4.0.0"],
// version: [2, 2204, 13],
msgRetryCounterMap,
// implement to handle retries
getMessage: async key => {
return {
conversation: '-pls ignore-'
}
}
});
Expand Down Expand Up @@ -140,34 +145,32 @@ setInterval(() => {
if ((lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
startSock()
} else {
console.log('Connection closed. You are logged out.')
console.log(chalk.redBright('Connection closed. You are logged out. Delete the BotsApp.db and session.data.json files to rescan the code.'));
process.exit(0);
}
} else if (connection === 'connecting') {
console.log(chalk.yellowBright("[INFO] Connecting to WhatsApp..."));
} else if (connection === 'open') {
console.log(chalk.greenBright.bold("[INFO] Connected! Welcome to BotsApp"));
if (firstInit) {
firstInit = false;
sock.sendMessage(
sock.user.id,
{
text: format(GENERAL.SUCCESSFUL_CONNECTION, {
worktype: config.WORK_TYPE,
})
}
);
}
// if (firstInit) {
// firstInit = false;
// sock.sendMessage(
// sock.user.id,
// {
// text: format(GENERAL.SUCCESSFUL_CONNECTION, {
// worktype: config.WORK_TYPE,
// })
// }
// );
// }
} else {
console.log('connection update', update);
}
})

sock.ev.on('creds.update', (creds) => {
saveCreds(creds)
})
sock.ev.on('creds.update', saveCreds);

return sock
return sock;
}

startSock();
Expand Down
1 change: 1 addition & 0 deletions core/dbAuth.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

180 changes: 0 additions & 180 deletions core/dbAuth.ts

This file was deleted.

28 changes: 4 additions & 24 deletions database/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,13 @@ import { DataTypes, InferAttributes, Model, InferCreationAttributes, Sequelize }

const sequelize: Sequelize = config.DATABASE;

class Cred extends Model<InferAttributes<Cred>, InferCreationAttributes<Cred>> {
declare key: string;
declare value: string;
}

Cred.init({
key: {
type: DataTypes.STRING,
allowNull: false,
},
value: {
type: DataTypes.JSON,
}

}, { sequelize,
tableName: "Creds",
timestamps: false
}
);

class Key extends Model<InferAttributes<Key>, InferCreationAttributes<Key>> {
class Auth extends Model<InferAttributes<Auth>, InferCreationAttributes<Auth>> {
declare key: string;
declare value: string;
declare type: string;
}

Key.init({
Auth.init({
key: {
type: DataTypes.STRING(1000000),
allowNull: false,
Expand All @@ -42,9 +22,9 @@ Key.init({
}
}, {
sequelize,
tableName: "Keys",
tableName: "Authentication",
timestamps: false,
}
);

export {Cred, Key};
export {Auth};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"author": "Prince Mendiratta",
"license": "ISC",
"dependencies": {
"@adiwajshing/baileys": "^4.1.0",
"@adiwajshing/baileys": "^4.2.0",
"@adiwajshing/keyed-db": "^0.2.4",
"@nuintun/qrcode": "^3.0.1",
"@vitalets/google-translate-api": "^7.0.0",
Expand Down
6 changes: 4 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"allowSyntheticDefaultImports": true
"allowSyntheticDefaultImports": true,
"allowJs": true
},
"exclude": ["**/*.test.ts"]
"exclude": ["**/*.test.ts", "./dist/**/*"],

}
Loading

0 comments on commit 83cf6cc

Please sign in to comment.