17 "go.mau.fi/whatsmeow/proto/waE2E"
18 "go.mau.fi/whatsmeow/store"
19 "go.mau.fi/whatsmeow/store/sqlstore"
20 "go.mau.fi/whatsmeow/types"
21 "go.mau.fi/whatsmeow/types/events"
22 waLog "go.mau.fi/whatsmeow/util/log"
23 // The session store of the library opens SQLite with this pure Go
25 _ "modernc.org/sqlite"
29 // whatsappDirName is the directory of the WhatsApp files in the data
31 whatsappDirName = "whatsapp"
33 // whatsappSessionFileName is the session database of the library in
35 whatsappSessionFileName = "session.db"
37 // whatsappCommand starts the input lines of the WhatsApp commands, such
38 // as "/whatsapp status".
39 whatsappCommand = "/whatsapp"
41 // whatsappUsage is the answer to a WhatsApp command that does not
43 whatsappUsage = "Use /whatsapp pair PHONE, /whatsapp status, or /whatsapp unlink. PHONE is the number of your WhatsApp account with its country code, such as +15550001111."
45 // whatsappPairSteps tells the user what to do with the pairing code,
46 // which comes in the next message.
47 whatsappPairSteps = "In WhatsApp on your phone, open Linked devices, tap Link a device, then tap Link with phone number instead, and enter the code of the next message. The code expires in about 2 minutes."
49 // whatsappPairExpired is the answer when the pairing code expires.
50 whatsappPairExpired = "The pairing code expired. Run /whatsapp pair PHONE again for a new code."
52 // whatsappTimeLayout is the layout of the times in the answers.
53 whatsappTimeLayout = "2006-01-02 15:04"
55 // whatsappPairTime is the longest time of a pairing. The library closes
56 // the pairing connection after about 160 seconds.
57 whatsappPairTime = 3 * time.Minute
59 // whatsappLogoutTime is the longest time of the logout call of an
61 whatsappLogoutTime = 30 * time.Second
63 // whatsappNoticeDelay is how long a disconnection lasts before the user
65 whatsappNoticeDelay = 10 * time.Minute
67 // whatsappRequests is the number of pair and unlink commands that can
71 // whatsappLookupTime is the longest time of a read of the names in the
72 // session database or of the groups from WhatsApp.
73 whatsappLookupTime = 10 * time.Second
75 // whatsappNotLinked is the answer of a WhatsApp tool without a link.
76 whatsappNotLinked = "WhatsApp is not linked. Tell the user to run /whatsapp pair PHONE in the terminal or in Telegram."
79 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
80 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
82 type WhatsAppClient interface {
83 ConnectContext(ctx context.Context) error
85 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
86 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
87 Logout(ctx context.Context) error
88 GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error)
89 GenerateMessageID() types.MessageID
90 SendMessage(ctx context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error)
93 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
94 // the session file, WhatsApp is not linked. The session gives full access to
95 // the account, so a file that another user can read is an error. The clock
96 // gives the times of the status, logger gets the failures, and newClient makes
97 // the client of a device with its event handler.
98 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 dir: filepath.Join(dir, whatsappDirName),
103 newClient: newClient,
104 noticeDelay: whatsappNoticeDelay,
105 requests: make(chan WhatsAppRequest, whatsappRequests),
106 logouts: make(chan struct{}, 1),
107 groups: newWhatsAppGroups(logger),
111 w.state, err = openWhatsAppState(filepath.Join(w.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
116 w.inbox = newWhatsAppInbox(w.state, clock, w.groups)
118 info, err := os.Stat(w.sessionPath())
119 if errors.Is(err, os.ErrNotExist) {
124 return nil, fmt.Errorf("read WhatsApp session: %w", err)
127 if info.Mode().Perm()&0o077 != 0 {
128 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
131 err = w.openSession(ctx)
136 if w.device.ID != nil {
138 w.inbox.waitForCatchup()
139 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
145 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as a
146 // linked device. The session database of the library in dir holds the keys of
147 // the device. Run keeps a linked device connected, and the library connects
148 // again by itself after a network failure.
150 // The commands pair and unlink go to Run as requests, and Run runs one at a
151 // time. A pairing runs in its own goroutine until its code expires, and a new
152 // pairing ends the one before. Its phone number and code go only to the answer
153 // of the client that asked. A logout from the phone comes as an event of the
154 // library, and Run deletes the session. The mutex protects the session, the
155 // client, and the state of the connection, which the event handler of the
156 // library changes from its own goroutines.
158 // The inbox puts the text messages into batches and logs them, and groups
159 // holds the names of the groups. Both get a WhatsAppLink from link for each
160 // call, so they use the current device and client.
162 // The library logs nothing, because its log lines hold the ID of the own
163 // account, which is the phone number of the user. The own number and the own
164 // LID never go to the log of the agent or to the log of the daemon: redact
165 // removes them from the errors, and a batch shows the messages of the user as
166 // You and a mention of the user as @you. The IDs of the other chats go to the
167 // log, and those of private chats hold phone numbers, because the agent needs
169 type WhatsApp struct {
171 clock func() time.Time
173 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
174 noticeDelay time.Duration
175 requests chan WhatsAppRequest
176 logouts chan struct{}
178 groups *WhatsAppGroups
182 container *sqlstore.Container
184 client WhatsAppClient
189 connectedAt time.Time
190 disconnectedAt time.Time
197 // Run connects a linked device, logs the closed batches in l, runs the pair and
198 // unlink commands, and handles a logout from the phone, until ctx ends. Its
199 // notes go to the log of l, and notify gets the notices for all clients. A
200 // failed first connection is logged, and the library tries again when the
201 // failure is one of the network. Run returns the error of a write of the log or
202 // of the state file, which stops the daemon, because then messages would be
204 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) error {
214 var pairing sync.WaitGroup
223 err := w.inbox.deliver(ctx, l, w.link(), false)
231 case err = <-w.inbox.failures:
234 case <-w.inbox.due():
236 err = w.loggedOut(ctx, l)
240 case request := <-w.requests:
247 err = w.unlink(ctx, l, request.answer)
252 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
254 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
259 w.pair(pairCtx, ctx, l, request.phone, request.answer)
266 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
267 // each answer to answer. The answers go only to the client that sent the
269 func (w *WhatsApp) Command(args string, answer func(text string)) {
270 fields := strings.Fields(args)
271 request := WhatsAppRequest{
276 case len(fields) == 1 && fields[0] == "status":
279 case len(fields) == 1 && fields[0] == "unlink":
280 request.unlink = true
281 case len(fields) >= 2 && fields[0] == "pair":
282 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
284 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
288 request.phone = phone
290 answer(whatsappUsage)
295 case w.requests <- request:
297 answer("Too many WhatsApp commands wait. Try again in a minute.")
301 // Status returns the state of the link: not linked, linked and connected, or
302 // linked and disconnected, with the times of the connection. It never holds the
304 func (w *WhatsApp) Status() string {
306 defer w.mutex.Unlock()
310 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it."
312 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "."
313 case w.disconnectedAt.IsZero():
314 return "WhatsApp is linked and not connected yet."
315 case w.connectedAt.IsZero():
316 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "."
318 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "."
322 // Close closes the session database.
323 func (w *WhatsApp) Close() error {
325 defer w.mutex.Unlock()
327 if w.container == nil {
331 err := w.container.Close()
337 // Find returns the answer of whatsapp_find for name, as whatsappFind says.
338 func (w *WhatsApp) Find(ctx context.Context, name string) (string, error) {
339 return whatsappFind(ctx, w.link(), w.groups, name)
342 // Send returns the answer of whatsapp_send for the send id of text to chat, as
343 // whatsappSend says.
344 func (w *WhatsApp) Send(ctx context.Context, id, chat, text string) (string, error) {
345 return whatsappSend(ctx, w.link(), w.groups, w.state, w.clock, id, chat, text)
348 func (w *WhatsApp) sessionPath() string {
349 return filepath.Join(w.dir, whatsappSessionFileName)
352 // openSession opens the session database and its first device. The caller holds
353 // the mutex, or no other goroutine uses w yet.
354 func (w *WhatsApp) openSession(ctx context.Context) error {
355 address, err := whatsappSessionAddress(w.sessionPath())
360 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
362 return fmt.Errorf("open WhatsApp session: %w", err)
365 device, err := container.GetFirstDevice(ctx)
367 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
370 w.container = container
376 func (w *WhatsApp) isLinked() bool {
378 defer w.mutex.Unlock()
383 // link returns a copy of the link of the device: whether it is linked, the
384 // device, the client, whether it is connected, and the own IDs.
385 func (w *WhatsApp) link() WhatsAppLink {
387 defer w.mutex.Unlock()
393 connected: w.connected,
394 own: slices.Clone(w.own),
398 // connect makes the client of the linked device and connects it.
399 func (w *WhatsApp) connect(ctx context.Context) {
401 w.client = w.newClient(w.device, w.handle)
405 err := client.ConnectContext(ctx)
407 w.logger.Printf("connect: %s", w.redact(err.Error()))
411 // close ends the connection and the timer of the notice, and stops all notices.
412 func (w *WhatsApp) close() {
430 // loggedOut logs the open batches, deletes the session after a logout from the
431 // phone, notes it in the log of l, and tells all clients one time.
432 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
437 err := w.inbox.deliver(ctx, l, w.link(), true)
442 err = w.removeSession()
444 w.logger.Printf("delete the session after the logout: %v", err)
447 err = l.note("WhatsApp was unlinked from the phone.")
449 w.logger.Printf("note the logout: %v", err)
452 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
457 // unlink logs the open batches, logs out the linked device, and deletes the
458 // session. When the logout call fails, as it does while WhatsApp is
459 // disconnected, the session is deleted all the same, and answer tells the user
460 // to remove the device in the phone. Its error is one of the log or the state
462 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
469 answer("WhatsApp is not linked.")
473 err := w.inbox.deliver(ctx, l, w.link(), true)
480 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
483 logoutErr = client.Logout(ctx)
486 err = w.removeSession()
488 answer("The unlink failed: " + w.redact(err.Error()))
492 err = l.note("WhatsApp is unlinked.")
494 w.logger.Printf("note the unlink: %v", err)
497 if client == nil || logoutErr != nil {
498 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 answer("WhatsApp is unlinked.")
507 // removeSession ends the connection, closes the session database, and deletes
509 func (w *WhatsApp) removeSession() error {
521 container := w.container
526 w.inbox.stopCatchup()
533 if container != nil {
534 err = container.Close()
537 for _, suffix := range []string{"", "-wal", "-shm"} {
538 removeErr := os.Remove(w.sessionPath() + suffix)
539 if !errors.Is(removeErr, os.ErrNotExist) {
540 err = errors.Join(err, removeErr)
547 // pair links a new device to the account of phone with a pairing code. It gives
548 // the steps and the code to answer, and then the end of the pairing: the linked
549 // number, an expired code, or a failure. A pairing that a new one ends gives no
550 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
551 // The client of a pairing that does not link is disconnected.
553 // ctx limits the pairing, but the connection uses runCtx, the context of Run.
554 // The library keeps the context of the connection for its keep-alive, its event
555 // handler, and its reconnections, and after the link the server ends the stream
556 // and the library connects again. With ctx, the end of the pairing would stop
557 // that reconnection, and the linked device would never connect.
558 func (w *WhatsApp) pair(ctx, runCtx context.Context, l *TurnLoop, phone string, answer func(text string)) {
559 device, err := w.newDevice(ctx)
561 answer("The pairing failed: " + err.Error())
565 client := w.newClient(device, w.handle)
573 qr, err := client.GetQRChannel(ctx)
575 err = client.ConnectContext(runCtx)
579 answer("The connection to WhatsApp failed: " + err.Error())
584 case item, open := <-qr:
585 if !open || item.Event != whatsmeow.QRChannelEventCode {
586 answer("WhatsApp did not start the pairing. Try again later.")
590 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
591 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
597 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
599 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
603 answer(whatsappPairSteps)
607 var item whatsmeow.QRChannelItem
610 case item, open = <-qr:
612 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
613 answer(whatsappPairExpired)
620 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
621 answer(whatsappPairExpired)
623 case item.Event == whatsmeow.QRChannelEventCode:
625 case item.Event == whatsmeow.QRChannelSuccess.Event:
629 err = l.note("WhatsApp is linked.")
631 w.logger.Printf("note the link: %v", err)
634 answer("WhatsApp is linked to +" + phone + ".")
638 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
644 // newDevice returns a new device in the session database. It makes the
645 // directory and the file of the session first, with their modes, when they do
647 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
649 defer w.mutex.Unlock()
651 if w.container == nil {
652 err := os.MkdirAll(w.dir, 0o700)
654 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
657 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
659 return nil, fmt.Errorf("create WhatsApp session: %w", err)
664 return nil, fmt.Errorf("create WhatsApp session: %w", err)
667 err = w.openSession(ctx)
673 w.device = w.container.NewDevice()
678 // linkedBy makes client the client of the linked device.
679 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
681 defer w.mutex.Unlock()
687 // handle takes one event of the library and tells if it was handled. A message
688 // goes to the inbox. The names of the groups follow the events of the groups. A
689 // connection starts a catch-up of the inbox, which ends at OfflineSyncCompleted
690 // or after its catchupLimit. A disconnection keeps the time of its start while
691 // the library tries again. After noticeDelay of a disconnection, all clients
692 // get one notice, and they get one more when the connection comes back. A
693 // disconnection that the library does not try again gives a notice at once.
694 func (w *WhatsApp) handle(event any) bool {
695 switch event := event.(type) {
696 case *events.Message:
697 return w.inbox.receive(w.link(), event)
698 case *events.GroupInfo:
699 if event.Name != nil {
700 w.groups.set(event.JID.String(), event.Name.Name)
704 case *events.JoinedGroup:
705 w.groups.set(event.JID.String(), event.Name)
707 case *events.OfflineSyncCompleted:
710 case *events.Connected:
711 w.inbox.startCatchup()
716 switch event := event.(type) {
717 case *events.PairSuccess:
718 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
719 case *events.Connected:
721 w.connectedAt = w.clock()
728 notice = "WhatsApp is connected again."
730 case *events.Disconnected:
731 if w.linked && (w.connected || w.disconnectedAt.IsZero()) {
732 w.disconnectedAt = w.clock()
734 disconnections := w.disconnections
735 w.timer = time.AfterFunc(w.noticeDelay, func() {
736 w.disconnectedLong(disconnections)
741 case *events.LoggedOut:
743 case w.logouts <- struct{}{}:
746 case events.PermanentDisconnect:
750 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
762 // disconnectedLong gives the notice of a long disconnection, unless the
763 // disconnection with the number disconnections ended.
764 func (w *WhatsApp) disconnectedLong(disconnections int) {
766 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
771 since := w.disconnectedAt
775 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
779 // broadcast gives text as a notice to all clients.
780 func (w *WhatsApp) broadcast(text string) {
786 if notify != nil && !closed {
794 // redact replaces the own number and the own LID in text with OWN.
795 func (w *WhatsApp) redact(text string) string {
797 defer w.mutex.Unlock()
799 return whatsappRedact(w.own, text)
802 // WhatsAppLink is a copy of the link of the device at one time, for the parts
803 // of WhatsApp that do not own it: the groups, the batches, find, and send.
804 type WhatsAppLink struct {
807 client WhatsAppClient
812 // WhatsAppRequest is a pair or unlink command for Run, with the function that
813 // gives its answers to the client that asked. A pairing has the phone number.
814 type WhatsAppRequest struct {
817 answer func(text string)
820 // whatsappNewClient returns the client of the library for device, with handle
821 // as its event handler. The client tries again after a failed first connection,
822 // acknowledges a message only after handle returns true, and downloads no old
823 // history. The phone shows the device with the name OneChat.
824 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
825 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
826 client := whatsmeow.NewClient(device, waLog.Noop)
827 client.InitialAutoReconnect = true
828 client.SynchronousAck = true
829 client.ManualHistorySyncDownload = true
830 client.AddEventHandlerWithSuccessStatus(handle)
835 // whatsappContactName returns the name of the person jid: the full name, the
836 // first name, the business name, or the push name of the contact in the session
837 // of device, then push, the push name of a message, then the phone number. A
838 // LID gets its phone number from the LID map of the session.
839 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
841 candidates := []types.JID{jid}
842 phone := types.EmptyJID
844 case types.DefaultUserServer:
846 case types.HiddenUserServer:
847 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
848 if err == nil && !mapped.IsEmpty() {
850 candidates = append(candidates, mapped)
854 for _, candidate := range candidates {
855 contact, err := device.Contacts.GetContact(ctx, candidate)
856 if err != nil || !contact.Found {
860 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
870 case !phone.IsEmpty():
871 return "+" + phone.User
877 // whatsappOwnIDs returns the own number and the own LID that are not empty.
878 func whatsappOwnIDs(ids ...string) []string {
880 for _, id := range ids {
882 own = append(own, id)
889 // whatsappRedact replaces each of the own IDs own in text with OWN.
890 func whatsappRedact(own []string, text string) string {
891 for _, id := range own {
892 text = strings.ReplaceAll(text, id, "OWN")
898 // whatsappSessionAddress returns the SQLite address of the session database at
899 // path, with foreign keys on, as the library needs, and a wait for a busy
901 func whatsappSessionAddress(path string) (string, error) {
902 path, err := filepath.Abs(path)
904 return "", fmt.Errorf("find WhatsApp session: %w", err)
910 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
913 return address.String(), nil
916 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
917 // command, or false for any other line.
918 func whatsappCommandArgs(line string) (string, bool) {
919 line = strings.TrimSpace(line)
920 if line == whatsappCommand {
924 args, found := strings.CutPrefix(line, whatsappCommand+" ")
929 return strings.TrimSpace(args), true
932 // whatsappPhone returns the digits of phone, a number with its country code and
933 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
934 // digits, with no 0 first.
935 func whatsappPhone(phone string) (string, bool) {
936 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
937 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
942 // whatsappItemError returns the error of a pairing item that is not a code, a
943 // success, or a timeout.
944 func whatsappItemError(item whatsmeow.QRChannelItem) string {
945 if item.Error != nil {
946 return item.Error.Error()