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