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