@synacwave/baileys 0.0.0-stage → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ATTRIBUTION.md +14 -0
- package/CHANGELOG.md +47 -0
- package/LICENSE +23 -0
- package/README.md +299 -2
- package/WAProto/index.d.ts +15942 -0
- package/WAProto/index.js +115911 -0
- package/engine-requirements.js +13 -0
- package/lib/Defaults/index.d.ts +145 -0
- package/lib/Defaults/index.js +155 -0
- package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
- package/lib/Signal/Group/ciphertext-message.js +12 -0
- package/lib/Signal/Group/group-session-builder.d.ts +8 -0
- package/lib/Signal/Group/group-session-builder.js +30 -0
- package/lib/Signal/Group/group_cipher.d.ts +11 -0
- package/lib/Signal/Group/group_cipher.js +82 -0
- package/lib/Signal/Group/index.d.ts +12 -0
- package/lib/Signal/Group/index.js +12 -0
- package/lib/Signal/Group/keyhelper.d.ts +7 -0
- package/lib/Signal/Group/keyhelper.js +18 -0
- package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
- package/lib/Signal/Group/sender-chain-key.js +26 -0
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
- package/lib/Signal/Group/sender-key-message.d.ts +19 -0
- package/lib/Signal/Group/sender-key-message.js +66 -0
- package/lib/Signal/Group/sender-key-name.d.ts +12 -0
- package/lib/Signal/Group/sender-key-name.js +48 -0
- package/lib/Signal/Group/sender-key-record.d.ts +13 -0
- package/lib/Signal/Group/sender-key-record.js +41 -0
- package/lib/Signal/Group/sender-key-state.d.ts +17 -0
- package/lib/Signal/Group/sender-key-state.js +84 -0
- package/lib/Signal/Group/sender-message-key.d.ts +12 -0
- package/lib/Signal/Group/sender-message-key.js +26 -0
- package/lib/Signal/libsignal.d.ts +55 -0
- package/lib/Signal/libsignal.js +431 -0
- package/lib/Signal/lid-mapping.d.ts +21 -0
- package/lib/Signal/lid-mapping.js +277 -0
- package/lib/Socket/Client/index.d.ts +3 -0
- package/lib/Socket/Client/index.js +3 -0
- package/lib/Socket/Client/types.d.ts +6 -0
- package/lib/Socket/Client/types.js +11 -0
- package/lib/Socket/Client/websocket.d.ts +13 -0
- package/lib/Socket/Client/websocket.js +54 -0
- package/lib/Socket/business.d.ts +395 -0
- package/lib/Socket/business.js +380 -0
- package/lib/Socket/chats.d.ts +144 -0
- package/lib/Socket/chats.js +1219 -0
- package/lib/Socket/communities.d.ts +562 -0
- package/lib/Socket/communities.js +432 -0
- package/lib/Socket/groups.d.ts +286 -0
- package/lib/Socket/groups.js +348 -0
- package/lib/Socket/index.d.ts +531 -0
- package/lib/Socket/index.js +13 -0
- package/lib/Socket/messages-recv.d.ts +334 -0
- package/lib/Socket/messages-recv.js +1772 -0
- package/lib/Socket/messages-send.d.ts +330 -0
- package/lib/Socket/messages-send.js +1372 -0
- package/lib/Socket/mex.d.ts +2 -0
- package/lib/Socket/mex.js +42 -0
- package/lib/Socket/newsletter.d.ts +283 -0
- package/lib/Socket/newsletter.js +226 -0
- package/lib/Socket/socket.d.ts +61 -0
- package/lib/Socket/socket.js +970 -0
- package/lib/Store/index.d.ts +4 -0
- package/lib/Store/index.js +4 -0
- package/lib/Store/make-in-memory-store.d.ts +63 -0
- package/lib/Store/make-in-memory-store.js +421 -0
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/make-ordered-dictionary.js +79 -0
- package/lib/Store/object-repository.d.ts +11 -0
- package/lib/Store/object-repository.js +24 -0
- package/lib/Types/Auth.d.ts +2 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Bussines.d.ts +2 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.d.ts +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.d.ts +2 -0
- package/lib/Types/Chat.js +8 -0
- package/lib/Types/Contact.d.ts +2 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.d.ts +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.d.ts +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.d.ts +3 -0
- package/lib/Types/Label.js +25 -0
- package/lib/Types/LabelAssociation.d.ts +3 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/Message.d.ts +12 -0
- package/lib/Types/Message.js +18 -0
- package/lib/Types/Mex.d.ts +3 -0
- package/lib/Types/Mex.js +39 -0
- package/lib/Types/Product.d.ts +2 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/RichType.d.ts +3 -0
- package/lib/Types/RichType.js +23 -0
- package/lib/Types/Signal.d.ts +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.d.ts +2 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.d.ts +6 -0
- package/lib/Types/State.js +56 -0
- package/lib/Types/USync.d.ts +2 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.d.ts +14 -0
- package/lib/Types/index.js +26 -0
- package/lib/Utils/api-wrappers.d.ts +70 -0
- package/lib/Utils/api-wrappers.js +248 -0
- package/lib/Utils/auth-utils.d.ts +58 -0
- package/lib/Utils/auth-utils.js +306 -0
- package/lib/Utils/browser-utils.d.ts +10 -0
- package/lib/Utils/browser-utils.js +29 -0
- package/lib/Utils/business.d.ts +50 -0
- package/lib/Utils/business.js +231 -0
- package/lib/Utils/chat-utils.d.ts +409 -0
- package/lib/Utils/chat-utils.js +886 -0
- package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
- package/lib/Utils/companion-reg-client-utils.js +40 -0
- package/lib/Utils/crypto.d.ts +40 -0
- package/lib/Utils/crypto.js +118 -0
- package/lib/Utils/decode-wa-message.d.ts +84 -0
- package/lib/Utils/decode-wa-message.js +317 -0
- package/lib/Utils/event-buffer.d.ts +13 -0
- package/lib/Utils/event-buffer.js +622 -0
- package/lib/Utils/generics.d.ts +64 -0
- package/lib/Utils/generics.js +395 -0
- package/lib/Utils/history.d.ts +76 -0
- package/lib/Utils/history.js +134 -0
- package/lib/Utils/identity-change-handler.d.ts +14 -0
- package/lib/Utils/identity-change-handler.js +50 -0
- package/lib/Utils/index.d.ts +28 -0
- package/lib/Utils/index.js +30 -0
- package/lib/Utils/link-preview.d.ts +13 -0
- package/lib/Utils/link-preview.js +85 -0
- package/lib/Utils/logger.d.ts +3 -0
- package/lib/Utils/logger.js +3 -0
- package/lib/Utils/lt-hash.d.ts +7 -0
- package/lib/Utils/lt-hash.js +8 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +33 -0
- package/lib/Utils/message-retry-manager.d.ts +80 -0
- package/lib/Utils/message-retry-manager.js +265 -0
- package/lib/Utils/messages-media.d.ts +137 -0
- package/lib/Utils/messages-media.js +843 -0
- package/lib/Utils/messages.d.ts +46 -0
- package/lib/Utils/messages.js +1848 -0
- package/lib/Utils/noise-handler.d.ts +21 -0
- package/lib/Utils/noise-handler.js +201 -0
- package/lib/Utils/offline-node-processor.d.ts +10 -0
- package/lib/Utils/offline-node-processor.js +40 -0
- package/lib/Utils/pre-key-manager.d.ts +26 -0
- package/lib/Utils/pre-key-manager.js +106 -0
- package/lib/Utils/process-message.d.ts +84 -0
- package/lib/Utils/process-message.js +749 -0
- package/lib/Utils/reporting-utils.d.ts +13 -0
- package/lib/Utils/reporting-utils.js +258 -0
- package/lib/Utils/rich-message-utils.d.ts +49 -0
- package/lib/Utils/rich-message-utils.js +363 -0
- package/lib/Utils/signal.d.ts +83 -0
- package/lib/Utils/signal.js +201 -0
- package/lib/Utils/stanza-ack.d.ts +17 -0
- package/lib/Utils/stanza-ack.js +38 -0
- package/lib/Utils/status-utils.js +178 -0
- package/lib/Utils/sticker-reaction.js +104 -0
- package/lib/Utils/synacwave.d.ts +111 -0
- package/lib/Utils/synacwave.js +564 -0
- package/lib/Utils/sync-action-utils.d.ts +3 -0
- package/lib/Utils/sync-action-utils.js +49 -0
- package/lib/Utils/tc-token-utils.d.ts +30 -0
- package/lib/Utils/tc-token-utils.js +164 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
- package/lib/Utils/use-multi-file-auth-state.js +121 -0
- package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
- package/lib/Utils/use-single-file-auth-state.js +109 -0
- package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
- package/lib/Utils/use-sqlite-auth-state.js +109 -0
- package/lib/Utils/validate-connection.d.ts +44 -0
- package/lib/Utils/validate-connection.js +210 -0
- package/lib/Utils/view-once-text.d.ts +32 -0
- package/lib/Utils/view-once-text.js +213 -0
- package/lib/WABinary/constants.d.ts +62 -0
- package/lib/WABinary/constants.js +1467 -0
- package/lib/WABinary/decode.d.ts +10 -0
- package/lib/WABinary/decode.js +262 -0
- package/lib/WABinary/encode.d.ts +3 -0
- package/lib/WABinary/encode.js +220 -0
- package/lib/WABinary/generic-utils.d.ts +77 -0
- package/lib/WABinary/generic-utils.js +226 -0
- package/lib/WABinary/index.d.ts +6 -0
- package/lib/WABinary/index.js +6 -0
- package/lib/WABinary/jid-utils.d.ts +29 -0
- package/lib/WABinary/jid-utils.js +96 -0
- package/lib/WABinary/types.d.ts +2 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +8 -0
- package/lib/WAM/BinaryInfo.js +10 -0
- package/lib/WAM/constants.d.ts +34927 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/encode.d.ts +2 -0
- package/lib/WAM/encode.js +150 -0
- package/lib/WAM/index.d.ts +4 -0
- package/lib/WAM/index.js +4 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
- package/lib/WAUSync/Protocols/index.d.ts +6 -0
- package/lib/WAUSync/Protocols/index.js +6 -0
- package/lib/WAUSync/USyncQuery.d.ts +21 -0
- package/lib/WAUSync/USyncQuery.js +98 -0
- package/lib/WAUSync/USyncUser.d.ts +17 -0
- package/lib/WAUSync/USyncUser.js +31 -0
- package/lib/WAUSync/index.d.ts +4 -0
- package/lib/WAUSync/index.js +4 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +12 -0
- package/package.json +118 -5
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { proto } from '../../WAProto/index.js';
|
|
2
|
+
import type { ViewOnceTextOptions, ViewOnceTextResult } from './view-once-text.js';
|
|
3
|
+
import type { ApiWrapperMethods } from './api-wrappers.js';
|
|
4
|
+
|
|
5
|
+
export type MediaInput = Buffer | string | { url: string };
|
|
6
|
+
|
|
7
|
+
export interface ChatThemeOptions {
|
|
8
|
+
/** Colour name from CHAT_THEME_COLORS, a preset key, or hex (RRGGBB / #RRGGBB / RRGGBBAA). */
|
|
9
|
+
color?: string;
|
|
10
|
+
/** Bubble scheme id (e.g. 'Emerald@Minimal') or a preset key (e.g. 'blue'). */
|
|
11
|
+
scheme?: string;
|
|
12
|
+
stockImageId?: string;
|
|
13
|
+
clear?: boolean;
|
|
14
|
+
wallpaper?: WallpaperMedia;
|
|
15
|
+
dimLevel?: number;
|
|
16
|
+
timestampMs?: number;
|
|
17
|
+
}
|
|
18
|
+
export interface WallpaperMedia {
|
|
19
|
+
directPath: string;
|
|
20
|
+
mediaKey: Uint8Array;
|
|
21
|
+
fileEncSha256: Uint8Array;
|
|
22
|
+
fileSha256: Uint8Array;
|
|
23
|
+
}
|
|
24
|
+
export interface ChatThemeResult { id: string; setting: proto.Message.IChatThemeSetting }
|
|
25
|
+
export interface SoundStickerInput {
|
|
26
|
+
sticker: MediaInput;
|
|
27
|
+
/** Ogg/Opus audio when mimetype contains "opus" */
|
|
28
|
+
audio: MediaInput;
|
|
29
|
+
mimetype?: string;
|
|
30
|
+
seconds?: number;
|
|
31
|
+
isAnimated?: boolean;
|
|
32
|
+
}
|
|
33
|
+
export interface MessageContext {
|
|
34
|
+
id?: string | null;
|
|
35
|
+
chat?: string | null;
|
|
36
|
+
sender?: string | null;
|
|
37
|
+
fromMe: boolean;
|
|
38
|
+
isGroup: boolean;
|
|
39
|
+
type?: string;
|
|
40
|
+
text: string;
|
|
41
|
+
mentions: string[];
|
|
42
|
+
isReply: boolean;
|
|
43
|
+
quoted: proto.IWebMessageInfo | { key: any; message: proto.IMessage } | null;
|
|
44
|
+
quotedText: string;
|
|
45
|
+
isMedia: boolean;
|
|
46
|
+
isViewOnce: boolean;
|
|
47
|
+
raw: proto.IWebMessageInfo;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export declare const MAX_REMOTE_MEDIA_BYTES: number;
|
|
51
|
+
export declare const CHAT_THEME_COLORS: Record<string, string>;
|
|
52
|
+
export declare const CHAT_BUBBLE_SCHEMES: Record<string, string>;
|
|
53
|
+
export declare const CHAT_THEME_PRESETS: Record<string, { scheme: string; bgLight: number; bgDark: number; doodleLight: number; doodleDark: number }>;
|
|
54
|
+
export declare const parseThemeColor: (input: string) => number | null;
|
|
55
|
+
export declare const buildChatThemeSetting: (opts?: ChatThemeOptions) => proto.Message.IChatThemeSetting;
|
|
56
|
+
export declare const verifyChatThemeEncoding: (setting: proto.Message.IChatThemeSetting) => { bytes: Uint8Array; decoded: proto.Message.IChatThemeSetting };
|
|
57
|
+
export declare const uploadChatWallpaper: (sock: any, image: Buffer, opts?: { logger?: any }) => Promise<WallpaperMedia>;
|
|
58
|
+
export declare const isAnimatedWebP: (buf: Buffer) => boolean;
|
|
59
|
+
export declare const isOggOpus: (buf: Buffer) => boolean;
|
|
60
|
+
export declare const verifySoundStickerWire: (message: proto.IMessage) => { bytes: Buffer; audioBytes: Buffer };
|
|
61
|
+
export declare const downloadRemoteMedia: (url: string, opts?: { maxBytes?: number; timeoutMs?: number; maxRedirects?: number }) => Promise<Buffer>;
|
|
62
|
+
export declare const getMessageType: (msg: any) => string | undefined;
|
|
63
|
+
export declare const getMessageText: (msg: any) => string;
|
|
64
|
+
export declare const getMentions: (msg: any) => string[];
|
|
65
|
+
export declare const getQuotedMessage: (msg: any) => { key: any; message: proto.IMessage } | null;
|
|
66
|
+
export declare const isViewOnce: (msg: any) => boolean;
|
|
67
|
+
export declare const isMediaMessage: (msg: any) => boolean;
|
|
68
|
+
export declare const buildMessageContext: (msg: proto.IWebMessageInfo, selfJid?: string) => MessageContext;
|
|
69
|
+
export declare const META_AI_JIDS: string[];
|
|
70
|
+
export declare const isMetaAiParticipant: (p: any) => boolean;
|
|
71
|
+
export declare const formatMention: (jid: string) => string;
|
|
72
|
+
|
|
73
|
+
export interface SynacwaveSocketExtensions extends ApiWrapperMethods {
|
|
74
|
+
sendViewOnceText(jid: string, text: string, options?: ViewOnceTextOptions): Promise<ViewOnceTextResult>;
|
|
75
|
+
sendViewOnceTextMessage(jid: string, text: string, options?: ViewOnceTextOptions): Promise<ViewOnceTextResult>;
|
|
76
|
+
sendVotext(jid: string, text: string, options?: ViewOnceTextOptions): Promise<ViewOnceTextResult>;
|
|
77
|
+
/** `current` is the favorites list you already know; WhatsApp syncs it as one value. */
|
|
78
|
+
addToFavorites(jids: string | string[], opts?: { current?: string[] }): Promise<void>;
|
|
79
|
+
removeFromFavorites(jids: string | string[], opts?: { current?: string[] }): Promise<void>;
|
|
80
|
+
sendSoundSticker(jid: string, input: SoundStickerInput, options?: { quoted?: proto.IWebMessageInfo; messageId?: string }): Promise<proto.IWebMessageInfo>;
|
|
81
|
+
/** colour / scheme string, wallpaper Buffer or URL, null to clear, or an options object */
|
|
82
|
+
setChatTheme(jid: string, value: string | Buffer | null | ChatThemeOptions): Promise<ChatThemeResult>;
|
|
83
|
+
setChatThemeColor(jid: string, color: string): Promise<ChatThemeResult>;
|
|
84
|
+
setChatBubbleScheme(jid: string, scheme: string): Promise<ChatThemeResult>;
|
|
85
|
+
setChatWallpaper(jid: string, image: MediaInput): Promise<ChatThemeResult>;
|
|
86
|
+
clearChatTheme(jid: string): Promise<ChatThemeResult>;
|
|
87
|
+
getChatThemeDiagnostics(): { encoderOk: boolean; error: string | null; type: string | null; wallpaperMediaMapped: boolean; note: string };
|
|
88
|
+
getMessageContext(msg: proto.IWebMessageInfo): Promise<MessageContext>;
|
|
89
|
+
getQuotedMessage: typeof getQuotedMessage;
|
|
90
|
+
getMessageText: typeof getMessageText;
|
|
91
|
+
getMessageType: typeof getMessageType;
|
|
92
|
+
getMentions: typeof getMentions;
|
|
93
|
+
isViewOnce: typeof isViewOnce;
|
|
94
|
+
getMediaBuffer(msg: proto.IWebMessageInfo, opts?: { maxBytes?: number }): Promise<Buffer>;
|
|
95
|
+
getBotJid(): string | undefined;
|
|
96
|
+
isFromBot(msg: proto.IWebMessageInfo): boolean;
|
|
97
|
+
isGroupAdmin(groupJid: string, jid: string): Promise<boolean>;
|
|
98
|
+
formatMention: typeof formatMention;
|
|
99
|
+
reply(msg: proto.IWebMessageInfo, text: string, options?: any): Promise<any>;
|
|
100
|
+
sendText(jid: string, text: string, options?: any): Promise<any>;
|
|
101
|
+
sendReact(msg: proto.IWebMessageInfo, emoji: string): Promise<any>;
|
|
102
|
+
sendImage(jid: string, image: MediaInput, caption?: string, options?: any): Promise<any>;
|
|
103
|
+
sendVideo(jid: string, video: MediaInput, caption?: string, options?: any): Promise<any>;
|
|
104
|
+
sendAudio(jid: string, audio: MediaInput, options?: { mimetype?: string; ptt?: boolean }): Promise<any>;
|
|
105
|
+
sendSticker(jid: string, sticker: MediaInput, options?: any): Promise<any>;
|
|
106
|
+
sendPremiumSticker(jid: string, sticker: MediaInput, options?: any): Promise<any>;
|
|
107
|
+
hasMetaAI(groupJid: string): Promise<boolean>;
|
|
108
|
+
addMetaAI(groupJid: string): Promise<{ ok: boolean; jid?: string; attempts: { jid: string; status?: string; error?: string }[] }>;
|
|
109
|
+
removeMetaAI(groupJid: string): Promise<{ ok: boolean; jid?: string; attempts: { jid: string; status?: string; error?: string }[] }>;
|
|
110
|
+
}
|
|
111
|
+
export declare const extendSocket: <T extends object>(sock: T, config?: any) => T & SynacwaveSocketExtensions;
|
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
import { lookup } from 'dns/promises';
|
|
2
|
+
import { promises as fs } from 'fs';
|
|
3
|
+
import { isIP } from 'net';
|
|
4
|
+
import { Boom } from '@hapi/boom';
|
|
5
|
+
import { proto } from '../../WAProto/index.js';
|
|
6
|
+
import { jidNormalizedUser, areJidsSameUser, isJidGroup } from '../WABinary/index.js';
|
|
7
|
+
import { encryptedStream } from './messages-media.js';
|
|
8
|
+
import { generateMessageIDV2 } from './generics.js';
|
|
9
|
+
import { createApiWrappers } from './api-wrappers.js';
|
|
10
|
+
import { sendViewOnceTextWithSocket } from './view-once-text.js';
|
|
11
|
+
import { sendGroupStatusMessage, sendGroupStatusMessageClosefriends, sendStatus, buildGroupStatusContextInfo, STATUS_RING_PALETTE } from './status-utils.js';
|
|
12
|
+
import { sendStickerReaction, buildStickerReactionPayload, extractStickerMessage, isStickerReactionMessage, ASSOCIATION_TYPE_STICKER_REACTION } from './sticker-reaction.js';
|
|
13
|
+
import { generateWAMessageFromContent, getContentType, normalizeMessageContent, prepareWAMessageMedia, downloadMediaMessage } from './messages.js';
|
|
14
|
+
|
|
15
|
+
export const MAX_REMOTE_MEDIA_BYTES = 16 * 1024 * 1024;
|
|
16
|
+
|
|
17
|
+
export const CHAT_THEME_COLORS = {
|
|
18
|
+
red: 'FF0000', green: '00FF00', blue: '0000FF', yellow: 'FFFF00',
|
|
19
|
+
orange: 'FF8000', pink: 'FF69B4', purple: '800080', black: '000000',
|
|
20
|
+
white: 'FFFFFF', brown: 'A52A2A', grey: '808080', gray: '808080',
|
|
21
|
+
cyan: '00FFFF', lime: '00FF00', gold: 'FFD700', silver: 'C0C0C0',
|
|
22
|
+
maroon: '800000', navy: '000080', teal: '008080', magenta: 'FF00FF',
|
|
23
|
+
violet: '8A2BE2', indigo: '4B0082', peach: 'FFDAB9', sky: '87CEEB',
|
|
24
|
+
mint: '98FF98', coral: 'FF7F50', lavender: 'E6E6FA', crimson: 'DC143C',
|
|
25
|
+
turquoise: '40E0D0'
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const CHAT_BUBBLE_SCHEMES = {
|
|
29
|
+
blue: 'Default-Blue@Minimal',
|
|
30
|
+
tonal: 'Default-Blue@Tonal@Minimal',
|
|
31
|
+
emerald: 'Emerald@Minimal',
|
|
32
|
+
emeraldtonal: 'Emerald@Tonal@Minimal',
|
|
33
|
+
pink: 'Pink@Minimal',
|
|
34
|
+
red: 'Red@Minimal',
|
|
35
|
+
royal: 'Royal-Blue@Minimal',
|
|
36
|
+
purple: 'Tyrian-Purple@Minimal',
|
|
37
|
+
green: 'WhatsApp-Green@Minimal'
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const preset = (scheme, bgLight, bgDark, doodleLight, doodleDark) => ({ scheme, bgLight, bgDark, doodleLight, doodleDark });
|
|
41
|
+
export const CHAT_THEME_PRESETS = {
|
|
42
|
+
blue: preset(CHAT_BUBBLE_SCHEMES.blue, 0xffe7f3fb, 0xff0b141a, 0xff7ec8e3, 0xff4a9fd8),
|
|
43
|
+
tonal: preset(CHAT_BUBBLE_SCHEMES.tonal, 0xffe7f3fb, 0xff0b141a, 0xff7ec8e3, 0xff4a9fd8),
|
|
44
|
+
emerald: preset(CHAT_BUBBLE_SCHEMES.emerald, 0xffe8f8ef, 0xff0b1a12, 0xff6bcf9b, 0xff3d9b6e),
|
|
45
|
+
emeraldtonal: preset(CHAT_BUBBLE_SCHEMES.emeraldtonal, 0xffe8f8ef, 0xff0b1a12, 0xff6bcf9b, 0xff3d9b6e),
|
|
46
|
+
pink: preset(CHAT_BUBBLE_SCHEMES.pink, 0xfffff0f5, 0xff1a0b12, 0xfff48fb1, 0xffe91e8c),
|
|
47
|
+
red: preset(CHAT_BUBBLE_SCHEMES.red, 0xffffebee, 0xff1a0b0b, 0xffef9a9a, 0xffe53935),
|
|
48
|
+
royal: preset(CHAT_BUBBLE_SCHEMES.royal, 0xffe8eeff, 0xff0b0f1a, 0xff90caf9, 0xff3f51b5),
|
|
49
|
+
purple: preset(CHAT_BUBBLE_SCHEMES.purple, 0xfff3e5f5, 0xff120b1a, 0xffce93d8, 0xff9c27b0),
|
|
50
|
+
green: preset(CHAT_BUBBLE_SCHEMES.green, 0xffe8f5e9, 0xff0b1a0f, 0xffa5d6a7, 0xff25d366)
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export const parseThemeColor = (input) => {
|
|
54
|
+
const raw = String(input ?? '').trim().toLowerCase();
|
|
55
|
+
if (CHAT_THEME_COLORS[raw]) {
|
|
56
|
+
return parseInt(CHAT_THEME_COLORS[raw], 16);
|
|
57
|
+
}
|
|
58
|
+
const hex = raw.replace(/^#/, '');
|
|
59
|
+
if (/^[0-9a-f]{6}([0-9a-f]{2})?$/.test(hex)) {
|
|
60
|
+
return parseInt(hex.slice(0, 6), 16);
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const argb = (rgb) => (0xff000000 | rgb) >>> 0;
|
|
66
|
+
const darken = (rgb, k = 0.35) => {
|
|
67
|
+
const r = Math.round(((rgb >> 16) & 255) * k);
|
|
68
|
+
const g = Math.round(((rgb >> 8) & 255) * k);
|
|
69
|
+
const b = Math.round((rgb & 255) * k);
|
|
70
|
+
return argb((r << 16) | (g << 8) | b);
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export const buildChatThemeSetting = (opts = {}) => {
|
|
74
|
+
const settingTimestampMs = opts.timestampMs ?? Date.now();
|
|
75
|
+
if (opts.clear) {
|
|
76
|
+
return { settingTimestampMs, clearTheme: true };
|
|
77
|
+
}
|
|
78
|
+
if (opts.wallpaper) {
|
|
79
|
+
const w = opts.wallpaper;
|
|
80
|
+
for (const k of ['directPath', 'mediaKey', 'fileEncSha256', 'fileSha256']) {
|
|
81
|
+
if (!w[k]) {
|
|
82
|
+
throw new Boom(`wallpaper media descriptor is missing ${k}`, { statusCode: 400 });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { settingTimestampMs, customImage: { directPath: w.directPath, mediaKey: w.mediaKey, fileEncSha256: w.fileEncSha256, fileSha256: w.fileSha256, dimLevel: opts.dimLevel ?? 0 } };
|
|
86
|
+
}
|
|
87
|
+
if (opts.stockImageId) {
|
|
88
|
+
return { settingTimestampMs, stockImage: { stockImageId: opts.stockImageId, dimLevel: opts.dimLevel ?? 0 } };
|
|
89
|
+
}
|
|
90
|
+
if (opts.scheme) {
|
|
91
|
+
const key = String(opts.scheme).trim().toLowerCase().replace(/[\s_-]+/g, '');
|
|
92
|
+
const p = CHAT_THEME_PRESETS[key] || Object.values(CHAT_THEME_PRESETS).find(v => v.scheme === opts.scheme);
|
|
93
|
+
const base = p || { scheme: opts.scheme, bgLight: 0xffe8f4fd, bgDark: 0xff0b141a, doodleLight: 0xff7ec8e3, doodleDark: 0xff4a9fd8 };
|
|
94
|
+
return {
|
|
95
|
+
settingTimestampMs,
|
|
96
|
+
colorSchemeId: base.scheme,
|
|
97
|
+
solidColor: { backgroundLightArgb: base.bgLight >>> 0, backgroundDarkArgb: base.bgDark >>> 0, isDoodleEnabled: true, doodleLightArgb: base.doodleLight >>> 0, doodleDarkArgb: base.doodleDark >>> 0 }
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (opts.color) {
|
|
101
|
+
const key = String(opts.color).trim().toLowerCase().replace(/[\s_-]+/g, '');
|
|
102
|
+
if (CHAT_THEME_PRESETS[key]) {
|
|
103
|
+
return buildChatThemeSetting({ scheme: key, timestampMs: settingTimestampMs });
|
|
104
|
+
}
|
|
105
|
+
const rgb = parseThemeColor(opts.color);
|
|
106
|
+
if (rgb == null) {
|
|
107
|
+
throw new Boom(`Invalid theme colour: ${opts.color}`, { statusCode: 400 });
|
|
108
|
+
}
|
|
109
|
+
const light = argb(rgb);
|
|
110
|
+
const dark = darken(rgb);
|
|
111
|
+
return { settingTimestampMs, solidColor: { backgroundLightArgb: light, backgroundDarkArgb: dark, isDoodleEnabled: true, doodleLightArgb: light, doodleDarkArgb: dark } };
|
|
112
|
+
}
|
|
113
|
+
throw new Boom('buildChatThemeSetting needs one of: color, scheme, wallpaper, stockImageId, clear', { statusCode: 400 });
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
export const verifyChatThemeEncoding = (setting) => {
|
|
117
|
+
const content = { protocolMessage: { type: 34, chatThemeSetting: setting } };
|
|
118
|
+
const bytes = proto.Message.encode(proto.Message.fromObject(content)).finish();
|
|
119
|
+
const back = proto.Message.decode(bytes);
|
|
120
|
+
const pm = back.protocolMessage;
|
|
121
|
+
if (!pm || pm.type !== 34 || !pm.chatThemeSetting) {
|
|
122
|
+
throw new Boom('chatThemeSetting did not survive protobuf encoding', { statusCode: 500 });
|
|
123
|
+
}
|
|
124
|
+
return { bytes, decoded: pm.chatThemeSetting };
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
export const uploadChatWallpaper = async (sock, image, { logger } = {}) => {
|
|
128
|
+
if (typeof sock.waUploadToServer !== 'function') {
|
|
129
|
+
throw new Boom('waUploadToServer is not available on this socket', { statusCode: 500 });
|
|
130
|
+
}
|
|
131
|
+
const media = Buffer.isBuffer(image) ? image : image;
|
|
132
|
+
const enc = await encryptedStream(media, 'chat-wallpaper-image', { logger: logger || sock.logger });
|
|
133
|
+
try {
|
|
134
|
+
const uploaded = await sock.waUploadToServer(enc.encFilePath, { mediaType: 'chat-wallpaper-image', fileEncSha256B64: enc.fileEncSha256.toString('base64') });
|
|
135
|
+
if (!uploaded?.directPath) {
|
|
136
|
+
throw new Boom('Wallpaper upload returned no directPath', { statusCode: 502 });
|
|
137
|
+
}
|
|
138
|
+
return { directPath: uploaded.directPath, mediaKey: enc.mediaKey, fileEncSha256: enc.fileEncSha256, fileSha256: enc.fileSha256 };
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
await fs.unlink(enc.encFilePath).catch(() => { });
|
|
142
|
+
if (enc.originalFilePath) {
|
|
143
|
+
await fs.unlink(enc.originalFilePath).catch(() => { });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
export const isAnimatedWebP = (buf) => {
|
|
149
|
+
if (!Buffer.isBuffer(buf) || buf.length < 21) {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WEBP') {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
if (buf.toString('ascii', 12, 16) === 'VP8X') {
|
|
156
|
+
return (buf[20] & 0x02) !== 0;
|
|
157
|
+
}
|
|
158
|
+
return buf.includes(Buffer.from('ANIM'));
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
export const isOggOpus = (buf) => Buffer.isBuffer(buf) && buf.length > 36 && buf.toString('ascii', 0, 4) === 'OggS' && buf.includes(Buffer.from('OpusHead'));
|
|
162
|
+
|
|
163
|
+
const readFields = (buf) => {
|
|
164
|
+
const out = [];
|
|
165
|
+
let pos = 0;
|
|
166
|
+
const varint = () => { let v = 0, shift = 0, b; do { b = buf[pos++]; v += (b & 0x7f) * 2 ** shift; shift += 7; } while (b & 0x80 && pos < buf.length); return v; };
|
|
167
|
+
while (pos < buf.length) {
|
|
168
|
+
const tag = varint();
|
|
169
|
+
const field = Math.floor(tag / 8), wire = tag & 7;
|
|
170
|
+
let start = pos, end;
|
|
171
|
+
if (wire === 0) { varint(); end = pos; }
|
|
172
|
+
else if (wire === 1) { pos += 8; end = pos; }
|
|
173
|
+
else if (wire === 2) { const len = varint(); start = pos; pos += len; end = pos; }
|
|
174
|
+
else if (wire === 5) { pos += 4; end = pos; }
|
|
175
|
+
else { throw new Boom(`unsupported wire type ${wire}`); }
|
|
176
|
+
out.push({ field, wire, start, end });
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export const verifySoundStickerWire = (message) => {
|
|
182
|
+
const bytes = Buffer.from(proto.Message.encode(proto.Message.fromObject(message)).finish());
|
|
183
|
+
const decoded = proto.Message.decode(bytes);
|
|
184
|
+
if (!decoded.stickerMessage?.audioMessage) {
|
|
185
|
+
throw new Boom('audioMessage was dropped during StickerMessage encoding', { statusCode: 500 });
|
|
186
|
+
}
|
|
187
|
+
const stickerBytes = Buffer.from(proto.Message.StickerMessage.encode(proto.Message.StickerMessage.fromObject(message.stickerMessage)).finish());
|
|
188
|
+
const audioField = readFields(stickerBytes).find(f => f.field === 26 && f.wire === 2);
|
|
189
|
+
if (!audioField) {
|
|
190
|
+
throw new Boom('StickerMessage field 26 missing on the wire', { statusCode: 500 });
|
|
191
|
+
}
|
|
192
|
+
return { bytes, audioBytes: stickerBytes.subarray(audioField.start, audioField.end) };
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const isPrivateAddress = (addr) => {
|
|
196
|
+
if (isIP(addr) === 6) {
|
|
197
|
+
const a = addr.toLowerCase();
|
|
198
|
+
return a === '::1' || a === '::' || a.startsWith('fc') || a.startsWith('fd') || a.startsWith('fe80') || (a.startsWith('::ffff:') && isPrivateAddress(a.slice(7)));
|
|
199
|
+
}
|
|
200
|
+
const p = addr.split('.').map(Number);
|
|
201
|
+
if (p.length !== 4 || p.some(n => Number.isNaN(n))) {
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
const [a, b] = p;
|
|
205
|
+
return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
export const downloadRemoteMedia = async (url, { maxBytes = MAX_REMOTE_MEDIA_BYTES, timeoutMs = 20000, maxRedirects = 3 } = {}) => {
|
|
209
|
+
let current = new URL(url);
|
|
210
|
+
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
211
|
+
if (!['http:', 'https:'].includes(current.protocol)) {
|
|
212
|
+
throw new Boom('Only http(s) URLs are allowed', { statusCode: 400 });
|
|
213
|
+
}
|
|
214
|
+
const host = current.hostname.replace(/^\[|\]$/g, '');
|
|
215
|
+
const addrs = isIP(host) ? [{ address: host }] : await lookup(host, { all: true });
|
|
216
|
+
if (!addrs.length || addrs.some(a => isPrivateAddress(a.address))) {
|
|
217
|
+
throw new Boom('Blocked host (private or unresolved address)', { statusCode: 400 });
|
|
218
|
+
}
|
|
219
|
+
const res = await fetch(current, { redirect: 'manual', signal: AbortSignal.timeout(timeoutMs) });
|
|
220
|
+
if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
|
|
221
|
+
current = new URL(res.headers.get('location'), current);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (!res.ok) {
|
|
225
|
+
throw new Boom(`Download failed with status ${res.status}`, { statusCode: 502 });
|
|
226
|
+
}
|
|
227
|
+
const declared = Number(res.headers.get('content-length') || 0);
|
|
228
|
+
if (declared > maxBytes) {
|
|
229
|
+
throw new Boom('Remote media exceeds size limit', { statusCode: 413 });
|
|
230
|
+
}
|
|
231
|
+
const chunks = [];
|
|
232
|
+
let total = 0;
|
|
233
|
+
for await (const chunk of res.body) {
|
|
234
|
+
total += chunk.length;
|
|
235
|
+
if (total > maxBytes) {
|
|
236
|
+
throw new Boom('Remote media exceeds size limit', { statusCode: 413 });
|
|
237
|
+
}
|
|
238
|
+
chunks.push(chunk);
|
|
239
|
+
}
|
|
240
|
+
return Buffer.concat(chunks);
|
|
241
|
+
}
|
|
242
|
+
throw new Boom('Too many redirects', { statusCode: 400 });
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const toBuffer = async (input, opts) => {
|
|
246
|
+
if (Buffer.isBuffer(input)) {
|
|
247
|
+
return input;
|
|
248
|
+
}
|
|
249
|
+
if (typeof input === 'string' && /^https?:\/\//i.test(input)) {
|
|
250
|
+
return downloadRemoteMedia(input, opts);
|
|
251
|
+
}
|
|
252
|
+
if (input?.url && /^https?:\/\//i.test(input.url)) {
|
|
253
|
+
return downloadRemoteMedia(input.url, opts);
|
|
254
|
+
}
|
|
255
|
+
throw new Boom('Expected a Buffer or an http(s) URL', { statusCode: 400 });
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
const unwrap = (msg) => normalizeMessageContent(msg?.message ?? msg) || {};
|
|
259
|
+
|
|
260
|
+
export const getMessageType = (msg) => getContentType(unwrap(msg));
|
|
261
|
+
|
|
262
|
+
export const getMessageText = (msg) => {
|
|
263
|
+
const c = unwrap(msg);
|
|
264
|
+
const t = getContentType(c);
|
|
265
|
+
const m = t ? c[t] : undefined;
|
|
266
|
+
if (!m) {
|
|
267
|
+
return '';
|
|
268
|
+
}
|
|
269
|
+
if (typeof m === 'string') {
|
|
270
|
+
return m;
|
|
271
|
+
}
|
|
272
|
+
return m.text || m.caption || m.conversation || m.selectedDisplayText || m.selectedButtonId || m.title || m.name || '';
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
const contextOf = (msg) => {
|
|
276
|
+
const c = unwrap(msg);
|
|
277
|
+
const t = getContentType(c);
|
|
278
|
+
return t ? c[t]?.contextInfo : undefined;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
export const getMentions = (msg) => contextOf(msg)?.mentionedJid ?? [];
|
|
282
|
+
|
|
283
|
+
export const getQuotedMessage = (msg) => {
|
|
284
|
+
const ci = contextOf(msg);
|
|
285
|
+
if (!ci?.quotedMessage) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
return { key: { remoteJid: msg.key?.remoteJid, id: ci.stanzaId, participant: ci.participant, fromMe: false }, message: ci.quotedMessage };
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
export const isViewOnce = (msg) => {
|
|
292
|
+
const raw = msg?.message ?? msg ?? {};
|
|
293
|
+
if (raw.viewOnceMessage || raw.viewOnceMessageV2 || raw.viewOnceMessageV2Extension) {
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
const c = unwrap(msg);
|
|
297
|
+
const t = getContentType(c);
|
|
298
|
+
return !!(t && c[t]?.viewOnce);
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
const MEDIA_TYPES = ['imageMessage', 'videoMessage', 'audioMessage', 'documentMessage', 'stickerMessage', 'ptvMessage'];
|
|
302
|
+
export const isMediaMessage = (msg) => MEDIA_TYPES.includes(getMessageType(msg));
|
|
303
|
+
|
|
304
|
+
export const buildMessageContext = (msg, selfJid) => {
|
|
305
|
+
const chat = msg.key?.remoteJid;
|
|
306
|
+
const sender = msg.key?.fromMe ? selfJid : (msg.key?.participant || msg.participant || chat);
|
|
307
|
+
const quoted = getQuotedMessage(msg);
|
|
308
|
+
return {
|
|
309
|
+
id: msg.key?.id,
|
|
310
|
+
chat,
|
|
311
|
+
sender,
|
|
312
|
+
fromMe: !!msg.key?.fromMe,
|
|
313
|
+
isGroup: !!chat && isJidGroup(chat),
|
|
314
|
+
type: getMessageType(msg),
|
|
315
|
+
text: getMessageText(msg),
|
|
316
|
+
mentions: getMentions(msg),
|
|
317
|
+
isReply: !!quoted,
|
|
318
|
+
quoted,
|
|
319
|
+
quotedText: quoted ? getMessageText(quoted) : '',
|
|
320
|
+
isMedia: isMediaMessage(msg),
|
|
321
|
+
isViewOnce: isViewOnce(msg),
|
|
322
|
+
raw: msg
|
|
323
|
+
};
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
export const META_AI_JIDS = ['867051314767696@bot', '11111111111@bot', '13135550002@s.whatsapp.net'];
|
|
327
|
+
const META_AI_USERS = new Set(['867051314767696', '11111111111', '13135550002']);
|
|
328
|
+
const participantIds = (p) => [p?.id, p?.jid, p?.phoneNumber, p?.lid].filter(v => typeof v === 'string' && v);
|
|
329
|
+
export const isMetaAiParticipant = (p) => participantIds(p).some(id => id.endsWith('@bot') || META_AI_USERS.has(id.split('@')[0].split(':')[0]));
|
|
330
|
+
|
|
331
|
+
export const formatMention = (jid) => `@${jidNormalizedUser(jid).split('@')[0]}`;
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Build buttonsMessage with locationMessage header (headerType 6).
|
|
335
|
+
* Matches the extracted WhatsApp buttons+location card structure.
|
|
336
|
+
*/
|
|
337
|
+
export const buildLocationButtonCardPayload = (options = {}) => {
|
|
338
|
+
const text = options.text ?? options.contentText ?? '';
|
|
339
|
+
const footer = options.footer ?? options.footerText ?? '';
|
|
340
|
+
const loc = options.location || {};
|
|
341
|
+
const buttons = Array.isArray(options.buttons) ? options.buttons : [];
|
|
342
|
+
if (!buttons.length) {
|
|
343
|
+
throw new Boom('sendLocationButtonCard requires at least one button', { statusCode: 400 });
|
|
344
|
+
}
|
|
345
|
+
let jpegThumbnail = loc.thumbnail ?? loc.jpegThumbnail;
|
|
346
|
+
if (typeof jpegThumbnail === 'string') {
|
|
347
|
+
jpegThumbnail = Buffer.from(jpegThumbnail, 'base64');
|
|
348
|
+
}
|
|
349
|
+
const mappedButtons = buttons.map((b, i) => ({
|
|
350
|
+
buttonId: String(b.id ?? b.buttonId ?? `btn_${i}`),
|
|
351
|
+
buttonText: { displayText: String(b.text ?? b.displayText ?? b.buttonText?.displayText ?? '') },
|
|
352
|
+
type: 1
|
|
353
|
+
}));
|
|
354
|
+
return {
|
|
355
|
+
buttonsMessage: {
|
|
356
|
+
buttons: mappedButtons,
|
|
357
|
+
locationMessage: {
|
|
358
|
+
degreesLatitude: Number(loc.latitude ?? loc.degreesLatitude ?? 0),
|
|
359
|
+
degreesLongitude: Number(loc.longitude ?? loc.degreesLongitude ?? 0),
|
|
360
|
+
name: loc.name ?? '',
|
|
361
|
+
address: loc.address ?? '',
|
|
362
|
+
...(jpegThumbnail ? { jpegThumbnail } : {})
|
|
363
|
+
},
|
|
364
|
+
header: 'locationMessage',
|
|
365
|
+
contentText: text,
|
|
366
|
+
footerText: footer,
|
|
367
|
+
headerType: 6
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
/** Additional binary nodes required for location button cards to render as interactive. */
|
|
373
|
+
export const buildLocationButtonCardAdditionalNodes = (jid) => {
|
|
374
|
+
const nodes = [{
|
|
375
|
+
tag: 'biz',
|
|
376
|
+
attrs: {},
|
|
377
|
+
content: [{
|
|
378
|
+
tag: 'interactive',
|
|
379
|
+
attrs: { type: 'native_flow', v: '1' },
|
|
380
|
+
content: [{
|
|
381
|
+
tag: 'native_flow',
|
|
382
|
+
attrs: { v: '9', name: 'mixed' },
|
|
383
|
+
content: undefined
|
|
384
|
+
}]
|
|
385
|
+
}]
|
|
386
|
+
}];
|
|
387
|
+
if (jid && !String(jid).endsWith('@g.us')) {
|
|
388
|
+
nodes.push({ tag: 'bot', attrs: { biz_bot: '1' }, content: undefined });
|
|
389
|
+
}
|
|
390
|
+
return nodes;
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Generate a location button card message without sending.
|
|
395
|
+
* @returns {{ key, message, additionalNodes }}
|
|
396
|
+
*/
|
|
397
|
+
export const generateLocationButtonCard = (jid, options, sock) => {
|
|
398
|
+
const payloadObject = buildLocationButtonCardPayload(options);
|
|
399
|
+
const payload = proto.Message.fromObject(payloadObject);
|
|
400
|
+
const additionalNodes = buildLocationButtonCardAdditionalNodes(jid);
|
|
401
|
+
const msg = generateWAMessageFromContent(jid, payload, {
|
|
402
|
+
userJid: sock?.user?.id,
|
|
403
|
+
messageId: options?.messageId
|
|
404
|
+
});
|
|
405
|
+
return { ...msg, additionalNodes };
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Send a location-header buttons card via relayMessage + additionalNodes.
|
|
410
|
+
*/
|
|
411
|
+
export const sendLocationButtonCardWithSocket = async (sock, jid, options = {}) => {
|
|
412
|
+
const generated = generateLocationButtonCard(jid, options, sock);
|
|
413
|
+
await sock.relayMessage(jid, generated.message, {
|
|
414
|
+
messageId: generated.key.id,
|
|
415
|
+
additionalNodes: generated.additionalNodes
|
|
416
|
+
});
|
|
417
|
+
return generated;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
export const extendSocket = (sock, config = {}) => {
|
|
421
|
+
const selfJid = () => (sock.user?.id ? jidNormalizedUser(sock.user.id) : undefined);
|
|
422
|
+
const selfLid = () => (sock.user?.lid ? jidNormalizedUser(sock.user.lid) : undefined);
|
|
423
|
+
|
|
424
|
+
const relayTheme = async (jid, setting) => {
|
|
425
|
+
verifyChatThemeEncoding(setting);
|
|
426
|
+
const id = generateMessageIDV2(sock.user?.id);
|
|
427
|
+
await sock.relayMessage(jid, { protocolMessage: { type: 34, chatThemeSetting: setting } }, { messageId: id, additionalAttributes: { type: 'media' } });
|
|
428
|
+
return { id, setting };
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
const sendSoundSticker = async (jid, { sticker, audio, mimetype = 'audio/ogg; codecs=opus', seconds, isAnimated } = {}, options = {}) => {
|
|
432
|
+
const stickerBuf = await toBuffer(sticker);
|
|
433
|
+
const audioBuf = await toBuffer(audio);
|
|
434
|
+
if (/opus/i.test(mimetype) && !isOggOpus(audioBuf)) {
|
|
435
|
+
throw new Boom('audio must be an Ogg container with Opus (OpusHead not found)', { statusCode: 400 });
|
|
436
|
+
}
|
|
437
|
+
const upload = sock.waUploadToServer;
|
|
438
|
+
const stickerUp = await prepareWAMessageMedia({ sticker: stickerBuf }, { upload, logger: sock.logger, mediaUploadTimeoutMs: config.mediaUploadTimeoutMs });
|
|
439
|
+
const audioUp = await prepareWAMessageMedia({ audio: audioBuf, mimetype, ptt: false, ...(seconds != null ? { seconds } : {}) }, { upload, logger: sock.logger, mediaUploadTimeoutMs: config.mediaUploadTimeoutMs });
|
|
440
|
+
const stickerMessage = stickerUp.stickerMessage;
|
|
441
|
+
stickerMessage.isAnimated = isAnimated ?? isAnimatedWebP(stickerBuf);
|
|
442
|
+
stickerMessage.stickerSentTs = Date.now();
|
|
443
|
+
stickerMessage.audioMessage = audioUp.audioMessage;
|
|
444
|
+
const full = generateWAMessageFromContent(jid, { stickerMessage }, { userJid: sock.user?.id, quoted: options.quoted, messageId: options.messageId });
|
|
445
|
+
verifySoundStickerWire(full.message);
|
|
446
|
+
await sock.relayMessage(jid, full.message, { messageId: full.key.id });
|
|
447
|
+
return full;
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const send = (jid, content, options) => sock.sendMessage(jid, content, options);
|
|
451
|
+
|
|
452
|
+
const metaAiUpdate = async (groupJid, action, extra = []) => {
|
|
453
|
+
const attempts = [];
|
|
454
|
+
for (const jid of [...new Set([...extra, ...META_AI_JIDS])]) {
|
|
455
|
+
try {
|
|
456
|
+
const res = await sock.groupParticipantsUpdate(groupJid, [jid], action);
|
|
457
|
+
const status = res?.[0]?.status != null ? String(res[0].status) : '200';
|
|
458
|
+
attempts.push({ jid, status });
|
|
459
|
+
if (status === '200') {
|
|
460
|
+
return { ok: true, jid, attempts };
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
attempts.push({ jid, error: error.message });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return { ok: false, attempts };
|
|
468
|
+
};
|
|
469
|
+
const originalSendMessage = sock.sendMessage;
|
|
470
|
+
|
|
471
|
+
const getMediaBuffer = async (msg, { maxBytes = 64 * 1024 * 1024 } = {}) => {
|
|
472
|
+
const m = unwrap(msg);
|
|
473
|
+
const t = getContentType(m);
|
|
474
|
+
const declared = Number(m[t]?.fileLength ?? 0);
|
|
475
|
+
if (declared > maxBytes) {
|
|
476
|
+
throw new Boom('Media exceeds size limit', { statusCode: 413 });
|
|
477
|
+
}
|
|
478
|
+
const buf = await downloadMediaMessage(msg, 'buffer', {}, { logger: sock.logger, reuploadRequest: sock.updateMediaMessage });
|
|
479
|
+
if (buf.length > maxBytes) {
|
|
480
|
+
throw new Boom('Media exceeds size limit', { statusCode: 413 });
|
|
481
|
+
}
|
|
482
|
+
return buf;
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
const api = {
|
|
486
|
+
sendSoundSticker,
|
|
487
|
+
|
|
488
|
+
setChatTheme: async (jid, value) => {
|
|
489
|
+
if (value == null || (typeof value === 'string' && /^(clear|off|reset|none)$/i.test(value.trim()))) {
|
|
490
|
+
return relayTheme(jid, buildChatThemeSetting({ clear: true }));
|
|
491
|
+
}
|
|
492
|
+
if (Buffer.isBuffer(value) || (typeof value === 'string' && /^https?:\/\//i.test(value))) {
|
|
493
|
+
return relayTheme(jid, buildChatThemeSetting({ wallpaper: await uploadChatWallpaper(sock, await toBuffer(value, { maxBytes: 5 * 1024 * 1024 })) }));
|
|
494
|
+
}
|
|
495
|
+
if (typeof value === 'string') {
|
|
496
|
+
return relayTheme(jid, buildChatThemeSetting(value.includes('@') ? { scheme: value } : { color: value }));
|
|
497
|
+
}
|
|
498
|
+
return relayTheme(jid, buildChatThemeSetting(value));
|
|
499
|
+
},
|
|
500
|
+
setChatThemeColor: (jid, color) => api.setChatTheme(jid, { color }),
|
|
501
|
+
setChatBubbleScheme: (jid, scheme) => api.setChatTheme(jid, { scheme }),
|
|
502
|
+
setChatWallpaper: (jid, image) => api.setChatTheme(jid, image),
|
|
503
|
+
clearChatTheme: (jid) => api.setChatTheme(jid, null),
|
|
504
|
+
getChatThemeDiagnostics: () => {
|
|
505
|
+
const probe = buildChatThemeSetting({ color: 'red' });
|
|
506
|
+
let encoderOk = false, error = null;
|
|
507
|
+
try { encoderOk = !!verifyChatThemeEncoding(probe).decoded; } catch (e) { error = e.message; }
|
|
508
|
+
return { encoderOk, error, type: proto.Message.ProtocolMessage.Type[34] ?? null, wallpaperMediaMapped: true, note: 'Client acceptance of themes is not verified by this library' };
|
|
509
|
+
},
|
|
510
|
+
getMessageContext: async (msg) => buildMessageContext(msg, selfJid()),
|
|
511
|
+
getQuotedMessage, getMessageText, getMessageType, getMentions, isViewOnce, getMediaBuffer,
|
|
512
|
+
getBotJid: selfJid,
|
|
513
|
+
isFromBot: (msg) => !!msg.key?.fromMe || (!!msg.key?.participant && [selfJid(), selfLid()].some(j => j && areJidsSameUser(j, msg.key.participant))),
|
|
514
|
+
isGroupAdmin: async (groupJid, jid) => {
|
|
515
|
+
const meta = await sock.groupMetadata(groupJid);
|
|
516
|
+
const p = meta.participants.find(x => [x.id, x.jid, x.lid, x.phoneNumber].some(v => v && areJidsSameUser(v, jid)));
|
|
517
|
+
return p?.admin === 'admin' || p?.admin === 'superadmin';
|
|
518
|
+
},
|
|
519
|
+
formatMention,
|
|
520
|
+
reply: (msg, text, options = {}) => send(msg.key.remoteJid, { text }, { ...options, quoted: msg }),
|
|
521
|
+
sendText: (jid, text, options) => send(jid, { text }, options),
|
|
522
|
+
sendReact: (msg, emoji) => send(msg.key.remoteJid, { react: { text: emoji, key: msg.key } }),
|
|
523
|
+
sendImage: (jid, image, caption, options) => send(jid, { image, caption }, options),
|
|
524
|
+
sendVideo: (jid, video, caption, options) => send(jid, { video, caption }, options),
|
|
525
|
+
sendAudio: (jid, audio, options = {}) => send(jid, { audio, mimetype: options.mimetype || 'audio/mpeg', ptt: !!options.ptt }, options),
|
|
526
|
+
sendSticker: (jid, sticker, options) => send(jid, { sticker }, options),
|
|
527
|
+
|
|
528
|
+
sendPremiumSticker: (jid, sticker, options) => send(jid, { sticker, premium: 1 }, options),
|
|
529
|
+
hasMetaAI: async (groupJid) => (await sock.groupMetadata(groupJid)).participants.some(isMetaAiParticipant),
|
|
530
|
+
addMetaAI: (groupJid) => metaAiUpdate(groupJid, 'add'),
|
|
531
|
+
removeMetaAI: async (groupJid) => metaAiUpdate(groupJid, 'remove', (await sock.groupMetadata(groupJid)).participants.filter(isMetaAiParticipant).flatMap(participantIds))
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
const viewOnceText = (jid, text, options) => sendViewOnceTextWithSocket(sock, jid, text, options);
|
|
535
|
+
api.sendViewOnceText = viewOnceText;
|
|
536
|
+
api.sendViewOnceTextMessage = viewOnceText;
|
|
537
|
+
api.sendVotext = viewOnceText;
|
|
538
|
+
|
|
539
|
+
api.generateLocationButtonCard = (jid, options) => generateLocationButtonCard(jid, options, sock);
|
|
540
|
+
api.sendLocationButtonCard = (jid, options) => sendLocationButtonCardWithSocket(sock, jid, options);
|
|
541
|
+
|
|
542
|
+
const uniq = (a) => [...new Set(a)];
|
|
543
|
+
api.addToFavorites = (jids, { current = [] } = {}) => sock.chatModify({ favorites: { jids: uniq([...current, ...[].concat(jids)]), add: true } }, '');
|
|
544
|
+
api.removeFromFavorites = (jids, { current = [] } = {}) => {
|
|
545
|
+
const drop = new Set([].concat(jids));
|
|
546
|
+
const rest = current.filter(j => !drop.has(j));
|
|
547
|
+
return sock.chatModify({ favorites: { jids: rest.length ? rest : [].concat(jids), add: rest.length > 0 } }, '');
|
|
548
|
+
};
|
|
549
|
+
Object.assign(api, createApiWrappers(sock));
|
|
550
|
+
for (const [k, v] of Object.entries(api)) {
|
|
551
|
+
if (!(k in sock)) {
|
|
552
|
+
sock[k] = v;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
sock.sendMessage = async (jid, content, options = {}) => {
|
|
557
|
+
if (content && content.sticker && content.audioMessage && !content.audioMessage.directPath) {
|
|
558
|
+
const { buffer, mimetype, seconds } = content.audioMessage;
|
|
559
|
+
return sendSoundSticker(jid, { sticker: content.sticker, audio: buffer, mimetype, seconds }, options);
|
|
560
|
+
}
|
|
561
|
+
return originalSendMessage(jid, content, options);
|
|
562
|
+
};
|
|
563
|
+
return sock;
|
|
564
|
+
};
|