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