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