11 "go.mau.fi/whatsmeow/store"
12 "go.mau.fi/whatsmeow/types"
13 "go.mau.fi/whatsmeow/types/events"
17 // whatsappSource is the source of the work events of the batches.
18 whatsappSource = "whatsapp"
20 // whatsappCatchupLimit is the longest wait for the end of the catch-up
21 // after a connection.
22 whatsappCatchupLimit = time.Minute
25 // newWhatsAppInbox returns the inbox of the batches in state, with clock for
26 // the times of the batch texts and groups for the names of the groups.
27 func newWhatsAppInbox(state *WhatsAppState, clock func() time.Time, groups *WhatsAppGroups) *WhatsAppInbox {
28 return &WhatsAppInbox{
32 catchupLimit: whatsappCatchupLimit,
33 wake: make(chan struct{}, 1),
34 failures: make(chan error, 1),
38 // WhatsAppInbox puts the text messages into batches, one chat at a time, as
39 // WhatsAppState says. deliver logs each closed batch as a work message that
40 // starts with [WhatsApp], and a batch that needs the user wakes the turn loop.
42 // After each connection, the servers send the messages that came while the
43 // daemon was away, and then OfflineSyncCompleted. Until then, or until
44 // catchupLimit passes, the closed batches wait in the state file. At the end of
45 // the catch-up, deliver closes all batches, logs them, and wakes the turn loop
46 // once, so the whole catch-up gives one turn and not one turn for each chat.
47 // The batches of the state file at the start wait for the first catch-up in the
48 // same way. The event handler acknowledges a message only after the state file
49 // holds it, so the servers send again a message that a crash lost. A batch
50 // leaves the state file only after its work message is durable in the log. A
51 // crash between the two makes the batch repeat once.
53 // The state file is the one of WhatsApp, which keeps the send records in it
54 // too. groups gives the names of the groups. The mutex protects the state of
55 // the catch-up, which the event handler of the library changes from its own
56 // goroutines. wake tells Run that a batch can be due or that a catch-up ended,
57 // and failures gives Run the error of a write of the state file.
58 type WhatsAppInbox struct {
60 clock func() time.Time
61 groups *WhatsAppGroups
62 catchupLimit time.Duration
70 catchupTimer *time.Timer
73 // due returns a channel that gets a value when the next open batch is due, or
74 // nil when no batch is open.
75 func (i *WhatsAppInbox) due() <-chan time.Time {
76 wait, open := i.state.Wait(time.Now())
81 return time.After(wait)
84 // deliver logs the closed batches in l in order, each as a work message of
85 // whatsappSource, and wakes the loop once with the batches that start a turn. A
86 // batch leaves the state file after its message is durable in the log. A group
87 // with no name gets its name from WhatsApp first, with the client of link.
88 // During a catch-up it logs nothing, and at its end it closes all batches
89 // first. With all, it closes and logs all batches also during a catch-up.
90 func (i *WhatsAppInbox) deliver(ctx context.Context, l *TurnLoop, link WhatsAppLink, all bool) error {
93 catchingUp := i.catchingUp
94 caughtUp := i.caughtUp
101 case all || caughtUp:
102 err = i.state.CloseAll()
106 _, err = i.state.CloseDue(time.Now())
115 for _, batch := range i.state.Closed() {
116 if batch.Chat.Group && batch.Chat.Name == "" {
117 batch.Chat.Name = i.groups.name(ctx, link, batch.Chat.ID)
120 message, err := l.Work(whatsappSource, batch.Text(i.clock().Location()), "")
122 return fmt.Errorf("log a WhatsApp batch: %w", err)
125 // A stop of the daemon during the flush is no failure: the
126 // batch stays in the state file and repeats once at the next
129 if ctx.Err() != nil {
134 return fmt.Errorf("log a WhatsApp batch: %w", err)
137 err = i.state.Remove(batch.Number)
143 turns = append(turns, message)
152 // waitForCatchup makes the batches wait for a catch-up, as for the batches of
153 // the state file at the start, before the first connection.
154 func (i *WhatsAppInbox) waitForCatchup() {
156 defer i.mutex.Unlock()
161 // startCatchup starts the catch-up of a new connection, which ends at
162 // endCatchup or after catchupLimit.
163 func (i *WhatsAppInbox) startCatchup() {
165 defer i.mutex.Unlock()
169 catchups := i.catchups
170 if i.catchupTimer != nil {
171 i.catchupTimer.Stop()
174 i.catchupTimer = time.AfterFunc(i.catchupLimit, func() {
175 i.caughtUpBy(catchups)
179 // receive puts the text of event into its batch and wakes Run. link gives the
180 // device and the own IDs. It returns false when the state file cannot hold the
181 // message, so that the library does not acknowledge it, and Run stops the
182 // daemon. A message that is not text, or that the batches do not take, is
183 // handled with nothing to do.
184 func (i *WhatsAppInbox) receive(link WhatsAppLink, event *events.Message) bool {
185 ctx, cancel := context.WithTimeout(context.Background(), whatsappLookupTime)
188 chat, message, found := whatsappMessage(ctx, link.device, link.own, event)
193 _, err := i.state.Add(chat, message, time.Now())
196 case i.failures <- err:
204 case i.wake <- struct{}{}:
211 // caughtUpBy ends the catch-up of the connection with the number catchups, when
212 // no later connection started a new one.
213 func (i *WhatsAppInbox) caughtUpBy(catchups int) {
215 defer i.mutex.Unlock()
217 if i.catchups == catchups {
222 // finishCatchup ends a running catch-up and wakes Run, which logs all batches.
223 // The caller holds the mutex.
224 func (i *WhatsAppInbox) finishCatchup() {
231 if i.catchupTimer != nil {
232 i.catchupTimer.Stop()
236 case i.wake <- struct{}{}:
241 // endCatchup ends a running catch-up at OfflineSyncCompleted.
242 func (i *WhatsAppInbox) endCatchup() {
244 defer i.mutex.Unlock()
249 // stopCatchup ends a running catch-up with no wake, after the session is
251 func (i *WhatsAppInbox) stopCatchup() {
253 defer i.mutex.Unlock()
258 // close stops the timer of the catch-up.
259 func (i *WhatsAppInbox) close() {
261 defer i.mutex.Unlock()
263 if i.catchupTimer != nil {
264 i.catchupTimer.Stop()
268 // whatsappMessage returns the chat and the batch message of event, or false
269 // when the batches do not take it. device is the linked device, and own holds
270 // the own IDs. The batches take the text of a private chat or a group, from
271 // another person or from the user. They do not take media, reactions, edits,
272 // deletions, view-once and disappearing messages, old history, status
273 // broadcasts, channels, and the chat of the user with itself.
275 // A mention of the user becomes @you, another mention @NAME when the name is
276 // known, and the own number and LID become OWN, so that they never go to the
278 func whatsappMessage(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
280 chatJID := info.Chat.ToNonAD()
283 case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.SourceWebMsg != nil:
284 case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
285 case slices.Contains(own, chatJID.User):
287 return whatsappText(ctx, device, own, event)
290 return WhatsAppChat{}, WhatsAppMessage{}, false
293 // whatsappText returns the chat and the batch message of event, a message that
294 // the batches take when it has text.
295 func whatsappText(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
297 text := event.Message.GetConversation()
298 extended := event.Message.GetExtendedTextMessage()
300 text = extended.GetText()
303 if strings.TrimSpace(text) == "" {
304 return WhatsAppChat{}, WhatsAppMessage{}, false
307 contextInfo := extended.GetContextInfo()
308 message := WhatsAppMessage{
310 Time: info.Timestamp,
315 message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
318 for _, mentioned := range contextInfo.GetMentionedJID() {
319 jid, err := types.ParseJID(mentioned)
322 case slices.Contains(own, jid.User):
323 message.Mention = true
324 text = strings.ReplaceAll(text, "@"+jid.User, "@you")
326 text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
330 participant, err := types.ParseJID(contextInfo.GetParticipant())
331 message.Reply = err == nil && slices.Contains(own, participant.User)
333 message.Text = whatsappRedact(own, text)
334 chatJID := info.Chat.ToNonAD()
335 chat := WhatsAppChat{
336 ID: chatJID.String(),
337 Group: chatJID.Server == types.GroupServer,
341 push := info.PushName
346 chat.Name = whatsappContactName(ctx, device, chatJID, push)
349 return chat, message, true