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