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.
38 func newWhatsAppInbox(state *WhatsAppState, clock func() time.Time, groups *WhatsAppGroups, images *ImageStore, logger *slog.Logger) *WhatsAppInbox {
39 return &WhatsAppInbox{
45 wake: make(chan struct{}, 1),
46 failures: make(chan error, 1),
50 // WhatsAppInbox puts messages into batches, one chat at a time, as
51 // WhatsAppState says. deliver logs each closed batch as a work message that
52 // starts with [WhatsApp], and a batch that needs the user wakes the turn loop.
54 // After each connection, the servers send the messages that came while the
55 // daemon was away, and then OfflineSyncCompleted. Until then, or until
56 // whatsappCatchupTimeout passes, the closed batches wait in the state file. At
57 // the end of the catch-up, deliver closes all batches and logs them. It wakes
58 // the root once for its batches, so their catch-up gives one turn, not one for
59 // each chat. The batches of the state file at the start wait for the first
60 // catch-up in the same way. The event handler acknowledges a message only after
61 // the state file holds it, so the servers send again a message that a crash
62 // lost. A batch leaves the state file only after its work message is durable in
63 // the log or agent queue. A crash between the two can repeat an unrouted batch
64 // once. A routed batch enters the durable agent queue, which prevents a second
65 // log entry and wakes only the child. A missing child uses the root.
67 // The state file is the one of WhatsApp, which keeps the send records in it
68 // too. groups gives the names of the groups. The mutex protects the state of
69 // the catch-up, which the event handler of the library changes from its own
70 // goroutines. wake tells Run that a batch can be due or that a catch-up ended,
71 // and failures gives Run the error of a write of the state file.
72 type WhatsAppInbox struct {
74 clock func() time.Time
75 groups *WhatsAppGroups
85 catchupTimer *time.Timer
88 // due returns a channel that gets a value when the next open batch is due, or
89 // nil when no batch is open.
90 func (i *WhatsAppInbox) due() <-chan time.Time {
91 wait, open := i.state.Wait(time.Now())
96 return time.After(wait)
99 // deliver logs the closed batches in l in order, each as a work message of
100 // whatsappSource, and wakes the loop once with the batches that start a turn. A
101 // batch leaves the state file after its message is durable in the log. A group
102 // with no name gets its name from WhatsApp first, with the client of link.
103 // During a catch-up it logs nothing, and at its end it closes all batches
104 // first. With all, it closes and logs all batches also during a catch-up.
105 // Routed batches enter the durable child queue instead of the root log and wake
106 // their child even when the batch does not need a root turn.
107 func (i *WhatsAppInbox) deliver(ctx context.Context, l *TurnLoop, link WhatsAppLink, all bool) error {
110 catchingUp := i.catchingUp
111 caughtUp := i.caughtUp
118 case all || caughtUp:
119 err = i.state.CloseAll()
123 _, err = i.state.CloseDue(time.Now())
130 batches := i.state.Closed()
131 if l.messages != nil {
132 err = l.messages.PruneWhatsApp(batches)
134 return fmt.Errorf("prune WhatsApp receipts: %w", err)
140 for _, batch := range batches {
141 if batch.Chat.Group && batch.Chat.Name == "" {
142 batch.Chat.Name = i.groups.name(ctx, link, batch.Chat.ID)
145 text := batch.Text(i.clock().Location())
146 if l.messages != nil {
147 routed, err := l.messages.RouteWhatsApp(batch, text)
149 return fmt.Errorf("route a WhatsApp batch: %w", err)
153 err = i.state.Remove(batch.Number)
155 return fmt.Errorf("remove routed WhatsApp batch: %w", err)
162 message, err := l.Work(whatsappSource, text, "")
164 return fmt.Errorf("log a WhatsApp batch: %w", err)
167 // A stop of the daemon during the flush is no failure: the
168 // batch stays in the state file and repeats once at the next
171 if ctx.Err() != nil {
176 return fmt.Errorf("log a WhatsApp batch: %w", err)
179 err = i.state.Remove(batch.Number)
185 turns = append(turns, message)
191 if l.messages != nil {
192 err = l.messages.PruneWhatsApp(i.state.Closed())
194 return fmt.Errorf("prune WhatsApp receipts: %w", err)
201 // waitForCatchup makes the batches wait for a catch-up, as for the batches of
202 // the state file at the start, before the first connection.
203 func (i *WhatsAppInbox) waitForCatchup() {
205 defer i.mutex.Unlock()
210 // startCatchup starts the catch-up of a new connection, which ends at
211 // endCatchup or after whatsappCatchupTimeout.
212 func (i *WhatsAppInbox) startCatchup() {
214 defer i.mutex.Unlock()
218 catchups := i.catchups
219 if i.catchupTimer != nil {
220 i.catchupTimer.Stop()
223 i.catchupTimer = time.AfterFunc(whatsappCatchupTimeout, func() {
224 i.caughtUpBy(catchups)
228 // receive stores an image before its batch and wakes Run. link gives the device
229 // and the own IDs. It returns false when the state file cannot hold the
230 // message, so that the library does not acknowledge it, and Run stops the
231 // daemon. An image that cannot be downloaded or stored gets a text marker. A
232 // message that the batches do not take is handled with nothing to do.
233 func (i *WhatsAppInbox) receive(ctx context.Context, link WhatsAppLink, event *events.Message) bool {
234 lookupCtx, cancel := context.WithTimeout(ctx, whatsappContactLookupTimeout)
237 chat, message, found := whatsappMessage(lookupCtx, link.device, link.own, event)
242 if event.Message.GetImageMessage() != nil {
243 ctx, cancel := context.WithTimeout(ctx, whatsappImageDownloadTimeout)
246 message.Text = i.imageText(ctx, link, event, message.Text)
249 _, err := i.state.Add(chat, message, time.Now())
252 case i.failures <- err:
260 case i.wake <- struct{}{}:
267 // imageText stores the image of event before returning its marker and caption.
268 // Failures keep the caption with a text marker. The daemon log identifies the
269 // chat by a short hash, not its phone number.
270 func (i *WhatsAppInbox) imageText(ctx context.Context, link WhatsAppLink, event *events.Message, caption string) string {
271 name, err := whatsappImage(ctx, link.client, i.images, event.Message.GetImageMessage())
273 chat := event.Info.Chat.ToNonAD()
274 digest := sha256.Sum256([]byte(chat.String()))
275 redact := append(slices.Clone(link.own), chat.User)
276 i.logger.Error("image receive failed", "chat", fmt.Sprintf("%x", digest[:6]), "err", whatsappRedact(redact, err.Error()))
278 text := "(image not downloaded)"
280 text += "\n" + caption
286 return imageText([]string{name}, caption)
289 // caughtUpBy ends the catch-up of the connection with the number catchups, when
290 // no later connection started a new one.
291 func (i *WhatsAppInbox) caughtUpBy(catchups int) {
293 defer i.mutex.Unlock()
295 if i.catchups == catchups {
300 // finishCatchup ends a running catch-up and wakes Run, which logs all batches.
301 // The caller holds the mutex.
302 func (i *WhatsAppInbox) finishCatchup() {
309 if i.catchupTimer != nil {
310 i.catchupTimer.Stop()
314 case i.wake <- struct{}{}:
319 // endCatchup ends a running catch-up at OfflineSyncCompleted.
320 func (i *WhatsAppInbox) endCatchup() {
322 defer i.mutex.Unlock()
327 // stopCatchup ends a running catch-up with no wake, after the session is
329 func (i *WhatsAppInbox) stopCatchup() {
331 defer i.mutex.Unlock()
336 // close stops the timer of the catch-up.
337 func (i *WhatsAppInbox) close() {
339 defer i.mutex.Unlock()
341 if i.catchupTimer != nil {
342 i.catchupTimer.Stop()
346 // whatsappMessage returns the chat and the batch message of event, or false
347 // when the batches do not take it. device is the linked device, and own holds
348 // the own IDs. The batches take text, images, and media markers from a private
349 // chat or a group, from another person or from the user. They do not take
350 // reactions, edits, deletions, view-once and disappearing messages, old
351 // history, status broadcasts, channels, and the chat of the user with itself.
353 // A mention of the user becomes @you, another mention @NAME when the name is
354 // known, and the own number and LID become OWN, so that they never go to the
356 func whatsappMessage(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
358 chatJID := info.Chat.ToNonAD()
361 case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.Message.GetImageMessage().GetViewOnce(), event.Message.GetVideoMessage().GetViewOnce(), event.SourceWebMsg != nil:
362 case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
363 case slices.Contains(own, chatJID.User):
365 return whatsappText(ctx, device, own, event)
368 return WhatsAppChat{}, WhatsAppMessage{}, false
371 // whatsappText returns the chat and the batch message of event, a message that
372 // the batches take. An image returns its caption until receive stores it.
373 func whatsappText(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
375 text := event.Message.GetConversation()
376 extended := event.Message.GetExtendedTextMessage()
378 text = extended.GetText()
381 contextInfo := extended.GetContextInfo()
383 case event.Message.GetImageMessage() != nil:
384 image := event.Message.GetImageMessage()
385 text = image.GetCaption()
386 contextInfo = image.GetContextInfo()
387 case event.Message.GetStickerMessage() != nil:
389 contextInfo = event.Message.GetStickerMessage().GetContextInfo()
390 case event.Message.GetVideoMessage() != nil:
391 video := event.Message.GetVideoMessage()
393 if video.GetGifPlayback() {
397 if video.GetCaption() != "" {
398 text += "\n" + video.GetCaption()
401 contextInfo = video.GetContextInfo()
403 if strings.TrimSpace(text) == "" {
404 return WhatsAppChat{}, WhatsAppMessage{}, false
408 message := WhatsAppMessage{
410 Time: info.Timestamp,
415 message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
418 for _, mentioned := range contextInfo.GetMentionedJID() {
419 jid, err := types.ParseJID(mentioned)
422 case slices.Contains(own, jid.User):
423 message.Mention = true
424 text = strings.ReplaceAll(text, "@"+jid.User, "@you")
426 text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
430 participant, err := types.ParseJID(contextInfo.GetParticipant())
431 message.Reply = err == nil && slices.Contains(own, participant.User)
433 message.Text = whatsappRedact(own, text)
434 chatJID := info.Chat.ToNonAD()
435 chat := WhatsAppChat{
436 ID: chatJID.String(),
437 Group: chatJID.Server == types.GroupServer,
441 push := info.PushName
446 chat.Name = whatsappContactName(ctx, device, chatJID, push)
449 return chat, message, true