@itznomo/baileys 0.0.0-stage → 0.0.3

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.
Files changed (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,158 @@
1
+ import { WA_MESSAGE_TAGS } from './shim/protocol.js';
2
+ import { WaCallManager } from './call/WaCallManager.js';
3
+ import { routeCallAck, routeCallReceipt, routeCallStanza } from './signaling/bridge.js';
4
+ export class WaVoipCoordinator {
5
+ manager;
6
+ deps;
7
+ logger;
8
+ unregisterHandlers = [];
9
+ constructor(ctx, options = {}) {
10
+ this.deps = ctx.deps;
11
+ this.logger = ctx.logger.child({ scope: 'voip' }, { level: options.logLevel });
12
+ this.manager = new WaCallManager({
13
+ deps: ctx.deps,
14
+ stores: ctx.stores,
15
+ logger: this.logger,
16
+ maxConcurrentCalls: options.maxConcurrentCalls
17
+ });
18
+ this.registerIncomingHandlers(ctx);
19
+ this.wireClientEvents(ctx);
20
+ }
21
+ async startCall(options) {
22
+ return this.manager.startCall(options);
23
+ }
24
+ async acceptCall(callId) {
25
+ return this.manager.acceptCall(callId);
26
+ }
27
+ async rejectCall(callId, reason) {
28
+ return this.manager.rejectCall(callId, reason);
29
+ }
30
+ async endCall(callId, reason) {
31
+ return this.manager.endCall(callId, reason);
32
+ }
33
+ async loadAudio(callId, audioPath) {
34
+ return this.manager.loadAudio(callId, audioPath);
35
+ }
36
+ async loadVideo(callId, videoPath) {
37
+ return this.manager.loadVideo(callId, videoPath);
38
+ }
39
+ async enableVideoMidCall(callId) {
40
+ return this.manager.enableVideoMidCall(callId);
41
+ }
42
+ async disableVideoMidCall(callId, options) {
43
+ return this.manager.disableVideoMidCall(callId, options);
44
+ }
45
+ async startVideoMidCall(callId) {
46
+ return this.manager.startVideoMidCall(callId);
47
+ }
48
+ async stopVideoMidCall(callId, options) {
49
+ return this.manager.stopVideoMidCall(callId, options);
50
+ }
51
+ async swapVideoSource(callId, videoPath) {
52
+ return this.manager.swapVideoSource(callId, videoPath);
53
+ }
54
+ setMute(callId, muted) {
55
+ this.manager.setMute(callId, muted);
56
+ }
57
+ async setHandRaised(callId, raised) {
58
+ return this.manager.setHandRaised(callId, raised);
59
+ }
60
+ async setScreenShare(callId, sharing) {
61
+ return this.manager.setScreenShare(callId, sharing);
62
+ }
63
+ sendReaction(callId, reaction) {
64
+ return this.manager.sendReaction(callId, reaction);
65
+ }
66
+ setExternalAudioMode(callId, enabled) {
67
+ this.manager.setExternalAudioMode(callId, enabled);
68
+ }
69
+ feedLiveAudio(callId, data) {
70
+ return this.manager.feedLiveAudio(callId, data);
71
+ }
72
+ getLiveBufferMs(callId) {
73
+ return this.manager.getLiveBufferMs(callId);
74
+ }
75
+ getFeedWatermarksMs() {
76
+ return this.manager.getFeedWatermarksMs();
77
+ }
78
+ getCall(callId) {
79
+ return this.manager.getCall(callId);
80
+ }
81
+ getCalls() {
82
+ return this.manager.getCalls();
83
+ }
84
+ on(event, listener) {
85
+ this.manager.on(event, listener);
86
+ return this;
87
+ }
88
+ off(event, listener) {
89
+ this.manager.off(event, listener);
90
+ return this;
91
+ }
92
+ once(event, listener) {
93
+ this.manager.once(event, listener);
94
+ return this;
95
+ }
96
+ dispose() {
97
+ for (const unregister of this.unregisterHandlers.splice(0)) {
98
+ unregister();
99
+ }
100
+ this.manager.destroy();
101
+ }
102
+ registerIncomingHandlers(ctx) {
103
+ this.unregisterHandlers.push(ctx.registerIncomingHandler({
104
+ tag: 'call',
105
+ prepend: true,
106
+ handler: async (node) => {
107
+ const tag = await routeCallStanza(this.manager, this.deps, node, this.logger);
108
+ return tag !== null;
109
+ }
110
+ }), ctx.registerIncomingHandler({
111
+ tag: WA_MESSAGE_TAGS.ACK,
112
+ prepend: true,
113
+ handler: async (node) => {
114
+ if (node.attrs.class !== 'call') {
115
+ return false;
116
+ }
117
+ await routeCallAck(this.manager, node);
118
+ return true;
119
+ }
120
+ }), ctx.registerIncomingHandler({
121
+ tag: WA_MESSAGE_TAGS.RECEIPT,
122
+ prepend: true,
123
+ handler: async (node) => routeCallReceipt(this.deps, node)
124
+ }));
125
+ }
126
+ wireClientEvents(ctx) {
127
+ this.manager.on('call_state', (call) => {
128
+ ctx.emit('voip_call_state', call);
129
+ });
130
+ this.manager.on('call_incoming', (call) => {
131
+ ctx.emit('voip_call_incoming', call);
132
+ });
133
+ this.manager.on('call_ended', (call) => {
134
+ ctx.emit('voip_call_ended', call);
135
+ });
136
+ this.manager.on('call_inbound_audio', (call, pcm) => {
137
+ ctx.emit('voip_call_inbound_audio', { call, pcm });
138
+ });
139
+ this.manager.on('call_outbound_audio_finished', (call) => {
140
+ ctx.emit('voip_call_outbound_audio_finished', call);
141
+ });
142
+ this.manager.on('call_peer_mute', (call, muted) => {
143
+ ctx.emit('voip_call_peer_mute', { call, muted });
144
+ });
145
+ this.manager.on('call_hand_raise', (call, participantJid, raised) => {
146
+ ctx.emit('voip_call_hand_raise', { call, participantJid, raised });
147
+ });
148
+ this.manager.on('call_reaction', (call, reaction) => {
149
+ ctx.emit('voip_call_reaction', { call, reaction });
150
+ });
151
+ this.manager.on('call_screen_share', (call, share) => {
152
+ ctx.emit('voip_call_screen_share', { call, share });
153
+ });
154
+ this.manager.on('call_error', (error) => {
155
+ ctx.emit('voip_call_error', error);
156
+ });
157
+ }
158
+ }
@@ -0,0 +1,193 @@
1
+ import { toError } from '../shim/util.js';
2
+ import { randomInt } from '../crypto/primitives.js';
3
+ import { RtpHeader, RtpPacket } from '../media/rtp.js';
4
+ import { decodeAppDataPayload, encodeReactionPayload } from './protocol.js';
5
+
6
+ const DEFAULT_RETRANSMISSION_INTERVAL_MS = 60;
7
+ const DEFAULT_CLEAR_INTERVAL_MS = 600;
8
+
9
+ const MAX_TRACKED_TRANSACTIONS = 64;
10
+
11
+ export const WA_APP_DATA_PAYLOAD_TYPE = 119;
12
+
13
+ export class WaAppDataStream {
14
+ ssrc;
15
+ logger;
16
+ sendPacket;
17
+ retransmissionIntervalMs;
18
+ clearIntervalMs;
19
+ sequenceNumber = randomInt(0, 65_536);
20
+
21
+ timestamp = randomInt(0, 0xffffffff);
22
+ outgoing = null;
23
+ retransmitTimer = null;
24
+
25
+ seenTransactions = new Set();
26
+
27
+ nextTransactionId = 1n;
28
+ learnedPayloadType;
29
+ configuredPayloadType;
30
+ sframeRequired = false;
31
+ sframeProtect = null;
32
+ txReactionCount = 0;
33
+ txReactionErrorCount = 0;
34
+ rxReactionCount = 0;
35
+ constructor(options) {
36
+ this.logger = options.logger;
37
+ this.ssrc = options.ssrc;
38
+ this.sendPacket = options.sendPacket;
39
+ this.configuredPayloadType = options.payloadType ?? null;
40
+ this.learnedPayloadType = null;
41
+ this.retransmissionIntervalMs =
42
+ options.retransmissionIntervalMs ?? DEFAULT_RETRANSMISSION_INTERVAL_MS;
43
+ this.clearIntervalMs = options.clearIntervalMs ?? DEFAULT_CLEAR_INTERVAL_MS;
44
+ }
45
+
46
+ get payloadType() {
47
+ return this.configuredPayloadType ?? WA_APP_DATA_PAYLOAD_TYPE;
48
+ }
49
+
50
+ get peerPayloadType() {
51
+ return this.learnedPayloadType;
52
+ }
53
+
54
+ observeInboundPayloadType(payloadType) {
55
+ if (this.configuredPayloadType !== null || this.learnedPayloadType === payloadType)
56
+ return;
57
+ this.learnedPayloadType = payloadType;
58
+ this.logger.debug('app data payload type learned from peer', {
59
+ payloadType,
60
+ ssrc: `0x${this.ssrc.toString(16)}`
61
+ });
62
+ }
63
+
64
+ setSframe(required, protect) {
65
+ this.sframeRequired = required;
66
+ this.sframeProtect = protect;
67
+ }
68
+
69
+ sendReaction(reaction) {
70
+ const transactionId = this.nextTransactionId++;
71
+ const payload = encodeReactionPayload({ transactionId, reaction });
72
+ const clearAt = Date.now() + this.clearIntervalMs;
73
+ this.outgoing = { payload, transactionId, reaction, clearAt };
74
+ this.txReactionCount++;
75
+ const sent = this.transmit();
76
+ this.armRetransmission();
77
+ this.logger.debug('call reaction queued', {
78
+ reaction,
79
+ transactionId: transactionId.toString(),
80
+ ssrc: `0x${this.ssrc.toString(16)}`,
81
+ firstAttemptSent: sent,
82
+ total: this.txReactionCount
83
+ });
84
+ return sent;
85
+ }
86
+
87
+ receive(payload, ssrc) {
88
+ if (payload.length === 0)
89
+ return EMPTY_REACTIONS;
90
+ const decoded = decodeAppDataPayload(payload);
91
+ if (!decoded) {
92
+ this.logger.debug('app data payload not understood', {
93
+ ssrc: `0x${this.ssrc.toString(16)}`,
94
+ bytes: payload.length,
95
+ sframeRequired: this.sframeRequired,
96
+ sframeKeyed: this.sframeProtect !== null
97
+ });
98
+ return EMPTY_REACTIONS;
99
+ }
100
+ if (decoded.truncated) {
101
+ this.logger.debug('app data payload carried more messages than are read', {
102
+ ssrc: `0x${ssrc.toString(16)}`,
103
+ read: decoded.items.length
104
+ });
105
+ }
106
+ const fresh = [];
107
+ for (const item of decoded.items) {
108
+ const reaction = item.reaction;
109
+ if (!reaction)
110
+ continue;
111
+ const key = `${ssrc}:${reaction.transactionId}`;
112
+ if (this.seenTransactions.has(key))
113
+ continue;
114
+ this.rememberTransaction(key);
115
+ this.rxReactionCount++;
116
+ fresh.push(reaction);
117
+ }
118
+ if (fresh.length > 0) {
119
+ this.logger.debug('call reaction received', {
120
+ shape: decoded.shape,
121
+ count: fresh.length,
122
+ total: this.rxReactionCount
123
+ });
124
+ }
125
+ return fresh;
126
+ }
127
+ close() {
128
+ this.clearOutgoing();
129
+ this.seenTransactions.clear();
130
+ }
131
+ rememberTransaction(key) {
132
+ if (this.seenTransactions.size >= MAX_TRACKED_TRANSACTIONS) {
133
+ const oldest = this.seenTransactions.values().next().value;
134
+ if (oldest !== undefined)
135
+ this.seenTransactions.delete(oldest);
136
+ }
137
+ this.seenTransactions.add(key);
138
+ }
139
+ armRetransmission() {
140
+ if (this.retransmitTimer)
141
+ return;
142
+ this.retransmitTimer = setInterval(() => {
143
+ this.onRetransmissionTick();
144
+ }, this.retransmissionIntervalMs);
145
+ this.retransmitTimer.unref?.();
146
+ }
147
+ onRetransmissionTick() {
148
+ const outgoing = this.outgoing;
149
+ if (!outgoing) {
150
+ this.clearOutgoing();
151
+ return;
152
+ }
153
+ if (Date.now() >= outgoing.clearAt) {
154
+ this.logger.debug('call reaction cleared from send buffer', {
155
+ transactionId: outgoing.transactionId.toString()
156
+ });
157
+ this.clearOutgoing();
158
+ return;
159
+ }
160
+ this.transmit();
161
+ }
162
+ clearOutgoing() {
163
+ this.outgoing = null;
164
+ if (this.retransmitTimer) {
165
+ clearInterval(this.retransmitTimer);
166
+ this.retransmitTimer = null;
167
+ }
168
+ }
169
+ transmit() {
170
+ const outgoing = this.outgoing;
171
+ if (!outgoing)
172
+ return false;
173
+ const payloadType = this.payloadType;
174
+ try {
175
+ const header = new RtpHeader(payloadType, this.sequenceNumber, this.timestamp, this.ssrc);
176
+ this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
177
+ const payload = this.sframeProtect
178
+ ? this.sframeProtect(outgoing.payload)
179
+ : outgoing.payload;
180
+ return this.sendPacket(new RtpPacket(header, payload));
181
+ }
182
+ catch (err) {
183
+ this.txReactionErrorCount++;
184
+ this.logger.debug('failed to send app data rtp packet', {
185
+ ssrc: `0x${this.ssrc.toString(16)}`,
186
+ errors: this.txReactionErrorCount,
187
+ message: toError(err).message
188
+ });
189
+ return false;
190
+ }
191
+ }
192
+ }
193
+ const EMPTY_REACTIONS = [];
@@ -0,0 +1,172 @@
1
+ import { concatBytes, EMPTY_BYTES, TEXT_DECODER, TEXT_ENCODER } from '../bytes.js';
2
+ import { encodeProtoLengthDelimited, encodeProtoVarintField } from '../protobuf.js';
3
+
4
+ const APP_DATA_PAYLOADS_MESSAGES = 1;
5
+ const APP_DATA_MESSAGE_REACTION_INFO = 1;
6
+ const APP_DATA_MESSAGE_AR_EFFECT_INFO = 3;
7
+ const REACTION_INFO_TRANSACTION_ID = 1;
8
+ const REACTION_INFO_REACTION = 2;
9
+ const AR_EFFECT_INFO_TRANSACTION_ID = 1;
10
+ const AR_EFFECT_INFO_AR_EFFECT_ID = 2;
11
+ const WIRE_TYPE_VARINT = 0;
12
+ const WIRE_TYPE_FIXED64 = 1;
13
+ const WIRE_TYPE_LENGTH_DELIMITED = 2;
14
+ const WIRE_TYPE_FIXED32 = 5;
15
+ const VARINT_CONTINUATION = 0x80;
16
+ const VARINT_PAYLOAD_MASK = 0x7f;
17
+ const VARINT_SHIFT = 7n;
18
+
19
+ const MAX_MESSAGES_PER_PAYLOAD = 32;
20
+ function readVarint(data, offset) {
21
+ let value = 0n;
22
+ let shift = 0n;
23
+ let cursor = offset;
24
+ while (cursor < data.length) {
25
+ const byte = data[cursor++];
26
+ value |= BigInt(byte & VARINT_PAYLOAD_MASK) << shift;
27
+ if ((byte & VARINT_CONTINUATION) === 0)
28
+ return { value, next: cursor };
29
+ shift += VARINT_SHIFT;
30
+ if (shift > 63n)
31
+ break;
32
+ }
33
+ throw new Error('truncated protobuf varint');
34
+ }
35
+
36
+ function* readFields(data) {
37
+ let offset = 0;
38
+ while (offset < data.length) {
39
+ const tag = readVarint(data, offset);
40
+ offset = tag.next;
41
+ const fieldNumber = Number(tag.value >> 3n);
42
+ const wireType = Number(tag.value & 0x7n);
43
+ if (fieldNumber === 0)
44
+ throw new Error('invalid protobuf field number 0');
45
+ if (wireType === WIRE_TYPE_VARINT) {
46
+ const read = readVarint(data, offset);
47
+ offset = read.next;
48
+ yield { fieldNumber, wireType, varint: read.value, bytes: EMPTY_BYTES };
49
+ continue;
50
+ }
51
+ if (wireType === WIRE_TYPE_LENGTH_DELIMITED) {
52
+ const length = readVarint(data, offset);
53
+ const start = length.next;
54
+ const end = start + Number(length.value);
55
+ if (end > data.length)
56
+ throw new Error('truncated protobuf length-delimited field');
57
+ offset = end;
58
+ yield { fieldNumber, wireType, varint: 0n, bytes: data.subarray(start, end) };
59
+ continue;
60
+ }
61
+ if (wireType === WIRE_TYPE_FIXED64) {
62
+ offset += 8;
63
+ }
64
+ else if (wireType === WIRE_TYPE_FIXED32) {
65
+ offset += 4;
66
+ }
67
+ else {
68
+ throw new Error(`unsupported protobuf wire type ${wireType}`);
69
+ }
70
+ if (offset > data.length)
71
+ throw new Error('truncated protobuf fixed-width field');
72
+ }
73
+ }
74
+
75
+ export function encodeReactionPayload(reaction) {
76
+ const reactionInfo = concatBytes([
77
+ encodeProtoVarintField(REACTION_INFO_TRANSACTION_ID, reaction.transactionId),
78
+ encodeProtoLengthDelimited(REACTION_INFO_REACTION, TEXT_ENCODER.encode(reaction.reaction))
79
+ ]);
80
+ const message = encodeProtoLengthDelimited(APP_DATA_MESSAGE_REACTION_INFO, reactionInfo);
81
+ return encodeProtoLengthDelimited(APP_DATA_PAYLOADS_MESSAGES, message);
82
+ }
83
+ function decodeReactionInfo(data, requireTransactionId) {
84
+ let transactionId = null;
85
+ let reaction = null;
86
+ for (const field of readFields(data)) {
87
+ if (field.fieldNumber === REACTION_INFO_TRANSACTION_ID && field.wireType === 0) {
88
+ transactionId = field.varint;
89
+ }
90
+ else if (field.fieldNumber === REACTION_INFO_REACTION && field.wireType === 2) {
91
+ reaction = TEXT_DECODER.decode(field.bytes);
92
+ }
93
+ }
94
+ if (reaction === null)
95
+ return null;
96
+ if (transactionId === null && requireTransactionId)
97
+ return null;
98
+ return { transactionId: transactionId ?? 0n, reaction };
99
+ }
100
+ function decodeArEffectInfo(data, requireTransactionId) {
101
+ let transactionId = null;
102
+ let arEffectId = null;
103
+ for (const field of readFields(data)) {
104
+ if (field.fieldNumber === AR_EFFECT_INFO_TRANSACTION_ID && field.wireType === 0) {
105
+ transactionId = field.varint;
106
+ }
107
+ else if (field.fieldNumber === AR_EFFECT_INFO_AR_EFFECT_ID && field.wireType === 2) {
108
+ arEffectId = TEXT_DECODER.decode(field.bytes);
109
+ }
110
+ }
111
+ if (arEffectId === null)
112
+ return null;
113
+ if (transactionId === null && requireTransactionId)
114
+ return null;
115
+ return { transactionId: transactionId ?? 0n, arEffectId };
116
+ }
117
+
118
+ function decodeAppDataMessage(data, strict) {
119
+ let reaction = null;
120
+ let arEffect = null;
121
+ for (const field of readFields(data)) {
122
+ if (field.wireType !== WIRE_TYPE_LENGTH_DELIMITED)
123
+ continue;
124
+ if (field.fieldNumber === APP_DATA_MESSAGE_REACTION_INFO) {
125
+ reaction = decodeReactionInfo(field.bytes, strict);
126
+ }
127
+ else if (field.fieldNumber === APP_DATA_MESSAGE_AR_EFFECT_INFO) {
128
+ arEffect = decodeArEffectInfo(field.bytes, strict);
129
+ }
130
+ }
131
+ if (reaction)
132
+ return arEffect ? { reaction, arEffect } : { reaction };
133
+ return arEffect ? { arEffect } : null;
134
+ }
135
+ function decodeAsPayloads(data) {
136
+ const items = [];
137
+ let truncated = false;
138
+ for (const field of readFields(data)) {
139
+ if (field.fieldNumber !== APP_DATA_PAYLOADS_MESSAGES)
140
+ continue;
141
+ if (field.wireType !== WIRE_TYPE_LENGTH_DELIMITED)
142
+ continue;
143
+ if (items.length >= MAX_MESSAGES_PER_PAYLOAD) {
144
+ truncated = true;
145
+ break;
146
+ }
147
+ const item = decodeAppDataMessage(field.bytes, false);
148
+ if (item)
149
+ items.push(item);
150
+ }
151
+ return { items, truncated };
152
+ }
153
+
154
+ export function decodeAppDataPayload(data) {
155
+ try {
156
+ const nested = decodeAsPayloads(data);
157
+ if (nested.items.length > 0) {
158
+ return { shape: 'payloads', items: nested.items, truncated: nested.truncated };
159
+ }
160
+ }
161
+ catch {
162
+ }
163
+ try {
164
+ const flat = decodeAppDataMessage(data, true);
165
+ if (flat)
166
+ return { shape: 'message', items: [flat], truncated: false };
167
+ }
168
+ catch {
169
+ return null;
170
+ }
171
+ return null;
172
+ }
@@ -0,0 +1,139 @@
1
+ // Auto answer / auto reject for incoming calls.
2
+ // Works on any object that looks like a Voip instance (listen, onIncoming, accept, reject, incoming).
3
+
4
+ const digits = value => String(value ?? '').split('@')[0].split(':')[0].replace(/\D/g, '')
5
+
6
+ const matches = (list, incoming) => {
7
+ if (!list?.length) return false
8
+ const candidates = [incoming.jid, incoming.creator].filter(Boolean)
9
+ return list.some(entry => {
10
+ const raw = String(entry)
11
+ const wanted = digits(raw)
12
+ return candidates.some(c => c === raw || (wanted && digits(c) === wanted))
13
+ })
14
+ }
15
+
16
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
17
+
18
+ const isStillRinging = (voip, callId) => {
19
+ try {
20
+ return voip.incoming.some(info => info.callId === callId)
21
+ } catch {
22
+ return true
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Answer incoming calls automatically and play audio / video on them.
28
+ *
29
+ * options:
30
+ * media path, URL, playlist array, { audio } / { video }, or a function (incoming) => media. Default: silence
31
+ * resolution '240p' .. '1080p' or { width, height, frameRate } (for video media)
32
+ * loop, autoEndCall, autoDowngrade same as voip.call() playlist options
33
+ * delayMs ring for this long before answering (default 0)
34
+ * allow only these numbers / jids are answered
35
+ * deny these numbers / jids are never answered
36
+ * unmatched what to do with callers outside `allow`: 'ignore' (default) or 'reject'
37
+ * audioCalls answer voice calls (default true)
38
+ * videoCalls answer video calls (default true)
39
+ * onAnswer(call, incoming), onReject(incoming, why), onError(error, incoming)
40
+ *
41
+ * returns { stop(), get answered() }
42
+ */
43
+ export const autoAnswer = async (voip, options = {}) => {
44
+ const { media, resolution, delayMs = 0, allow, deny, unmatched = 'ignore', audioCalls = true, videoCalls = true } = options
45
+ const playOptions = { loop: options.loop, autoEndCall: options.autoEndCall, autoDowngrade: options.autoDowngrade }
46
+ const handled = new Set()
47
+ let answered = 0
48
+
49
+ const decline = async (incoming, why) => {
50
+ try {
51
+ await voip.reject(incoming.callId)
52
+ } catch (error) {
53
+ options.onError?.(error, incoming)
54
+ return
55
+ }
56
+ options.onReject?.(incoming, why)
57
+ }
58
+
59
+ await voip.listen()
60
+
61
+ const off = voip.onIncoming(async incoming => {
62
+ if (handled.has(incoming.callId)) return
63
+ handled.add(incoming.callId)
64
+ try {
65
+ if (deny?.length && matches(deny, incoming)) return void (await decline(incoming, 'denied'))
66
+ if (allow?.length && !matches(allow, incoming)) {
67
+ if (unmatched === 'reject') await decline(incoming, 'not_allowed')
68
+ return
69
+ }
70
+ if (incoming.isVideo ? !videoCalls : !audioCalls) return void (await decline(incoming, incoming.isVideo ? 'video_off' : 'audio_off'))
71
+
72
+ if (delayMs > 0) {
73
+ await sleep(delayMs)
74
+ if (!isStillRinging(voip, incoming.callId)) return
75
+ }
76
+
77
+ const resolved = typeof media === 'function' ? await media(incoming) : media
78
+ try {
79
+ const call = await voip.accept(incoming.callId, resolved, resolution, playOptions)
80
+ answered++
81
+ options.onAnswer?.(call, incoming)
82
+ } catch (error) {
83
+ options.onError?.(error, incoming)
84
+ if (/Maximum concurrent calls/i.test(error?.message ?? '')) await decline(incoming, 'busy')
85
+ }
86
+ } catch (error) {
87
+ options.onError?.(error, incoming)
88
+ }
89
+ })
90
+
91
+ return {
92
+ stop: () => off?.(),
93
+ get answered() {
94
+ return answered
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Reject incoming calls automatically ("anti call").
101
+ *
102
+ * options:
103
+ * allow numbers / jids that are NOT rejected
104
+ * message text sent to the caller after rejecting, or (incoming) => text | undefined
105
+ * delayMs wait before rejecting
106
+ * onReject(incoming), onError(error, incoming)
107
+ *
108
+ * returns { stop(), get rejected() }
109
+ */
110
+ export const autoReject = async (voip, options = {}) => {
111
+ const { allow, message, delayMs = 0 } = options
112
+ const handled = new Set()
113
+ let rejected = 0
114
+
115
+ await voip.listen()
116
+
117
+ const off = voip.onIncoming(async incoming => {
118
+ if (handled.has(incoming.callId)) return
119
+ handled.add(incoming.callId)
120
+ try {
121
+ if (allow?.length && matches(allow, incoming)) return
122
+ if (delayMs > 0) await sleep(delayMs)
123
+ await voip.reject(incoming.callId)
124
+ rejected++
125
+ options.onReject?.(incoming)
126
+ const text = typeof message === 'function' ? await message(incoming) : message
127
+ if (text && voip.socket?.sendMessage) await voip.socket.sendMessage(incoming.jid, { text })
128
+ } catch (error) {
129
+ options.onError?.(error, incoming)
130
+ }
131
+ })
132
+
133
+ return {
134
+ stop: () => off?.(),
135
+ get rejected() {
136
+ return rejected
137
+ }
138
+ }
139
+ }