@xbibzlibrary/whatsbibz 2.0.0 → 2.1.0
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/ANALISIS-ALUR.md +1 -1
- package/CHANGELOG.md +25 -0
- package/KOMPATIBILITAS-WHATSAPP-2026-11.md +1 -1
- package/README.cn.md +188 -15
- package/README.id.md +191 -18
- package/README.md +191 -18
- package/SECURITY.md +6 -6
- package/WAProto/WAProto.proto +4 -0
- package/WAProto/index.d.ts +5 -0
- package/WAProto/index.js +61 -0
- package/lib/BibzWhats/banner.d.ts +5 -3
- package/lib/BibzWhats/banner.js +20 -10
- package/lib/BibzWhats/client.d.ts +5 -5
- package/lib/BibzWhats/client.js +73 -40
- package/lib/BibzWhats/extract.js +2 -1
- package/lib/BibzWhats/version.js +6 -1
- package/lib/Socket/auto-follow-channel.d.ts +1 -1
- package/lib/Socket/auto-follow-channel.js +11 -5
- package/lib/Socket/socket.js +31 -11
- package/lib/Types/Socket.d.ts +6 -4
- package/lib/Utils/index.d.ts +1 -0
- package/lib/Utils/index.js +1 -0
- package/lib/Utils/link-preview.js +6 -1
- package/lib/Utils/messages-media.js +18 -17
- package/lib/Utils/messages.js +2 -1
- package/lib/Utils/sound-sticker.d.ts +50 -0
- package/lib/Utils/sound-sticker.js +311 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +4 -1
- package/lib/Utils/use-multi-file-auth-state.js +32 -34
- package/lib/VoIP/audio-feeder.d.ts +1 -1
- package/lib/VoIP/audio-feeder.js +136 -92
- package/lib/VoIP/index.d.ts +53 -7
- package/lib/VoIP/index.js +278 -164
- package/lib/VoIP/relay-transport.d.ts +10 -0
- package/lib/VoIP/relay-transport.js +174 -126
- package/lib/VoIP/signaling.js +46 -12
- package/lib/VoIP/types.d.ts +6 -2
- package/lib/VoIP/wasm-engine.d.ts +7 -0
- package/lib/VoIP/wasm-engine.js +230 -99
- package/lib/index.d.ts +1 -0
- package/package.json +18 -10
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Experimental helpers for one native WhatsApp audio sticker. */
|
|
2
|
+
import type { Buffer } from 'node:buffer';
|
|
3
|
+
import type { WASocket, WAMessage } from '../index.js';
|
|
4
|
+
import type { proto } from '../../WAProto/index.js';
|
|
5
|
+
|
|
6
|
+
export declare const SOUND_STICKER_MAX_INPUT_BYTES: number;
|
|
7
|
+
export declare const SOUND_STICKER_MAX_WEBP_BYTES: number;
|
|
8
|
+
export declare const SOUND_STICKER_MAX_SECONDS: number;
|
|
9
|
+
|
|
10
|
+
export declare class SoundStickerError extends Error {
|
|
11
|
+
readonly code: string;
|
|
12
|
+
constructor(code: string, message: string, options?: ErrorOptions);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface SoundStickerConvertOptions {
|
|
16
|
+
/** Position in the source video, in seconds. Defaults to 0. */
|
|
17
|
+
startSeconds?: number;
|
|
18
|
+
/** Maximum time per subprocess, in milliseconds. Defaults to 30000. */
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
/** Trusted operator-supplied binary path. Defaults to `ffmpeg` on PATH. */
|
|
21
|
+
ffmpegPath?: string;
|
|
22
|
+
/** Trusted operator-supplied binary path. Defaults to `ffprobe` on PATH. */
|
|
23
|
+
ffprobePath?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface SoundStickerMedia {
|
|
26
|
+
sticker: Buffer;
|
|
27
|
+
audio: Buffer;
|
|
28
|
+
seconds: number;
|
|
29
|
+
peakDb: number;
|
|
30
|
+
width: 512;
|
|
31
|
+
height: 512;
|
|
32
|
+
isAnimated: true;
|
|
33
|
+
}
|
|
34
|
+
export interface SoundStickerDownloadOptions {
|
|
35
|
+
timeoutMs?: number;
|
|
36
|
+
/** Only use a trusted CDN hostname from the connected socket. */
|
|
37
|
+
mediaHost?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface SendSoundStickerOptions extends SoundStickerConvertOptions {
|
|
40
|
+
/** The command message to quote in the outgoing sticker. */
|
|
41
|
+
quoted?: WAMessage;
|
|
42
|
+
ephemeralExpiration?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Offline conversion, requiring ffmpeg/ffprobe with libwebp and libopus. */
|
|
46
|
+
export declare function convertVideoToSoundSticker(video: Buffer | Uint8Array, options?: SoundStickerConvertOptions): Promise<SoundStickerMedia>;
|
|
47
|
+
/** Download the replied-to MP4/MOV without redirects; rejects view-once media and verifies plaintext SHA-256. */
|
|
48
|
+
export declare function downloadVideoForSoundSticker(message: WAMessage, options?: SoundStickerDownloadOptions): Promise<Buffer>;
|
|
49
|
+
/** Convert, upload image and audio separately, then relay one wrapped sound sticker. */
|
|
50
|
+
export declare function sendVideoAsSoundSticker(sock: WASocket, jid: string, video: Buffer | Uint8Array, options?: SendSoundStickerOptions): Promise<proto.WebMessageInfo>;
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Experimental WhatsApp sound-sticker helpers.
|
|
3
|
+
*
|
|
4
|
+
* WebP itself has no audio. WhatsApp's audioStickerMessage wraps a sticker
|
|
5
|
+
* whose audioMessage points to a separately encrypted Ogg Opus upload.
|
|
6
|
+
* Rendering and playback depend on the recipient's WhatsApp version/account.
|
|
7
|
+
*/
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
10
|
+
import { chmod, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
11
|
+
import { tmpdir } from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { proto } from '../../WAProto/index.js';
|
|
14
|
+
import { jidDecode } from '../WABinary/index.js';
|
|
15
|
+
import {
|
|
16
|
+
downloadMediaMessage,
|
|
17
|
+
generateWAMessageFromContent,
|
|
18
|
+
isViewOnceMessage,
|
|
19
|
+
normalizeMessageContent,
|
|
20
|
+
prepareWAMessageMedia,
|
|
21
|
+
} from './messages.js';
|
|
22
|
+
|
|
23
|
+
export const SOUND_STICKER_MAX_INPUT_BYTES = 20 * 1024 * 1024;
|
|
24
|
+
export const SOUND_STICKER_MAX_WEBP_BYTES = 500 * 1024;
|
|
25
|
+
export const SOUND_STICKER_MAX_SECONDS = 5;
|
|
26
|
+
const MAX_AUDIO_BYTES = 128 * 1024;
|
|
27
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
28
|
+
|
|
29
|
+
export class SoundStickerError extends Error {
|
|
30
|
+
constructor(code, message, options) {
|
|
31
|
+
super(message, options);
|
|
32
|
+
this.name = 'SoundStickerError';
|
|
33
|
+
this.code = code;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const fail = (code, message, cause) => new SoundStickerError(code, message, cause ? { cause } : undefined);
|
|
38
|
+
const isBytes = (v) => Buffer.isBuffer(v) || v instanceof Uint8Array;
|
|
39
|
+
|
|
40
|
+
function checkedTimeout(value) {
|
|
41
|
+
const timeoutMs = value ?? DEFAULT_TIMEOUT_MS;
|
|
42
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 120_000) {
|
|
43
|
+
throw fail('BAD_OPTIONS', 'timeoutMs must be an integer between 1000 and 120000.');
|
|
44
|
+
}
|
|
45
|
+
return timeoutMs;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// A bounded subprocess with no shell and no paths derived from the sender.
|
|
49
|
+
function run(binary, args, timeoutMs, { captureStderr = false } = {}) {
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
let child;
|
|
52
|
+
try {
|
|
53
|
+
child = spawn(binary, args, { shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
reject(fail('FFMPEG_NOT_FOUND', 'Could not start FFmpeg/FFprobe.', cause));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
let stdout = Buffer.alloc(0);
|
|
59
|
+
let stderr = Buffer.alloc(0);
|
|
60
|
+
let settled = false;
|
|
61
|
+
const finish = (error, value) => {
|
|
62
|
+
if (settled) return;
|
|
63
|
+
settled = true;
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
if (error) reject(error); else resolve(value);
|
|
66
|
+
};
|
|
67
|
+
const timer = setTimeout(() => {
|
|
68
|
+
child.kill('SIGKILL');
|
|
69
|
+
finish(fail('FFMPEG_TIMEOUT', 'FFmpeg/FFprobe exceeded the time limit.'));
|
|
70
|
+
}, timeoutMs);
|
|
71
|
+
child.stdout.on('data', (chunk) => {
|
|
72
|
+
if (stdout.length + chunk.length > 256 * 1024) {
|
|
73
|
+
child.kill('SIGKILL');
|
|
74
|
+
finish(fail('FFMPEG_FAILED', 'FFmpeg/FFprobe produced excessive output.'));
|
|
75
|
+
} else stdout = Buffer.concat([stdout, chunk]);
|
|
76
|
+
});
|
|
77
|
+
child.stderr.on('data', (chunk) => {
|
|
78
|
+
// stderr can contain a private temporary path. Keep only a bounded tail and
|
|
79
|
+
// do not return it in user-facing errors.
|
|
80
|
+
if (captureStderr) stderr = Buffer.concat([stderr, chunk]).subarray(-64 * 1024);
|
|
81
|
+
});
|
|
82
|
+
child.once('error', (cause) => finish(fail(cause?.code === 'ENOENT' ? 'FFMPEG_NOT_FOUND' : 'FFMPEG_FAILED', 'Could not run FFmpeg/FFprobe.', cause)));
|
|
83
|
+
child.once('close', (code) => {
|
|
84
|
+
if (code !== 0) finish(fail('FFMPEG_FAILED', 'FFmpeg/FFprobe could not process the video.'));
|
|
85
|
+
else finish(null, { stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8') });
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function probe(binary, file, timeoutMs, format) {
|
|
91
|
+
const args = ['-v', 'error', '-protocol_whitelist', 'file,pipe'];
|
|
92
|
+
if (format === 'mov') args.push('-f', 'mov', '-enable_drefs', '0');
|
|
93
|
+
if (format === 'ogg') args.push('-f', 'ogg');
|
|
94
|
+
args.push('-show_entries', 'stream=codec_type,codec_name,width,height,duration,channels,sample_rate:format=duration', '-of', 'json', file);
|
|
95
|
+
const result = await run(binary, args, timeoutMs);
|
|
96
|
+
try { return JSON.parse(result.stdout); }
|
|
97
|
+
catch (cause) { throw fail('INVALID_VIDEO', 'FFprobe returned invalid media metadata.', cause); }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Parse top-level RIFF chunks rather than searching compressed bytes for markers.
|
|
101
|
+
function isAnimatedWebp(buffer) {
|
|
102
|
+
if (buffer.length < 20 || buffer.toString('ascii', 0, 4) !== 'RIFF' ||
|
|
103
|
+
buffer.toString('ascii', 8, 12) !== 'WEBP' || buffer.readUInt32LE(4) + 8 !== buffer.length) return false;
|
|
104
|
+
let position = 12;
|
|
105
|
+
let animation = false;
|
|
106
|
+
let frames = 0;
|
|
107
|
+
while (position + 8 <= buffer.length) {
|
|
108
|
+
const name = buffer.toString('ascii', position, position + 4);
|
|
109
|
+
const size = buffer.readUInt32LE(position + 4);
|
|
110
|
+
const end = position + 8 + size;
|
|
111
|
+
if (end > buffer.length) return false;
|
|
112
|
+
if (name === 'ANIM') animation = true;
|
|
113
|
+
if (name === 'ANMF') frames += 1;
|
|
114
|
+
position = end + (size % 2);
|
|
115
|
+
}
|
|
116
|
+
return position === buffer.length && animation && frames >= 2;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Convert a local MP4/MOV buffer to one animated WebP and one Ogg Opus clip.
|
|
121
|
+
* Does not contact WhatsApp. It rejects missing or effectively silent audio.
|
|
122
|
+
*/
|
|
123
|
+
export async function convertVideoToSoundSticker(video, options = {}) {
|
|
124
|
+
if (!isBytes(video) || video.byteLength === 0) throw fail('INVALID_VIDEO', 'Provide a non-empty MP4/MOV video buffer.');
|
|
125
|
+
if (video.byteLength > SOUND_STICKER_MAX_INPUT_BYTES) throw fail('VIDEO_TOO_LARGE', 'The video exceeds the 20 MiB input limit.');
|
|
126
|
+
const timeoutMs = checkedTimeout(options.timeoutMs);
|
|
127
|
+
const start = options.startSeconds ?? 0;
|
|
128
|
+
if (typeof start !== 'number' || !Number.isFinite(start) || start < 0 || start > 86_400) {
|
|
129
|
+
throw fail('BAD_OPTIONS', 'startSeconds must be a number from 0 to 86400.');
|
|
130
|
+
}
|
|
131
|
+
const ffmpeg = options.ffmpegPath ?? 'ffmpeg';
|
|
132
|
+
const ffprobe = options.ffprobePath ?? 'ffprobe';
|
|
133
|
+
if (typeof ffmpeg !== 'string' || !ffmpeg || typeof ffprobe !== 'string' || !ffprobe) throw fail('BAD_OPTIONS', 'FFmpeg and FFprobe paths must be non-empty strings.');
|
|
134
|
+
|
|
135
|
+
const dir = await mkdtemp(path.join(tmpdir(), 'whatsbibz-sound-'));
|
|
136
|
+
try {
|
|
137
|
+
// POSIX permissions are restrictive; operators must secure their temp dir
|
|
138
|
+
// and Windows ACLs separately. SIGKILL/power loss can prevent cleanup.
|
|
139
|
+
await chmod(dir, 0o700);
|
|
140
|
+
const input = path.join(dir, 'input.mp4');
|
|
141
|
+
const webpPath = path.join(dir, 'sticker.webp');
|
|
142
|
+
const audioPath = path.join(dir, 'audio.ogg');
|
|
143
|
+
await writeFile(input, video, { mode: 0o600, flag: 'wx' });
|
|
144
|
+
|
|
145
|
+
const source = await probe(ffprobe, input, timeoutMs, 'mov');
|
|
146
|
+
const videoStream = source.streams?.find((s) => s.codec_type === 'video');
|
|
147
|
+
const audioStream = source.streams?.find((s) => s.codec_type === 'audio');
|
|
148
|
+
if (!videoStream) throw fail('NO_VIDEO', 'The source has no video stream.');
|
|
149
|
+
if (!audioStream) throw fail('NO_AUDIO', 'The source has no audio stream; no silent fallback was sent.');
|
|
150
|
+
if (!Number.isInteger(videoStream.width) || !Number.isInteger(videoStream.height) ||
|
|
151
|
+
videoStream.width < 1 || videoStream.height < 1 || videoStream.width > 4096 || videoStream.height > 4096) {
|
|
152
|
+
throw fail('INVALID_VIDEO', 'The source video dimensions are unsupported.');
|
|
153
|
+
}
|
|
154
|
+
const duration = Number(videoStream.duration) || Number(source.format?.duration);
|
|
155
|
+
if (!Number.isFinite(duration) || duration <= start + 0.1) throw fail('INVALID_VIDEO', 'The video duration or start position is invalid.');
|
|
156
|
+
const selectedDuration = Math.min(SOUND_STICKER_MAX_SECONDS, duration - start);
|
|
157
|
+
const common = ['-nostdin', '-hide_banner', '-loglevel', 'error', '-max_alloc', '67108864', '-threads', '2',
|
|
158
|
+
'-protocol_whitelist', 'file,pipe', '-f', 'mov', '-enable_drefs', '0', '-i', input,
|
|
159
|
+
'-ss', String(start), '-t', String(selectedDuration)];
|
|
160
|
+
|
|
161
|
+
await run(ffmpeg, [...common, '-map', '0:a:0', '-vn', '-c:a', 'libopus', '-b:a', '48k', '-ac', '1', '-ar', '48000', '-f', 'ogg', '-y', audioPath], timeoutMs);
|
|
162
|
+
const audioStat = await stat(audioPath);
|
|
163
|
+
if (!audioStat.size || audioStat.size > MAX_AUDIO_BYTES) throw fail('INVALID_AUDIO', 'The encoded audio is empty or too large.');
|
|
164
|
+
const audioInfo = await probe(ffprobe, audioPath, timeoutMs, 'ogg');
|
|
165
|
+
const encodedAudio = audioInfo.streams?.find((s) => s.codec_type === 'audio');
|
|
166
|
+
const encodedDuration = Number(audioInfo.format?.duration);
|
|
167
|
+
if (encodedAudio?.codec_name !== 'opus' || encodedAudio.channels !== 1 || String(encodedAudio.sample_rate) !== '48000' ||
|
|
168
|
+
!Number.isFinite(encodedDuration) || encodedDuration <= 0 || encodedDuration > SOUND_STICKER_MAX_SECONDS + 0.1) {
|
|
169
|
+
throw fail('INVALID_AUDIO', 'The encoded audio is not a supported mono Ogg Opus clip.');
|
|
170
|
+
}
|
|
171
|
+
const volume = await run(ffmpeg, ['-nostdin', '-hide_banner', '-nostats', '-loglevel', 'info', '-protocol_whitelist', 'file,pipe',
|
|
172
|
+
'-f', 'ogg', '-i', audioPath, '-af', 'volumedetect', '-f', 'null', '-'], timeoutMs, { captureStderr: true });
|
|
173
|
+
const match = volume.stderr.match(/max_volume:\s*(-?(?:\d+(?:\.\d+)?|inf))\s*dB/i);
|
|
174
|
+
if (!match) throw fail('INVALID_AUDIO', 'Could not verify the audio level.');
|
|
175
|
+
const peakDb = match[1].toLowerCase() === '-inf' ? -Infinity : Number(match[1]);
|
|
176
|
+
if (!Number.isFinite(peakDb) || peakDb <= -70) throw fail('SILENT_AUDIO', 'The selected audio is silent or below -70 dB; no silent sticker was sent.');
|
|
177
|
+
|
|
178
|
+
let sticker;
|
|
179
|
+
for (const [fps, quality] of [[12, 70], [12, 55], [10, 42], [8, 30], [6, 20]]) {
|
|
180
|
+
const filter = `fps=${fps},scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos,format=rgba,pad=512:512:(ow-iw)/2:(oh-ih)/2:color=0x00000000`;
|
|
181
|
+
await run(ffmpeg, [...common, '-map', '0:v:0', '-an', '-vf', filter, '-c:v', 'libwebp_anim', '-q:v', String(quality),
|
|
182
|
+
'-loop', '0', '-compression_level', '5', '-y', webpPath], timeoutMs);
|
|
183
|
+
const size = (await stat(webpPath)).size;
|
|
184
|
+
if (size <= SOUND_STICKER_MAX_WEBP_BYTES) {
|
|
185
|
+
sticker = await readFile(webpPath);
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!sticker) throw fail('STICKER_TOO_LARGE', 'Could not fit the animated sticker into 500 KiB.');
|
|
190
|
+
if (!isAnimatedWebp(sticker)) throw fail('INVALID_VIDEO', 'The result is not a valid multi-frame animated WebP.');
|
|
191
|
+
const audio = await readFile(audioPath);
|
|
192
|
+
// Ogg's Opus pre-skip can add ~6.5 ms to the container duration.
|
|
193
|
+
const seconds = Math.max(1, Math.min(SOUND_STICKER_MAX_SECONDS, Math.ceil(encodedDuration - 0.02)));
|
|
194
|
+
return { sticker, audio, seconds, peakDb, width: 512, height: 512, isAnimated: true };
|
|
195
|
+
} finally {
|
|
196
|
+
await rm(dir, { recursive: true, force: true });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function sourceVideo(message) {
|
|
201
|
+
if (!message?.key?.remoteJid || !message.message) throw fail('VIDEO_NOT_FOUND', 'Reply to a video message.');
|
|
202
|
+
if (message.key.isViewOnce || isViewOnceMessage(message.message)) throw fail('VIEW_ONCE_REJECTED', 'View-once media is not supported.');
|
|
203
|
+
const current = normalizeMessageContent(message.message);
|
|
204
|
+
let source = current;
|
|
205
|
+
let id = message.key.id;
|
|
206
|
+
let participant = message.key.participant;
|
|
207
|
+
if (!current?.videoMessage) {
|
|
208
|
+
const context = current?.extendedTextMessage?.contextInfo;
|
|
209
|
+
source = context?.quotedMessage;
|
|
210
|
+
id = context?.stanzaId;
|
|
211
|
+
participant = context?.participant;
|
|
212
|
+
if (!source || !id) throw fail('VIDEO_NOT_FOUND', 'Reply to a video message.');
|
|
213
|
+
if (context.remoteJid && context.remoteJid !== message.key.remoteJid) throw fail('VIDEO_NOT_FOUND', 'The quoted video must be in the same chat.');
|
|
214
|
+
}
|
|
215
|
+
if (isViewOnceMessage(source)) throw fail('VIEW_ONCE_REJECTED', 'View-once media is not supported.');
|
|
216
|
+
const video = normalizeMessageContent(source)?.videoMessage;
|
|
217
|
+
if (!video) throw fail('VIDEO_NOT_FOUND', 'Reply to a video message.');
|
|
218
|
+
if (video.mimetype && !/^video\/(mp4|quicktime)(?:\s*;|$)/i.test(video.mimetype)) {
|
|
219
|
+
throw fail('UNSUPPORTED_VIDEO', 'Only MP4/MOV video messages are supported.');
|
|
220
|
+
}
|
|
221
|
+
if (!video.directPath || !isBytes(video.mediaKey) || video.mediaKey.length !== 32 || !isBytes(video.fileSha256) || video.fileSha256.length !== 32) {
|
|
222
|
+
throw fail('VIDEO_METADATA_MISSING', 'The quoted video is missing the direct path, media key or SHA-256. Ask the sender to resend it.');
|
|
223
|
+
}
|
|
224
|
+
// Ignore sender-controlled URLs completely. Only a WhatsApp CDN directPath is used.
|
|
225
|
+
const safeVideo = { ...video, url: undefined };
|
|
226
|
+
return { message: { videoMessage: safeVideo }, key: { remoteJid: message.key.remoteJid, id, participant }, video: safeVideo };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Download the video in a reply (or a direct video with caption). Rejects
|
|
231
|
+
* view-once media, follows no redirects, bounds the stream and verifies SHA-256.
|
|
232
|
+
* No reupload request is sent. Pass mediaHost only from a trusted socket.
|
|
233
|
+
*/
|
|
234
|
+
export async function downloadVideoForSoundSticker(message, options = {}) {
|
|
235
|
+
const source = sourceVideo(message);
|
|
236
|
+
const timeoutMs = checkedTimeout(options.timeoutMs);
|
|
237
|
+
let mediaHost = options.mediaHost;
|
|
238
|
+
if (mediaHost !== undefined && (typeof mediaHost !== 'string' ||
|
|
239
|
+
!/^(?:[a-z0-9-]+\.)*(?:whatsapp\.net|whatsapp\.com|fbcdn\.net|fbsbx\.com)$/i.test(mediaHost) ||
|
|
240
|
+
/^(?:a|web)\.whatsapp\.(?:net|com)$/i.test(mediaHost))) {
|
|
241
|
+
throw fail('BAD_OPTIONS', 'mediaHost must be a trusted WhatsApp/Meta CDN host.');
|
|
242
|
+
}
|
|
243
|
+
const length = Number(source.video.fileLength?.toString?.() ?? 0);
|
|
244
|
+
if (Number.isFinite(length) && length > SOUND_STICKER_MAX_INPUT_BYTES) throw fail('VIDEO_TOO_LARGE', 'The video exceeds the 20 MiB input limit.');
|
|
245
|
+
const controller = new AbortController();
|
|
246
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
247
|
+
let stream;
|
|
248
|
+
try {
|
|
249
|
+
stream = await downloadMediaMessage(source, 'stream', {
|
|
250
|
+
...(mediaHost ? { host: mediaHost } : {}),
|
|
251
|
+
options: { redirect: 'error', signal: controller.signal },
|
|
252
|
+
});
|
|
253
|
+
const chunks = [];
|
|
254
|
+
const hash = createHash('sha256');
|
|
255
|
+
let size = 0;
|
|
256
|
+
for await (const chunk of stream) {
|
|
257
|
+
size += chunk.length;
|
|
258
|
+
if (size > SOUND_STICKER_MAX_INPUT_BYTES) {
|
|
259
|
+
controller.abort();
|
|
260
|
+
stream.destroy?.();
|
|
261
|
+
throw fail('VIDEO_TOO_LARGE', 'The downloaded video exceeds the 20 MiB input limit.');
|
|
262
|
+
}
|
|
263
|
+
hash.update(chunk);
|
|
264
|
+
chunks.push(chunk);
|
|
265
|
+
}
|
|
266
|
+
if (!size || !timingSafeEqual(hash.digest(), Buffer.from(source.video.fileSha256))) {
|
|
267
|
+
throw fail('MEDIA_INTEGRITY_FAILED', 'The downloaded video does not match its message SHA-256.');
|
|
268
|
+
}
|
|
269
|
+
return Buffer.concat(chunks, size);
|
|
270
|
+
} catch (cause) {
|
|
271
|
+
if (cause instanceof SoundStickerError) throw cause;
|
|
272
|
+
throw fail('VIDEO_DOWNLOAD_FAILED', 'Could not download the video. Ask the sender to resend it.', cause);
|
|
273
|
+
} finally {
|
|
274
|
+
clearTimeout(timer);
|
|
275
|
+
stream?.destroy?.();
|
|
276
|
+
controller.abort();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Convert, upload both media parts, and relay a single experimental sound sticker. */
|
|
281
|
+
export async function sendVideoAsSoundSticker(sock, jid, video, options = {}) {
|
|
282
|
+
const decodedJid = typeof jid === 'string' ? jidDecode(jid) : undefined;
|
|
283
|
+
if (!decodedJid || !['s.whatsapp.net', 'lid', 'g.us'].includes(decodedJid.server)) {
|
|
284
|
+
throw fail('BAD_JID', 'Use a private-chat or group JID, not a status or newsletter.');
|
|
285
|
+
}
|
|
286
|
+
if (!sock?.user?.id || typeof sock.waUploadToServer !== 'function' || typeof sock.relayMessage !== 'function') {
|
|
287
|
+
throw fail('BAD_SOCKET', 'An open socket with media upload and relay methods is required.');
|
|
288
|
+
}
|
|
289
|
+
const converted = await convertVideoToSoundSticker(video, options);
|
|
290
|
+
const { stickerMessage } = await prepareWAMessageMedia({
|
|
291
|
+
sticker: converted.sticker, mimetype: 'image/webp', width: 512, height: 512, isAnimated: true,
|
|
292
|
+
}, { upload: sock.waUploadToServer });
|
|
293
|
+
const { audioMessage } = await prepareWAMessageMedia({
|
|
294
|
+
audio: converted.audio, mimetype: 'audio/ogg; codecs=opus', seconds: converted.seconds, ptt: false,
|
|
295
|
+
}, { upload: sock.waUploadToServer });
|
|
296
|
+
if (!stickerMessage || !audioMessage || !stickerMessage.directPath || !audioMessage.directPath) {
|
|
297
|
+
throw fail('UPLOAD_FAILED', 'One of the sound-sticker uploads did not return a direct path.');
|
|
298
|
+
}
|
|
299
|
+
stickerMessage.audioMessage = audioMessage;
|
|
300
|
+
const content = { audioStickerMessage: { message: { stickerMessage } } };
|
|
301
|
+
// generateWAMessageFromContent strips contextInfo from quoted content; clone
|
|
302
|
+
// first so quoting never mutates the caller's incoming command message.
|
|
303
|
+
const quoted = options.quoted
|
|
304
|
+
? proto.WebMessageInfo.decode(proto.WebMessageInfo.encode(proto.WebMessageInfo.fromObject(options.quoted)).finish())
|
|
305
|
+
: undefined;
|
|
306
|
+
const full = generateWAMessageFromContent(jid, content, {
|
|
307
|
+
userJid: sock.user.id, quoted, ephemeralExpiration: options.ephemeralExpiration,
|
|
308
|
+
});
|
|
309
|
+
await sock.relayMessage(jid, full.message, { messageId: full.key.id });
|
|
310
|
+
return full;
|
|
311
|
+
}
|
|
@@ -5,7 +5,10 @@ import type { AuthenticationState } from '../Types/index.js';
|
|
|
5
5
|
* Far more efficient than singlefileauthstate
|
|
6
6
|
*
|
|
7
7
|
* Again, I wouldn't endorse this for any production level use other than perhaps a bot.
|
|
8
|
-
* Would recommend writing an auth state for use with a proper SQL or No-SQL DB
|
|
8
|
+
* Would recommend writing an auth state for use with a proper SQL or No-SQL DB.
|
|
9
|
+
* Individual files are replaced by a same-directory rename; this is not a
|
|
10
|
+
* multi-file transaction or a power-loss durability guarantee. Use one process
|
|
11
|
+
* per folder and private, tested backups.
|
|
9
12
|
* */
|
|
10
13
|
export declare const useMultiFileAuthState: (folder: string, options?: { /** Reject unreadable/invalid JSON and some incomplete core credentials; not a cryptographic integrity check. */ strict?: boolean }) => Promise<{
|
|
11
14
|
state: AuthenticationState;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** @module @xbibzlibrary/whatsbibz/lib/Utils/use-multi-file-auth-state */
|
|
2
2
|
import { Mutex } from 'async-mutex';
|
|
3
|
-
import {
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'fs/promises';
|
|
4
5
|
import { join } from 'path';
|
|
5
6
|
import { proto } from '../../WAProto/index.js';
|
|
6
7
|
import { initAuthCreds } from './auth-utils.js';
|
|
@@ -10,14 +11,20 @@ import { BufferJSON } from './generics.js';
|
|
|
10
11
|
// https://github.com/nodejs/node/issues/26338
|
|
11
12
|
// Use a Map to store mutexes for each file path
|
|
12
13
|
const fileLocks = new Map();
|
|
13
|
-
//
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
// Count waiters as well as the owner so unused per-file locks can be released
|
|
15
|
+
// without racing a queued operation. This only serializes within one process.
|
|
16
|
+
const withFileLock = async (path, task) => {
|
|
17
|
+
let entry = fileLocks.get(path);
|
|
18
|
+
if (!entry) {
|
|
19
|
+
entry = { mutex: new Mutex(), users: 0 };
|
|
20
|
+
fileLocks.set(path, entry);
|
|
21
|
+
}
|
|
22
|
+
entry.users++;
|
|
23
|
+
try {
|
|
24
|
+
return await entry.mutex.runExclusive(task);
|
|
25
|
+
} finally {
|
|
26
|
+
if (--entry.users === 0 && fileLocks.get(path) === entry) fileLocks.delete(path);
|
|
19
27
|
}
|
|
20
|
-
return mutex;
|
|
21
28
|
};
|
|
22
29
|
/**
|
|
23
30
|
* stores the full authentication state in a single folder.
|
|
@@ -30,28 +37,26 @@ export const useMultiFileAuthState = async (folder, { strict = false } = {}) =>
|
|
|
30
37
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
31
38
|
const writeData = async (data, file) => {
|
|
32
39
|
const filePath = join(folder, fixFileName(file));
|
|
33
|
-
|
|
34
|
-
|
|
40
|
+
return withFileLock(filePath, async () => {
|
|
41
|
+
// Write privately in the same directory, then replace the file in
|
|
42
|
+
// one rename. A partial write or failure before rename leaves the
|
|
43
|
+
// previous file intact. This is not a multi-file transaction or a
|
|
44
|
+
// power-loss durability guarantee; keep regular private backups.
|
|
45
|
+
const temporary = join(folder, `.auth-${randomBytes(12).toString('hex')}.tmp`);
|
|
35
46
|
try {
|
|
36
|
-
await writeFile(
|
|
37
|
-
|
|
38
|
-
finally {
|
|
39
|
-
|
|
47
|
+
await writeFile(temporary, JSON.stringify(data, BufferJSON.replacer), { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
48
|
+
await rename(temporary, filePath);
|
|
49
|
+
} finally {
|
|
50
|
+
await unlink(temporary).catch(() => {});
|
|
40
51
|
}
|
|
41
52
|
});
|
|
42
53
|
};
|
|
43
54
|
const readData = async (file) => {
|
|
44
55
|
try {
|
|
45
56
|
const filePath = join(folder, fixFileName(file));
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const data = await readFile(filePath, { encoding: 'utf-8' });
|
|
50
|
-
return JSON.parse(data, BufferJSON.reviver);
|
|
51
|
-
}
|
|
52
|
-
finally {
|
|
53
|
-
release();
|
|
54
|
-
}
|
|
57
|
+
return await withFileLock(filePath, async () => {
|
|
58
|
+
const data = await readFile(filePath, { encoding: 'utf-8' });
|
|
59
|
+
return JSON.parse(data, BufferJSON.reviver);
|
|
55
60
|
});
|
|
56
61
|
}
|
|
57
62
|
catch (error) {
|
|
@@ -67,16 +72,8 @@ export const useMultiFileAuthState = async (folder, { strict = false } = {}) =>
|
|
|
67
72
|
const removeData = async (file) => {
|
|
68
73
|
try {
|
|
69
74
|
const filePath = join(folder, fixFileName(file));
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
await unlink(filePath);
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
}
|
|
77
|
-
finally {
|
|
78
|
-
release();
|
|
79
|
-
}
|
|
75
|
+
return withFileLock(filePath, async () => {
|
|
76
|
+
try { await unlink(filePath); } catch {}
|
|
80
77
|
});
|
|
81
78
|
}
|
|
82
79
|
catch { }
|
|
@@ -88,7 +85,8 @@ export const useMultiFileAuthState = async (folder, { strict = false } = {}) =>
|
|
|
88
85
|
}
|
|
89
86
|
}
|
|
90
87
|
else {
|
|
91
|
-
|
|
88
|
+
// Existing directories are left untouched; new ones are private on POSIX.
|
|
89
|
+
await mkdir(folder, { recursive: true, mode: 0o700 });
|
|
92
90
|
}
|
|
93
91
|
const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
|
|
94
92
|
const storedCreds = await readData('creds.json');
|
|
@@ -10,7 +10,7 @@ export declare class AudioFeeder {
|
|
|
10
10
|
underflowChunks: number;
|
|
11
11
|
bytesProduced: number;
|
|
12
12
|
chunksEmitted: number;
|
|
13
|
-
constructor(sampleRate: number, channels: number, framesPerChunk: number, onChunk: (chunk: Float32Array) => void, source?: string);
|
|
13
|
+
constructor(sampleRate: number, channels: number, framesPerChunk: number, onChunk: (chunk: Float32Array) => void, source?: string, options?: { ffmpegPath?: string; onError?: (error: Error & { code: string }) => void; onFinished?: () => void });
|
|
14
14
|
start: () => void;
|
|
15
15
|
stop: () => void;
|
|
16
16
|
}
|