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