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