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