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"
21 // The session store of the library opens SQLite with this pure Go
23 _ "modernc.org/sqlite"
27 // whatsappDirName is the directory of the WhatsApp files in the data
29 whatsappDirName = "whatsapp"
31 // whatsappSessionFileName is the session database of the library in
33 whatsappSessionFileName = "session.db"
35 // whatsappCommand starts the input lines of the WhatsApp commands, such
36 // as "/whatsapp status".
37 whatsappCommand = "/whatsapp"
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."
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."
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."
49 // whatsappTimeLayout is the layout of the times in the answers.
50 whatsappTimeLayout = "2006-01-02 15:04"
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
56 // whatsappLogoutTime is the longest time of the logout call of an
58 whatsappLogoutTime = 30 * time.Second
60 // whatsappNoticeDelay is how long a disconnection lasts before the user
62 whatsappNoticeDelay = 10 * time.Minute
64 // whatsappRequests is the number of pair and unlink commands that can
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
72 type WhatsAppClient interface {
73 ConnectContext(ctx context.Context) error
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
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) {
87 dir: filepath.Join(dir, whatsappDirName),
91 noticeDelay: whatsappNoticeDelay,
92 requests: make(chan WhatsAppRequest, whatsappRequests),
93 logouts: make(chan struct{}, 1),
96 info, err := os.Stat(w.sessionPath())
97 if errors.Is(err, os.ErrNotExist) {
102 return nil, fmt.Errorf("read WhatsApp session: %w", err)
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))
109 err = w.openSession(ctx)
114 if w.device.ID != nil {
116 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
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.
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.
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 {
141 clock func() time.Time
143 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
144 noticeDelay time.Duration
145 requests chan WhatsAppRequest
146 logouts chan struct{}
149 container *sqlstore.Container
151 client WhatsAppClient
156 connectedAt time.Time
157 disconnectedAt time.Time
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)) {
178 var pairing sync.WaitGroup
192 case request := <-w.requests:
199 w.unlink(ctx, l, request.answer)
201 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
203 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
208 w.pair(pairCtx, l, request.phone, request.answer)
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
218 func (w *WhatsApp) Command(args string, answer func(text string)) {
219 fields := strings.Fields(args)
220 request := WhatsAppRequest{
225 case len(fields) == 1 && fields[0] == "status":
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:], ""))
233 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
237 request.phone = phone
239 answer(whatsappUsage)
244 case w.requests <- request:
246 answer("Too many WhatsApp commands wait. Try again in a minute.")
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
253 func (w *WhatsApp) Status() string {
255 defer w.mutex.Unlock()
259 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it."
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) + "."
267 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "."
271 // Close closes the session database.
272 func (w *WhatsApp) Close() error {
274 defer w.mutex.Unlock()
276 if w.container == nil {
280 err := w.container.Close()
286 func (w *WhatsApp) sessionPath() string {
287 return filepath.Join(w.dir, whatsappSessionFileName)
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())
298 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
300 return fmt.Errorf("open WhatsApp session: %w", err)
303 device, err := container.GetFirstDevice(ctx)
305 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
308 w.container = container
314 func (w *WhatsApp) isLinked() bool {
316 defer w.mutex.Unlock()
321 // connect makes the client of the linked device and connects it.
322 func (w *WhatsApp) connect(ctx context.Context) {
324 w.client = w.newClient(w.device, w.handle)
328 err := client.ConnectContext(ctx)
330 w.logger.Printf("connect: %s", w.redact(err.Error()))
334 // close ends the connection and the timer of the notice, and stops all
336 func (w *WhatsApp) close() {
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) {
359 err := w.removeSession()
361 w.logger.Printf("delete the session after the logout: %v", err)
364 err = l.note("WhatsApp was unlinked from the phone.")
366 w.logger.Printf("note the logout: %v", err)
369 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
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
376 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) {
383 answer("WhatsApp is not linked.")
389 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
392 logoutErr = client.Logout(ctx)
395 err := w.removeSession()
397 answer("The unlink failed: " + w.redact(err.Error()))
401 err = l.note("WhatsApp is unlinked.")
403 w.logger.Printf("note the unlink: %v", err)
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.")
411 answer("WhatsApp is unlinked.")
414 // removeSession ends the connection, closes the session database, and deletes
416 func (w *WhatsApp) removeSession() error {
428 container := w.container
438 if container != nil {
439 err = container.Close()
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)
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)
460 answer("The pairing failed: " + err.Error())
464 client := w.newClient(device, w.handle)
472 qr, err := client.GetQRChannel(ctx)
474 err = client.ConnectContext(ctx)
478 answer("The connection to WhatsApp failed: " + err.Error())
483 case item, open := <-qr:
484 if !open || item.Event != whatsmeow.QRChannelEventCode {
485 answer("WhatsApp did not start the pairing. Try again later.")
489 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
490 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
496 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
498 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
502 answer(whatsappPairSteps)
506 var item whatsmeow.QRChannelItem
509 case item, open = <-qr:
511 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
512 answer(whatsappPairExpired)
519 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
520 answer(whatsappPairExpired)
522 case item.Event == whatsmeow.QRChannelEventCode:
524 case item.Event == whatsmeow.QRChannelSuccess.Event:
528 err = l.note("WhatsApp is linked.")
530 w.logger.Printf("note the link: %v", err)
533 answer("WhatsApp is linked to +" + phone + ".")
537 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
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
546 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
548 defer w.mutex.Unlock()
550 if w.container == nil {
551 err := os.MkdirAll(w.dir, 0o700)
553 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
556 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
558 return nil, fmt.Errorf("create WhatsApp session: %w", err)
563 return nil, fmt.Errorf("create WhatsApp session: %w", err)
566 err = w.openSession(ctx)
572 w.device = w.container.NewDevice()
577 // linkedBy makes client the client of the linked device.
578 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
580 defer w.mutex.Unlock()
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 {
594 switch event := event.(type) {
595 case *events.PairSuccess:
596 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
597 case *events.Connected:
599 w.connectedAt = w.clock()
606 notice = "WhatsApp is connected again."
608 case *events.Disconnected:
609 if w.linked && (w.connected || w.disconnectedAt.IsZero()) {
610 w.disconnectedAt = w.clock()
612 disconnections := w.disconnections
613 w.timer = time.AfterFunc(w.noticeDelay, func() {
614 w.disconnectedLong(disconnections)
619 case *events.LoggedOut:
621 case w.logouts <- struct{}{}:
624 case events.PermanentDisconnect:
628 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
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) {
644 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
649 since := w.disconnectedAt
653 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
657 // broadcast gives text as a notice to all clients.
658 func (w *WhatsApp) broadcast(text string) {
664 if notify != nil && !closed {
672 // redact replaces the own number and the own LID in text with OWN.
673 func (w *WhatsApp) redact(text string) string {
675 defer w.mutex.Unlock()
677 for _, id := range w.own {
678 text = strings.ReplaceAll(text, id, "OWN")
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 {
689 answer func(text string)
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)
707 // whatsappOwnIDs returns the own number and the own LID that are not empty.
708 func whatsappOwnIDs(ids ...string) []string {
710 for _, id := range ids {
712 own = append(own, id)
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
722 func whatsappSessionAddress(path string) (string, error) {
723 path, err := filepath.Abs(path)
725 return "", fmt.Errorf("find WhatsApp session: %w", err)
731 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
734 return address.String(), nil
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 {
745 args, found := strings.CutPrefix(line, whatsappCommand+" ")
750 return strings.TrimSpace(args), true
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") == ""
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()