Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Master oficial save 16082024 #3

Merged
merged 10 commits into from
Aug 16, 2024
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
## 6.7.5 (2024-06-12)
## 6.7.6 (2024-08-14)


### Bug Fixes

* **master:** fix lockfile (after [#847](https://github.com/WhiskeySockets/Baileys/issues/847)) ([c964615](https://github.com/WhiskeySockets/Baileys/commit/c964615cf9b2eaaa6f72e2bd5fa660eb2ae9ab9b))
* remove 'none' from updateGroupsAddPrivacy ([#966](https://github.com/WhiskeySockets/Baileys/issues/966)) ([ffafc16](https://github.com/WhiskeySockets/Baileys/commit/ffafc167fb667713229467d2ad62a9444fddc6e3))



79 changes: 71 additions & 8 deletions Example/example.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
import { Boom } from '@hapi/boom'
import NodeCache from 'node-cache'
import readline from 'readline'
import makeWASocket, { AnyMessageContent, BinaryInfo, delay, DisconnectReason, encodeWAM, fetchLatestBaileysVersion, getAggregateVotesInPollMessage, makeCacheableSignalKeyStore, makeInMemoryStore, PHONENUMBER_MCC, proto, useMultiFileAuthState, WAMessageContent, WAMessageKey } from '../src'
import MAIN_LOGGER from '../src/Utils/logger'
import makeWASocket, { AnyMessageContent, BinaryInfo, delay, DisconnectReason, downloadAndProcessHistorySyncNotification, encodeWAM, fetchLatestBaileysVersion, getAggregateVotesInPollMessage, getHistoryMsg, isJidNewsletter, makeCacheableSignalKeyStore, makeInMemoryStore, PHONENUMBER_MCC, proto, useMultiFileAuthState, WAMessageContent, WAMessageKey } from '../src'
//import MAIN_LOGGER from '../src/Utils/logger'
import open from 'open'
import fs from 'fs'
import P from 'pino'

const logger = MAIN_LOGGER.child({})
const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` }, P.destination('./wa-logs.txt'))
logger.level = 'trace'

const useStore = !process.argv.includes('--no-store')
const doReplies = !process.argv.includes('--no-reply')
const doReplies = process.argv.includes('--do-reply')
const usePairingCode = process.argv.includes('--use-pairing-code')
const useMobile = process.argv.includes('--mobile')

// external map to store retry counts of messages when decryption/encryption fails
// keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts
const msgRetryCounterCache = new NodeCache()

const onDemandMap = new Map<string, string>()

// Read line interface
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
const question = (text: string) => new Promise<string>((resolve) => rl.question(text, resolve))
Expand Down Expand Up @@ -231,8 +234,11 @@ const startSock = async() => {

// history received
if(events['messaging-history.set']) {
const { chats, contacts, messages, isLatest } = events['messaging-history.set']
console.log(`recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest})`)
const { chats, contacts, messages, isLatest, progress, syncType } = events['messaging-history.set']
if (syncType === proto.HistorySync.HistorySyncType.ON_DEMAND) {
console.log('received on-demand history sync, messages=', messages)
}
console.log(`recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`)
}

// received a new message
Expand All @@ -241,8 +247,65 @@ const startSock = async() => {
console.log('recv messages ', JSON.stringify(upsert, undefined, 2))

if(upsert.type === 'notify') {
for(const msg of upsert.messages) {
if(!msg.key.fromMe && doReplies) {
for (const msg of upsert.messages) {
//TODO: More built-in implementation of this
/* if (
msg.message?.protocolMessage?.type ===
proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION
) {
const historySyncNotification = getHistoryMsg(msg.message)
if (
historySyncNotification?.syncType ==
proto.HistorySync.HistorySyncType.ON_DEMAND
) {
const { messages } =
await downloadAndProcessHistorySyncNotification(
historySyncNotification,
{}
)


const chatId = onDemandMap.get(
historySyncNotification!.peerDataRequestSessionId!
)

console.log(messages)

onDemandMap.delete(
historySyncNotification!.peerDataRequestSessionId!
)

/*
// 50 messages is the limit imposed by whatsapp
//TODO: Add ratelimit of 7200 seconds
//TODO: Max retries 10
const messageId = await sock.fetchMessageHistory(
50,
oldestMessageKey,
oldestMessageTimestamp
)
onDemandMap.set(messageId, chatId)
}
} */

if (msg.message?.conversation || msg.message?.extendedTextMessage?.text) {
const text = msg.message?.conversation || msg.message?.extendedTextMessage?.text
if (text == "requestPlaceholder" && !upsert.requestId) {
const messageId = await sock.requestPlaceholderResend(msg.key)
console.log('requested placeholder resync, id=', messageId)
} else if (upsert.requestId) {
console.log('Message received from phone, id=', upsert.requestId, msg)
}

// go to an old chat and send this
if (text == "onDemandHistSync") {
const messageId = await sock.fetchMessageHistory(50, msg.key, msg.messageTimestamp!)
console.log('requested on-demand sync, id=', messageId)
}
}

if(!msg.key.fromMe && doReplies && !isJidNewsletter(msg.key?.remoteJid!)) {

console.log('replying to', msg.key.remoteJid)
await sock!.readMessages([msg.key])
await sendMessageWTyping({ text: 'Hello there!' }, msg.key.remoteJid!)
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,7 @@ Of course, replace ``` xyz ``` with an actual ID.
```
- To update the Groups Add privacy
``` ts
const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
const value = 'all' // 'contacts' | 'contact_blacklist'
await sock.updateGroupsAddPrivacy(value)
```
- To update the Default Disappearing Mode
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "baileys",
"version": "6.7.6-d",
"version": "6.7.6",
"description": "WhatsApp API",
"keywords": [
"whatsapp",
Expand Down
4 changes: 3 additions & 1 deletion src/Defaults/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export const PROCESSABLE_HISTORY_TYPES = [
proto.Message.HistorySyncNotification.HistorySyncType.INITIAL_BOOTSTRAP,
proto.Message.HistorySyncNotification.HistorySyncType.PUSH_NAME,
proto.Message.HistorySyncNotification.HistorySyncType.RECENT,
proto.Message.HistorySyncNotification.HistorySyncType.FULL
proto.Message.HistorySyncNotification.HistorySyncType.FULL,
proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND,
]

export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
Expand Down Expand Up @@ -81,6 +82,7 @@ export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
snapshot: false,
},
getMessage: async() => undefined,
cachedGroupMetadata: async() => undefined,
makeSignalRepository: makeLibSignalRepository
}

Expand Down
17 changes: 14 additions & 3 deletions src/Socket/chats.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Boom } from '@hapi/boom'
import NodeCache from 'node-cache'
import { proto } from '../../WAProto'
import { PROCESSABLE_HISTORY_TYPES } from '../Defaults'
import { ALL_WA_PATCH_NAMES, ChatModification, ChatMutation, LTHashState, MessageUpsertType, PresenceData, SocketConfig, WABusinessHoursConfig, WABusinessProfile, WAMediaUpload, WAMessage, WAPatchCreate, WAPatchName, WAPresence, WAPrivacyCallValue, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '../Types'
import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults'
import { ALL_WA_PATCH_NAMES, ChatModification, ChatMutation, LTHashState, MessageUpsertType, PresenceData, SocketConfig, WABusinessHoursConfig, WABusinessProfile, WAMediaUpload, WAMessage, WAPatchCreate, WAPatchName, WAPresence, WAPrivacyCallValue, WAPrivacyGroupAddValue, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '../Types'
import { chatModificationToAppPatch, ChatMutationMap, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils'
import { makeMutex } from '../Utils/make-mutex'
import processMessage from '../Utils/process-message'
Expand Down Expand Up @@ -36,6 +37,15 @@ export const makeChatsSocket = (config: SocketConfig) => {
/** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
const processingMutex = makeMutex()

const placeholderResendCache = config.placeholderResendCache || new NodeCache({
stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
useClones: false
})

if(!config.placeholderResendCache) {
config.placeholderResendCache = placeholderResendCache
}

/** helper function to fetch the given app state sync key */
const getAppStateSyncKey = async(keyId: string) => {
const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
Expand Down Expand Up @@ -107,7 +117,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
await privacyQuery('readreceipts', value)
}

const updateGroupsAddPrivacy = async(value: WAPrivacyValue) => {
const updateGroupsAddPrivacy = async(value: WAPrivacyGroupAddValue) => {
await privacyQuery('groupadd', value)
}

Expand Down Expand Up @@ -876,6 +886,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
msg,
{
shouldProcessHistoryMsg,
placeholderResendCache,
ev,
creds: authState.creds,
keyStore: authState.keys,
Expand Down
14 changes: 13 additions & 1 deletion src/Socket/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
]
)
const node = getBinaryNodeChild(result, action)
const participantsAffected = getBinaryNodeChildren(node!, 'participant')
const participantsAffected = getBinaryNodeChildren(node, 'participant')
return participantsAffected.map(p => {
return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p }
})
Expand Down Expand Up @@ -232,6 +232,18 @@ export const makeGroupsSocket = (config: SocketConfig) => {
const result = getBinaryNodeChild(results, 'group')
return result?.attrs.jid
},

/**
* revoke a v4 invite for someone
* @param groupJid group jid
* @param invitedJid jid of person you invited
* @returns true if successful
*/
groupRevokeInviteV4: async(groupJid: string, invitedJid: string) => {
const result = await groupQuery(groupJid, 'set', [{ tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }])
return !!result
},

/**
* accept a GroupInviteMessage
* @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
Expand Down
Loading
Loading