@hiroosy/baileys-lite 0.3.9 → 0.4.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/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
  - [x] High performance for multi sessions.
13
13
  - [x] Zero dependency.
14
14
  - [x] Low memory & CPU consumption.
15
- - [x] Calls: Video & Audio.
15
+ - [x] Calls: Video & Audio, group calls, call links, and waiting rooms.
16
16
 
17
17
  ---
18
18
 
@@ -504,7 +504,7 @@ await sock.sendMessage([contactJid1, contactJid2], { text: 'Status update text'
504
504
 
505
505
  ## Call
506
506
 
507
- Calls need `ffmpeg` and `ffprobe` in `PATH`. Create one `Voip` per socket once it is open. After a reconnect there is a new socket, so create a new `Voip`.
507
+ Calls need `ffmpeg` and `ffprobe` in `PATH`. Create one `Voip` per socket once it is open. After a reconnect there is a new socket, so create a new `Voip`. The same `Voip` handles 1:1 calls, group calls, and call links.
508
508
 
509
509
  <details> <summary>Quick start</summary>
510
510
 
@@ -532,7 +532,7 @@ await voip.call('628123456789')
532
532
 
533
533
  ```javascript
534
534
  await voip.call(jid, './song.mp3') // local file
535
- await voip.call(jid, 'https://example.com/song.mp3') // url, downloaded first (audio max 20MB, video max 50MB)
535
+ await voip.call(jid, 'https://example.com/song.mp3') // audio url is streamed, video url is downloaded first (max 50MB)
536
536
  await voip.call(jid, { audio: './voice.ogg' })
537
537
  await voip.call(jid, './clip.mp4', '720p') // video call
538
538
 
@@ -603,6 +603,13 @@ call.on('peer_video', change => {})
603
603
  call.on('inbound_audio', pcm => {}) // Float32Array, 16 kHz mono, 60 ms
604
604
  call.on('inbound_video', frame => {}) // decoded H.264 frame
605
605
  call.on('audio_finished', () => {}) // current audio item reached its end
606
+ call.on('reconnecting', detail => {}) // connection is recovering
607
+ call.on('reconnected', () => {})
608
+
609
+ call.on('group_state', state => {}) // group roster snapshot
610
+ call.on('participants_changed', ({ added, removed }) => {})
611
+ call.on('waiting_room', room => {})
612
+ call.on('participant_audio', (jid, pcm) => {}) // audio from one participant
606
613
  ```
607
614
 
608
615
  </details>
@@ -625,13 +632,97 @@ await voip.hangup(callId)
625
632
 
626
633
  // events: call_incoming, call_state, call_ended, call_peer_mute, call_inbound_audio,
627
634
  // call_inbound_video, call_hand_raise, call_reaction, call_screen_share,
628
- // call_peer_video_state, call_outbound_audio_finished, call_error
635
+ // call_video_state, call_outbound_audio_finished, call_error, call_reconnecting,
636
+ // call_reconnected, call_group_state, call_waiting_room, call_participant_audio
629
637
  ```
630
638
 
639
+ `voip.incoming()` returns the ringing incoming calls. It is a method, not a getter.
640
+
631
641
  `voip.coordinator` is the raw engine (`feedLiveAudio`, `feedLiveVideo`, `setExternalAudioMode`, ...).
632
642
 
633
643
  </details>
634
644
 
645
+ <details> <summary>Participants & Approval</summary>
646
+
647
+ ```javascript
648
+ call.participants // current group members
649
+ call.waitingRoom // people waiting for approval, null if none
650
+ call.link // call link, null if the call has none
651
+
652
+ await call.addParticipant('628111111111') // invite into the call
653
+ await call.ringParticipant('628111111111') // invite and ring
654
+ await call.setApprovalRequired(true) // waiting room on or off
655
+ await call.admit('628111111111') // let a waiting person in
656
+ await call.deny('628111111111') // reject a waiting person
657
+ ```
658
+
659
+ Targets can be a number or a jid. Numbers are converted to a LID before the request is sent.
660
+
661
+ </details>
662
+
663
+ <details> <summary>Group Calls</summary>
664
+
665
+ ```javascript
666
+ const call = await voip.groupCall(
667
+ ['628111111111', '628222222222'], // at least two numbers besides yourself
668
+ './song.mp3',
669
+ '480p',
670
+ { groupJid: '120363000000000000@g.us' } // group chat the call belongs to
671
+ )
672
+
673
+ call.on('participants_changed', ({ added, removed }) => {
674
+ console.log('joined:', added.map(p => p.number), 'left:', removed.map(p => p.number))
675
+ })
676
+ ```
677
+
678
+ A group call is one call with several participants, so it uses one slot in `maxConcurrentCalls`.
679
+
680
+ </details>
681
+
682
+ <details> <summary>Call Links & Rooms</summary>
683
+
684
+ ```javascript
685
+ // create a room, the call stays open until you hang up
686
+ const room = await voip.createRoom('./song.mp3', '480p', {
687
+ requireApproval: true, // waiting room, approve people with call.admit()
688
+ loop: true
689
+ })
690
+ console.log(room.link)
691
+
692
+ // join an existing link
693
+ const joined = await voip.joinLink('https://call.whatsapp.com/voice/xxxx', './song.mp3')
694
+
695
+ // read the link of a call, and check a link before joining
696
+ const link = await voip.getLink(room) // or getLink(callId)
697
+ const info = await voip.previewLink('https://call.whatsapp.com/voice/xxxx')
698
+ ```
699
+
700
+ - `createRoom()` sets `autoEndCall: false` unless you pass your own.
701
+ - `joinLink()` uses a 10 minute safety timeout by default (`safetyMs` changes it). See Multi Call for what happens when it fires.
702
+ - `requireApproval` in `createRoom()` turns the waiting room on once the call is connected.
703
+
704
+ </details>
705
+
706
+ <details> <summary>Helpers by Call ID</summary>
707
+
708
+ ```javascript
709
+ voip.activeCalls() // summaries of active calls
710
+ voip.info(callId) // details of one call, or null
711
+ voip.silent(callId, true)
712
+ voip.mute(callId, true)
713
+ voip.react(callId, '👍')
714
+ voip.hand(callId, true)
715
+ voip.add(callId, '628111111111')
716
+ voip.admit(callId, '628111111111')
717
+ voip.deny(callId, '628111111111')
718
+ voip.approval(callId, true)
719
+ voip.link(callId)
720
+ ```
721
+
722
+ All helpers except `info()` throw `No active call with id ...` if the call is gone.
723
+
724
+ </details>
725
+
635
726
  <details> <summary>Multi Call</summary>
636
727
 
637
728
  ```javascript
@@ -665,9 +756,9 @@ await voip.end(true) // only release the slots
665
756
  ```
666
757
 
667
758
  - `maxConcurrentCalls` defaults to `1`. Each call gets its own relay, codec and audio.
668
- - Incoming calls count toward the limit too.
759
+ - Incoming calls, group calls, call links, and rooms count toward the limit too.
669
760
  - A call over the limit throws `Maximum concurrent calls reached`. In `callMany()` it is returned as `error` for that number and the rest still go through.
670
761
  - `callMany()` takes the same media and options as `call()` and calls duplicate numbers once.
671
- - A safety timeout emits `error` if a call never ends (starts at 105s).
762
+ - A safety timeout emits `error` if a call never ends. It starts at 105s, or 10 minutes for `joinLink()` and `createRoom()`. When a playlist item starts, video items reset it to 10 minutes and audio items clear it. The call is not hung up by the timeout, so call `hangup()` yourself when you are done.
672
763
 
673
764
  </details>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hiroosy/baileys-lite",
3
- "version": "0.3.9",
3
+ "version": "0.4.1",
4
4
  "description": "A Lightweight Baileys built with Pure NodeJs 18+",
5
5
  "repository": {
6
6
  "type": "git",
@@ -37,6 +37,7 @@ import {
37
37
  NO_MESSAGE_FOUND_ERROR_TEXT,
38
38
  readTcTokenIndex,
39
39
  resolveIssuanceJid,
40
+ resolvePlaceholderResendSkipSubtype,
40
41
  resolveTcTokenJid,
41
42
  SERVER_ERROR_CODES,
42
43
  storeTcTokensFromIqResult,
@@ -1346,12 +1347,9 @@ export const makeMessagesRecvSocket = (config) => {
1346
1347
  }
1347
1348
  if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
1348
1349
 
1349
- const unavailableNode = getBinaryNodeChild(node, 'unavailable');
1350
- const unavailableType = unavailableNode?.attrs?.type;
1351
- if (unavailableType === 'bot_unavailable_fanout' ||
1352
- unavailableType === 'hosted_unavailable_fanout' ||
1353
- unavailableType === 'view_once_unavailable_fanout') {
1354
- logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
1350
+ const skipSubtype = resolvePlaceholderResendSkipSubtype(node);
1351
+ if (skipSubtype) {
1352
+ logger.debug({ msgId: msg.key.id, subtype: skipSubtype }, 'skipping placeholder resend for excluded unavailable type');
1355
1353
  acked = true;
1356
1354
  return sendMessageAck(node);
1357
1355
  }
@@ -26,6 +26,7 @@ import {
26
26
  generateWAMessage,
27
27
  generateWAMessageFromContent,
28
28
  hasValidAlbumMedia,
29
+ isViewOnceMessage,
29
30
  normalizeMessageContent,
30
31
  shouldIncludeBizBinaryNode
31
32
  } from '../utils/message-compose.js'
@@ -550,8 +551,12 @@ export const makeMessagesSocket = (config) => {
550
551
  const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
551
552
  const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
552
553
  const isPollUpdate = innerMessage?.pollUpdateMessage;
553
- if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
554
+ const isViewOnce = isViewOnceMessage(message);
555
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate || isViewOnce) {
554
556
  const metaAttrs = {};
557
+ if (isViewOnce) {
558
+ metaAttrs.view_once = 'true';
559
+ }
555
560
  if (isNeedMetaAttrs) {
556
561
  metaAttrs.content_type = 'add_on';
557
562
  }
@@ -522,6 +522,34 @@ function isSessionRecordError(error) {
522
522
  return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(pattern => errorMessage.includes(pattern))
523
523
  }
524
524
 
525
+ const UNAVAILABLE_SKIP_SUBTYPE_BY_KIND = {
526
+ bot: 'bot_unavailable_fanout',
527
+ hosted: 'hosted_unavailable_fanout',
528
+ view_once: 'view_once_unavailable_fanout',
529
+ sender_drop: 'acp_unavailable_fanout'
530
+ }
531
+ const UNAVAILABLE_SKIP_SUBTYPES = new Set(Object.values(UNAVAILABLE_SKIP_SUBTYPE_BY_KIND))
532
+
533
+ export function resolveUnavailableKind(node) {
534
+ const content = Array.isArray(node?.content) ? node.content : []
535
+ const unavailable = content.find(child => child?.tag === 'unavailable')
536
+ if (!unavailable) return null
537
+ if (content.some(child => child?.tag === 'bot')) return 'bot'
538
+ if (unavailable.attrs?.hosted === 'true') return 'hosted'
539
+ const type = unavailable.attrs?.type
540
+ return type === 'view_once' || type === 'sender_drop' ? type : 'other'
541
+ }
542
+
543
+ export function resolvePlaceholderResendSkipSubtype(node) {
544
+ const subtype = node?.attrs?.subtype
545
+ if (typeof subtype === 'string' && UNAVAILABLE_SKIP_SUBTYPES.has(subtype)) return subtype
546
+ const unavailable = Array.isArray(node?.content) ? node.content.find(child => child?.tag === 'unavailable') : undefined
547
+ const legacyType = unavailable?.attrs?.type
548
+ if (typeof legacyType === 'string' && UNAVAILABLE_SKIP_SUBTYPES.has(legacyType)) return legacyType
549
+ const kind = resolveUnavailableKind(node)
550
+ return kind && kind !== 'other' ? UNAVAILABLE_SKIP_SUBTYPE_BY_KIND[kind] : null
551
+ }
552
+
525
553
  export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
526
554
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
527
555
  return {
@@ -530,6 +558,10 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
530
558
  author,
531
559
  async decrypt() {
532
560
  let decryptables = 0
561
+ let decryptedAny = false
562
+ let decryptFailed = false
563
+ let skmsgFailed = false
564
+ if (resolveUnavailableKind(stanza) === 'view_once') fullMessage.key.isViewOnce = true
533
565
  if (Array.isArray(stanza.content)) {
534
566
  for (const { tag, attrs, content } of stanza.content) {
535
567
  if (tag === 'verified_name' && content instanceof Uint8Array) {
@@ -537,9 +569,6 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
537
569
  const details = proto.VerifiedNameCertificate.Details.decode(cert.details)
538
570
  fullMessage.verifiedBizName = details.verifiedName
539
571
  }
540
- if (tag === 'unavailable' && attrs.type === 'view_once') {
541
- fullMessage.key.isViewOnce = true
542
- }
543
572
  if (attrs.count && tag === 'enc') fullMessage.retryCount = Number(attrs.count)
544
573
  if (tag !== 'enc' && tag !== 'plaintext') continue
545
574
  if (!(content instanceof Uint8Array)) continue
@@ -577,6 +606,7 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
577
606
  }
578
607
  if (fullMessage.message) Object.assign(fullMessage.message, msg)
579
608
  else fullMessage.message = msg
609
+ decryptedAny = true
580
610
  } catch (err) {
581
611
  logger.error(
582
612
  {
@@ -589,6 +619,8 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
589
619
  },
590
620
  'failed to decrypt message'
591
621
  )
622
+ decryptFailed = true
623
+ if (attrs.type === 'skmsg') skmsgFailed = true
592
624
  fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
593
625
  fullMessage.messageStubParameters = [err.message.toString()]
594
626
  }
@@ -597,6 +629,9 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
597
629
  if (!decryptables && !fullMessage.key?.isViewOnce) {
598
630
  fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
599
631
  fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT]
632
+ } else if (decryptFailed && decryptedAny && !skmsgFailed) {
633
+ delete fullMessage.messageStubType
634
+ delete fullMessage.messageStubParameters
600
635
  }
601
636
  }
602
637
  }
@@ -1553,6 +1553,15 @@ export const normalizeMessageContent = content => {
1553
1553
  return content
1554
1554
  }
1555
1555
 
1556
+ const VIEW_ONCE_MEDIA_KEYS = ['imageMessage', 'videoMessage', 'ptvMessage', 'audioMessage']
1557
+
1558
+ export const isViewOnceMessage = message => {
1559
+ if (!message) return false
1560
+ if (message.viewOnceMessage || message.viewOnceMessageV2) return true
1561
+ const inner = normalizeMessageContent(message)
1562
+ return !!inner && VIEW_ONCE_MEDIA_KEYS.some(key => !!inner[key]?.viewOnce)
1563
+ }
1564
+
1556
1565
  export const extractMessageContent = content => {
1557
1566
  const extractFromTemplateMessage = msg => {
1558
1567
  if (msg.imageMessage) return { imageMessage: msg.imageMessage }
@@ -17,6 +17,7 @@ import {
17
17
  isHostedLidUser,
18
18
  isHostedPnUser,
19
19
  isJidBroadcast,
20
+ isJidGroup,
20
21
  isJidStatusBroadcast,
21
22
  isLidUser,
22
23
  isPnUser,
@@ -152,11 +153,57 @@ export function decryptMessageEdit({ encPayload, encIv }, { originalSenderJid, o
152
153
  return proto.Message.decode(decrypted)
153
154
  }
154
155
 
156
+ const orderLidFirst = jids => [...jids.filter(jid => isLidUser(jid)), ...jids.filter(jid => !isLidUser(jid))]
157
+
158
+ const collectUserJids = (...candidates) => {
159
+ const out = []
160
+ for (const candidate of candidates) {
161
+ if (typeof candidate !== 'string' || !candidate) continue
162
+ const user = jidNormalizedUser(candidate)
163
+ if (user && !out.includes(user)) out.push(user)
164
+ }
165
+ return out
166
+ }
167
+
168
+ const resolveSenderJids = async (rawJid, alternates, lidMapping) => {
169
+ let lid
170
+ let pn
171
+ if (rawJid && isLidUser(rawJid)) {
172
+ lid = rawJid
173
+ pn = await lidMapping?.getPNForLID(rawJid).catch(() => null)
174
+ } else if (rawJid && isPnUser(rawJid)) {
175
+ pn = rawJid
176
+ lid = await lidMapping?.getLIDForPN(rawJid).catch(() => null)
177
+ }
178
+ return orderLidFirst(collectUserJids(lid, pn, rawJid, ...alternates))
179
+ }
180
+
181
+ const resolveEditParentJids = async (targetKey, meId, meLid, lidMapping) => {
182
+ if (targetKey?.fromMe) return orderLidFirst(collectUserJids(meLid, meId))
183
+ return resolveSenderJids(targetKey?.participant || targetKey?.remoteJid, [targetKey?.participantAlt, targetKey?.remoteJidAlt], lidMapping)
184
+ }
185
+
186
+ const resolveEditEditorJids = async (messageKey, meId, meLid, lidMapping) => {
187
+ if (messageKey?.fromMe) return orderLidFirst(collectUserJids(meLid, meId))
188
+ return resolveSenderJids(messageKey?.participant || messageKey?.remoteJid, [messageKey?.participantAlt, messageKey?.remoteJidAlt], lidMapping)
189
+ }
190
+
191
+ const decryptEditWithSenderFallback = ({ encPayload, encIv, editEncKey, originalMsgId, parentJids, editorJids }) => {
192
+ let lastError
193
+ for (const originalSenderJid of parentJids) {
194
+ for (const editorJid of editorJids) {
195
+ try {
196
+ return decryptMessageEdit({ encPayload, encIv }, { editEncKey, originalSenderJid, originalMsgId, editorJid })
197
+ } catch (err) {
198
+ lastError = err
199
+ }
200
+ }
201
+ }
202
+ throw lastError ?? new Error('no sender candidates for message edit')
203
+ }
204
+
155
205
  const buildEditUpdate = args => {
156
- const editedInner = decryptMessageEdit(
157
- { encPayload: args.encPayload, encIv: args.encIv },
158
- { editEncKey: args.editEncKey, originalSenderJid: args.originalSenderJid, originalMsgId: args.originalMsgId, editorJid: args.editorJid }
159
- )
206
+ const editedInner = decryptEditWithSenderFallback(args)
160
207
  const editProtocol = editedInner.protocolMessage
161
208
  const innerEdited = editProtocol?.editedMessage
162
209
  if (!innerEdited) {
@@ -212,7 +259,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
212
259
  processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }].slice(-MAX_PROCESSED_HISTORY_MESSAGES)
213
260
  })
214
261
  }
215
- const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger)
262
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger, meId)
216
263
  if (data.lidPnMappings?.length) {
217
264
  logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync')
218
265
  await signalRepository.lidMapping.storeLIDPNMappings(data.lidPnMappings).catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'))
@@ -356,30 +403,29 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
356
403
  const targetMsg = await getMessage(targetKey)
357
404
  if (targetMsg) {
358
405
  try {
359
- const meIdNormalised = jidNormalizedUser(meId)
360
- const origSenderRaw = targetKey.participant || targetKey.remoteJid
361
- const origSenderPn = isLidUser(origSenderRaw) ? await signalRepository.lidMapping.getPNForLID(origSenderRaw) : origSenderRaw
362
- const originalSenderJid = getKeyAuthor({ remoteJid: jidNormalizedUser(origSenderPn), fromMe: meIdNormalised === origSenderPn }, meIdNormalised)
363
- const editorJid = getKeyAuthor(message.key, meIdNormalised)
364
406
  const editEncKey = targetMsg?.messageContextInfo?.messageSecret
365
407
  if (!editEncKey) {
366
408
  logger?.warn({ targetKey }, 'message edit: missing messageSecret on original message — cannot decrypt')
367
- return
409
+ } else {
410
+ const meIdNormalised = jidNormalizedUser(meId)
411
+ const meLid = creds.me?.lid
412
+ const parentJids = await resolveEditParentJids(targetKey, meIdNormalised, meLid, signalRepository.lidMapping)
413
+ const editorJids = await resolveEditEditorJids(message.key, meIdNormalised, meLid, signalRepository.lidMapping)
414
+ const update = buildEditUpdate({
415
+ editEncKey,
416
+ encPayload: secEnc.encPayload,
417
+ encIv: secEnc.encIv,
418
+ parentJids,
419
+ editorJids,
420
+ originalMsgId: targetKey.id,
421
+ messageKey: message.key,
422
+ targetKeyId: targetKey.id,
423
+ fallbackTimestamp: toNumber(message.messageTimestamp),
424
+ logger,
425
+ targetKey
426
+ })
427
+ if (update) ev.emit('messages.update', [update])
368
428
  }
369
- const update = buildEditUpdate({
370
- editEncKey,
371
- encPayload: secEnc.encPayload,
372
- encIv: secEnc.encIv,
373
- originalSenderJid,
374
- originalMsgId: targetKey.id,
375
- editorJid,
376
- messageKey: message.key,
377
- targetKeyId: targetKey.id,
378
- fallbackTimestamp: toNumber(message.messageTimestamp),
379
- logger,
380
- targetKey
381
- })
382
- if (update) ev.emit('messages.update', [update])
383
429
  } catch (err) {
384
430
  logger?.warn({ err, targetKey }, 'failed to decrypt secretEncryptedMessage MESSAGE_EDIT')
385
431
  }
@@ -738,7 +784,15 @@ export const downloadHistory = async (msg, options) => {
738
784
  return proto.HistorySync.decode(inflated)
739
785
  }
740
786
 
741
- export const processHistoryMessage = (item, logger) => {
787
+ const applyHistoryMessageAuthor = (message, chatId, meId) => {
788
+ if (!isJidGroup(chatId) && !isJidBroadcast(chatId)) return
789
+ if (message.key.participant) return
790
+ const selfAuthor = message.originalSelfAuthorUserJidString || meId
791
+ const author = message.participant || (message.key.fromMe && selfAuthor ? jidNormalizedUser(selfAuthor) : undefined)
792
+ if (author) message.key.participant = author
793
+ }
794
+
795
+ export const processHistoryMessage = (item, logger, meId) => {
742
796
  const messages = []
743
797
  const contacts = []
744
798
  const chats = []
@@ -747,18 +801,23 @@ export const processHistoryMessage = (item, logger) => {
747
801
  for (const m of item.phoneNumberToLidMappings || []) {
748
802
  if (m.lidJid && m.pnJid) lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid })
749
803
  }
804
+ for (const m of item.inlineContacts || []) {
805
+ if (m.lidJid && m.pnJid) lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid })
806
+ }
750
807
  switch (item.syncType) {
751
808
  case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
752
809
  case proto.HistorySync.HistorySyncType.RECENT:
753
810
  case proto.HistorySync.HistorySyncType.FULL:
754
811
  case proto.HistorySync.HistorySyncType.ON_DEMAND:
755
- for (const chat of item.conversations) {
756
- contacts.push({ id: chat.id, name: chat.displayName || chat.name || chat.username || undefined, username: chat.username || undefined, lid: chat.lidJid || chat.accountLid || undefined, phoneNumber: chat.pnJid || undefined })
812
+ for (const chat of item.conversations || []) {
813
+ if (!chat?.id) continue
814
+ const chatLid = chat.lidJid || chat.accountLid || undefined
815
+ contacts.push({ id: chat.id, name: chat.displayName || chat.name || chat.username || undefined, username: chat.username || undefined, lid: chatLid, phoneNumber: chat.pnJid || undefined })
757
816
  const chatId = chat.id
758
817
  const isLid = isLidUser(chatId) || isHostedLidUser(chatId)
759
818
  const isPn = isPnUser(chatId) || isHostedPnUser(chatId)
760
819
  if (isLid && chat.pnJid) lidPnMappings.push({ lid: chatId, pn: chat.pnJid })
761
- else if (isPn && chat.lidJid) lidPnMappings.push({ lid: chat.lidJid, pn: chatId })
820
+ else if (isPn && chatLid) lidPnMappings.push({ lid: chatLid, pn: chatId })
762
821
  else if (isLid && !chat.pnJid) {
763
822
  const pnFromReceipt = extractPnFromMessages(chat.messages || [])
764
823
  if (pnFromReceipt) lidPnMappings.push({ lid: chatId, pn: pnFromReceipt })
@@ -766,7 +825,9 @@ export const processHistoryMessage = (item, logger) => {
766
825
  const msgs = chat.messages || []
767
826
  delete chat.messages
768
827
  for (const item_ of msgs) {
769
- const message = item_.message
828
+ const message = item_?.message
829
+ if (!message?.key) continue
830
+ applyHistoryMessageAuthor(message, chatId, meId)
770
831
  messages.push(message)
771
832
  if (!chat.messages?.length) chat.messages = [{ message }]
772
833
  if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
@@ -781,17 +842,17 @@ export const processHistoryMessage = (item, logger) => {
781
842
  }
782
843
  break
783
844
  case proto.HistorySync.HistorySyncType.PUSH_NAME:
784
- for (const c of item.pushnames) contacts.push({ id: c.id, notify: c.pushname })
845
+ for (const c of item.pushnames || []) contacts.push({ id: c.id, notify: c.pushname })
785
846
  break
786
847
  }
787
848
  return { chats, contacts, messages, lidPnMappings, pastParticipants: item.pastParticipants, syncType: item.syncType, progress: item.progress }
788
849
  }
789
850
 
790
- export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
851
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger, meId) => {
791
852
  const historyMsg = msg.initialHistBootstrapInlinePayload
792
853
  ? proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload))
793
854
  : await downloadHistory(msg, options)
794
- return processHistoryMessage(historyMsg, logger)
855
+ return processHistoryMessage(historyMsg, logger, meId)
795
856
  }
796
857
 
797
858
  export const getHistoryMsg = message => {
@@ -6,7 +6,9 @@ export class WaVoipCoordinator {
6
6
  deps;
7
7
  logger;
8
8
  unregisterHandlers = [];
9
+ ctx;
9
10
  constructor(ctx, options = {}) {
11
+ this.ctx = ctx;
10
12
  this.deps = ctx.deps;
11
13
  this.logger = ctx.logger.child({ scope: 'voip' }, { level: options.logLevel });
12
14
  this.manager = new WaCallManager({
@@ -21,6 +23,39 @@ export class WaVoipCoordinator {
21
23
  async startCall(options) {
22
24
  return this.manager.startCall(options);
23
25
  }
26
+ async startGroupCall(options) {
27
+ return this.manager.startGroupCall(options);
28
+ }
29
+ async createCallLink(options) {
30
+ return this.manager.createCallLink(options);
31
+ }
32
+ async queryCallLink(tokenOrUrl, options) {
33
+ return this.manager.queryCallLink(tokenOrUrl, options);
34
+ }
35
+ async joinCallLink(tokenOrUrl, options) {
36
+ return this.manager.joinCallLink(tokenOrUrl, options);
37
+ }
38
+ async addGroupParticipant(callId, target) {
39
+ return this.manager.addGroupParticipant(callId, target);
40
+ }
41
+ async ringGroupParticipant(callId, target) {
42
+ return this.manager.ringGroupParticipant(callId, target);
43
+ }
44
+ async setApprovalRequired(callId, enabled) {
45
+ return this.manager.setApprovalRequired(callId, enabled);
46
+ }
47
+ async admitParticipant(callId, jid) {
48
+ return this.manager.admitParticipant(callId, jid);
49
+ }
50
+ async denyParticipant(callId, jid) {
51
+ return this.manager.denyParticipant(callId, jid);
52
+ }
53
+ async getCallLink(callId) {
54
+ return this.manager.getCallLink(callId);
55
+ }
56
+ getParticipants(callId) {
57
+ return this.manager.getParticipants(callId);
58
+ }
24
59
  async acceptCall(callId) {
25
60
  return this.manager.acceptCall(callId);
26
61
  }
@@ -94,10 +129,22 @@ export class WaVoipCoordinator {
94
129
  return this;
95
130
  }
96
131
  dispose() {
132
+ this.suspendIncoming();
133
+ this.manager.destroy();
134
+ }
135
+ suspendIncoming() {
97
136
  for (const unregister of this.unregisterHandlers.splice(0)) {
98
137
  unregister();
99
138
  }
100
- this.manager.destroy();
139
+ }
140
+ resumeIncoming() {
141
+ this.registerIncomingHandlers(this.ctx);
142
+ }
143
+ notifyReconnecting() {
144
+ this.manager.notifyReconnecting();
145
+ }
146
+ notifyReconnected() {
147
+ this.manager.notifyReconnected();
101
148
  }
102
149
  registerIncomingHandlers(ctx) {
103
150
  this.unregisterHandlers.push(ctx.registerIncomingHandler({
@@ -151,6 +198,15 @@ export class WaVoipCoordinator {
151
198
  this.manager.on('call_screen_share', (call, share) => {
152
199
  ctx.emit('voip_call_screen_share', { call, share });
153
200
  });
201
+ this.manager.on('call_group_state', (call, state) => {
202
+ ctx.emit('voip_call_group_state', { call, state });
203
+ });
204
+ this.manager.on('call_waiting_room', (call, room) => {
205
+ ctx.emit('voip_call_waiting_room', { call, room });
206
+ });
207
+ this.manager.on('call_participant_audio', (call, participantJid, pcm) => {
208
+ ctx.emit('voip_call_participant_audio', { call, participantJid, pcm });
209
+ });
154
210
  this.manager.on('call_error', (error) => {
155
211
  ctx.emit('voip_call_error', error);
156
212
  });