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