12 "go.mau.fi/whatsmeow/store"
13 "go.mau.fi/whatsmeow/types"
14 "go.mau.fi/whatsmeow/types/events"
18 // whatsappContactLookupTimeout is the longest time of a read of names
20 whatsappContactLookupTimeout = 10 * time.Second
22 // whatsappImageDownloadTimeout is the longest time of an image
24 whatsappImageDownloadTimeout = 2 * time.Minute
26 // whatsappSource is the source of the work events of the batches.
27 whatsappSource = "whatsapp"
29 // whatsappCatchupTimeout is the longest wait for the end of the
30 // catch-up after a connection.
31 whatsappCatchupTimeout = time.Minute
34 // newWhatsAppInbox returns the inbox of the batches in state, with clock for
35 // the times of the batch texts and groups for the names of the groups. images
36 // holds shared images, and logger gets image failures.
37 func newWhatsAppInbox(state *WhatsAppState, clock func() time.Time, groups *WhatsAppGroups, images *ImageStore, logger *slog.Logger) *WhatsAppInbox {
38 return &WhatsAppInbox{
44 wake: make(chan struct{}, 1),
45 failures: make(chan error, 1),
49 // WhatsAppInbox puts messages into batches, one chat at a time, as
50 // WhatsAppState says. deliver logs each closed batch as a work message that
51 // starts with [WhatsApp], and a batch that needs the user wakes the turn loop.
53 // After each connection, the servers send the messages that came while the
54 // daemon was away, and then OfflineSyncCompleted. Until then, or until
55 // whatsappCatchupTimeout passes, the closed batches wait in the state file. At
56 // the end of the catch-up, deliver closes all batches and logs them. It wakes
57 // the root once for its batches, so their catch-up gives one turn, not one for
58 // each chat. The batches of the state file at the start wait for the first
59 // catch-up in the same way. The event handler acknowledges a message only after
60 // the state file holds it, so the servers send again a message that a crash
61 // lost. A batch leaves the state file only after its work message is durable in
62 // the log or agent queue. A crash between the two can repeat an unrouted batch
63 // once. A routed batch enters the durable agent queue, which prevents a second
64 // log entry and wakes only the child. A missing child uses the root.
66 // The state file is the one of WhatsApp, which keeps the send records in it
67 // too. groups gives the names of the groups. The mutex protects the state of
68 // the catch-up, which the event handler of the library changes from its own
69 // goroutines. wake tells Run that a batch can be due or that a catch-up ended,
70 // and failures gives Run the error of a write of the state file.
71 type WhatsAppInbox struct {
73 clock func() time.Time
74 groups *WhatsAppGroups
84 catchupTimer *time.Timer
87 // due returns a channel that gets a value when the next open batch is due, or
88 // nil when no batch is open.
89 func (i *WhatsAppInbox) due() <-chan time.Time {
90 wait, open := i.state.Wait(time.Now())
95 return time.After(wait)
98 // deliver logs the closed batches in l in order, each as a work message of
99 // whatsappSource, and wakes the loop once with the batches that start a turn. A
100 // batch leaves the state file after its message is durable in the log. A group
101 // with no name gets its name from WhatsApp first, with the client of link.
102 // During a catch-up it logs nothing, and at its end it closes all batches
103 // first. With all, it closes and logs all batches also during a catch-up.
104 // Routed batches enter the durable child queue instead of the root log and wake
105 // their child even when the batch does not need a root turn.
106 func (i *WhatsAppInbox) deliver(ctx context.Context, l *TurnLoop, link WhatsAppLink, all bool) error {
109 catchingUp := i.catchingUp
110 caughtUp := i.caughtUp
117 case all || caughtUp:
118 err = i.state.CloseAll()
122 _, err = i.state.CloseDue(time.Now())
129 batches := i.state.Closed()
130 if l.messages != nil {
131 err = l.messages.PruneWhatsApp(batches)
133 return fmt.Errorf("prune WhatsApp receipts: %w", err)
139 for _, batch := range batches {
140 if batch.Chat.Group && batch.Chat.Name == "" {
141 batch.Chat.Name = i.groups.name(ctx, link, batch.Chat.ID)
144 text := batch.Text(i.clock().Location())
145 if l.messages != nil {
146 routed, err := l.messages.RouteWhatsApp(batch, text)
148 return fmt.Errorf("route a WhatsApp batch: %w", err)
152 err = i.state.Remove(batch.Number)
154 return fmt.Errorf("remove routed WhatsApp batch: %w", err)
161 message, err := l.Work(whatsappSource, text, "")
163 return fmt.Errorf("log a WhatsApp batch: %w", err)
166 // A stop of the daemon during the flush is no failure: the
167 // batch stays in the state file and repeats once at the next
170 if ctx.Err() != nil {
175 return fmt.Errorf("log a WhatsApp batch: %w", err)
178 err = i.state.Remove(batch.Number)
184 turns = append(turns, message)
190 if l.messages != nil {
191 err = l.messages.PruneWhatsApp(i.state.Closed())
193 return fmt.Errorf("prune WhatsApp receipts: %w", err)
200 // waitForCatchup makes the batches wait for a catch-up, as for the batches of
201 // the state file at the start, before the first connection.
202 func (i *WhatsAppInbox) waitForCatchup() {
204 defer i.mutex.Unlock()
209 // startCatchup starts the catch-up of a new connection, which ends at
210 // endCatchup or after whatsappCatchupTimeout.
211 func (i *WhatsAppInbox) startCatchup() {
213 defer i.mutex.Unlock()
217 catchups := i.catchups
218 if i.catchupTimer != nil {
219 i.catchupTimer.Stop()
222 i.catchupTimer = time.AfterFunc(whatsappCatchupTimeout, func() {
223 i.caughtUpBy(catchups)
227 // receive stores an image before its batch and wakes Run. link gives the device
228 // and the own IDs. It returns false when the state file cannot hold the
229 // message, so that the library does not acknowledge it, and Run stops the
230 // daemon. An image that cannot be downloaded or stored gets a text marker. A
231 // message that the batches do not take is handled with nothing to do.
232 func (i *WhatsAppInbox) receive(ctx context.Context, link WhatsAppLink, event *events.Message) bool {
233 lookupCtx, cancel := context.WithTimeout(ctx, whatsappContactLookupTimeout)
236 chat, message, found := whatsappMessage(lookupCtx, link.device, link.own, event)
241 if event.Message.GetImageMessage() != nil {
242 ctx, cancel := context.WithTimeout(ctx, whatsappImageDownloadTimeout)
245 message.Text = i.imageText(ctx, link, event, message.Text)
248 _, err := i.state.Add(chat, message, time.Now())
251 case i.failures <- err:
259 case i.wake <- struct{}{}:
266 // imageText stores the image of event before returning its marker and caption.
267 // Failures keep the caption with a text marker. The daemon log identifies the
268 // chat by a short hash, not its phone number.
269 func (i *WhatsAppInbox) imageText(ctx context.Context, link WhatsAppLink, event *events.Message, caption string) string {
270 name, err := whatsappImage(ctx, link.client, i.images, event.Message.GetImageMessage())
272 chat := event.Info.Chat.ToNonAD()
273 redact := append(slices.Clone(link.own), chat.User)
274 i.logger.Error("image receive failed", "chat", whatsappChatHash(chat), "err", whatsappRedact(redact, err.Error()))
276 text := "(image not downloaded)"
278 text += "\n" + caption
284 return imageText([]string{name}, caption)
287 // caughtUpBy ends the catch-up of the connection with the number catchups, when
288 // no later connection started a new one.
289 func (i *WhatsAppInbox) caughtUpBy(catchups int) {
291 defer i.mutex.Unlock()
293 if i.catchups == catchups {
298 // finishCatchup ends a running catch-up and wakes Run, which logs all batches.
299 // The caller holds the mutex.
300 func (i *WhatsAppInbox) finishCatchup() {
307 if i.catchupTimer != nil {
308 i.catchupTimer.Stop()
312 case i.wake <- struct{}{}:
317 // endCatchup ends a running catch-up at OfflineSyncCompleted.
318 func (i *WhatsAppInbox) endCatchup() {
320 defer i.mutex.Unlock()
325 // stopCatchup ends a running catch-up with no wake, after the session is
327 func (i *WhatsAppInbox) stopCatchup() {
329 defer i.mutex.Unlock()
334 // close stops the timer of the catch-up.
335 func (i *WhatsAppInbox) close() {
337 defer i.mutex.Unlock()
339 if i.catchupTimer != nil {
340 i.catchupTimer.Stop()
344 // whatsappMessage returns the chat and the batch message of event, or false
345 // when the batches do not take it. device is the linked device, and own holds
346 // the own IDs. The batches take text, images, and media markers from a private
347 // chat or a group, from another person or from the user. They do not take
348 // reactions, edits, deletions, view-once and disappearing messages, old
349 // history, status broadcasts, channels, and the chat of the user with itself.
351 // A mention of the user becomes @you, another mention @NAME when the name is
352 // known, and the own number and LID become OWN, so that they never go to the
354 func whatsappMessage(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
356 chatJID := info.Chat.ToNonAD()
359 case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.Message.GetImageMessage().GetViewOnce(), event.Message.GetVideoMessage().GetViewOnce(), event.SourceWebMsg != nil:
360 case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
361 case slices.Contains(own, chatJID.User):
363 return whatsappText(ctx, device, own, event)
366 return WhatsAppChat{}, WhatsAppMessage{}, false
369 // whatsappText returns the chat and the batch message of event, a message that
370 // the batches take. An image returns its caption until receive stores it.
371 func whatsappText(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
373 text := event.Message.GetConversation()
374 extended := event.Message.GetExtendedTextMessage()
376 text = extended.GetText()
379 contextInfo := extended.GetContextInfo()
381 case event.Message.GetImageMessage() != nil:
382 image := event.Message.GetImageMessage()
383 text = image.GetCaption()
384 contextInfo = image.GetContextInfo()
385 case event.Message.GetStickerMessage() != nil:
387 contextInfo = event.Message.GetStickerMessage().GetContextInfo()
388 case event.Message.GetVideoMessage() != nil:
389 video := event.Message.GetVideoMessage()
391 if video.GetGifPlayback() {
395 if video.GetCaption() != "" {
396 text += "\n" + video.GetCaption()
399 contextInfo = video.GetContextInfo()
401 if strings.TrimSpace(text) == "" {
402 return WhatsAppChat{}, WhatsAppMessage{}, false
406 message := WhatsAppMessage{
408 Time: info.Timestamp,
413 message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
416 for _, mentioned := range contextInfo.GetMentionedJID() {
417 jid, err := types.ParseJID(mentioned)
420 case slices.Contains(own, jid.User):
421 message.Mention = true
422 text = strings.ReplaceAll(text, "@"+jid.User, "@you")
424 text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
428 participant, err := types.ParseJID(contextInfo.GetParticipant())
429 message.Reply = err == nil && slices.Contains(own, participant.User)
431 message.Text = whatsappRedact(own, text)
432 chatJID := info.Chat.ToNonAD()
433 chat := WhatsAppChat{
434 ID: chatJID.String(),
435 Group: chatJID.Server == types.GroupServer,
439 push := info.PushName
444 chat.Name = whatsappContactName(ctx, device, chatJID, push)
447 return chat, message, true