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