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