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