13 "go.mau.fi/whatsmeow/store"
14 "go.mau.fi/whatsmeow/types"
15 "go.mau.fi/whatsmeow/types/events"
19 // whatsappSource is the source of the work events of the batches.
20 whatsappSource = "whatsapp"
22 // whatsappCatchupLimit is the longest wait for the end of the catch-up
23 // after a connection.
24 whatsappCatchupLimit = time.Minute
27 // newWhatsAppInbox returns the inbox of the batches in state, with clock for
28 // the times of the batch texts and groups for the names of the groups. images
29 // holds shared images, and logger gets image failures.
30 func newWhatsAppInbox(state *WhatsAppState, clock func() time.Time, groups *WhatsAppGroups, images *ImageStore, logger *slog.Logger) *WhatsAppInbox {
31 return &WhatsAppInbox{
37 lookupTime: whatsappLookupTime,
38 imageTime: whatsappImageTime,
39 catchupLimit: whatsappCatchupLimit,
40 wake: make(chan struct{}, 1),
41 failures: make(chan error, 1),
45 // WhatsAppInbox puts messages into batches, one chat at a time, as
46 // WhatsAppState says. deliver logs each closed batch as a work message that
47 // starts with [WhatsApp], and a batch that needs the user wakes the turn loop.
49 // After each connection, the servers send the messages that came while the
50 // daemon was away, and then OfflineSyncCompleted. Until then, or until
51 // catchupLimit passes, the closed batches wait in the state file. At the end of
52 // the catch-up, deliver closes all batches and logs them. It wakes the root
53 // once for its batches, so their catch-up gives one turn, not one for each
54 // chat. The batches of the state file at the start wait for the first catch-up
55 // in the same way. The event handler acknowledges a message only after the
56 // state file holds it, so the servers send again a message that a crash lost. A
57 // batch leaves the state file only after its work message is durable in the log
58 // or agent queue. A crash between the two can repeat an unrouted batch once. A
59 // routed batch enters the durable agent queue, which prevents a second log
60 // entry and wakes only the child. A missing child uses the root.
62 // The state file is the one of WhatsApp, which keeps the send records in it
63 // too. groups gives the names of the groups. The mutex protects the state of
64 // the catch-up, which the event handler of the library changes from its own
65 // goroutines. wake tells Run that a batch can be due or that a catch-up ended,
66 // and failures gives Run the error of a write of the state file.
67 type WhatsAppInbox struct {
69 clock func() time.Time
70 groups *WhatsAppGroups
73 lookupTime time.Duration
74 imageTime time.Duration
75 catchupLimit time.Duration
83 catchupTimer *time.Timer
86 // due returns a channel that gets a value when the next open batch is due, or
87 // nil when no batch is open.
88 func (i *WhatsAppInbox) due() <-chan time.Time {
89 wait, open := i.state.Wait(time.Now())
94 return time.After(wait)
97 // deliver logs the closed batches in l in order, each as a work message of
98 // whatsappSource, and wakes the loop once with the batches that start a turn. A
99 // batch leaves the state file after its message is durable in the log. A group
100 // with no name gets its name from WhatsApp first, with the client of link.
101 // During a catch-up it logs nothing, and at its end it closes all batches
102 // first. With all, it closes and logs all batches also during a catch-up.
103 // Routed batches enter the durable child queue instead of the root log and wake
104 // their child even when the batch does not need a root turn.
105 func (i *WhatsAppInbox) deliver(ctx context.Context, l *TurnLoop, link WhatsAppLink, all bool) error {
108 catchingUp := i.catchingUp
109 caughtUp := i.caughtUp
116 case all || caughtUp:
117 err = i.state.CloseAll()
121 _, err = i.state.CloseDue(time.Now())
128 batches := i.state.Closed()
129 if l.messages != nil {
130 err = l.messages.PruneWhatsApp(batches)
132 return fmt.Errorf("prune WhatsApp receipts: %w", err)
138 for _, batch := range batches {
139 if batch.Chat.Group && batch.Chat.Name == "" {
140 batch.Chat.Name = i.groups.name(ctx, link, batch.Chat.ID)
143 text := batch.Text(i.clock().Location())
144 if l.messages != nil {
145 routed, err := l.messages.RouteWhatsApp(batch, text)
147 return fmt.Errorf("route a WhatsApp batch: %w", err)
151 err = i.state.Remove(batch.Number)
153 return fmt.Errorf("remove routed WhatsApp batch: %w", err)
160 message, err := l.Work(whatsappSource, text, "")
162 return fmt.Errorf("log a WhatsApp batch: %w", err)
165 // A stop of the daemon during the flush is no failure: the
166 // batch stays in the state file and repeats once at the next
169 if ctx.Err() != nil {
174 return fmt.Errorf("log a WhatsApp batch: %w", err)
177 err = i.state.Remove(batch.Number)
183 turns = append(turns, message)
189 if l.messages != nil {
190 err = l.messages.PruneWhatsApp(i.state.Closed())
192 return fmt.Errorf("prune WhatsApp receipts: %w", err)
199 // waitForCatchup makes the batches wait for a catch-up, as for the batches of
200 // the state file at the start, before the first connection.
201 func (i *WhatsAppInbox) waitForCatchup() {
203 defer i.mutex.Unlock()
208 // startCatchup starts the catch-up of a new connection, which ends at
209 // endCatchup or after catchupLimit.
210 func (i *WhatsAppInbox) startCatchup() {
212 defer i.mutex.Unlock()
216 catchups := i.catchups
217 if i.catchupTimer != nil {
218 i.catchupTimer.Stop()
221 i.catchupTimer = time.AfterFunc(i.catchupLimit, func() {
222 i.caughtUpBy(catchups)
226 // receive stores an image before its batch and wakes Run. link gives the device
227 // and the own IDs. It returns false when the state file cannot hold the
228 // message, so that the library does not acknowledge it, and Run stops the
229 // daemon. An image that cannot be downloaded or stored gets a text marker. A
230 // message that the batches do not take is handled with nothing to do.
231 func (i *WhatsAppInbox) receive(link WhatsAppLink, event *events.Message) bool {
232 ctx, cancel := context.WithTimeout(context.Background(), i.lookupTime)
235 chat, message, found := whatsappMessage(ctx, link.device, link.own, event)
240 if event.Message.GetImageMessage() != nil {
241 ctx, cancel := context.WithTimeout(context.Background(), i.imageTime)
244 message.Text = i.imageText(ctx, link, event, message.Text)
247 _, err := i.state.Add(chat, message, time.Now())
250 case i.failures <- err:
258 case i.wake <- struct{}{}:
265 // imageText stores the image of event before returning its marker and caption.
266 // Failures keep the caption with a text marker. The daemon log identifies the
267 // chat by a short hash, not its phone number.
268 func (i *WhatsAppInbox) imageText(ctx context.Context, link WhatsAppLink, event *events.Message, caption string) string {
269 name, err := whatsappImage(ctx, link.client, i.images, event.Message.GetImageMessage())
271 chat := event.Info.Chat.ToNonAD()
272 digest := sha256.Sum256([]byte(chat.String()))
273 redact := append(slices.Clone(link.own), chat.User)
274 i.logger.Error("image receive failed", "chat", fmt.Sprintf("%x", digest[:6]), "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