13 "go.mau.fi/whatsmeow/store"
14 "go.mau.fi/whatsmeow/types"
15 "go.mau.fi/whatsmeow/types/events"
19 // whatsappContactLookupTimeout is the longest time of a read of names
21 whatsappContactLookupTimeout = 10 * time.Second
23 // whatsappImageDownloadTimeout is the longest time of an image
25 whatsappImageDownloadTimeout = 2 * time.Minute
27 // whatsappSource is the source of the work events of the batches.
28 whatsappSource = "whatsapp"
30 // whatsappCatchupTimeout is the longest wait for the end of the
31 // catch-up after a connection.
32 whatsappCatchupTimeout = time.Minute
35 // newWhatsAppInbox returns the inbox of the batches in state, with clock for
36 // the times of the batch texts and groups for the names of the groups. images
37 // holds shared images, and logger gets image failures. Audio shares the data
38 // directory of state.
39 func newWhatsAppInbox(state *WhatsAppState, clock func() time.Time, groups *WhatsAppGroups, images *ImageStore, logger *slog.Logger) *WhatsAppInbox {
40 return &WhatsAppInbox{
45 voices: &VoiceStore{dir: filepath.Join(filepath.Dir(filepath.Dir(state.path)), voiceDirName)},
46 voice: &VoiceTranscriber{},
48 wake: make(chan struct{}, 1),
49 failures: make(chan error, 1),
53 // WhatsAppInbox puts messages into batches, one chat at a time, as
54 // WhatsAppState says. deliver logs each closed batch as a work message that
55 // starts with [WhatsApp], and a batch that needs the user wakes the turn loop.
57 // After each connection, the servers send the messages that came while the
58 // daemon was away, and then OfflineSyncCompleted. Until then, or until
59 // whatsappCatchupTimeout passes, the closed batches wait in the state file. At
60 // the end of the catch-up, deliver closes all batches and logs them. It wakes
61 // the root once for its batches, so their catch-up gives one turn, not one for
62 // each chat. The batches of the state file at the start wait for the first
63 // catch-up in the same way. The event handler acknowledges a message only after
64 // the state file holds it, so the servers send again a message that a crash
65 // lost. A batch leaves the state file only after its work message is durable in
66 // the log or agent queue. A crash between the two can repeat an unrouted batch
67 // once. A routed batch enters the durable agent queue, which prevents a second
68 // log entry and wakes only the child. A missing child uses the root.
70 // The state file is the one of WhatsApp, which keeps the send records in it
71 // too. groups gives the names of the groups. The mutex protects the state of
72 // the catch-up, which the event handler of the library changes from its own
73 // goroutines. wake tells Run that a batch can be due or that a catch-up ended,
74 // and failures gives Run the error of a write of the state file.
75 type WhatsAppInbox struct {
77 clock func() time.Time
78 groups *WhatsAppGroups
81 voice *VoiceTranscriber
90 catchupTimer *time.Timer
93 // due returns a channel that gets a value when the next open batch is due, or
94 // nil when no batch is open.
95 func (i *WhatsAppInbox) due() <-chan time.Time {
96 wait, open := i.state.Wait(time.Now())
101 return time.After(wait)
104 // deliver logs the closed batches in l in order, each as a work message of
105 // whatsappSource, and wakes the loop once with the batches that start a turn. A
106 // batch leaves the state file after its message is durable in the log. A group
107 // with no name gets its name from WhatsApp first, with the client of link.
108 // During a catch-up it logs nothing, and at its end it closes all batches
109 // first. With all, it closes and logs all batches also during a catch-up.
110 // Routed batches enter the durable child queue instead of the root log and wake
111 // their child even when the batch does not need a root turn.
112 func (i *WhatsAppInbox) deliver(ctx context.Context, l *TurnLoop, link WhatsAppLink, all bool) error {
115 catchingUp := i.catchingUp
116 caughtUp := i.caughtUp
123 case all || caughtUp:
124 err = i.state.CloseAll()
128 _, err = i.state.CloseDue(time.Now())
135 batches := i.state.Closed()
136 if l.messages != nil {
137 err = l.messages.PruneWhatsApp(batches)
139 return fmt.Errorf("prune WhatsApp receipts: %w", err)
145 for _, batch := range batches {
146 if batch.Chat.Group && batch.Chat.Name == "" {
147 batch.Chat.Name = i.groups.name(ctx, link, batch.Chat.ID)
150 text := batch.Text(i.clock().Location())
151 if l.messages != nil {
152 routed, err := l.messages.RouteWhatsApp(batch, text)
154 return fmt.Errorf("route a WhatsApp batch: %w", err)
158 err = i.state.Remove(batch.Number)
160 return fmt.Errorf("remove routed WhatsApp batch: %w", err)
167 message, err := l.Work(whatsappSource, text, "")
169 return fmt.Errorf("log a WhatsApp batch: %w", err)
172 // A stop of the daemon during the flush is no failure: the
173 // batch stays in the state file and repeats once at the next
176 if ctx.Err() != nil {
181 return fmt.Errorf("log a WhatsApp batch: %w", err)
184 err = i.state.Remove(batch.Number)
190 turns = append(turns, message)
196 if l.messages != nil {
197 err = l.messages.PruneWhatsApp(i.state.Closed())
199 return fmt.Errorf("prune WhatsApp receipts: %w", err)
206 // waitForCatchup makes the batches wait for a catch-up, as for the batches of
207 // the state file at the start, before the first connection.
208 func (i *WhatsAppInbox) waitForCatchup() {
210 defer i.mutex.Unlock()
215 // startCatchup starts the catch-up of a new connection, which ends at
216 // endCatchup or after whatsappCatchupTimeout.
217 func (i *WhatsAppInbox) startCatchup() {
219 defer i.mutex.Unlock()
223 catchups := i.catchups
224 if i.catchupTimer != nil {
225 i.catchupTimer.Stop()
228 i.catchupTimer = time.AfterFunc(whatsappCatchupTimeout, func() {
229 i.caughtUpBy(catchups)
233 // receive stores images and transcribed voice notes before their batches and
234 // wakes Run. link gives the device and the own IDs. It returns false when the
235 // state file cannot hold the message, so that the library does not acknowledge
236 // it, and Run stops the daemon. Failed media input gets a text marker. A
237 // message that the batches do not take is handled with nothing to do.
238 func (i *WhatsAppInbox) receive(ctx context.Context, link WhatsAppLink, event *events.Message) bool {
239 lookupCtx, cancel := context.WithTimeout(ctx, whatsappContactLookupTimeout)
242 chat, message, found := whatsappMessage(lookupCtx, link.device, link.own, event)
247 if event.Message.GetImageMessage() != nil {
248 ctx, cancel := context.WithTimeout(ctx, whatsappImageDownloadTimeout)
251 message.Text = i.imageText(ctx, link, event, message.Text)
252 } else if event.Message.GetAudioMessage().GetPTT() {
253 message.Text = whatsappRedact(link.own, whatsappVoice(ctx, link.client, i.voices, i.voice, event.Message.GetAudioMessage()))
256 _, err := i.state.Add(chat, message, time.Now())
259 case i.failures <- err:
267 case i.wake <- struct{}{}:
274 // imageText stores the image of event before returning its marker and caption.
275 // Failures keep the caption with a text marker. The daemon log identifies the
276 // chat by a short hash, not its phone number.
277 func (i *WhatsAppInbox) imageText(ctx context.Context, link WhatsAppLink, event *events.Message, caption string) string {
278 name, err := whatsappImage(ctx, link.client, i.images, event.Message.GetImageMessage())
280 chat := event.Info.Chat.ToNonAD()
281 redact := append(slices.Clone(link.own), chat.User)
282 i.logger.Error("image receive failed", "chat", whatsappChatHash(chat), "err", whatsappRedact(redact, err.Error()))
284 text := "(image not downloaded)"
286 text += "\n" + caption
292 return imageText([]string{name}, caption)
295 // caughtUpBy ends the catch-up of the connection with the number catchups, when
296 // no later connection started a new one.
297 func (i *WhatsAppInbox) caughtUpBy(catchups int) {
299 defer i.mutex.Unlock()
301 if i.catchups == catchups {
306 // finishCatchup ends a running catch-up and wakes Run, which logs all batches.
307 // The caller holds the mutex.
308 func (i *WhatsAppInbox) finishCatchup() {
315 if i.catchupTimer != nil {
316 i.catchupTimer.Stop()
320 case i.wake <- struct{}{}:
325 // endCatchup ends a running catch-up at OfflineSyncCompleted.
326 func (i *WhatsAppInbox) endCatchup() {
328 defer i.mutex.Unlock()
333 // stopCatchup ends a running catch-up with no wake, after the session is
335 func (i *WhatsAppInbox) stopCatchup() {
337 defer i.mutex.Unlock()
342 // close stops the timer of the catch-up.
343 func (i *WhatsAppInbox) close() {
345 defer i.mutex.Unlock()
347 if i.catchupTimer != nil {
348 i.catchupTimer.Stop()
352 // whatsappMessage returns the chat and the batch message of event, or false
353 // when the batches do not take it. device is the linked device, and own holds
354 // the own IDs. The batches take text, images, and media markers from a private
355 // chat or a group, from another person or from the user. They do not take
356 // reactions, edits, deletions, view-once and disappearing messages, old
357 // history, status broadcasts, channels, and the chat of the user with itself.
359 // A mention of the user becomes @you, another mention @NAME when the name is
360 // known, and the own number and LID become OWN, so that they never go to the
362 func whatsappMessage(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
364 chatJID := info.Chat.ToNonAD()
367 case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.Message.GetImageMessage().GetViewOnce(), event.Message.GetVideoMessage().GetViewOnce(), event.Message.GetAudioMessage().GetViewOnce(), event.SourceWebMsg != nil:
368 case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
369 case slices.Contains(own, chatJID.User):
371 return whatsappText(ctx, device, own, event)
374 return WhatsAppChat{}, WhatsAppMessage{}, false
377 // whatsappText returns the chat and the batch message of event, a message that
378 // the batches take. An image returns its caption until receive stores it. A
379 // voice note returns a marker until receive transcribes it.
380 func whatsappText(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
382 text := event.Message.GetConversation()
383 extended := event.Message.GetExtendedTextMessage()
385 text = extended.GetText()
388 contextInfo := extended.GetContextInfo()
390 case event.Message.GetAudioMessage().GetPTT():
391 text = "(voice not downloaded)"
392 contextInfo = event.Message.GetAudioMessage().GetContextInfo()
393 case event.Message.GetImageMessage() != nil:
394 image := event.Message.GetImageMessage()
395 text = image.GetCaption()
396 contextInfo = image.GetContextInfo()
397 case event.Message.GetStickerMessage() != nil:
399 contextInfo = event.Message.GetStickerMessage().GetContextInfo()
400 case event.Message.GetVideoMessage() != nil:
401 video := event.Message.GetVideoMessage()
403 if video.GetGifPlayback() {
407 if video.GetCaption() != "" {
408 text += "\n" + video.GetCaption()
411 contextInfo = video.GetContextInfo()
413 if strings.TrimSpace(text) == "" {
414 return WhatsAppChat{}, WhatsAppMessage{}, false
418 message := WhatsAppMessage{
420 Time: info.Timestamp,
425 message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
428 for _, mentioned := range contextInfo.GetMentionedJID() {
429 jid, err := types.ParseJID(mentioned)
432 case slices.Contains(own, jid.User):
433 message.Mention = true
434 text = strings.ReplaceAll(text, "@"+jid.User, "@you")
436 text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
440 participant, err := types.ParseJID(contextInfo.GetParticipant())
441 message.Reply = err == nil && slices.Contains(own, participant.User)
443 message.Text = whatsappRedact(own, text)
444 chatJID := info.Chat.ToNonAD()
445 chat := WhatsAppChat{
446 ID: chatJID.String(),
447 Group: chatJID.Server == types.GroupServer,
451 push := info.PushName
456 chat.Name = whatsappContactName(ctx, device, chatJID, push)
459 return chat, message, true