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