@hiroosy/baileys-lite 0.0.4 → 0.3.1
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/LICENSE +21 -0
- package/README.md +658 -10
- package/WAProto/index.js +2 -2558
- package/engine-requirements.js +3 -4
- package/package.json +8 -3
- package/src/binary/wa-binary.js +3 -25
- package/src/constants.js +7 -15
- package/src/defaults.js +2 -5
- package/src/foundation/ai-rich.js +530 -0
- package/src/foundation/audio-duration.js +43 -103
- package/src/foundation/audio-samples.js +19 -37
- package/src/foundation/boom.js +0 -7
- package/src/foundation/cache.js +4 -26
- package/src/foundation/concurrency.js +1 -19
- package/src/foundation/curve25519.js +7 -39
- package/src/foundation/link-preview.js +15 -57
- package/src/foundation/logger.js +0 -11
- package/src/foundation/long.js +4 -14
- package/src/foundation/protobuf-minimal.js +21 -53
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +2 -31
- package/src/foundation/zip.js +25 -41
- package/src/index.js +8 -18
- package/src/signal/libsignal.js +23 -78
- package/src/signal/signal-group.js +0 -35
- package/src/signal/signal-repository.js +10 -29
- package/src/socket/business-communities.js +12 -31
- package/src/socket/chats.js +5 -8
- package/src/socket/groups-newsletter.js +18 -17
- package/src/socket/messages-recv.js +81 -127
- package/src/socket/messages-send.js +372 -139
- package/src/socket/socket-core.js +227 -157
- package/src/socket/usync.js +2 -6
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +84 -38
- package/src/utils/auth-state-core.js +14 -56
- package/src/utils/auth-state-storage.js +7 -42
- package/src/utils/chat-sync.js +4 -26
- package/src/utils/media.js +15 -71
- package/src/utils/message-compose.js +208 -85
- package/src/utils/message-processing.js +10 -65
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +71 -127
- package/src/vendor/jpeg-js/decoder.js +75 -136
- package/src/vendor/jpeg-js/encoder.js +179 -264
- package/src/vendor/pngjs/bitmapper.js +5 -27
- package/src/vendor/pngjs/bitpacker.js +4 -12
- package/src/vendor/pngjs/constants.js +3 -11
- package/src/vendor/pngjs/crc.js +0 -6
- package/src/vendor/pngjs/filter-pack.js +1 -7
- package/src/vendor/pngjs/filter-parse-sync.js +0 -6
- package/src/vendor/pngjs/filter-parse.js +1 -11
- package/src/vendor/pngjs/format-normaliser.js +5 -11
- package/src/vendor/pngjs/interlace.js +7 -24
- package/src/vendor/pngjs/packer-sync.js +0 -11
- package/src/vendor/pngjs/packer.js +7 -15
- package/src/vendor/pngjs/paeth-predictor.js +0 -6
- package/src/vendor/pngjs/parser-sync.js +0 -8
- package/src/vendor/pngjs/parser.js +5 -29
- package/src/vendor/pngjs/png-sync.js +0 -7
- package/src/vendor/pngjs/sync-inflate.js +7 -16
- package/src/vendor/pngjs/sync-reader.js +4 -11
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1705 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +628 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +0 -1
- package/src/wam/wam.js +2 -7
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { parseSignalAddressFromJid } from './shim/protocol.js';
|
|
2
|
+
import { resolveBaileysModule } from './shim/baileys-resolve.js';
|
|
3
|
+
const SESSION_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
4
|
+
const TC_TOKEN_REQUEST_TIMEOUT_MS = 3500;
|
|
5
|
+
let cachedBaileysHelpers = null;
|
|
6
|
+
async function loadBaileysHelpers() {
|
|
7
|
+
if (cachedBaileysHelpers)
|
|
8
|
+
return cachedBaileysHelpers;
|
|
9
|
+
const mod = await resolveBaileysModule();
|
|
10
|
+
cachedBaileysHelpers = {
|
|
11
|
+
jidDecode: mod.jidDecode,
|
|
12
|
+
jidEncode: mod.jidEncode,
|
|
13
|
+
parseAndInjectE2ESessions: mod.parseAndInjectE2ESessions,
|
|
14
|
+
encodeSignedDeviceIdentity: mod.encodeSignedDeviceIdentity,
|
|
15
|
+
getBinaryNodeChild: mod.getBinaryNodeChild,
|
|
16
|
+
getAllBinaryNodeChildren: mod.getAllBinaryNodeChildren
|
|
17
|
+
};
|
|
18
|
+
return cachedBaileysHelpers;
|
|
19
|
+
}
|
|
20
|
+
function addressToJid(address) {
|
|
21
|
+
return address.device
|
|
22
|
+
? `${address.user}:${address.device}@${address.server}`
|
|
23
|
+
: `${address.user}@${address.server}`;
|
|
24
|
+
}
|
|
25
|
+
function normalizeDeviceList(baileysHelpers, jids) {
|
|
26
|
+
const { jidDecode, jidEncode } = baileysHelpers;
|
|
27
|
+
const result = new Set();
|
|
28
|
+
for (const jid of jids) {
|
|
29
|
+
const decoded = jidDecode(jid);
|
|
30
|
+
if (!decoded?.user) {
|
|
31
|
+
result.add(jid);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const server = String(jid).endsWith('@lid') ? 'lid' : 's.whatsapp.net';
|
|
35
|
+
result.add(jidEncode(decoded.user, server));
|
|
36
|
+
if (decoded.device != null)
|
|
37
|
+
result.add(`${decoded.user}:${decoded.device}@${server}`);
|
|
38
|
+
}
|
|
39
|
+
return [...result].slice(0, 5);
|
|
40
|
+
}
|
|
41
|
+
async function resolvePeerLid(sock, target) {
|
|
42
|
+
const raw = String(target || '').trim();
|
|
43
|
+
if (!raw)
|
|
44
|
+
throw new Error('resolvePeerLid: target is required');
|
|
45
|
+
if (raw.endsWith('@lid'))
|
|
46
|
+
return raw;
|
|
47
|
+
const pnJid = raw.includes('@') ? raw : `${raw.replace(/\D/g, '')}@s.whatsapp.net`;
|
|
48
|
+
const lid = await sock.signalRepository.lidMapping?.getLIDForPN(pnJid);
|
|
49
|
+
if (lid)
|
|
50
|
+
return lid;
|
|
51
|
+
return pnJid;
|
|
52
|
+
}
|
|
53
|
+
async function discoverPeerDevices(sock, baileysHelpers, peerLid) {
|
|
54
|
+
const devices = await sock.getUSyncDevices([peerLid], true, false);
|
|
55
|
+
const jids = devices.map((d) => d.jid).filter(Boolean);
|
|
56
|
+
if (!jids.length)
|
|
57
|
+
return [];
|
|
58
|
+
return normalizeDeviceList(baileysHelpers, jids);
|
|
59
|
+
}
|
|
60
|
+
async function ensureSignalSessions(sock, baileysHelpers, jids, cache) {
|
|
61
|
+
const missing = [];
|
|
62
|
+
for (const jid of [...new Set(jids.filter(Boolean))]) {
|
|
63
|
+
const signalId = sock.signalRepository.jidToSignalProtocolAddress(jid);
|
|
64
|
+
const cachedAt = cache.get(signalId);
|
|
65
|
+
if (cachedAt && Date.now() - cachedAt < SESSION_CACHE_TTL_MS)
|
|
66
|
+
continue;
|
|
67
|
+
const validation = await sock.signalRepository.validateSession(jid);
|
|
68
|
+
if (validation?.exists) {
|
|
69
|
+
cache.set(signalId, Date.now());
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
missing.push(jid);
|
|
73
|
+
}
|
|
74
|
+
if (!missing.length)
|
|
75
|
+
return;
|
|
76
|
+
const sessionNode = await sock.query({
|
|
77
|
+
tag: 'iq',
|
|
78
|
+
attrs: { xmlns: 'encrypt', type: 'get', to: 's.whatsapp.net' },
|
|
79
|
+
content: [
|
|
80
|
+
{ tag: 'key', attrs: {}, content: missing.map((jid) => ({ tag: 'user', attrs: { jid } })) }
|
|
81
|
+
]
|
|
82
|
+
});
|
|
83
|
+
await baileysHelpers.parseAndInjectE2ESessions(sessionNode, sock.signalRepository);
|
|
84
|
+
for (const jid of missing) {
|
|
85
|
+
cache.set(sock.signalRepository.jidToSignalProtocolAddress(jid), Date.now());
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function toBareJid(jid) {
|
|
89
|
+
const at = String(jid).indexOf('@');
|
|
90
|
+
if (at < 0)
|
|
91
|
+
return jid;
|
|
92
|
+
const user = String(jid).slice(0, at).split(':')[0];
|
|
93
|
+
return `${user}@${String(jid).slice(at + 1)}`;
|
|
94
|
+
}
|
|
95
|
+
async function issueTcToken(sock, baileysHelpers, jid) {
|
|
96
|
+
const userJid = toBareJid(jid);
|
|
97
|
+
const issuedAt = Math.floor(Date.now() / 1000);
|
|
98
|
+
try {
|
|
99
|
+
const response = await sock.query({
|
|
100
|
+
tag: 'iq',
|
|
101
|
+
attrs: { to: 's.whatsapp.net', type: 'set', xmlns: 'privacy', id: sock.generateMessageTag() },
|
|
102
|
+
content: [
|
|
103
|
+
{
|
|
104
|
+
tag: 'tokens',
|
|
105
|
+
attrs: {},
|
|
106
|
+
content: [{ tag: 'token', attrs: { jid: userJid, t: String(issuedAt), type: 'trusted_contact' } }]
|
|
107
|
+
}
|
|
108
|
+
]
|
|
109
|
+
});
|
|
110
|
+
const { getBinaryNodeChild, getAllBinaryNodeChildren } = baileysHelpers;
|
|
111
|
+
const tokensNode = getBinaryNodeChild(response, 'tokens');
|
|
112
|
+
const tokenNodes = tokensNode ? getAllBinaryNodeChildren(tokensNode).filter((c) => c.tag === 'token') : [];
|
|
113
|
+
for (const tokenNode of tokenNodes) {
|
|
114
|
+
if (tokenNode.attrs.type !== 'trusted_contact')
|
|
115
|
+
continue;
|
|
116
|
+
const content = tokenNode.content;
|
|
117
|
+
if (content instanceof Uint8Array && content.length > 0) {
|
|
118
|
+
await sock.authState.keys.set({
|
|
119
|
+
tctoken: { [userJid]: { token: Buffer.from(content), timestamp: String(tokenNode.attrs.t ?? issuedAt) } }
|
|
120
|
+
});
|
|
121
|
+
return Buffer.from(content);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function getCachedTcToken(sock, jid) {
|
|
131
|
+
try {
|
|
132
|
+
const result = await sock.authState.keys.get('tctoken', [jid]);
|
|
133
|
+
const cached = result?.[jid];
|
|
134
|
+
return cached?.token?.length ? Buffer.from(cached.token) : undefined;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function ensureTcToken(sock, baileysHelpers, jid) {
|
|
141
|
+
const bare = toBareJid(jid);
|
|
142
|
+
const cached = await getCachedTcToken(sock, bare);
|
|
143
|
+
if (cached?.length)
|
|
144
|
+
return cached;
|
|
145
|
+
return Promise.race([
|
|
146
|
+
issueTcToken(sock, baileysHelpers, bare),
|
|
147
|
+
new Promise((resolve) => setTimeout(() => resolve(undefined), TC_TOKEN_REQUEST_TIMEOUT_MS))
|
|
148
|
+
]);
|
|
149
|
+
}
|
|
150
|
+
export async function createVoipDeps(sock) {
|
|
151
|
+
const baileysHelpers = await loadBaileysHelpers();
|
|
152
|
+
const sessionCache = new Map();
|
|
153
|
+
const deps = {
|
|
154
|
+
authClient: {
|
|
155
|
+
getCurrentCredentials() {
|
|
156
|
+
const creds = sock.authState?.creds;
|
|
157
|
+
const account = creds?.account;
|
|
158
|
+
let signedIdentity;
|
|
159
|
+
if (account) {
|
|
160
|
+
try {
|
|
161
|
+
signedIdentity = baileysHelpers.encodeSignedDeviceIdentity(account, true);
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
signedIdentity = undefined;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
meLid: creds?.me?.lid,
|
|
169
|
+
meJid: creds?.me?.id,
|
|
170
|
+
signedIdentity
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
lowLevelCoordinator: {
|
|
175
|
+
async sendNode(node) {
|
|
176
|
+
await sock.sendNode(node);
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
signalDeviceSync: {
|
|
180
|
+
async syncDeviceList(jids) {
|
|
181
|
+
const out = [];
|
|
182
|
+
for (const jid of jids) {
|
|
183
|
+
try {
|
|
184
|
+
const peerLid = await resolvePeerLid(sock, jid);
|
|
185
|
+
const deviceJids = await discoverPeerDevices(sock, baileysHelpers, peerLid);
|
|
186
|
+
out.push({ deviceJids });
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
out.push({ deviceJids: [] });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
},
|
|
194
|
+
async queryLidsByPhoneJids(jids) {
|
|
195
|
+
const out = [];
|
|
196
|
+
for (const jid of jids) {
|
|
197
|
+
try {
|
|
198
|
+
out.push({ lidJid: await resolvePeerLid(sock, jid) });
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
out.push({ lidJid: undefined });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
sessionResolver: {
|
|
208
|
+
async ensureSessionsBatch(devices) {
|
|
209
|
+
await ensureSignalSessions(sock, baileysHelpers, devices, sessionCache);
|
|
210
|
+
return devices.map((jid) => ({ address: parseSignalAddressFromJid(jid), session: null }));
|
|
211
|
+
}
|
|
212
|
+
},
|
|
213
|
+
signalProtocol: {
|
|
214
|
+
async encryptMessage(address, plaintext) {
|
|
215
|
+
const jid = addressToJid(address);
|
|
216
|
+
const { type, ciphertext } = await sock.signalRepository.encryptMessage({
|
|
217
|
+
jid,
|
|
218
|
+
data: Buffer.from(plaintext)
|
|
219
|
+
});
|
|
220
|
+
return { type, ciphertext: new Uint8Array(ciphertext) };
|
|
221
|
+
},
|
|
222
|
+
async decryptMessage(address, { type, ciphertext }) {
|
|
223
|
+
const jid = addressToJid(address);
|
|
224
|
+
const decrypted = await sock.signalRepository.decryptMessage({ jid, type, ciphertext });
|
|
225
|
+
return new Uint8Array(decrypted);
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
messageDispatch: {
|
|
229
|
+
async syncSignalSession(jid) {
|
|
230
|
+
await ensureSignalSessions(sock, baileysHelpers, [jid], sessionCache);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
const stores = {
|
|
235
|
+
privacyToken: {
|
|
236
|
+
async getByJid(jid) {
|
|
237
|
+
const token = await ensureTcToken(sock, baileysHelpers, jid);
|
|
238
|
+
return token?.length ? { tcToken: token } : undefined;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
return { deps, stores };
|
|
243
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { WaVoipCoordinator } from './WaVoipCoordinator.js';
|
|
3
|
+
import { createVoipDeps } from './voip-deps.js';
|
|
4
|
+
import { createConsoleLogger } from './shim/core.js';
|
|
5
|
+
|
|
6
|
+
async function resolvePeerLid(sock, target) {
|
|
7
|
+
const raw = String(target || '').trim();
|
|
8
|
+
if (!raw)
|
|
9
|
+
throw new Error('resolvePeerLid: target is required');
|
|
10
|
+
if (raw.endsWith('@lid'))
|
|
11
|
+
return raw;
|
|
12
|
+
const pnJid = raw.includes('@') ? raw : `${raw.replace(/\D/g, '')}@s.whatsapp.net`;
|
|
13
|
+
const lid = await sock.signalRepository.lidMapping?.getLIDForPN(pnJid);
|
|
14
|
+
return lid || pnJid;
|
|
15
|
+
}
|
|
16
|
+
function createVoipCtx(sock, deps, stores, logger, emitter) {
|
|
17
|
+
return {
|
|
18
|
+
deps,
|
|
19
|
+
stores,
|
|
20
|
+
logger,
|
|
21
|
+
registerIncomingHandler({ tag, prepend, handler }) {
|
|
22
|
+
const listener = (node) => {
|
|
23
|
+
Promise.resolve(handler(node)).catch((err) => {
|
|
24
|
+
logger.error('voip incoming handler failed', { tag, message: err?.message });
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
const key = `CB:${tag}`;
|
|
28
|
+
if (prepend && typeof sock.ws.prependListener === 'function') {
|
|
29
|
+
sock.ws.prependListener(key, listener);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
sock.ws.on(key, listener);
|
|
33
|
+
}
|
|
34
|
+
return () => {
|
|
35
|
+
try {
|
|
36
|
+
sock.ws.off(key, listener);
|
|
37
|
+
}
|
|
38
|
+
catch { }
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
emit(event, payload) {
|
|
42
|
+
emitter.emit(event, payload);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export class ActiveCall extends EventEmitter {
|
|
47
|
+
callId;
|
|
48
|
+
#coordinator;
|
|
49
|
+
#endResolver;
|
|
50
|
+
#endPromise;
|
|
51
|
+
#endTimer = null;
|
|
52
|
+
#ended = false;
|
|
53
|
+
#connectedEmitted = false;
|
|
54
|
+
constructor(coordinator, callId, durationMs) {
|
|
55
|
+
super();
|
|
56
|
+
this.callId = callId;
|
|
57
|
+
this.#coordinator = coordinator;
|
|
58
|
+
this.#endPromise = new Promise((res) => { this.#endResolver = res; });
|
|
59
|
+
if (durationMs > 0)
|
|
60
|
+
this.#endTimer = setTimeout(() => this.end(), durationMs);
|
|
61
|
+
}
|
|
62
|
+
_onState(call) {
|
|
63
|
+
if (call.callId !== this.callId)
|
|
64
|
+
return;
|
|
65
|
+
if (call.isRinging)
|
|
66
|
+
this.emit('ringing');
|
|
67
|
+
if (call.isActive && !this.#connectedEmitted) {
|
|
68
|
+
this.#connectedEmitted = true;
|
|
69
|
+
this.emit('connected');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
_onEnded(call) {
|
|
73
|
+
if (call.callId !== this.callId)
|
|
74
|
+
return;
|
|
75
|
+
this._forceEnd(call.stateData?.endReason ?? 'ended');
|
|
76
|
+
}
|
|
77
|
+
_onError(err) {
|
|
78
|
+
this.emit('error', err);
|
|
79
|
+
}
|
|
80
|
+
setMute = (muted) => this.#coordinator.setMute(this.callId, !!muted);
|
|
81
|
+
raiseHand = (raised = true) => this.#coordinator.setHandRaised(this.callId, !!raised);
|
|
82
|
+
shareScreen = (sharing = true) => this.#coordinator.setScreenShare(this.callId, !!sharing);
|
|
83
|
+
react = (emoji) => this.#coordinator.sendReaction(this.callId, emoji);
|
|
84
|
+
upgradeToVideo = () => this.#coordinator.startVideoMidCall(this.callId);
|
|
85
|
+
end = async () => {
|
|
86
|
+
if (this.#ended)
|
|
87
|
+
return;
|
|
88
|
+
if (this.#endTimer) {
|
|
89
|
+
clearTimeout(this.#endTimer);
|
|
90
|
+
this.#endTimer = null;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
await this.#coordinator.endCall(this.callId);
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
this._forceEnd('ended');
|
|
97
|
+
throw e;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
waitForEnd = () => this.#endPromise;
|
|
101
|
+
get connected() {
|
|
102
|
+
return this.#connectedEmitted;
|
|
103
|
+
}
|
|
104
|
+
get ended() {
|
|
105
|
+
return this.#ended;
|
|
106
|
+
}
|
|
107
|
+
_forceEnd = (reason) => {
|
|
108
|
+
if (this.#ended)
|
|
109
|
+
return;
|
|
110
|
+
this.#ended = true;
|
|
111
|
+
if (this.#endTimer) {
|
|
112
|
+
clearTimeout(this.#endTimer);
|
|
113
|
+
this.#endTimer = null;
|
|
114
|
+
}
|
|
115
|
+
this.emit('ended', reason);
|
|
116
|
+
this.#endResolver(reason);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
export class VoipClient {
|
|
120
|
+
#config;
|
|
121
|
+
#sock = null;
|
|
122
|
+
#coordinator = null;
|
|
123
|
+
#activeCalls = new Map();
|
|
124
|
+
#offSocketClose = null;
|
|
125
|
+
#connecting = null;
|
|
126
|
+
constructor(config) {
|
|
127
|
+
this.#config = config;
|
|
128
|
+
if (!config?.existingSocket) {
|
|
129
|
+
throw new Error('VoipClient requires { existingSocket }: VOIP always runs on the main bot session now, there is no standalone-device mode.');
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
get coordinator() {
|
|
133
|
+
return this.#coordinator;
|
|
134
|
+
}
|
|
135
|
+
get activeCalls() {
|
|
136
|
+
return [...this.#activeCalls.values()];
|
|
137
|
+
}
|
|
138
|
+
connect = () => {
|
|
139
|
+
if (this.#coordinator && this.#sock === this.#config.existingSocket) {
|
|
140
|
+
return Promise.resolve();
|
|
141
|
+
}
|
|
142
|
+
if (!this.#connecting) {
|
|
143
|
+
this.#connecting = this.#setup().finally(() => {
|
|
144
|
+
this.#connecting = null;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return this.#connecting;
|
|
148
|
+
};
|
|
149
|
+
#setup = async () => {
|
|
150
|
+
this.#sock = this.#config.existingSocket;
|
|
151
|
+
const { deps, stores } = await createVoipDeps(this.#sock);
|
|
152
|
+
const logger = createConsoleLogger(this.#config.voipLogLevel ?? 'warn');
|
|
153
|
+
const emitter = new EventEmitter();
|
|
154
|
+
const ctx = createVoipCtx(this.#sock, deps, stores, logger, emitter);
|
|
155
|
+
this.#coordinator = new WaVoipCoordinator(ctx, {
|
|
156
|
+
maxConcurrentCalls: this.#config.maxConcurrentCalls ?? 1,
|
|
157
|
+
logLevel: this.#config.voipLogLevel ?? 'warn'
|
|
158
|
+
});
|
|
159
|
+
const sock = this.#sock;
|
|
160
|
+
const onUpdate = (update) => {
|
|
161
|
+
if (update?.connection !== 'close')
|
|
162
|
+
return;
|
|
163
|
+
if (this.#sock !== sock)
|
|
164
|
+
return;
|
|
165
|
+
logger.warn('voip: socket closed, tearing down active calls');
|
|
166
|
+
this.#teardown('connection_closed');
|
|
167
|
+
};
|
|
168
|
+
sock.ev?.on?.('connection.update', onUpdate);
|
|
169
|
+
this.#offSocketClose = () => {
|
|
170
|
+
try {
|
|
171
|
+
sock.ev?.off?.('connection.update', onUpdate);
|
|
172
|
+
}
|
|
173
|
+
catch { }
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
#teardown(reason) {
|
|
177
|
+
const calls = [...this.#activeCalls.values()];
|
|
178
|
+
this.#activeCalls.clear();
|
|
179
|
+
this.#offSocketClose?.();
|
|
180
|
+
this.#offSocketClose = null;
|
|
181
|
+
for (const call of calls) {
|
|
182
|
+
try {
|
|
183
|
+
call._forceEnd(reason);
|
|
184
|
+
}
|
|
185
|
+
catch { }
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
this.#coordinator?.dispose();
|
|
189
|
+
}
|
|
190
|
+
catch { }
|
|
191
|
+
this.#sock = null;
|
|
192
|
+
this.#coordinator = null;
|
|
193
|
+
}
|
|
194
|
+
call = async (phoneNumber, opts = {}) => {
|
|
195
|
+
const coordinator = this.#coordinator;
|
|
196
|
+
if (!this.#sock || !coordinator)
|
|
197
|
+
throw new Error('Not connected. Call connect() first.');
|
|
198
|
+
const durationMs = opts.durationMs ?? 120_000;
|
|
199
|
+
const peerJid = await resolvePeerLid(this.#sock, phoneNumber);
|
|
200
|
+
const audioFile = opts.audioSource && opts.audioSource !== 'silence' ? opts.audioSource : undefined;
|
|
201
|
+
const callId = await coordinator.startCall({
|
|
202
|
+
peerJid,
|
|
203
|
+
isVideo: !!opts.isVideo,
|
|
204
|
+
audioFile,
|
|
205
|
+
videoConfig: opts.videoConfig
|
|
206
|
+
});
|
|
207
|
+
if (this.#coordinator !== coordinator) {
|
|
208
|
+
throw new Error('Connection closed while placing the call.');
|
|
209
|
+
}
|
|
210
|
+
if (audioFile) {
|
|
211
|
+
try {
|
|
212
|
+
await coordinator.loadAudio(callId, audioFile);
|
|
213
|
+
} catch (e) {
|
|
214
|
+
console.error(`[ VOIP ] Failed to load audio "${audioFile}" for call ${callId}:`, e?.message || e);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (opts.isVideo && opts.videoSource) {
|
|
218
|
+
try {
|
|
219
|
+
await coordinator.loadVideo(callId, opts.videoSource);
|
|
220
|
+
} catch (e) {
|
|
221
|
+
console.error(`[ VOIP ] Failed to load video "${opts.videoSource}" for call ${callId}:`, e?.message || e);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (this.#coordinator !== coordinator) {
|
|
225
|
+
throw new Error('Connection closed while placing the call.');
|
|
226
|
+
}
|
|
227
|
+
return this.#track(coordinator, callId, durationMs);
|
|
228
|
+
};
|
|
229
|
+
#track = (coordinator, callId, durationMs) => {
|
|
230
|
+
const call = new ActiveCall(coordinator, callId, durationMs);
|
|
231
|
+
this.#activeCalls.set(callId, call);
|
|
232
|
+
call.coordinator = coordinator;
|
|
233
|
+
const onState = (info) => call._onState(info);
|
|
234
|
+
const onEnded = (info) => call._onEnded(info);
|
|
235
|
+
const onError = (err) => {
|
|
236
|
+
if (err?.callId && err.callId !== callId)
|
|
237
|
+
return;
|
|
238
|
+
call._onError(err);
|
|
239
|
+
};
|
|
240
|
+
coordinator.on('call_state', onState);
|
|
241
|
+
coordinator.on('call_ended', onEnded);
|
|
242
|
+
coordinator.on('call_error', onError);
|
|
243
|
+
const forwarded = [
|
|
244
|
+
['call_peer_mute', 'peer_mute', (c, muted) => [muted]],
|
|
245
|
+
['call_hand_raise', 'hand_raise', (c, jid, raised) => [{ jid, raised }]],
|
|
246
|
+
['call_reaction', 'reaction', (c, reaction) => [reaction]],
|
|
247
|
+
['call_screen_share', 'screen_share', (c, share) => [share]],
|
|
248
|
+
['call_video_state', 'peer_video', (c, change) => [change]],
|
|
249
|
+
['call_inbound_audio', 'inbound_audio', (c, pcm) => [pcm]],
|
|
250
|
+
['call_inbound_video', 'inbound_video', (c, frame) => [frame]],
|
|
251
|
+
['call_outbound_audio_finished', 'audio_finished', () => []]
|
|
252
|
+
].map(([source, target, shape]) => {
|
|
253
|
+
const listener = (info, ...rest) => {
|
|
254
|
+
if (info?.callId === callId)
|
|
255
|
+
call.emit(target, ...shape(info, ...rest));
|
|
256
|
+
};
|
|
257
|
+
coordinator.on(source, listener);
|
|
258
|
+
return [source, listener];
|
|
259
|
+
});
|
|
260
|
+
call.once('ended', () => {
|
|
261
|
+
for (const [source, listener] of forwarded)
|
|
262
|
+
coordinator.off(source, listener);
|
|
263
|
+
coordinator.off('call_state', onState);
|
|
264
|
+
coordinator.off('call_ended', onEnded);
|
|
265
|
+
coordinator.off('call_error', onError);
|
|
266
|
+
if (this.#activeCalls.get(callId) === call)
|
|
267
|
+
this.#activeCalls.delete(callId);
|
|
268
|
+
});
|
|
269
|
+
return call;
|
|
270
|
+
};
|
|
271
|
+
answer = async (callId, opts = {}) => {
|
|
272
|
+
const coordinator = this.#coordinator;
|
|
273
|
+
if (!this.#sock || !coordinator)
|
|
274
|
+
throw new Error('Not connected. Call connect() first.');
|
|
275
|
+
const info = coordinator.getCall(callId);
|
|
276
|
+
if (!info)
|
|
277
|
+
throw new Error(`Unknown call ${callId}.`);
|
|
278
|
+
if (!info.canAccept)
|
|
279
|
+
throw new Error(`Call ${callId} cannot be accepted right now.`);
|
|
280
|
+
const call = this.#track(coordinator, callId, opts.durationMs ?? 0);
|
|
281
|
+
try {
|
|
282
|
+
await coordinator.acceptCall(callId);
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
call._forceEnd('failed');
|
|
286
|
+
throw err;
|
|
287
|
+
}
|
|
288
|
+
const audioFile = opts.audioSource && opts.audioSource !== 'silence' ? opts.audioSource : undefined;
|
|
289
|
+
if (audioFile) {
|
|
290
|
+
try {
|
|
291
|
+
await coordinator.loadAudio(callId, audioFile);
|
|
292
|
+
} catch (e) {
|
|
293
|
+
console.error(`[ VOIP ] Failed to load audio "${audioFile}" for call ${callId}:`, e?.message || e);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (opts.videoSource) {
|
|
297
|
+
try {
|
|
298
|
+
await coordinator.loadVideo(callId, opts.videoSource);
|
|
299
|
+
} catch (e) {
|
|
300
|
+
console.error(`[ VOIP ] Failed to load video "${opts.videoSource}" for call ${callId}:`, e?.message || e);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return call;
|
|
304
|
+
};
|
|
305
|
+
disconnect = () => {
|
|
306
|
+
for (const call of this.#activeCalls.values()) {
|
|
307
|
+
try {
|
|
308
|
+
call.end()?.catch?.(() => { });
|
|
309
|
+
}
|
|
310
|
+
catch { }
|
|
311
|
+
}
|
|
312
|
+
this.#teardown('disconnected');
|
|
313
|
+
};
|
|
314
|
+
}
|
package/src/wam/wam-constants.js
CHANGED
|
@@ -22850,4 +22850,3 @@ export const WEB_GLOBALS = [
|
|
|
22850
22850
|
}
|
|
22851
22851
|
];
|
|
22852
22852
|
export const FLAG_BYTE = 8, FLAG_GLOBAL = 0, FLAG_EVENT = 1, FLAG_FIELD = 2, FLAG_EXTENDED = 4;
|
|
22853
|
-
//# sourceMappingURL=constants.js.map
|
package/src/wam/wam.js
CHANGED
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* WAM (telemetry) binary encoder. Combines BinaryInfo.js + encode.js.
|
|
3
|
-
* WEB_EVENTS/WEB_GLOBALS/flag constants (wam-constants.js) are a pure,
|
|
4
|
-
* effectively auto-generated data table — kept as its own file, unedited.
|
|
5
|
-
*/
|
|
6
1
|
import { FLAG_BYTE, FLAG_EVENT, FLAG_EXTENDED, FLAG_FIELD, FLAG_GLOBAL, WEB_EVENTS, WEB_GLOBALS } from './wam-constants.js'
|
|
7
2
|
|
|
8
3
|
export class BinaryInfo {
|
|
@@ -35,9 +30,9 @@ function encodeWAMHeader(binaryInfo) {
|
|
|
35
30
|
const headerBuffer = Buffer.alloc(8)
|
|
36
31
|
headerBuffer.write('WAM', 0, 'utf8')
|
|
37
32
|
headerBuffer.writeUInt8(binaryInfo.protocolVersion, 3)
|
|
38
|
-
headerBuffer.writeUInt8(1, 4)
|
|
33
|
+
headerBuffer.writeUInt8(1, 4)
|
|
39
34
|
headerBuffer.writeUInt16BE(binaryInfo.sequence, 5)
|
|
40
|
-
headerBuffer.writeUInt8(0, 7)
|
|
35
|
+
headerBuffer.writeUInt8(0, 7)
|
|
41
36
|
binaryInfo.buffer.push(headerBuffer)
|
|
42
37
|
}
|
|
43
38
|
|