Skip to content

Commit

Permalink
Fixed a bug
Browse files Browse the repository at this point in the history
  • Loading branch information
BochilGaming committed Dec 11, 2022
1 parent e6d5e83 commit e4151d3
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 250 deletions.
2 changes: 1 addition & 1 deletion handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import db, { loadDatabase } from './lib/database.js'
import Queque from './lib/queque.js'

/** @type {import('@adiwajshing/baileys')} */
const { getContentType, proto } = (await import('@adiwajshing/baileys')).default
const { getContentType } = (await import('@adiwajshing/baileys')).default

const isNumber = x => typeof x === 'number' && !isNaN(x)
/**
Expand Down
53 changes: 28 additions & 25 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import P from 'pino'
const {
DisconnectReason,
default: makeWASocket,
useMultiFileAuthState
// useSingleFileAuthState
} = (await import('@adiwajshing/baileys')).default

Expand All @@ -27,7 +28,7 @@ let [
] = await Promise.all([
Helper.checkFileExists(authFolder + '/creds.json'),
Helper.checkFileExists(authFile),
storeSystem.useMultiFileAuthState(authFolder)
useMultiFileAuthState(authFolder)
])

const store = storeSystem.makeInMemoryStore()
Expand All @@ -38,7 +39,7 @@ if (Helper.opts['singleauth'] || Helper.opts['singleauthstate']) {
console.debug('- singleauth -', 'creds.json not found', 'compiling singleauth to multiauth...')
await single2multi(authFile, authFolder, authState)
console.debug('- singleauth -', 'compiled successfully')
authState = await storeSystem.useMultiFileAuthState(authFolder)
authState = await useMultiFileAuthState(authFolder)
} else if (!isAuthSingleFileExist) console.error('- singleauth -', 'singleauth file not found')
}

Expand All @@ -63,7 +64,7 @@ const connectionOptions = {
* participantsUpdate?: typeof import('../handler').participantsUpdate;
* groupsUpdate?: typeof import('../handler').groupsUpdate;
* onDelete?:typeof import('../handler').deleteUpdate;
* connectionUpdate?: typeof connectionUpdate;
* connectionUpdate?: (update: import('@adiwajshing/baileys').BaileysEventMap<unknown>['connection.update']) => any;
* credsUpdate?: () => void
* }} EventHandlers
* @typedef {Required<import('@adiwajshing/baileys').UserFacingSocketConfig>['logger']} Logger
Expand All @@ -73,25 +74,30 @@ const connectionOptions = {
* msgqueque?: import('./queque').default;
* logger?: Logger
* }} Socket
* @typedef {{
* handler?: Promise<typeof import('../handler')> | typeof import('../handler');
* isChild?: boolean;
* connectionOptions?: Partial<import('@adiwajshing/baileys').UserFacingSocketConfig>;
* logger?: Logger;
* store: typeof store;
* authState: Awaited<ReturnType<typeof useMultiFileAuthState>>
* }} StartOptions
*/


/** @type {Map<string, Socket>} */
let conns = new Map();
/**
* @param {Socket?} oldSocket
* @param {{
* handler?: typeof import('../handler');
* isChild?: boolean;
* connectionOptions?: Partial<import('@adiwajshing/baileys').UserFacingSocketConfig>;
* store: typeof store
* }} opts
* @param {StartOptions} opts
*/
async function start(oldSocket = null, opts = { store }) {
async function start(oldSocket = null, opts = { store, logger, authState }) {
/** @type {Socket} */
let conn = makeWASocket({
...connectionOptions,
...opts.connectionOptions,
logger: opts.logger,
auth: opts.authState.state,
getMessage: async (key) => (
opts.store.loadMessage(/** @type {string} */(key.remoteJid), key.id) ||
opts.store.loadMessage(/** @type {string} */(key.id)) || {}
Expand Down Expand Up @@ -121,12 +127,9 @@ let OldHandler = null
/**
* @param {Socket} conn
* @param {boolean} restartConnection
* @param {{
* handler?: Promise<typeof import('../handler')> | typeof import('../handler');
* isChild?: boolean
* }} opts
* @param {StartOptions} opts
*/
async function reload(conn, restartConnection, opts = {}) {
async function reload(conn, restartConnection, opts = { store, authState }) {
if (!opts.handler) opts.handler = importFile(Helper.__filename(path.resolve('./handler.js'))).catch(console.error)
if (opts.handler instanceof Promise) opts.handler = await opts.handler;
if (!opts.handler && OldHandler) opts.handler = OldHandler
Expand All @@ -137,7 +140,7 @@ async function reload(conn, restartConnection, opts = {}) {
try { conn.ws.close() } catch { }
// @ts-ignore
conn.ev.removeAllListeners()
Object.assign(conn, await start(conn) || {})
Object.assign(conn, await start(conn, opts) || {})
}

// Assign message like welcome, bye, etc.. to the connection
Expand All @@ -157,9 +160,8 @@ async function reload(conn, restartConnection, opts = {}) {
conn.groupsUpdate = /** @type {typeof import('../handler')} */(opts.handler).groupsUpdate.bind(conn)
conn.onDelete = /** @type {typeof import('../handler')} */(opts.handler).deleteUpdate.bind(conn)
}
if (!opts.isChild) conn.connectionUpdate = connectionUpdate.bind(conn)
conn.credsUpdate = authState.saveCreds.bind(conn)
// conn.credsUpdate = authState.saveState.bind(conn)
if (!opts.isChild) conn.connectionUpdate = connectionUpdate.bind(conn, opts)
conn.credsUpdate = opts.authState.saveCreds.bind(conn)

/** @typedef {Required<EventHandlers>} Event */
conn.ev.on('messages.upsert', /** @type {Event} */(conn).handler)
Expand All @@ -176,16 +178,17 @@ async function reload(conn, restartConnection, opts = {}) {

/**
* @this {Socket}
* @param {StartOptions} opts
* @param {import('@adiwajshing/baileys').BaileysEventMap<unknown>['connection.update']} update
*/
async function connectionUpdate(update) {
console.log(update)
async function connectionUpdate(opts, update) {
opts.logger?.info(update)
const { connection, lastDisconnect, isNewLogin } = update
if (isNewLogin) this.isInit = true
// if (isNewLogin) this.isInit = true
// @ts-ignore
const code = lastDisconnect?.error?.output?.statusCode || lastDisconnect?.error?.output?.payload?.statusCode
if (code && code !== DisconnectReason.loggedOut && this?.ws.readyState !== ws.CONNECTING) {
console.log(await reload(this, true).catch(console.error))
console.log(await reload(this, true, opts).catch(console.error))
global.timestamp.connect = new Date
}
if (connection == 'open') console.log('- opened connection -')
Expand Down Expand Up @@ -215,8 +218,8 @@ function getMessageConfig() {
}
}

const conn = start(null, { store }).catch(console.error)

const conn = start(null, { store, logger, authState })
.catch(console.error)

export default {
start,
Expand Down
2 changes: 1 addition & 1 deletion lib/simple.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export function HelperConnection(conn, { store, logger }) {
trace: logger.trace?.bind(logger)
},
enumerable: true,
writable: false
writable: true
},
getFile: {
/**
Expand Down
153 changes: 6 additions & 147 deletions lib/store.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// @ts-check
import { readFileSync, writeFileSync, existsSync, promises } from 'fs'
import { join } from 'path'
import {
readFileSync,
writeFileSync,
existsSync
} from 'fs'

/** @type {typeof import('@adiwajshing/baileys')} */ // @ts-ignore
const {
Expand All @@ -12,8 +15,6 @@ const {
WAMessageStubType,
updateMessageWithReceipt,
updateMessageWithReaction,
// @ts-ignore
useMultiFileAuthState: baileysMultiFileAuthState
} = (await import('@adiwajshing/baileys')).default

const TIME_TO_DATA_STALE = 5 * 60 * 1000
Expand Down Expand Up @@ -384,151 +385,9 @@ function JSONreplacer(key, value) {

const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-')

/**
* @typedef {typeof baileysMultiFileAuthState} MultiFileAuthStateStore
*/
/** @type {MultiFileAuthStateStore} */
const useMultiFileAuthState = baileysMultiFileAuthState ||
/**
* Re implement useMultiFileAuthState if baileysMultiFileAuthState is undefined
* @type {MultiFileAuthStateStore}
*/
async function useMultiFileAuthState(folder) {

const writeData = (data, file) => {
return promises.writeFile(join(folder, fixFileName(file)), JSON.stringify(data, JSONreplacer))
}

const readData = async (file) => {
try {
const data = await promises.readFile(join(folder, fixFileName(file)), { encoding: 'utf-8' })
return JSON.parse(data, BufferJSON.reviver)
} catch (error) {
return null
}
}

const removeData = async (file) => {
try {
await promises.unlink(fixFileName(file))
} catch {

}
}

const folderInfo = await promises.stat(folder).catch(() => { })
if (folderInfo) {
if (!folderInfo.isDirectory()) {
throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
}
} else {
await promises.mkdir(folder, { recursive: true })
}

const creds = await readData('creds.json') || initAuthCreds()

return {
state: {
creds,
keys: {
// @ts-ignore
get: async (type, ids) => {
const data = {}
await Promise.all(
ids.map(
async id => {
let value = await readData(`${type}-${id}.json`)
if (type === 'app-state-sync-key') {
value = proto.AppStateSyncKeyData.fromObject(value)
}

data[id] = value
}
)
)

return data
},
set: async (data) => {
const tasks = []
for (const category in data) {
for (const id in data[category]) {
const value = data[category][id]
const file = `${category}-${id}.json`
tasks.push(value ? writeData(value, file) : removeData(file))
}
}

await Promise.all(tasks)
}
}
},
saveCreds: () => {
return writeData(creds, 'creds.json')
}
}
}

const KEY_MAP = {
'pre-key': 'preKeys',
'session': 'sessions',
'sender-key': 'senderKeys',
'app-state-sync-key': 'appStateSyncKeys',
'app-state-sync-version': 'appStateVersions',
'sender-key-memory': 'senderKeyMemory'
}

/**
*
* @returns {ReturnType<typeof import('@adiwajshing/baileys').useSingleFileAuthState>}
*/
const useMemoryAuthState = function useMemoryAuthState() {
const creds = initAuthCreds()
const keys = {}

const saveCreds = () => undefined
return {
state: {
creds,
keys: {
get: (type, ids) => {
const key = KEY_MAP[type]
return ids.reduce(
(dict, id) => {
// @ts-ignore
let value = keys[key]?.[id]
if (value) {
if (type === 'app-state-sync-key') {
value = proto.AppStateSyncKeyData.fromObject(value)
}

dict[id] = value
}

return dict
}, {}
)
},
set: (data) => {
for (const _key in data) {
const key = KEY_MAP[_key]
keys[key] = keys[key] || {}
Object.assign(keys[key], data[_key])
}
}
}
},
// @ts-ignore
saveCreds
}
}
export default {
makeInMemoryStore,
useMultiFileAuthState,
useMemoryAuthState,

fixFileName,
JSONreplacer,

KEY_MAP
JSONreplacer
}
Loading

1 comment on commit e4151d3

@Ftwrr
Copy link

@Ftwrr Ftwrr commented on e4151d3 Dec 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kenapa jadibot dihapus bang?

Please sign in to comment.