]> git.giacomolli.uk - onechat/blob - whatsapp.go
Log failed turns and the ends of subagents
[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/proto/waCompanionReg"
18 "go.mau.fi/whatsmeow/proto/waE2E"
19 "go.mau.fi/whatsmeow/store"
20 "go.mau.fi/whatsmeow/store/sqlstore"
21 "go.mau.fi/whatsmeow/types"
22 "go.mau.fi/whatsmeow/types/events"
23 waLog "go.mau.fi/whatsmeow/util/log"
24 // The session store of the library opens SQLite with this pure Go
25 // driver.
26 _ "modernc.org/sqlite"
27 )
28
29 const (
30 // whatsappDirName is the directory of the WhatsApp files in the data
31 // directory.
32 whatsappDirName = "whatsapp"
33
34 // whatsappSessionFileName is the session database of the library in
35 // whatsappDirName.
36 whatsappSessionFileName = "session.db"
37
38 // whatsappCommand starts the input lines of the WhatsApp commands, such
39 // as "/whatsapp status".
40 whatsappCommand = "/whatsapp"
41
42 // whatsappUsage is the answer to a WhatsApp command that does not
43 // exist.
44 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."
45
46 // whatsappPairSteps tells the user what to do with the pairing code,
47 // which comes in the next message.
48 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."
49
50 // whatsappPairExpired is the answer when the pairing code expires.
51 whatsappPairExpired = "The pairing code expired. Run /whatsapp pair PHONE again for a new code."
52
53 // whatsappTimeLayout is the layout of the times in the answers.
54 whatsappTimeLayout = "2006-01-02 15:04"
55
56 // whatsappPairTime is the longest time of a pairing. The library closes
57 // the pairing connection after about 160 seconds.
58 whatsappPairTime = 3 * time.Minute
59
60 // whatsappLogoutTime is the longest time of the logout call of an
61 // unlink.
62 whatsappLogoutTime = 30 * time.Second
63
64 // whatsappNoticeDelay is how long a disconnection lasts before the user
65 // gets a notice.
66 whatsappNoticeDelay = 10 * time.Minute
67
68 // whatsappRequests is the number of pair and unlink commands that can
69 // wait for Run.
70 whatsappRequests = 8
71
72 // whatsappLookupTime is the longest time of a read of the names in the
73 // session database or of the groups from WhatsApp.
74 whatsappLookupTime = 10 * time.Second
75
76 // whatsappNotLinked is the answer of a WhatsApp tool without a link.
77 whatsappNotLinked = "WhatsApp is not linked. Tell the user to run /whatsapp pair PHONE in the terminal or in Telegram."
78 )
79
80 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
81 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
82 // fake.
83 type WhatsAppClient interface {
84 ConnectContext(ctx context.Context) error
85 Disconnect()
86 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
87 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
88 Logout(ctx context.Context) error
89 GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error)
90 GenerateMessageID() types.MessageID
91 SendMessage(ctx context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error)
92 }
93
94 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
95 // the session file, WhatsApp is not linked. The session gives full access to
96 // the account, so a file that another user can read is an error. The clock
97 // gives the times of the status, logger gets the failures, and newClient makes
98 // the client of a device with its event handler.
99 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) {
100 w := &WhatsApp{
101 dir: filepath.Join(dir, whatsappDirName),
102 clock: clock,
103 logger: logger,
104 newClient: newClient,
105 noticeDelay: whatsappNoticeDelay,
106 requests: make(chan WhatsAppRequest, whatsappRequests),
107 logouts: make(chan struct{}, 1),
108 groups: newWhatsAppGroups(logger),
109 }
110
111 var err error
112 w.state, err = openWhatsAppState(filepath.Join(w.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
113 if err != nil {
114 return nil, err
115 }
116
117 w.inbox = newWhatsAppInbox(w.state, clock, w.groups)
118
119 info, err := os.Stat(w.sessionPath())
120 if errors.Is(err, os.ErrNotExist) {
121 return w, nil
122 }
123
124 if err != nil {
125 return nil, fmt.Errorf("read WhatsApp session: %w", err)
126 }
127
128 if info.Mode().Perm()&0o077 != 0 {
129 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
130 }
131
132 err = w.openSession(ctx)
133 if err != nil {
134 return nil, err
135 }
136
137 if w.device.ID != nil {
138 w.linked = true
139 w.inbox.waitForCatchup()
140 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
141 }
142
143 return w, nil
144 }
145
146 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as a
147 // linked device. The session database of the library in dir holds the keys of
148 // the device. Run keeps a linked device connected, and the library connects
149 // again by itself after a network failure.
150 //
151 // The commands pair and unlink go to Run as requests, and Run runs one at a
152 // time. A pairing runs in its own goroutine until its code expires, and a new
153 // pairing ends the one before. Its phone number and code go only to the answer
154 // of the client that asked. A logout from the phone comes as an event of the
155 // library, and Run deletes the session. The mutex protects the session, the
156 // client, and the state of the connection, which the event handler of the
157 // library changes from its own goroutines.
158 //
159 // The inbox puts the text messages into batches and logs them, and groups
160 // holds the names of the groups. Both get a WhatsAppLink from link for each
161 // call, so they use the current device and client.
162 //
163 // The library logs nothing, because its log lines hold the ID of the own
164 // account, which is the phone number of the user. The own number and the own
165 // LID never go to the log of the agent or to the log of the daemon: redact
166 // removes them from the errors, and a batch shows the messages of the user as
167 // You and a mention of the user as @you. The IDs of the other chats go to the
168 // log, and those of private chats hold phone numbers, because the agent needs
169 // them to send.
170 type WhatsApp struct {
171 dir string
172 clock func() time.Time
173 logger *log.Logger
174 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
175 noticeDelay time.Duration
176 requests chan WhatsAppRequest
177 logouts chan struct{}
178 state *WhatsAppState
179 groups *WhatsAppGroups
180 inbox *WhatsAppInbox
181
182 mutex sync.Mutex
183 container *sqlstore.Container
184 device *store.Device
185 client WhatsAppClient
186 linked bool
187 own []string
188 notify func(Event)
189 connected bool
190 connectedAt time.Time
191 disconnectedAt time.Time
192 disconnections int
193 noticed bool
194 timer *time.Timer
195 closed bool
196 }
197
198 // Run connects a linked device, logs the closed batches in l, runs the pair and
199 // unlink commands, and handles a logout from the phone, until ctx ends. Its
200 // notes go to the log of l, and notify gets the notices for all clients. A
201 // failed first connection is logged, and the library tries again when the
202 // failure is one of the network. Run returns the error of a write of the log or
203 // of the state file, which stops the daemon, because then messages would be
204 // lost.
205 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) error {
206 w.mutex.Lock()
207 w.notify = notify
208 linked := w.linked
209 w.mutex.Unlock()
210
211 if linked {
212 w.connect(ctx)
213 }
214
215 var pairing sync.WaitGroup
216 cancel := func() {}
217 defer func() {
218 cancel()
219 pairing.Wait()
220 w.close()
221 }()
222
223 for {
224 err := w.inbox.deliver(ctx, l, w.link(), false)
225 if err != nil {
226 return err
227 }
228
229 select {
230 case <-ctx.Done():
231 return nil
232 case err = <-w.inbox.failures:
233 return err
234 case <-w.inbox.wake:
235 case <-w.inbox.due():
236 case <-w.logouts:
237 err = w.loggedOut(ctx, l)
238 if err != nil {
239 return err
240 }
241 case request := <-w.requests:
242 cancel()
243 pairing.Wait()
244 cancel = func() {}
245
246 switch {
247 case request.unlink:
248 err = w.unlink(ctx, l, request.answer)
249 if err != nil {
250 return err
251 }
252 case w.isLinked():
253 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
254 default:
255 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
256 cancel = cancelPair
257 pairing.Go(func() {
258 defer cancelPair()
259
260 w.pair(pairCtx, ctx, l, request.phone, request.answer)
261 })
262 }
263 }
264 }
265 }
266
267 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
268 // each answer to answer. The answers go only to the client that sent the
269 // command.
270 func (w *WhatsApp) Command(args string, answer func(text string)) {
271 fields := strings.Fields(args)
272 request := WhatsAppRequest{
273 answer: answer,
274 }
275
276 switch {
277 case len(fields) == 1 && fields[0] == "status":
278 answer(w.Status())
279 return
280 case len(fields) == 1 && fields[0] == "unlink":
281 request.unlink = true
282 case len(fields) >= 2 && fields[0] == "pair":
283 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
284 if !valid {
285 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
286 return
287 }
288
289 request.phone = phone
290 default:
291 answer(whatsappUsage)
292 return
293 }
294
295 select {
296 case w.requests <- request:
297 default:
298 answer("Too many WhatsApp commands wait. Try again in a minute.")
299 }
300 }
301
302 // Status returns the state of the link: not linked, linked and connected, or
303 // linked and disconnected, with the times of the connection. It never holds the
304 // phone number.
305 func (w *WhatsApp) Status() string {
306 w.mutex.Lock()
307 defer w.mutex.Unlock()
308
309 switch {
310 case !w.linked:
311 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it."
312 case w.connected:
313 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "."
314 case w.disconnectedAt.IsZero():
315 return "WhatsApp is linked and not connected yet."
316 case w.connectedAt.IsZero():
317 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "."
318 default:
319 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "."
320 }
321 }
322
323 // Close closes the session database.
324 func (w *WhatsApp) Close() error {
325 w.mutex.Lock()
326 defer w.mutex.Unlock()
327
328 if w.container == nil {
329 return nil
330 }
331
332 err := w.container.Close()
333 w.container = nil
334
335 return err
336 }
337
338 // Find returns the answer of whatsapp_find for name, as whatsappFind says.
339 func (w *WhatsApp) Find(ctx context.Context, name string) (string, error) {
340 return whatsappFind(ctx, w.link(), w.groups, name)
341 }
342
343 // Send returns the answer of whatsapp_send for the send id of text to chat, as
344 // whatsappSend says.
345 func (w *WhatsApp) Send(ctx context.Context, id, chat, text string) (string, error) {
346 return whatsappSend(ctx, w.link(), w.groups, w.state, w.clock, id, chat, text)
347 }
348
349 func (w *WhatsApp) sessionPath() string {
350 return filepath.Join(w.dir, whatsappSessionFileName)
351 }
352
353 // openSession opens the session database and its first device. The caller holds
354 // the mutex, or no other goroutine uses w yet.
355 func (w *WhatsApp) openSession(ctx context.Context) error {
356 address, err := whatsappSessionAddress(w.sessionPath())
357 if err != nil {
358 return err
359 }
360
361 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
362 if err != nil {
363 return fmt.Errorf("open WhatsApp session: %w", err)
364 }
365
366 device, err := container.GetFirstDevice(ctx)
367 if err != nil {
368 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
369 }
370
371 w.container = container
372 w.device = device
373
374 return nil
375 }
376
377 func (w *WhatsApp) isLinked() bool {
378 w.mutex.Lock()
379 defer w.mutex.Unlock()
380
381 return w.linked
382 }
383
384 // link returns a copy of the link of the device: whether it is linked, the
385 // device, the client, whether it is connected, and the own IDs.
386 func (w *WhatsApp) link() WhatsAppLink {
387 w.mutex.Lock()
388 defer w.mutex.Unlock()
389
390 return WhatsAppLink{
391 linked: w.linked,
392 device: w.device,
393 client: w.client,
394 connected: w.connected,
395 own: slices.Clone(w.own),
396 }
397 }
398
399 // connect makes the client of the linked device and connects it.
400 func (w *WhatsApp) connect(ctx context.Context) {
401 w.mutex.Lock()
402 w.client = w.newClient(w.device, w.handle)
403 client := w.client
404 w.mutex.Unlock()
405
406 err := client.ConnectContext(ctx)
407 if err != nil {
408 w.logger.Printf("WhatsApp messages do not come, because the connection failed, and it is tried again only at a restart of the daemon: %s", w.redact(err.Error()))
409 }
410 }
411
412 // close ends the connection and the timer of the notice, and stops all notices.
413 func (w *WhatsApp) close() {
414 w.mutex.Lock()
415 w.closed = true
416 if w.timer != nil {
417 w.timer.Stop()
418 }
419
420 client := w.client
421 w.client = nil
422 w.mutex.Unlock()
423
424 w.inbox.close()
425
426 if client != nil {
427 client.Disconnect()
428 }
429 }
430
431 // loggedOut logs the open batches, deletes the session after a logout from the
432 // phone, notes it in the log of l, and tells all clients one time.
433 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
434 if !w.isLinked() {
435 return nil
436 }
437
438 w.logger.Print("WhatsApp messages stop, because the phone logged out this device (run /whatsapp pair PHONE to link it again)")
439 err := w.inbox.deliver(ctx, l, w.link(), true)
440 if err != nil {
441 return err
442 }
443
444 err = w.removeSession()
445 if err != nil {
446 w.logger.Printf("the session of the logged out device stays on the disk, because its delete failed: %v", err)
447 }
448
449 err = l.note("WhatsApp was unlinked from the phone.")
450 if err != nil {
451 w.logger.Printf("the chat has no note of the logout, because its write failed: %v", err)
452 }
453
454 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
455
456 return nil
457 }
458
459 // unlink logs the open batches, logs out the linked device, and deletes the
460 // session. When the logout call fails, as it does while WhatsApp is
461 // disconnected, the session is deleted all the same, and answer tells the user
462 // to remove the device in the phone. Its error is one of the log or the state
463 // file.
464 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
465 w.mutex.Lock()
466 linked := w.linked
467 client := w.client
468 w.mutex.Unlock()
469
470 if !linked {
471 answer("WhatsApp is not linked.")
472 return nil
473 }
474
475 err := w.inbox.deliver(ctx, l, w.link(), true)
476 if err != nil {
477 return err
478 }
479
480 var logoutErr error
481 if client != nil {
482 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
483 defer cancel()
484
485 logoutErr = client.Logout(ctx)
486 }
487
488 err = w.removeSession()
489 if err != nil {
490 answer("The unlink failed: " + w.redact(err.Error()))
491 return nil
492 }
493
494 w.logger.Print("WhatsApp messages stop, because the user unlinked WhatsApp")
495 err = l.note("WhatsApp is unlinked.")
496 if err != nil {
497 w.logger.Printf("the chat has no note of the unlink, because its write failed: %v", err)
498 }
499
500 if client == nil || logoutErr != nil {
501 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.")
502 return nil
503 }
504
505 answer("WhatsApp is unlinked.")
506
507 return nil
508 }
509
510 // removeSession ends the connection, closes the session database, and deletes
511 // its files.
512 func (w *WhatsApp) removeSession() error {
513 w.mutex.Lock()
514 client := w.client
515 w.client = nil
516 w.linked = false
517 w.own = nil
518 w.connected = false
519 w.disconnectedAt = time.Time{}
520 if w.timer != nil {
521 w.timer.Stop()
522 }
523
524 w.noticed = false
525 container := w.container
526 w.container = nil
527 w.device = nil
528 w.mutex.Unlock()
529
530 w.inbox.stopCatchup()
531
532 if client != nil {
533 client.Disconnect()
534 }
535
536 var err error
537 if container != nil {
538 err = container.Close()
539 }
540
541 for _, suffix := range []string{"", "-wal", "-shm"} {
542 removeErr := os.Remove(w.sessionPath() + suffix)
543 if !errors.Is(removeErr, os.ErrNotExist) {
544 err = errors.Join(err, removeErr)
545 }
546 }
547
548 return err
549 }
550
551 // pair links a new device to the account of phone with a pairing code. It gives
552 // the steps and the code to answer, and then the end of the pairing: the linked
553 // number, an expired code, or a failure. A pairing that a new one ends gives no
554 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
555 // The client of a pairing that does not link is disconnected.
556 //
557 // ctx limits the pairing, but the connection uses runCtx, the context of Run.
558 // The library keeps the context of the connection for its keep-alive, its event
559 // handler, and its reconnections, and after the link the server ends the stream
560 // and the library connects again. With ctx, the end of the pairing would stop
561 // that reconnection, and the linked device would never connect.
562 func (w *WhatsApp) pair(ctx, runCtx context.Context, l *TurnLoop, phone string, answer func(text string)) {
563 device, err := w.newDevice(ctx)
564 if err != nil {
565 answer("The pairing failed: " + err.Error())
566 return
567 }
568
569 client := w.newClient(device, w.handle)
570 linked := false
571 defer func() {
572 if !linked {
573 client.Disconnect()
574 }
575 }()
576
577 qr, err := client.GetQRChannel(ctx)
578 if err == nil {
579 err = client.ConnectContext(runCtx)
580 }
581
582 if err != nil {
583 answer("The connection to WhatsApp failed: " + err.Error())
584 return
585 }
586
587 select {
588 case item, open := <-qr:
589 if !open || item.Event != whatsmeow.QRChannelEventCode {
590 answer("WhatsApp did not start the pairing. Try again later.")
591 return
592 }
593 case <-ctx.Done():
594 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
595 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
596 }
597
598 return
599 }
600
601 // The server accepts only a display name of the form "Browser (OS)"
602 // with a common browser and OS, and refuses the pairing otherwise.
603 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
604 if err != nil {
605 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
606 return
607 }
608
609 answer(whatsappPairSteps)
610 answer(code)
611
612 for {
613 var item whatsmeow.QRChannelItem
614 open := true
615 select {
616 case item, open = <-qr:
617 case <-ctx.Done():
618 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
619 answer(whatsappPairExpired)
620 }
621
622 return
623 }
624
625 switch {
626 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
627 answer(whatsappPairExpired)
628 return
629 case item.Event == whatsmeow.QRChannelEventCode:
630 continue
631 case item.Event == whatsmeow.QRChannelSuccess.Event:
632 linked = true
633 w.linkedBy(client)
634 w.logger.Print("WhatsApp is linked")
635
636 err = l.note("WhatsApp is linked.")
637 if err != nil {
638 w.logger.Printf("the chat has no note of the link, because its write failed: %v", err)
639 }
640
641 answer("WhatsApp is linked to +" + phone + ".")
642
643 return
644 default:
645 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
646 return
647 }
648 }
649 }
650
651 // newDevice returns a new device in the session database. It makes the
652 // directory and the file of the session first, with their modes, when they do
653 // not exist.
654 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
655 w.mutex.Lock()
656 defer w.mutex.Unlock()
657
658 if w.container == nil {
659 err := os.MkdirAll(w.dir, 0o700)
660 if err != nil {
661 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
662 }
663
664 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
665 if err != nil {
666 return nil, fmt.Errorf("create WhatsApp session: %w", err)
667 }
668
669 err = file.Close()
670 if err != nil {
671 return nil, fmt.Errorf("create WhatsApp session: %w", err)
672 }
673
674 err = w.openSession(ctx)
675 if err != nil {
676 return nil, err
677 }
678 }
679
680 w.device = w.container.NewDevice()
681
682 return w.device, nil
683 }
684
685 // linkedBy makes client the client of the linked device.
686 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
687 w.mutex.Lock()
688 defer w.mutex.Unlock()
689
690 w.client = client
691 w.linked = true
692 }
693
694 // handle takes one event of the library and tells if it was handled. A message
695 // goes to the inbox. The names of the groups follow the events of the groups. A
696 // connection starts a catch-up of the inbox, which ends at OfflineSyncCompleted
697 // or after its catchupLimit. A disconnection keeps the time of its start while
698 // the library tries again. After noticeDelay of a disconnection, all clients
699 // get one notice, and they get one more when the connection comes back. A
700 // disconnection that the library does not try again gives a notice at once.
701 //
702 // The log of the daemon gets one line for each change of the connection of the
703 // linked device: connected, a failed first connection, a lost connection, and
704 // connected again with the length of the outage. The retries of the library
705 // between them log nothing.
706 func (w *WhatsApp) handle(event any) bool {
707 switch event := event.(type) {
708 case *events.Message:
709 return w.inbox.receive(w.link(), event)
710 case *events.GroupInfo:
711 if event.Name != nil {
712 w.groups.set(event.JID.String(), event.Name.Name)
713 }
714
715 return true
716 case *events.JoinedGroup:
717 w.groups.set(event.JID.String(), event.Name)
718 return true
719 case *events.OfflineSyncCompleted:
720 w.inbox.endCatchup()
721 return true
722 case *events.Connected:
723 w.inbox.startCatchup()
724 }
725
726 var notice, line string
727 w.mutex.Lock()
728 switch event := event.(type) {
729 case *events.PairSuccess:
730 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
731 case *events.Connected:
732 switch {
733 case !w.linked || w.connected:
734 case w.disconnectedAt.IsZero():
735 line = "WhatsApp is connected, and new messages come in"
736 default:
737 line = "WhatsApp is connected again, after " + durationText(w.clock().Sub(w.disconnectedAt))
738 }
739
740 w.connected = true
741 w.connectedAt = w.clock()
742 if w.timer != nil {
743 w.timer.Stop()
744 }
745
746 if w.noticed {
747 w.noticed = false
748 notice = "WhatsApp is connected again."
749 }
750 case *events.Disconnected:
751 if w.linked && (w.connected || w.disconnectedAt.IsZero()) {
752 line = "new WhatsApp messages wait, because the connection is lost (the next try is automatic)"
753 if !w.connected {
754 line = "new WhatsApp messages wait, because the first connection failed (the next try is automatic)"
755 }
756
757 w.disconnectedAt = w.clock()
758 w.disconnections++
759 disconnections := w.disconnections
760 w.timer = time.AfterFunc(w.noticeDelay, func() {
761 w.disconnectedLong(disconnections)
762 })
763 }
764
765 w.connected = false
766 case *events.LoggedOut:
767 select {
768 case w.logouts <- struct{}{}:
769 default:
770 }
771 case events.PermanentDisconnect:
772 if w.linked {
773 w.connected = false
774 w.noticed = true
775 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
776 line = "WhatsApp messages do not come, because the connection is lost and it is tried again only at a restart of the daemon: " + whatsappRedact(w.own, event.PermanentDisconnectDescription())
777 }
778 }
779
780 if w.closed {
781 line = ""
782 }
783
784 w.mutex.Unlock()
785
786 if line != "" {
787 w.logger.Print(line)
788 }
789
790 if notice != "" {
791 w.broadcast(notice)
792 }
793
794 return true
795 }
796
797 // disconnectedLong gives the notice of a long disconnection, unless the
798 // disconnection with the number disconnections ended.
799 func (w *WhatsApp) disconnectedLong(disconnections int) {
800 w.mutex.Lock()
801 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
802 if long {
803 w.noticed = true
804 }
805
806 since := w.disconnectedAt
807 w.mutex.Unlock()
808
809 if long {
810 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
811 }
812 }
813
814 // broadcast gives text as a notice to all clients.
815 func (w *WhatsApp) broadcast(text string) {
816 w.mutex.Lock()
817 notify := w.notify
818 closed := w.closed
819 w.mutex.Unlock()
820
821 if notify != nil && !closed {
822 notify(Event{
823 Kind: "notice",
824 Text: text,
825 })
826 }
827 }
828
829 // redact replaces the own number and the own LID in text with OWN.
830 func (w *WhatsApp) redact(text string) string {
831 w.mutex.Lock()
832 defer w.mutex.Unlock()
833
834 return whatsappRedact(w.own, text)
835 }
836
837 // WhatsAppLink is a copy of the link of the device at one time, for the parts
838 // of WhatsApp that do not own it: the groups, the batches, find, and send.
839 type WhatsAppLink struct {
840 linked bool
841 device *store.Device
842 client WhatsAppClient
843 connected bool
844 own []string
845 }
846
847 // WhatsAppRequest is a pair or unlink command for Run, with the function that
848 // gives its answers to the client that asked. A pairing has the phone number.
849 type WhatsAppRequest struct {
850 phone string
851 unlink bool
852 answer func(text string)
853 }
854
855 // whatsappSetDeviceProps sets the device properties that the library sends at
856 // the pairing. They are global values of the library, so the daemon sets them
857 // once before any client exists. The phone shows the linked device with the
858 // name OneChat and a desktop icon only when the platform type is known.
859 func whatsappSetDeviceProps() {
860 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
861 store.DeviceProps.PlatformType = waCompanionReg.DeviceProps_DESKTOP.Enum()
862 }
863
864 // whatsappNewClient returns the client of the library for device, with handle
865 // as its event handler. The client tries again after a failed first connection,
866 // acknowledges a message only after handle returns true, and downloads no old
867 // history.
868 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
869 client := whatsmeow.NewClient(device, waLog.Noop)
870 client.InitialAutoReconnect = true
871 client.SynchronousAck = true
872 client.ManualHistorySyncDownload = true
873 client.AddEventHandlerWithSuccessStatus(handle)
874
875 return client
876 }
877
878 // whatsappContactName returns the name of the person jid: the full name, the
879 // first name, the business name, or the push name of the contact in the session
880 // of device, then push, the push name of a message, then the phone number. A
881 // LID gets its phone number from the LID map of the session.
882 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
883 jid = jid.ToNonAD()
884 candidates := []types.JID{jid}
885 phone := types.EmptyJID
886 switch jid.Server {
887 case types.DefaultUserServer:
888 phone = jid
889 case types.HiddenUserServer:
890 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
891 if err == nil && !mapped.IsEmpty() {
892 phone = mapped
893 candidates = append(candidates, mapped)
894 }
895 }
896
897 for _, candidate := range candidates {
898 contact, err := device.Contacts.GetContact(ctx, candidate)
899 if err != nil || !contact.Found {
900 continue
901 }
902
903 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
904 if name != "" {
905 return name
906 }
907 }
908 }
909
910 switch {
911 case push != "":
912 return push
913 case !phone.IsEmpty():
914 return "+" + phone.User
915 default:
916 return jid.User
917 }
918 }
919
920 // whatsappOwnIDs returns the own number and the own LID that are not empty.
921 func whatsappOwnIDs(ids ...string) []string {
922 var own []string
923 for _, id := range ids {
924 if id != "" {
925 own = append(own, id)
926 }
927 }
928
929 return own
930 }
931
932 // whatsappRedact replaces each of the own IDs own in text with OWN.
933 func whatsappRedact(own []string, text string) string {
934 for _, id := range own {
935 text = strings.ReplaceAll(text, id, "OWN")
936 }
937
938 return text
939 }
940
941 // whatsappSessionAddress returns the SQLite address of the session database at
942 // path, with foreign keys on, as the library needs, and a wait for a busy
943 // database.
944 func whatsappSessionAddress(path string) (string, error) {
945 path, err := filepath.Abs(path)
946 if err != nil {
947 return "", fmt.Errorf("find WhatsApp session: %w", err)
948 }
949
950 address := url.URL{
951 Scheme: "file",
952 Path: path,
953 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
954 }
955
956 return address.String(), nil
957 }
958
959 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
960 // command, or false for any other line.
961 func whatsappCommandArgs(line string) (string, bool) {
962 line = strings.TrimSpace(line)
963 if line == whatsappCommand {
964 return "", true
965 }
966
967 args, found := strings.CutPrefix(line, whatsappCommand+" ")
968 if !found {
969 return "", false
970 }
971
972 return strings.TrimSpace(args), true
973 }
974
975 // whatsappPhone returns the digits of phone, a number with its country code and
976 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
977 // digits, with no 0 first.
978 func whatsappPhone(phone string) (string, bool) {
979 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
980 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
981
982 return phone, valid
983 }
984
985 // whatsappItemError returns the error of a pairing item that is not a code, a
986 // success, or a timeout.
987 func whatsappItemError(item whatsmeow.QRChannelItem) string {
988 if item.Error != nil {
989 return item.Error.Error()
990 }
991
992 return item.Event
993 }