]> git.giacomolli.uk - onechat/blob - whatsapp.go
Give the WhatsApp batches to the agent
[onechat] / whatsapp.go
1 package main
2
3 import (
4         "context"
5         "errors"
6         "fmt"
7         "log"
8         "net/url"
9         "os"
10         "path/filepath"
11         "slices"
12         "strings"
13         "sync"
14         "time"
15
16         "go.mau.fi/whatsmeow"
17         "go.mau.fi/whatsmeow/store"
18         "go.mau.fi/whatsmeow/store/sqlstore"
19         "go.mau.fi/whatsmeow/types"
20         "go.mau.fi/whatsmeow/types/events"
21         waLog "go.mau.fi/whatsmeow/util/log"
22
23         // The session store of the library opens SQLite with this pure Go
24         // driver.
25         _ "modernc.org/sqlite"
26 )
27
28 const (
29         // whatsappDirName is the directory of the WhatsApp files in the data
30         // directory.
31         whatsappDirName = "whatsapp"
32
33         // whatsappSessionFileName is the session database of the library in
34         // whatsappDirName.
35         whatsappSessionFileName = "session.db"
36
37         // whatsappCommand starts the input lines of the WhatsApp commands, such
38         // as "/whatsapp status".
39         whatsappCommand = "/whatsapp"
40
41         // whatsappUsage is the answer to a WhatsApp command that does not
42         // exist.
43         whatsappUsage = "Use /whatsapp pair PHONE, /whatsapp status, or /whatsapp unlink. PHONE is the number of your WhatsApp account with its country code, such as +15550001111."
44
45         // whatsappPairSteps tells the user what to do with the pairing code,
46         // which comes in the next message.
47         whatsappPairSteps = "In WhatsApp on your phone, open Linked devices, tap Link a device, then tap Link with phone number instead, and enter the code of the next message. The code expires in about 2 minutes."
48
49         // whatsappPairExpired is the answer when the pairing code expires.
50         whatsappPairExpired = "The pairing code expired. Run /whatsapp pair PHONE again for a new code."
51
52         // whatsappTimeLayout is the layout of the times in the answers.
53         whatsappTimeLayout = "2006-01-02 15:04"
54
55         // whatsappPairTime is the longest time of a pairing. The library closes
56         // the pairing connection after about 160 seconds.
57         whatsappPairTime = 3 * time.Minute
58
59         // whatsappLogoutTime is the longest time of the logout call of an
60         // unlink.
61         whatsappLogoutTime = 30 * time.Second
62
63         // whatsappNoticeDelay is how long a disconnection lasts before the user
64         // gets a notice.
65         whatsappNoticeDelay = 10 * time.Minute
66
67         // whatsappRequests is the number of pair and unlink commands that can
68         // wait for Run.
69         whatsappRequests = 8
70
71         // whatsappSource is the source of the work events of the batches.
72         whatsappSource = "whatsapp"
73
74         // whatsappLookupTime is the longest time of a read of the names in the
75         // session database or of the groups from WhatsApp.
76         whatsappLookupTime = 10 * time.Second
77
78         // whatsappGroupsRefresh is the shortest time between two reads of the
79         // groups from WhatsApp for a group with no name.
80         whatsappGroupsRefresh = time.Minute
81
82         // whatsappUnknownGroup is the name of a group whose name is not known.
83         whatsappUnknownGroup = "A group with no known name"
84 )
85
86 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
87 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
88 // fake.
89 type WhatsAppClient interface {
90         ConnectContext(ctx context.Context) error
91         Disconnect()
92         GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
93         PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
94         Logout(ctx context.Context) error
95         GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error)
96 }
97
98 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
99 // the session file, WhatsApp is not linked. The session gives full access to
100 // the account, so a file that another user can read is an error. The clock
101 // gives the times of the status, logger gets the failures, and newClient makes
102 // the client of a device with its event handler.
103 func openWhatsApp(ctx context.Context, dir string, clock func() time.Time, logger *log.Logger, newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient) (*WhatsApp, error) {
104         w := &WhatsApp{
105                 dir:         filepath.Join(dir, whatsappDirName),
106                 clock:       clock,
107                 logger:      logger,
108                 newClient:   newClient,
109                 noticeDelay: whatsappNoticeDelay,
110                 requests:    make(chan WhatsAppRequest, whatsappRequests),
111                 logouts:     make(chan struct{}, 1),
112                 wake:        make(chan struct{}, 1),
113                 failures:    make(chan error, 1),
114                 groupNames:  make(map[string]string),
115         }
116
117         var err error
118         w.batches, err = openWhatsAppBatches(filepath.Join(w.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
119         if err != nil {
120                 return nil, err
121         }
122
123         info, err := os.Stat(w.sessionPath())
124         if errors.Is(err, os.ErrNotExist) {
125                 return w, nil
126         }
127
128         if err != nil {
129                 return nil, fmt.Errorf("read WhatsApp session: %w", err)
130         }
131
132         if info.Mode().Perm()&0o077 != 0 {
133                 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
134         }
135
136         err = w.openSession(ctx)
137         if err != nil {
138                 return nil, err
139         }
140
141         if w.device.ID != nil {
142                 w.linked = true
143                 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
144         }
145
146         return w, nil
147 }
148
149 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as a
150 // linked device. The session database of the library in dir holds the keys of
151 // the device. Run keeps a linked device connected, and the library connects
152 // again by itself after a network failure.
153 //
154 // The commands pair and unlink go to Run as requests, and Run runs one at a
155 // time. A pairing runs in its own goroutine until its code expires, and a new
156 // pairing ends the one before. Its phone number and code go only to the answer
157 // of the client that asked. A logout from the phone comes as an event of the
158 // library, and Run deletes the session. The mutex protects the session, the
159 // client, and the state of the connection, which the event handler of the
160 // library changes from its own goroutines.
161 //
162 // The text messages go into batches, one chat at a time, as WhatsAppBatches
163 // says. Run logs each closed batch as a work message that starts with
164 // [WhatsApp], and a batch that needs the user wakes the turn loop. The event
165 // handler acknowledges a message only after the state file holds it, so the
166 // servers send again a message that a crash lost. A batch leaves the state file
167 // only after its work message is durable in the log. A crash between the two
168 // makes the batch repeat once.
169 //
170 // The library logs nothing, because its log lines hold the ID of the own
171 // account, which is the phone number of the user. The own number and the own
172 // LID never go to the log of the agent or to the log of the daemon: redact
173 // removes them from the errors, and a batch shows the messages of the user as
174 // You and a mention of the user as @you. The IDs of the other chats go to the
175 // log, and those of private chats hold phone numbers, because the agent needs
176 // them to send.
177 type WhatsApp struct {
178         dir         string
179         clock       func() time.Time
180         logger      *log.Logger
181         newClient   func(device *store.Device, handle func(event any) bool) WhatsAppClient
182         noticeDelay time.Duration
183         requests    chan WhatsAppRequest
184         logouts     chan struct{}
185         wake        chan struct{}
186         failures    chan error
187         batches     *WhatsAppBatches
188
189         mutex          sync.Mutex
190         container      *sqlstore.Container
191         device         *store.Device
192         client         WhatsAppClient
193         linked         bool
194         own            []string
195         notify         func(Event)
196         connected      bool
197         connectedAt    time.Time
198         disconnectedAt time.Time
199         disconnections int
200         noticed        bool
201         timer          *time.Timer
202         closed         bool
203         groupNames     map[string]string
204         groupsAt       time.Time
205 }
206
207 // Run connects a linked device, logs the closed batches in l, runs the pair and
208 // unlink commands, and handles a logout from the phone, until ctx ends. Its
209 // notes go to the log of l, and notify gets the notices for all clients. A
210 // failed first connection is logged, and the library tries again when the
211 // failure is one of the network. Run returns the error of a write of the log or
212 // of the state file, which stops the daemon, because then messages would be
213 // lost.
214 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) error {
215         w.mutex.Lock()
216         w.notify = notify
217         linked := w.linked
218         w.mutex.Unlock()
219
220         if linked {
221                 w.connect(ctx)
222         }
223
224         var pairing sync.WaitGroup
225         cancel := func() {}
226         defer func() {
227                 cancel()
228                 pairing.Wait()
229                 w.close()
230         }()
231
232         for {
233                 err := w.deliver(ctx, l)
234                 if err != nil {
235                         return err
236                 }
237
238                 var due <-chan time.Time
239                 wait, open := w.batches.Wait(time.Now())
240                 if open {
241                         due = time.After(wait)
242                 }
243
244                 select {
245                 case <-ctx.Done():
246                         return nil
247                 case err = <-w.failures:
248                         return err
249                 case <-w.wake:
250                 case <-due:
251                 case <-w.logouts:
252                         err = w.loggedOut(ctx, l)
253                         if err != nil {
254                                 return err
255                         }
256                 case request := <-w.requests:
257                         cancel()
258                         pairing.Wait()
259                         cancel = func() {}
260
261                         switch {
262                         case request.unlink:
263                                 err = w.unlink(ctx, l, request.answer)
264                                 if err != nil {
265                                         return err
266                                 }
267                         case w.isLinked():
268                                 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
269                         default:
270                                 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
271                                 cancel = cancelPair
272                                 pairing.Go(func() {
273                                         defer cancelPair()
274
275                                         w.pair(pairCtx, l, request.phone, request.answer)
276                                 })
277                         }
278                 }
279         }
280 }
281
282 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
283 // each answer to answer. The answers go only to the client that sent the
284 // command.
285 func (w *WhatsApp) Command(args string, answer func(text string)) {
286         fields := strings.Fields(args)
287         request := WhatsAppRequest{
288                 answer: answer,
289         }
290
291         switch {
292         case len(fields) == 1 && fields[0] == "status":
293                 answer(w.Status())
294                 return
295         case len(fields) == 1 && fields[0] == "unlink":
296                 request.unlink = true
297         case len(fields) >= 2 && fields[0] == "pair":
298                 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
299                 if !valid {
300                         answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
301                         return
302                 }
303
304                 request.phone = phone
305         default:
306                 answer(whatsappUsage)
307                 return
308         }
309
310         select {
311         case w.requests <- request:
312         default:
313                 answer("Too many WhatsApp commands wait. Try again in a minute.")
314         }
315 }
316
317 // Status returns the state of the link: not linked, linked and connected, or
318 // linked and disconnected, with the times of the connection. It never holds the
319 // phone number.
320 func (w *WhatsApp) Status() string {
321         w.mutex.Lock()
322         defer w.mutex.Unlock()
323
324         switch {
325         case !w.linked:
326                 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it."
327         case w.connected:
328                 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "."
329         case w.disconnectedAt.IsZero():
330                 return "WhatsApp is linked and not connected yet."
331         case w.connectedAt.IsZero():
332                 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "."
333         default:
334                 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "."
335         }
336 }
337
338 // Close closes the session database.
339 func (w *WhatsApp) Close() error {
340         w.mutex.Lock()
341         defer w.mutex.Unlock()
342
343         if w.container == nil {
344                 return nil
345         }
346
347         err := w.container.Close()
348         w.container = nil
349
350         return err
351 }
352
353 func (w *WhatsApp) sessionPath() string {
354         return filepath.Join(w.dir, whatsappSessionFileName)
355 }
356
357 // openSession opens the session database and its first device. The caller holds
358 // the mutex, or no other goroutine uses w yet.
359 func (w *WhatsApp) openSession(ctx context.Context) error {
360         address, err := whatsappSessionAddress(w.sessionPath())
361         if err != nil {
362                 return err
363         }
364
365         container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
366         if err != nil {
367                 return fmt.Errorf("open WhatsApp session: %w", err)
368         }
369
370         device, err := container.GetFirstDevice(ctx)
371         if err != nil {
372                 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
373         }
374
375         w.container = container
376         w.device = device
377
378         return nil
379 }
380
381 func (w *WhatsApp) isLinked() bool {
382         w.mutex.Lock()
383         defer w.mutex.Unlock()
384
385         return w.linked
386 }
387
388 // connect makes the client of the linked device and connects it.
389 func (w *WhatsApp) connect(ctx context.Context) {
390         w.mutex.Lock()
391         w.client = w.newClient(w.device, w.handle)
392         client := w.client
393         w.mutex.Unlock()
394
395         err := client.ConnectContext(ctx)
396         if err != nil {
397                 w.logger.Printf("connect: %s", w.redact(err.Error()))
398         }
399 }
400
401 // close ends the connection and the timer of the notice, and stops all notices.
402 func (w *WhatsApp) close() {
403         w.mutex.Lock()
404         w.closed = true
405         if w.timer != nil {
406                 w.timer.Stop()
407         }
408
409         client := w.client
410         w.client = nil
411         w.mutex.Unlock()
412
413         if client != nil {
414                 client.Disconnect()
415         }
416 }
417
418 // loggedOut logs the open batches, deletes the session after a logout from the
419 // phone, notes it in the log of l, and tells all clients one time.
420 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
421         if !w.isLinked() {
422                 return nil
423         }
424
425         err := w.deliverAll(ctx, l)
426         if err != nil {
427                 return err
428         }
429
430         err = w.removeSession()
431         if err != nil {
432                 w.logger.Printf("delete the session after the logout: %v", err)
433         }
434
435         err = l.note("WhatsApp was unlinked from the phone.")
436         if err != nil {
437                 w.logger.Printf("note the logout: %v", err)
438         }
439
440         w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
441
442         return nil
443 }
444
445 // unlink logs the open batches, logs out the linked device, and deletes the
446 // session. When the logout call fails, as it does while WhatsApp is
447 // disconnected, the session is deleted all the same, and answer tells the user
448 // to remove the device in the phone. Its error is one of the log or the state
449 // file.
450 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
451         w.mutex.Lock()
452         linked := w.linked
453         client := w.client
454         w.mutex.Unlock()
455
456         if !linked {
457                 answer("WhatsApp is not linked.")
458                 return nil
459         }
460
461         err := w.deliverAll(ctx, l)
462         if err != nil {
463                 return err
464         }
465
466         var logoutErr error
467         if client != nil {
468                 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
469                 defer cancel()
470
471                 logoutErr = client.Logout(ctx)
472         }
473
474         err = w.removeSession()
475         if err != nil {
476                 answer("The unlink failed: " + w.redact(err.Error()))
477                 return nil
478         }
479
480         err = l.note("WhatsApp is unlinked.")
481         if err != nil {
482                 w.logger.Printf("note the unlink: %v", err)
483         }
484
485         if client == nil || logoutErr != nil {
486                 answer("WhatsApp is unlinked here, but the phone did not get the logout. In WhatsApp on your phone, open Linked devices and remove the device.")
487                 return nil
488         }
489
490         answer("WhatsApp is unlinked.")
491
492         return nil
493 }
494
495 // deliver logs the closed batches in l in order, each as a work message of
496 // whatsappSource that wakes the loop when the batch starts a turn. A batch
497 // leaves the state file after its message is durable in the log. A group with
498 // no name gets its name from WhatsApp first.
499 func (w *WhatsApp) deliver(ctx context.Context, l *TurnLoop) error {
500         _, err := w.batches.CloseDue(time.Now())
501         if err != nil {
502                 return err
503         }
504
505         for _, batch := range w.batches.Closed() {
506                 if batch.Chat.Group && batch.Chat.Name == "" {
507                         batch.Chat.Name = w.groupName(ctx, batch.Chat.ID)
508                 }
509
510                 _, err = l.Work(whatsappSource, batch.Text(w.clock().Location()), "", batch.Turn())
511                 if err != nil {
512                         return fmt.Errorf("log a WhatsApp batch: %w", err)
513                 }
514
515                 // A stop of the daemon during the flush is no failure: the
516                 // batch stays in the state file and repeats once at the next
517                 // start.
518                 err = l.Flush(ctx)
519                 if ctx.Err() != nil {
520                         return nil
521                 }
522
523                 if err != nil {
524                         return fmt.Errorf("log a WhatsApp batch: %w", err)
525                 }
526
527                 err = w.batches.Remove(batch.Number)
528                 if err != nil {
529                         return err
530                 }
531         }
532
533         return nil
534 }
535
536 // deliverAll closes every open batch and logs all of them.
537 func (w *WhatsApp) deliverAll(ctx context.Context, l *TurnLoop) error {
538         err := w.batches.CloseAll()
539         if err != nil {
540                 return err
541         }
542
543         return w.deliver(ctx, l)
544 }
545
546 // groupName returns the name of the group id, or whatsappUnknownGroup. A group
547 // that is not in the names of the groups reads the groups from WhatsApp again,
548 // at most once in whatsappGroupsRefresh.
549 func (w *WhatsApp) groupName(ctx context.Context, id string) string {
550         w.mutex.Lock()
551         name, found := w.groupNames[id]
552         client := w.client
553         fresh := time.Since(w.groupsAt) < whatsappGroupsRefresh
554         w.mutex.Unlock()
555
556         if found {
557                 return name
558         }
559
560         if client == nil || fresh {
561                 return whatsappUnknownGroup
562         }
563
564         ctx, cancel := context.WithTimeout(ctx, whatsappLookupTime)
565         defer cancel()
566
567         groups, err := client.GetJoinedGroups(ctx)
568         if err != nil {
569                 w.logger.Printf("read the groups: %s", w.redact(err.Error()))
570         }
571
572         w.mutex.Lock()
573         defer w.mutex.Unlock()
574
575         w.groupsAt = time.Now()
576         for _, group := range groups {
577                 w.groupNames[group.JID.String()] = group.Name
578         }
579
580         name, found = w.groupNames[id]
581         if !found || name == "" {
582                 return whatsappUnknownGroup
583         }
584
585         return name
586 }
587
588 // removeSession ends the connection, closes the session database, and deletes
589 // its files.
590 func (w *WhatsApp) removeSession() error {
591         w.mutex.Lock()
592         client := w.client
593         w.client = nil
594         w.linked = false
595         w.own = nil
596         w.connected = false
597         if w.timer != nil {
598                 w.timer.Stop()
599         }
600
601         w.noticed = false
602         container := w.container
603         w.container = nil
604         w.device = nil
605         w.mutex.Unlock()
606
607         if client != nil {
608                 client.Disconnect()
609         }
610
611         var err error
612         if container != nil {
613                 err = container.Close()
614         }
615
616         for _, suffix := range []string{"", "-wal", "-shm"} {
617                 removeErr := os.Remove(w.sessionPath() + suffix)
618                 if !errors.Is(removeErr, os.ErrNotExist) {
619                         err = errors.Join(err, removeErr)
620                 }
621         }
622
623         return err
624 }
625
626 // pair links a new device to the account of phone with a pairing code. It gives
627 // the steps and the code to answer, and then the end of the pairing: the linked
628 // number, an expired code, or a failure. A pairing that a new one ends gives no
629 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
630 // The client of a pairing that does not link is disconnected.
631 func (w *WhatsApp) pair(ctx context.Context, l *TurnLoop, phone string, answer func(text string)) {
632         device, err := w.newDevice(ctx)
633         if err != nil {
634                 answer("The pairing failed: " + err.Error())
635                 return
636         }
637
638         client := w.newClient(device, w.handle)
639         linked := false
640         defer func() {
641                 if !linked {
642                         client.Disconnect()
643                 }
644         }()
645
646         qr, err := client.GetQRChannel(ctx)
647         if err == nil {
648                 err = client.ConnectContext(ctx)
649         }
650
651         if err != nil {
652                 answer("The connection to WhatsApp failed: " + err.Error())
653                 return
654         }
655
656         select {
657         case item, open := <-qr:
658                 if !open || item.Event != whatsmeow.QRChannelEventCode {
659                         answer("WhatsApp did not start the pairing. Try again later.")
660                         return
661                 }
662         case <-ctx.Done():
663                 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
664                         answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
665                 }
666
667                 return
668         }
669
670         code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
671         if err != nil {
672                 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
673                 return
674         }
675
676         answer(whatsappPairSteps)
677         answer(code)
678
679         for {
680                 var item whatsmeow.QRChannelItem
681                 open := true
682                 select {
683                 case item, open = <-qr:
684                 case <-ctx.Done():
685                         if errors.Is(ctx.Err(), context.DeadlineExceeded) {
686                                 answer(whatsappPairExpired)
687                         }
688
689                         return
690                 }
691
692                 switch {
693                 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
694                         answer(whatsappPairExpired)
695                         return
696                 case item.Event == whatsmeow.QRChannelEventCode:
697                         continue
698                 case item.Event == whatsmeow.QRChannelSuccess.Event:
699                         linked = true
700                         w.linkedBy(client)
701
702                         err = l.note("WhatsApp is linked.")
703                         if err != nil {
704                                 w.logger.Printf("note the link: %v", err)
705                         }
706
707                         answer("WhatsApp is linked to +" + phone + ".")
708
709                         return
710                 default:
711                         answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
712                         return
713                 }
714         }
715 }
716
717 // newDevice returns a new device in the session database. It makes the
718 // directory and the file of the session first, with their modes, when they do
719 // not exist.
720 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
721         w.mutex.Lock()
722         defer w.mutex.Unlock()
723
724         if w.container == nil {
725                 err := os.MkdirAll(w.dir, 0o700)
726                 if err != nil {
727                         return nil, fmt.Errorf("create WhatsApp directory: %w", err)
728                 }
729
730                 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
731                 if err != nil {
732                         return nil, fmt.Errorf("create WhatsApp session: %w", err)
733                 }
734
735                 err = file.Close()
736                 if err != nil {
737                         return nil, fmt.Errorf("create WhatsApp session: %w", err)
738                 }
739
740                 err = w.openSession(ctx)
741                 if err != nil {
742                         return nil, err
743                 }
744         }
745
746         w.device = w.container.NewDevice()
747
748         return w.device, nil
749 }
750
751 // linkedBy makes client the client of the linked device.
752 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
753         w.mutex.Lock()
754         defer w.mutex.Unlock()
755
756         w.client = client
757         w.linked = true
758 }
759
760 // handle takes one event of the library and tells if it was handled. A message
761 // goes to receive. The names of the groups follow the events of the groups. A
762 // disconnection keeps the time of its start while the library tries again.
763 // After noticeDelay of a disconnection, all clients get one notice, and they
764 // get one more when the connection comes back. A disconnection that the library
765 // does not try again gives a notice at once.
766 func (w *WhatsApp) handle(event any) bool {
767         message, isMessage := event.(*events.Message)
768         if isMessage {
769                 return w.receive(message)
770         }
771
772         var notice string
773         w.mutex.Lock()
774         switch event := event.(type) {
775         case *events.GroupInfo:
776                 if event.Name != nil {
777                         w.groupNames[event.JID.String()] = event.Name.Name
778                 }
779         case *events.JoinedGroup:
780                 w.groupNames[event.JID.String()] = event.Name
781         case *events.PairSuccess:
782                 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
783         case *events.Connected:
784                 w.connected = true
785                 w.connectedAt = w.clock()
786                 if w.timer != nil {
787                         w.timer.Stop()
788                 }
789
790                 if w.noticed {
791                         w.noticed = false
792                         notice = "WhatsApp is connected again."
793                 }
794         case *events.Disconnected:
795                 if w.linked && (w.connected || w.disconnectedAt.IsZero()) {
796                         w.disconnectedAt = w.clock()
797                         w.disconnections++
798                         disconnections := w.disconnections
799                         w.timer = time.AfterFunc(w.noticeDelay, func() {
800                                 w.disconnectedLong(disconnections)
801                         })
802                 }
803
804                 w.connected = false
805         case *events.LoggedOut:
806                 select {
807                 case w.logouts <- struct{}{}:
808                 default:
809                 }
810         case events.PermanentDisconnect:
811                 if w.linked {
812                         w.connected = false
813                         w.noticed = true
814                         notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
815                 }
816         }
817         w.mutex.Unlock()
818
819         if notice != "" {
820                 w.broadcast(notice)
821         }
822
823         return true
824 }
825
826 // receive puts the text of event into its batch and wakes Run. It returns false
827 // when the state file cannot hold the message, so that the library does not
828 // acknowledge it, and Run stops the daemon. A message that is not text, or that
829 // the batches do not take, is handled with nothing to do.
830 func (w *WhatsApp) receive(event *events.Message) bool {
831         ctx, cancel := context.WithTimeout(context.Background(), whatsappLookupTime)
832         defer cancel()
833
834         chat, message, found := w.message(ctx, event)
835         if !found {
836                 return true
837         }
838
839         _, err := w.batches.Add(chat, message, time.Now())
840         if err != nil {
841                 select {
842                 case w.failures <- err:
843                 default:
844                 }
845
846                 return false
847         }
848
849         select {
850         case w.wake <- struct{}{}:
851         default:
852         }
853
854         return true
855 }
856
857 // message returns the chat and the batch message of event, or false when the
858 // batches do not take it. They take the text of a private chat or a group, from
859 // another person or from the user. They do not take media, reactions, edits,
860 // deletions, view-once and disappearing messages, old history, status
861 // broadcasts, channels, and the chat of the user with itself.
862 //
863 // A mention of the user becomes @you, another mention @NAME when the name is
864 // known, and the own number and LID become OWN, so that they never go to the
865 // log.
866 func (w *WhatsApp) message(ctx context.Context, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
867         w.mutex.Lock()
868         device := w.device
869         own := slices.Clone(w.own)
870         w.mutex.Unlock()
871
872         info := event.Info
873         chatJID := info.Chat.ToNonAD()
874         switch {
875         case device == nil:
876         case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.SourceWebMsg != nil:
877         case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
878         case slices.Contains(own, chatJID.User):
879         default:
880                 return w.text(ctx, device, own, event)
881         }
882
883         return WhatsAppChat{}, WhatsAppMessage{}, false
884 }
885
886 // text returns the chat and the batch message of event, a message that the
887 // batches take when it has text.
888 func (w *WhatsApp) text(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
889         info := event.Info
890         text := event.Message.GetConversation()
891         extended := event.Message.GetExtendedTextMessage()
892         if text == "" {
893                 text = extended.GetText()
894         }
895
896         if strings.TrimSpace(text) == "" {
897                 return WhatsAppChat{}, WhatsAppMessage{}, false
898         }
899
900         contextInfo := extended.GetContextInfo()
901         message := WhatsAppMessage{
902                 ID:   info.ID,
903                 Time: info.Timestamp,
904                 Mine: info.IsFromMe,
905         }
906
907         if !message.Mine {
908                 message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
909         }
910
911         for _, mentioned := range contextInfo.GetMentionedJID() {
912                 jid, err := types.ParseJID(mentioned)
913                 switch {
914                 case err != nil:
915                 case slices.Contains(own, jid.User):
916                         message.Mention = true
917                         text = strings.ReplaceAll(text, "@"+jid.User, "@you")
918                 default:
919                         text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
920                 }
921         }
922
923         participant, err := types.ParseJID(contextInfo.GetParticipant())
924         message.Reply = err == nil && slices.Contains(own, participant.User)
925
926         for _, id := range own {
927                 text = strings.ReplaceAll(text, id, "OWN")
928         }
929
930         message.Text = text
931         chatJID := info.Chat.ToNonAD()
932         chat := WhatsAppChat{
933                 ID:    chatJID.String(),
934                 Group: chatJID.Server == types.GroupServer,
935         }
936
937         if !chat.Group {
938                 push := info.PushName
939                 if message.Mine {
940                         push = ""
941                 }
942
943                 chat.Name = whatsappContactName(ctx, device, chatJID, push)
944         }
945
946         return chat, message, true
947 }
948
949 // disconnectedLong gives the notice of a long disconnection, unless the
950 // disconnection with the number disconnections ended.
951 func (w *WhatsApp) disconnectedLong(disconnections int) {
952         w.mutex.Lock()
953         long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
954         if long {
955                 w.noticed = true
956         }
957
958         since := w.disconnectedAt
959         w.mutex.Unlock()
960
961         if long {
962                 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
963         }
964 }
965
966 // broadcast gives text as a notice to all clients.
967 func (w *WhatsApp) broadcast(text string) {
968         w.mutex.Lock()
969         notify := w.notify
970         closed := w.closed
971         w.mutex.Unlock()
972
973         if notify != nil && !closed {
974                 notify(Event{
975                         Kind: "notice",
976                         Text: text,
977                 })
978         }
979 }
980
981 // redact replaces the own number and the own LID in text with OWN.
982 func (w *WhatsApp) redact(text string) string {
983         w.mutex.Lock()
984         defer w.mutex.Unlock()
985
986         for _, id := range w.own {
987                 text = strings.ReplaceAll(text, id, "OWN")
988         }
989
990         return text
991 }
992
993 // WhatsAppRequest is a pair or unlink command for Run, with the function that
994 // gives its answers to the client that asked. A pairing has the phone number.
995 type WhatsAppRequest struct {
996         phone  string
997         unlink bool
998         answer func(text string)
999 }
1000
1001 // whatsappNewClient returns the client of the library for device, with handle
1002 // as its event handler. The client tries again after a failed first connection,
1003 // acknowledges a message only after handle returns true, and downloads no old
1004 // history. The phone shows the device with the name OneChat.
1005 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
1006         store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
1007         client := whatsmeow.NewClient(device, waLog.Noop)
1008         client.InitialAutoReconnect = true
1009         client.SynchronousAck = true
1010         client.ManualHistorySyncDownload = true
1011         client.AddEventHandlerWithSuccessStatus(handle)
1012
1013         return client
1014 }
1015
1016 // whatsappContactName returns the name of the person jid: the full name, the
1017 // first name, the business name, or the push name of the contact in the session
1018 // of device, then push, the push name of a message, then the phone number. A
1019 // LID gets its phone number from the LID map of the session.
1020 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
1021         jid = jid.ToNonAD()
1022         candidates := []types.JID{jid}
1023         phone := types.EmptyJID
1024         switch jid.Server {
1025         case types.DefaultUserServer:
1026                 phone = jid
1027         case types.HiddenUserServer:
1028                 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
1029                 if err == nil && !mapped.IsEmpty() {
1030                         phone = mapped
1031                         candidates = append(candidates, mapped)
1032                 }
1033         }
1034
1035         for _, candidate := range candidates {
1036                 contact, err := device.Contacts.GetContact(ctx, candidate)
1037                 if err != nil || !contact.Found {
1038                         continue
1039                 }
1040
1041                 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
1042                         if name != "" {
1043                                 return name
1044                         }
1045                 }
1046         }
1047
1048         switch {
1049         case push != "":
1050                 return push
1051         case !phone.IsEmpty():
1052                 return "+" + phone.User
1053         default:
1054                 return jid.User
1055         }
1056 }
1057
1058 // whatsappOwnIDs returns the own number and the own LID that are not empty.
1059 func whatsappOwnIDs(ids ...string) []string {
1060         var own []string
1061         for _, id := range ids {
1062                 if id != "" {
1063                         own = append(own, id)
1064                 }
1065         }
1066
1067         return own
1068 }
1069
1070 // whatsappSessionAddress returns the SQLite address of the session database at
1071 // path, with foreign keys on, as the library needs, and a wait for a busy
1072 // database.
1073 func whatsappSessionAddress(path string) (string, error) {
1074         path, err := filepath.Abs(path)
1075         if err != nil {
1076                 return "", fmt.Errorf("find WhatsApp session: %w", err)
1077         }
1078
1079         address := url.URL{
1080                 Scheme:   "file",
1081                 Path:     path,
1082                 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
1083         }
1084
1085         return address.String(), nil
1086 }
1087
1088 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
1089 // command, or false for any other line.
1090 func whatsappCommandArgs(line string) (string, bool) {
1091         line = strings.TrimSpace(line)
1092         if line == whatsappCommand {
1093                 return "", true
1094         }
1095
1096         args, found := strings.CutPrefix(line, whatsappCommand+" ")
1097         if !found {
1098                 return "", false
1099         }
1100
1101         return strings.TrimSpace(args), true
1102 }
1103
1104 // whatsappPhone returns the digits of phone, a number with its country code and
1105 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
1106 // digits, with no 0 first.
1107 func whatsappPhone(phone string) (string, bool) {
1108         phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
1109         valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
1110
1111         return phone, valid
1112 }
1113
1114 // whatsappItemError returns the error of a pairing item that is not a code, a
1115 // success, or a timeout.
1116 func whatsappItemError(item whatsmeow.QRChannelItem) string {
1117         if item.Error != nil {
1118                 return item.Error.Error()
1119         }
1120
1121         return item.Event
1122 }