]> git.giacomolli.uk - onechat/blob - whatsapp.go
Link WhatsApp with a pairing code
[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 "strings"
12 "sync"
13 "time"
14
15 "go.mau.fi/whatsmeow"
16 "go.mau.fi/whatsmeow/store"
17 "go.mau.fi/whatsmeow/store/sqlstore"
18 "go.mau.fi/whatsmeow/types/events"
19 waLog "go.mau.fi/whatsmeow/util/log"
20
21 // The session store of the library opens SQLite with this pure Go
22 // driver.
23 _ "modernc.org/sqlite"
24 )
25
26 const (
27 // whatsappDirName is the directory of the WhatsApp files in the data
28 // directory.
29 whatsappDirName = "whatsapp"
30
31 // whatsappSessionFileName is the session database of the library in
32 // whatsappDirName.
33 whatsappSessionFileName = "session.db"
34
35 // whatsappCommand starts the input lines of the WhatsApp commands, such
36 // as "/whatsapp status".
37 whatsappCommand = "/whatsapp"
38
39 // whatsappUsage is the answer to a WhatsApp command that does not exist.
40 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."
41
42 // whatsappPairSteps tells the user what to do with the pairing code,
43 // which comes in the next message.
44 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."
45
46 // whatsappPairExpired is the answer when the pairing code expires.
47 whatsappPairExpired = "The pairing code expired. Run /whatsapp pair PHONE again for a new code."
48
49 // whatsappTimeLayout is the layout of the times in the answers.
50 whatsappTimeLayout = "2006-01-02 15:04"
51
52 // whatsappPairTime is the longest time of a pairing. The library closes
53 // the pairing connection after about 160 seconds.
54 whatsappPairTime = 3 * time.Minute
55
56 // whatsappLogoutTime is the longest time of the logout call of an
57 // unlink.
58 whatsappLogoutTime = 30 * time.Second
59
60 // whatsappNoticeDelay is how long a disconnection lasts before the user
61 // gets a notice.
62 whatsappNoticeDelay = 10 * time.Minute
63
64 // whatsappRequests is the number of pair and unlink commands that can
65 // wait for Run.
66 whatsappRequests = 8
67 )
68
69 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
70 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
71 // fake.
72 type WhatsAppClient interface {
73 ConnectContext(ctx context.Context) error
74 Disconnect()
75 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
76 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
77 Logout(ctx context.Context) error
78 }
79
80 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
81 // the session file, WhatsApp is not linked. The session gives full access to
82 // the account, so a file that another user can read is an error. The clock
83 // gives the times of the status, logger gets the failures, and newClient makes
84 // the client of a device with its event handler.
85 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) {
86 w := &WhatsApp{
87 dir: filepath.Join(dir, whatsappDirName),
88 clock: clock,
89 logger: logger,
90 newClient: newClient,
91 noticeDelay: whatsappNoticeDelay,
92 requests: make(chan WhatsAppRequest, whatsappRequests),
93 logouts: make(chan struct{}, 1),
94 }
95
96 info, err := os.Stat(w.sessionPath())
97 if errors.Is(err, os.ErrNotExist) {
98 return w, nil
99 }
100
101 if err != nil {
102 return nil, fmt.Errorf("read WhatsApp session: %w", err)
103 }
104
105 if info.Mode().Perm()&0o077 != 0 {
106 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
107 }
108
109 err = w.openSession(ctx)
110 if err != nil {
111 return nil, err
112 }
113
114 if w.device.ID != nil {
115 w.linked = true
116 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
117 }
118
119 return w, nil
120 }
121
122 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as
123 // a linked device. The session database of the library in dir holds the keys
124 // of the device. Run keeps a linked device connected, and the library connects
125 // again by itself after a network failure.
126 //
127 // The commands pair and unlink go to Run as requests, and Run runs one at a
128 // time. A pairing runs in its own goroutine until its code expires, and a new
129 // pairing ends the one before. Its phone number and code go only to the answer
130 // of the client that asked. A logout from the phone comes as an event of the
131 // library, and Run deletes the session. The mutex protects the session, the
132 // client, and the state of the connection, which the event handler of the
133 // library changes from its own goroutines.
134 //
135 // The library logs nothing, because its log lines hold the ID of the own
136 // account, which is the phone number of the user. The own number and the own
137 // LID never go to the log of the agent or to the log of the daemon: redact
138 // removes them from the errors.
139 type WhatsApp struct {
140 dir string
141 clock func() time.Time
142 logger *log.Logger
143 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
144 noticeDelay time.Duration
145 requests chan WhatsAppRequest
146 logouts chan struct{}
147
148 mutex sync.Mutex
149 container *sqlstore.Container
150 device *store.Device
151 client WhatsAppClient
152 linked bool
153 own []string
154 notify func(Event)
155 connected bool
156 connectedAt time.Time
157 disconnectedAt time.Time
158 disconnections int
159 noticed bool
160 timer *time.Timer
161 closed bool
162 }
163
164 // Run connects a linked device, runs the pair and unlink commands, and handles
165 // a logout from the phone, until ctx ends. Its notes go to the log of l, and
166 // notify gets the notices for all clients. A failed first connection is
167 // logged, and the library tries again when the failure is one of the network.
168 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) {
169 w.mutex.Lock()
170 w.notify = notify
171 linked := w.linked
172 w.mutex.Unlock()
173
174 if linked {
175 w.connect(ctx)
176 }
177
178 var pairing sync.WaitGroup
179 cancel := func() {}
180 defer func() {
181 cancel()
182 pairing.Wait()
183 w.close()
184 }()
185
186 for {
187 select {
188 case <-ctx.Done():
189 return
190 case <-w.logouts:
191 w.loggedOut(l)
192 case request := <-w.requests:
193 cancel()
194 pairing.Wait()
195 cancel = func() {}
196
197 switch {
198 case request.unlink:
199 w.unlink(ctx, l, request.answer)
200 case w.isLinked():
201 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
202 default:
203 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
204 cancel = cancelPair
205 pairing.Go(func() {
206 defer cancelPair()
207
208 w.pair(pairCtx, l, request.phone, request.answer)
209 })
210 }
211 }
212 }
213 }
214
215 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
216 // each answer to answer. The answers go only to the client that sent the
217 // command.
218 func (w *WhatsApp) Command(args string, answer func(text string)) {
219 fields := strings.Fields(args)
220 request := WhatsAppRequest{
221 answer: answer,
222 }
223
224 switch {
225 case len(fields) == 1 && fields[0] == "status":
226 answer(w.Status())
227 return
228 case len(fields) == 1 && fields[0] == "unlink":
229 request.unlink = true
230 case len(fields) >= 2 && fields[0] == "pair":
231 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
232 if !valid {
233 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
234 return
235 }
236
237 request.phone = phone
238 default:
239 answer(whatsappUsage)
240 return
241 }
242
243 select {
244 case w.requests <- request:
245 default:
246 answer("Too many WhatsApp commands wait. Try again in a minute.")
247 }
248 }
249
250 // Status returns the state of the link: not linked, linked and connected, or
251 // linked and disconnected, with the times of the connection. It never holds
252 // the phone number.
253 func (w *WhatsApp) Status() string {
254 w.mutex.Lock()
255 defer w.mutex.Unlock()
256
257 switch {
258 case !w.linked:
259 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it."
260 case w.connected:
261 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "."
262 case w.disconnectedAt.IsZero():
263 return "WhatsApp is linked and not connected yet."
264 case w.connectedAt.IsZero():
265 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "."
266 default:
267 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "."
268 }
269 }
270
271 // Close closes the session database.
272 func (w *WhatsApp) Close() error {
273 w.mutex.Lock()
274 defer w.mutex.Unlock()
275
276 if w.container == nil {
277 return nil
278 }
279
280 err := w.container.Close()
281 w.container = nil
282
283 return err
284 }
285
286 func (w *WhatsApp) sessionPath() string {
287 return filepath.Join(w.dir, whatsappSessionFileName)
288 }
289
290 // openSession opens the session database and its first device. The caller
291 // holds the mutex, or no other goroutine uses w yet.
292 func (w *WhatsApp) openSession(ctx context.Context) error {
293 address, err := whatsappSessionAddress(w.sessionPath())
294 if err != nil {
295 return err
296 }
297
298 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
299 if err != nil {
300 return fmt.Errorf("open WhatsApp session: %w", err)
301 }
302
303 device, err := container.GetFirstDevice(ctx)
304 if err != nil {
305 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
306 }
307
308 w.container = container
309 w.device = device
310
311 return nil
312 }
313
314 func (w *WhatsApp) isLinked() bool {
315 w.mutex.Lock()
316 defer w.mutex.Unlock()
317
318 return w.linked
319 }
320
321 // connect makes the client of the linked device and connects it.
322 func (w *WhatsApp) connect(ctx context.Context) {
323 w.mutex.Lock()
324 w.client = w.newClient(w.device, w.handle)
325 client := w.client
326 w.mutex.Unlock()
327
328 err := client.ConnectContext(ctx)
329 if err != nil {
330 w.logger.Printf("connect: %s", w.redact(err.Error()))
331 }
332 }
333
334 // close ends the connection and the timer of the notice, and stops all
335 // notices.
336 func (w *WhatsApp) close() {
337 w.mutex.Lock()
338 w.closed = true
339 if w.timer != nil {
340 w.timer.Stop()
341 }
342
343 client := w.client
344 w.client = nil
345 w.mutex.Unlock()
346
347 if client != nil {
348 client.Disconnect()
349 }
350 }
351
352 // loggedOut deletes the session after a logout from the phone, notes it in the
353 // log of l, and tells all clients one time.
354 func (w *WhatsApp) loggedOut(l *TurnLoop) {
355 if !w.isLinked() {
356 return
357 }
358
359 err := w.removeSession()
360 if err != nil {
361 w.logger.Printf("delete the session after the logout: %v", err)
362 }
363
364 err = l.note("WhatsApp was unlinked from the phone.")
365 if err != nil {
366 w.logger.Printf("note the logout: %v", err)
367 }
368
369 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
370 }
371
372 // unlink logs out the linked device and deletes the session. When the logout
373 // call fails, as it does while WhatsApp is disconnected, the session is
374 // deleted all the same, and answer tells the user to remove the device in the
375 // phone.
376 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) {
377 w.mutex.Lock()
378 linked := w.linked
379 client := w.client
380 w.mutex.Unlock()
381
382 if !linked {
383 answer("WhatsApp is not linked.")
384 return
385 }
386
387 var logoutErr error
388 if client != nil {
389 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
390 defer cancel()
391
392 logoutErr = client.Logout(ctx)
393 }
394
395 err := w.removeSession()
396 if err != nil {
397 answer("The unlink failed: " + w.redact(err.Error()))
398 return
399 }
400
401 err = l.note("WhatsApp is unlinked.")
402 if err != nil {
403 w.logger.Printf("note the unlink: %v", err)
404 }
405
406 if client == nil || logoutErr != nil {
407 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.")
408 return
409 }
410
411 answer("WhatsApp is unlinked.")
412 }
413
414 // removeSession ends the connection, closes the session database, and deletes
415 // its files.
416 func (w *WhatsApp) removeSession() error {
417 w.mutex.Lock()
418 client := w.client
419 w.client = nil
420 w.linked = false
421 w.own = nil
422 w.connected = false
423 if w.timer != nil {
424 w.timer.Stop()
425 }
426
427 w.noticed = false
428 container := w.container
429 w.container = nil
430 w.device = nil
431 w.mutex.Unlock()
432
433 if client != nil {
434 client.Disconnect()
435 }
436
437 var err error
438 if container != nil {
439 err = container.Close()
440 }
441
442 for _, suffix := range []string{"", "-wal", "-shm"} {
443 removeErr := os.Remove(w.sessionPath() + suffix)
444 if !errors.Is(removeErr, os.ErrNotExist) {
445 err = errors.Join(err, removeErr)
446 }
447 }
448
449 return err
450 }
451
452 // pair links a new device to the account of phone with a pairing code. It
453 // gives the steps and the code to answer, and then the end of the pairing:
454 // the linked number, an expired code, or a failure. A pairing that a new one
455 // ends gives no answer. A link notes "WhatsApp is linked." in the log of l,
456 // with no number. The client of a pairing that does not link is disconnected.
457 func (w *WhatsApp) pair(ctx context.Context, l *TurnLoop, phone string, answer func(text string)) {
458 device, err := w.newDevice(ctx)
459 if err != nil {
460 answer("The pairing failed: " + err.Error())
461 return
462 }
463
464 client := w.newClient(device, w.handle)
465 linked := false
466 defer func() {
467 if !linked {
468 client.Disconnect()
469 }
470 }()
471
472 qr, err := client.GetQRChannel(ctx)
473 if err == nil {
474 err = client.ConnectContext(ctx)
475 }
476
477 if err != nil {
478 answer("The connection to WhatsApp failed: " + err.Error())
479 return
480 }
481
482 select {
483 case item, open := <-qr:
484 if !open || item.Event != whatsmeow.QRChannelEventCode {
485 answer("WhatsApp did not start the pairing. Try again later.")
486 return
487 }
488 case <-ctx.Done():
489 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
490 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
491 }
492
493 return
494 }
495
496 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
497 if err != nil {
498 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
499 return
500 }
501
502 answer(whatsappPairSteps)
503 answer(code)
504
505 for {
506 var item whatsmeow.QRChannelItem
507 open := true
508 select {
509 case item, open = <-qr:
510 case <-ctx.Done():
511 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
512 answer(whatsappPairExpired)
513 }
514
515 return
516 }
517
518 switch {
519 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
520 answer(whatsappPairExpired)
521 return
522 case item.Event == whatsmeow.QRChannelEventCode:
523 continue
524 case item.Event == whatsmeow.QRChannelSuccess.Event:
525 linked = true
526 w.linkedBy(client)
527
528 err = l.note("WhatsApp is linked.")
529 if err != nil {
530 w.logger.Printf("note the link: %v", err)
531 }
532
533 answer("WhatsApp is linked to +" + phone + ".")
534
535 return
536 default:
537 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
538 return
539 }
540 }
541 }
542
543 // newDevice returns a new device in the session database. It makes the
544 // directory and the file of the session first, with their modes, when they do
545 // not exist.
546 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
547 w.mutex.Lock()
548 defer w.mutex.Unlock()
549
550 if w.container == nil {
551 err := os.MkdirAll(w.dir, 0o700)
552 if err != nil {
553 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
554 }
555
556 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
557 if err != nil {
558 return nil, fmt.Errorf("create WhatsApp session: %w", err)
559 }
560
561 err = file.Close()
562 if err != nil {
563 return nil, fmt.Errorf("create WhatsApp session: %w", err)
564 }
565
566 err = w.openSession(ctx)
567 if err != nil {
568 return nil, err
569 }
570 }
571
572 w.device = w.container.NewDevice()
573
574 return w.device, nil
575 }
576
577 // linkedBy makes client the client of the linked device.
578 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
579 w.mutex.Lock()
580 defer w.mutex.Unlock()
581
582 w.client = client
583 w.linked = true
584 }
585
586 // handle takes one event of the library and tells if it was handled. A
587 // disconnection keeps the time of its start while the library tries again.
588 // After noticeDelay of a disconnection, all clients get one notice, and they
589 // get one more when the connection comes back. A disconnection that the
590 // library does not try again gives a notice at once.
591 func (w *WhatsApp) handle(event any) bool {
592 var notice string
593 w.mutex.Lock()
594 switch event := event.(type) {
595 case *events.PairSuccess:
596 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
597 case *events.Connected:
598 w.connected = true
599 w.connectedAt = w.clock()
600 if w.timer != nil {
601 w.timer.Stop()
602 }
603
604 if w.noticed {
605 w.noticed = false
606 notice = "WhatsApp is connected again."
607 }
608 case *events.Disconnected:
609 if w.linked && (w.connected || w.disconnectedAt.IsZero()) {
610 w.disconnectedAt = w.clock()
611 w.disconnections++
612 disconnections := w.disconnections
613 w.timer = time.AfterFunc(w.noticeDelay, func() {
614 w.disconnectedLong(disconnections)
615 })
616 }
617
618 w.connected = false
619 case *events.LoggedOut:
620 select {
621 case w.logouts <- struct{}{}:
622 default:
623 }
624 case events.PermanentDisconnect:
625 if w.linked {
626 w.connected = false
627 w.noticed = true
628 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
629 }
630 }
631 w.mutex.Unlock()
632
633 if notice != "" {
634 w.broadcast(notice)
635 }
636
637 return true
638 }
639
640 // disconnectedLong gives the notice of a long disconnection, unless the
641 // disconnection with the number disconnections ended.
642 func (w *WhatsApp) disconnectedLong(disconnections int) {
643 w.mutex.Lock()
644 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
645 if long {
646 w.noticed = true
647 }
648
649 since := w.disconnectedAt
650 w.mutex.Unlock()
651
652 if long {
653 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
654 }
655 }
656
657 // broadcast gives text as a notice to all clients.
658 func (w *WhatsApp) broadcast(text string) {
659 w.mutex.Lock()
660 notify := w.notify
661 closed := w.closed
662 w.mutex.Unlock()
663
664 if notify != nil && !closed {
665 notify(Event{
666 Kind: "notice",
667 Text: text,
668 })
669 }
670 }
671
672 // redact replaces the own number and the own LID in text with OWN.
673 func (w *WhatsApp) redact(text string) string {
674 w.mutex.Lock()
675 defer w.mutex.Unlock()
676
677 for _, id := range w.own {
678 text = strings.ReplaceAll(text, id, "OWN")
679 }
680
681 return text
682 }
683
684 // WhatsAppRequest is a pair or unlink command for Run, with the function that
685 // gives its answers to the client that asked. A pairing has the phone number.
686 type WhatsAppRequest struct {
687 phone string
688 unlink bool
689 answer func(text string)
690 }
691
692 // whatsappNewClient returns the client of the library for device, with handle
693 // as its event handler. The client tries again after a failed first
694 // connection, acknowledges a message only after handle returns true, and
695 // downloads no old history. The phone shows the device with the name OneChat.
696 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
697 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
698 client := whatsmeow.NewClient(device, waLog.Noop)
699 client.InitialAutoReconnect = true
700 client.SynchronousAck = true
701 client.ManualHistorySyncDownload = true
702 client.AddEventHandlerWithSuccessStatus(handle)
703
704 return client
705 }
706
707 // whatsappOwnIDs returns the own number and the own LID that are not empty.
708 func whatsappOwnIDs(ids ...string) []string {
709 var own []string
710 for _, id := range ids {
711 if id != "" {
712 own = append(own, id)
713 }
714 }
715
716 return own
717 }
718
719 // whatsappSessionAddress returns the SQLite address of the session database at
720 // path, with foreign keys on, as the library needs, and a wait for a busy
721 // database.
722 func whatsappSessionAddress(path string) (string, error) {
723 path, err := filepath.Abs(path)
724 if err != nil {
725 return "", fmt.Errorf("find WhatsApp session: %w", err)
726 }
727
728 address := url.URL{
729 Scheme: "file",
730 Path: path,
731 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
732 }
733
734 return address.String(), nil
735 }
736
737 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
738 // command, or false for any other line.
739 func whatsappCommandArgs(line string) (string, bool) {
740 line = strings.TrimSpace(line)
741 if line == whatsappCommand {
742 return "", true
743 }
744
745 args, found := strings.CutPrefix(line, whatsappCommand+" ")
746 if !found {
747 return "", false
748 }
749
750 return strings.TrimSpace(args), true
751 }
752
753 // whatsappPhone returns the digits of phone, a number with its country code
754 // and an optional + and dashes, and tells if it has the form of a number: 7 to
755 // 15 digits, with no 0 first.
756 func whatsappPhone(phone string) (string, bool) {
757 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
758 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
759
760 return phone, valid
761 }
762
763 // whatsappItemError returns the error of a pairing item that is not a code, a
764 // success, or a timeout.
765 func whatsappItemError(item whatsmeow.QRChannelItem) string {
766 if item.Error != nil {
767 return item.Error.Error()
768 }
769
770 return item.Event
771 }