18 "go.mau.fi/whatsmeow/proto/waCompanionReg"
19 "go.mau.fi/whatsmeow/proto/waE2E"
20 "go.mau.fi/whatsmeow/store"
21 "go.mau.fi/whatsmeow/store/sqlstore"
22 "go.mau.fi/whatsmeow/types"
23 "go.mau.fi/whatsmeow/types/events"
24 waLog "go.mau.fi/whatsmeow/util/log"
25 // The session store of the library opens SQLite with this pure Go
27 _ "modernc.org/sqlite"
31 // whatsappDirName is the directory of the WhatsApp files in the data
33 whatsappDirName = "whatsapp"
35 // whatsappSessionFileName is the session database of the library in
37 whatsappSessionFileName = "session.db"
39 // whatsappCommand starts the input lines of the WhatsApp commands, such
40 // as "/whatsapp status".
41 whatsappCommand = "/whatsapp"
43 // whatsappUsage is the answer to a WhatsApp command that does not
45 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."
47 // whatsappPairSteps tells the user what to do with the pairing code,
48 // which comes in the next message.
49 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."
51 // whatsappPairExpired is the answer when the pairing code expires.
52 whatsappPairExpired = "The pairing code expired. Run /whatsapp pair PHONE again for a new code."
54 // whatsappTimeLayout is the layout of the times in the answers.
55 whatsappTimeLayout = "2006-01-02 15:04"
57 // whatsappPairTime is the longest time of a pairing. The library closes
58 // the pairing connection after about 160 seconds.
59 whatsappPairTime = 3 * time.Minute
61 // whatsappLogoutTime is the longest time of the logout call of an
63 whatsappLogoutTime = 30 * time.Second
65 // whatsappNoticeDelay is how long a disconnection lasts before the user
67 whatsappNoticeDelay = 10 * time.Minute
69 // whatsappRetryDelay is the first wait after a failed starting
71 whatsappRetryDelay = 2 * time.Second
73 // whatsappRetryLimit is the longest wait between starting connections.
74 whatsappRetryLimit = 5 * time.Minute
76 // whatsappRequests is the number of pair and unlink commands that can
80 // whatsappLookupTime is the longest time of a read of the names in the
81 // session database or of the groups from WhatsApp.
82 whatsappLookupTime = 10 * time.Second
84 // whatsappNotLinked is the answer of a WhatsApp tool without a link.
85 whatsappNotLinked = "WhatsApp is not linked. Tell the user to run /whatsapp pair PHONE in the terminal or in Telegram."
88 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
89 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
91 type WhatsAppClient interface {
92 ConnectContext(ctx context.Context) error
94 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
95 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
96 Logout(ctx context.Context) error
97 GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error)
98 GenerateMessageID() types.MessageID
99 SendMessage(ctx context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error)
102 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
103 // the session file, WhatsApp is not linked. The session gives full access to
104 // the account, so a file that another user can read is an error. The clock
105 // gives the times of the status, logger gets the failures, and newClient makes
106 // the client of a device with its event handler.
107 func openWhatsApp(ctx context.Context, dir string, clock func() time.Time, logger *slog.Logger, newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient) (*WhatsApp, error) {
109 dir: filepath.Join(dir, whatsappDirName),
112 newClient: newClient,
113 noticeDelay: whatsappNoticeDelay,
114 requests: make(chan WhatsAppRequest, whatsappRequests),
115 logouts: make(chan struct{}, 1),
116 groups: newWhatsAppGroups(logger),
121 w.state, err = openWhatsAppState(filepath.Join(w.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
126 w.inbox = newWhatsAppInbox(w.state, clock, w.groups)
128 info, err := os.Stat(w.sessionPath())
129 if errors.Is(err, os.ErrNotExist) {
134 return nil, fmt.Errorf("read WhatsApp session: %w", err)
137 if info.Mode().Perm()&0o077 != 0 {
138 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
141 err = w.openSession(ctx)
146 if w.device.ID != nil {
148 w.inbox.waitForCatchup()
150 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
156 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as a
157 // linked device. The session database of the library in dir holds the keys of
158 // the device. Run keeps a linked device connected, and the library connects
159 // again by itself after a network failure.
161 // The commands pair and unlink go to Run as requests, and Run runs one at a
162 // time. A pairing runs in its own goroutine until its code expires, and a new
163 // pairing ends the one before. Its phone number and code go only to the answer
164 // of the client that asked. A logout from the phone comes as an event of the
165 // library, and Run deletes the session. The mutex protects the session, the
166 // client, and the state of the connection, which the event handler of the
167 // library changes from its own goroutines. The sessionMutex serializes session
168 // creation, close, removal, and snapshots. It is held before mutex, and stays
169 // held when removal releases mutex for client callbacks.
171 // The inbox puts the text messages into batches and logs them, and groups
172 // holds the names of the groups. Both get a WhatsAppLink from link for each
173 // call, so they use the current device and client.
175 // The library logs nothing, because its log lines hold the ID of the own
176 // account, which is the phone number of the user. The own number and the own
177 // LID never go to the log of the agent or to the log of the daemon: redact
178 // removes them from the errors, and a batch shows the messages of the user as
179 // You and a mention of the user as @you. The IDs of the other chats go to the
180 // log, and those of private chats hold phone numbers, because the agent needs
182 type WhatsApp struct {
184 clock func() time.Time
186 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
187 noticeDelay time.Duration
188 requests chan WhatsAppRequest
189 logouts chan struct{}
191 groups *WhatsAppGroups
195 sessionMutex sync.Mutex
197 container *sqlstore.Container
199 client WhatsAppClient
205 connectedAt time.Time
206 disconnectedAt time.Time
213 // Run connects a linked device, logs the closed batches in l, runs the pair and
214 // unlink commands, and handles a logout from the phone, until ctx ends. Its
215 // notes go to the log of l, and notify gets the notices for all clients. A
216 // failed first connection starts the same outage notice as a lost connection. A
217 // timer in the select retries it with a doubled wait from 2 seconds to 5
218 // minutes, without a retry goroutine or a wait that blocks commands or the
219 // inbox. A connection, unlink, logout, or ctx end stops retries. The library
220 // owns retries after a connection opens. Run returns the error of a write of
221 // the log or of the state file, which stops the daemon, because then messages
223 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) error {
231 timer := time.NewTimer(whatsappRetryDelay)
235 var retry <-chan time.Time
237 delay := whatsappRetryDelay
244 delay = min(2*delay, whatsappRetryLimit)
248 stopRetry := func() {
259 var pairing sync.WaitGroup
273 err := w.inbox.deliver(ctx, l, w.link(), false)
281 case err = <-w.inbox.failures:
284 case <-w.inbox.due():
290 err = w.loggedOut(ctx, l)
294 case request := <-w.requests:
304 err = w.unlink(ctx, l, request.answer)
309 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
311 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
316 w.pair(pairCtx, ctx, l, request.phone, request.answer)
323 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
324 // each answer to answer. The answers go only to the client that sent the
326 func (w *WhatsApp) Command(args string, answer func(text string)) {
327 fields := strings.Fields(args)
328 request := WhatsAppRequest{
333 case len(fields) == 1 && fields[0] == "status":
337 case len(fields) == 1 && fields[0] == "unlink":
338 request.unlink = true
339 case len(fields) >= 2 && fields[0] == "pair":
340 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
342 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
347 request.phone = phone
349 answer(whatsappUsage)
355 case w.requests <- request:
357 answer("Too many WhatsApp commands wait. Try again in a minute.")
361 // Status returns the state of the link: not linked, linked and connected, or
362 // linked and disconnected, with the times of the connection and the routes.
363 // Route source IDs can hold the phone numbers of other chats.
364 func (w *WhatsApp) Status() string {
366 defer w.mutex.Unlock()
370 listed := w.routes.List()
371 if listed != "No routes." {
372 routes = "\nWhatsApp routes:\n" + listed
378 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it." + routes
380 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "." + routes
381 case w.disconnectedAt.IsZero():
382 return "WhatsApp is linked and not connected yet." + routes
383 case w.connectedAt.IsZero():
384 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "." + routes
386 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "." + routes
390 // BackupSession writes a consistent SQLite snapshot to path while the session
391 // cannot be created, closed, or removed. The source opens without creation
392 // permission. No session file means no linked state to copy.
393 func (w *WhatsApp) BackupSession(ctx context.Context, path string) (err error) {
394 w.sessionMutex.Lock()
395 defer w.sessionMutex.Unlock()
398 defer w.mutex.Unlock()
400 _, err = os.Stat(w.sessionPath())
401 if errors.Is(err, os.ErrNotExist) {
406 return fmt.Errorf("read session file: %w", err)
409 err = os.MkdirAll(filepath.Dir(path), 0o700)
411 return fmt.Errorf("create session snapshot directory: %w", err)
414 address, err := whatsappSessionAddress(w.sessionPath())
416 return fmt.Errorf("find session database: %w", err)
419 database, err := sql.Open("sqlite", address+"&mode=rw")
421 return fmt.Errorf("open session snapshot source: %w", err)
425 err = errors.Join(err, database.Close())
428 _, err = database.ExecContext(ctx, "VACUUM INTO ?", path)
430 return fmt.Errorf("snapshot session database: %w", err)
433 err = os.Chmod(path, 0o600)
435 return fmt.Errorf("set session snapshot mode: %w", err)
441 // Close closes the session database.
442 func (w *WhatsApp) Close() error {
443 w.sessionMutex.Lock()
444 defer w.sessionMutex.Unlock()
447 defer w.mutex.Unlock()
449 if w.container == nil {
453 err := w.container.Close()
459 // Find returns the answer of whatsapp_find for name, as whatsappFind says.
460 func (w *WhatsApp) Find(ctx context.Context, name string) (string, error) {
461 return whatsappFind(ctx, w.link(), w.groups, name)
464 // Send returns the answer of whatsapp_send for the send id of text to chat, as
465 // whatsappSend says.
466 func (w *WhatsApp) Send(ctx context.Context, id, chat, text string) (string, error) {
467 return whatsappSend(ctx, w.link(), w.groups, w.state, w.clock, id, chat, text)
470 func (w *WhatsApp) sessionPath() string {
471 return filepath.Join(w.dir, whatsappSessionFileName)
474 // openSession opens the session database and its first device. The caller holds
475 // the mutex, or no other goroutine uses w yet.
476 func (w *WhatsApp) openSession(ctx context.Context) error {
477 address, err := whatsappSessionAddress(w.sessionPath())
482 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
484 return fmt.Errorf("open WhatsApp session: %w", err)
487 device, err := container.GetFirstDevice(ctx)
489 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
492 w.container = container
498 func (w *WhatsApp) isLinked() bool {
500 defer w.mutex.Unlock()
505 // link returns a copy of the link of the device: whether it is linked, the
506 // device, the client, whether it is connected, and the own IDs.
507 func (w *WhatsApp) link() WhatsAppLink {
509 defer w.mutex.Unlock()
515 connected: w.connected,
516 own: slices.Clone(w.own),
520 // connect tries the starting connection of the linked device with one client.
521 // It returns whether Run must retry. A failed call starts the shared outage
522 // state and logs its redacted cause once, because a returned ConnectContext
523 // error does not emit Disconnected. Connected logs recovery after
525 func (w *WhatsApp) connect(ctx context.Context) bool {
528 if ctx.Err() != nil || !w.linked || !w.retrying || w.closed {
535 w.client = w.newClient(w.device, w.handle)
541 err := client.ConnectContext(ctx)
545 if err == nil || ctx.Err() != nil || !w.retrying || !w.linked {
552 first := w.startOutage()
553 cause := whatsappRedact(w.own, err.Error())
557 w.logger.Warn("first connect failed, retrying", "err", cause)
563 // startOutage starts the shared outage time and notice timer once. The caller
564 // holds the mutex. Its result tells whether this is the first failure.
565 func (w *WhatsApp) startOutage() bool {
566 first := w.linked && (w.connected || w.disconnectedAt.IsZero())
568 w.disconnectedAt = w.clock()
570 disconnections := w.disconnections
571 w.timer = time.AfterFunc(w.noticeDelay, func() {
572 w.disconnectedLong(disconnections)
581 // close ends the connection and the timer of the notice, and stops all notices.
582 func (w *WhatsApp) close() {
601 // loggedOut logs the open batches, deletes the session after a logout from the
602 // phone, notes it in the log of l, and tells all clients one time.
603 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
608 w.logger.Error("logged out by the phone, run /whatsapp pair PHONE")
610 err := w.inbox.deliver(ctx, l, w.link(), true)
615 err = w.removeSession()
617 w.logger.Error("session delete failed", "err", err)
620 err = l.note("WhatsApp was unlinked from the phone.")
622 w.logger.Error("chat note failed", "err", err)
625 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
630 // unlink logs the open batches, logs out the linked device, and deletes the
631 // session. When the logout call fails, as it does while WhatsApp is
632 // disconnected, the session is deleted all the same, and answer tells the user
633 // to remove the device in the phone. Its error is one of the log or the state
635 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
643 answer("WhatsApp is not linked.")
648 err := w.inbox.deliver(ctx, l, w.link(), true)
656 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
659 logoutErr = client.Logout(ctx)
662 err = w.removeSession()
664 answer("The unlink failed: " + w.redact(err.Error()))
669 w.logger.Info("unlinked")
671 err = l.note("WhatsApp is unlinked.")
673 w.logger.Error("chat note failed", "err", err)
676 if client == nil || logoutErr != nil {
677 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.")
682 answer("WhatsApp is unlinked.")
687 // removeSession ends the connection, closes the session database, and deletes
688 // its files. The session lock covers the cleanup after mutex is released, so a
689 // snapshot or a new session cannot open files that cleanup removes.
690 func (w *WhatsApp) removeSession() error {
691 w.sessionMutex.Lock()
692 defer w.sessionMutex.Unlock()
702 w.disconnectedAt = time.Time{}
708 container := w.container
713 w.inbox.stopCatchup()
721 if container != nil {
722 err = container.Close()
725 for _, suffix := range []string{"", "-wal", "-shm"} {
726 removeErr := os.Remove(w.sessionPath() + suffix)
727 if !errors.Is(removeErr, os.ErrNotExist) {
728 err = errors.Join(err, removeErr)
735 // pair links a new device to the account of phone with a pairing code. It gives
736 // the steps and the code to answer, and then the end of the pairing: the linked
737 // number, an expired code, or a failure. A pairing that a new one ends gives no
738 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
739 // The client of a pairing that does not link is disconnected.
741 // ctx limits the pairing, but the connection uses runCtx, the context of Run.
742 // The library keeps the context of the connection for its keep-alive, its event
743 // handler, and its reconnections, and after the link the server ends the stream
744 // and the library connects again. With ctx, the end of the pairing would stop
745 // that reconnection, and the linked device would never connect.
746 func (w *WhatsApp) pair(ctx, runCtx context.Context, l *TurnLoop, phone string, answer func(text string)) {
747 device, err := w.newDevice(ctx)
749 answer("The pairing failed: " + err.Error())
754 client := w.newClient(device, w.handle)
762 qr, err := client.GetQRChannel(ctx)
764 err = client.ConnectContext(runCtx)
768 answer("The connection to WhatsApp failed: " + err.Error())
774 case item, open := <-qr:
775 if !open || item.Event != whatsmeow.QRChannelEventCode {
776 answer("WhatsApp did not start the pairing. Try again later.")
781 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
782 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
788 // The server accepts only a display name of the form "Browser (OS)"
789 // with a common browser and OS, and refuses the pairing otherwise.
790 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
792 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
797 answer(whatsappPairSteps)
801 var item whatsmeow.QRChannelItem
805 case item, open = <-qr:
807 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
808 answer(whatsappPairExpired)
815 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
816 answer(whatsappPairExpired)
819 case item.Event == whatsmeow.QRChannelEventCode:
821 case item.Event == whatsmeow.QRChannelSuccess.Event:
825 w.logger.Info("linked")
827 err = l.note("WhatsApp is linked.")
829 w.logger.Error("chat note failed", "err", err)
832 answer("WhatsApp is linked to +" + phone + ".")
836 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
843 // newDevice returns a new device in the session database. It makes the
844 // directory and the file of the session first, with their modes, when they do
846 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
847 w.sessionMutex.Lock()
848 defer w.sessionMutex.Unlock()
851 defer w.mutex.Unlock()
853 if w.container == nil {
854 err := os.MkdirAll(w.dir, 0o700)
856 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
859 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
861 return nil, fmt.Errorf("create WhatsApp session: %w", err)
866 return nil, fmt.Errorf("create WhatsApp session: %w", err)
869 err = w.openSession(ctx)
875 w.device = w.container.NewDevice()
880 // linkedBy makes client the client of the linked device.
881 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
883 defer w.mutex.Unlock()
889 // handle takes one event of the library and tells if it was handled. A message
890 // goes to the inbox. The names of the groups follow the events of the groups. A
891 // connection starts a catch-up of the inbox, which ends at OfflineSyncCompleted
892 // or after its catchupLimit. A disconnection keeps the time of its start while
893 // Run or the library tries again. After noticeDelay of a disconnection, all
894 // clients get one notice, and they get one more when the connection comes back.
895 // A disconnection that the library does not try again gives a notice at once.
897 // The log of the daemon gets one line for each change of the connection of the
898 // linked device: connected, a failed first connection, a lost connection, and
899 // connected again with the length of the outage. The retries of the library and
900 // Run between them log nothing.
901 func (w *WhatsApp) handle(event any) bool {
902 switch event := event.(type) {
903 case *events.Message:
904 return w.inbox.receive(w.link(), event)
905 case *events.GroupInfo:
906 if event.Name != nil {
907 w.groups.set(event.JID.String(), event.Name.Name)
911 case *events.JoinedGroup:
912 w.groups.set(event.JID.String(), event.Name)
915 case *events.OfflineSyncCompleted:
919 case *events.Connected:
920 w.inbox.startCatchup()
923 var notice, line string
925 level := slog.LevelInfo
931 switch event := event.(type) {
932 case *events.PairSuccess:
933 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
934 case *events.Connected:
936 case !w.linked || w.connected:
937 case w.disconnectedAt.IsZero():
940 line = "connected again"
941 attrs = append(attrs, "after", w.clock().Sub(w.disconnectedAt))
946 w.connectedAt = w.clock()
953 notice = "WhatsApp is connected again."
955 case *events.Disconnected:
956 connected := w.connected
958 level = slog.LevelWarn
959 line = "disconnected, retrying"
961 line = "first connect failed, retrying"
964 case *events.LoggedOut:
967 case w.logouts <- struct{}{}:
970 case events.PermanentDisconnect:
975 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
976 level = slog.LevelError
977 line = "disconnected for good, restart to retry"
978 attrs = append(attrs, "err", whatsappRedact(w.own, event.PermanentDisconnectDescription()))
989 w.logger.Log(context.Background(), level, line, attrs...)
999 // disconnectedLong gives the notice of a long disconnection, unless the
1000 // disconnection with the number disconnections ended.
1001 func (w *WhatsApp) disconnectedLong(disconnections int) {
1004 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
1009 since := w.disconnectedAt
1013 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
1017 // broadcast gives text as a notice to all clients.
1018 func (w *WhatsApp) broadcast(text string) {
1025 if notify != nil && !closed {
1033 // redact replaces the own number and the own LID in text with OWN.
1034 func (w *WhatsApp) redact(text string) string {
1036 defer w.mutex.Unlock()
1038 return whatsappRedact(w.own, text)
1041 // WhatsAppLink is a copy of the link of the device at one time, for the parts
1042 // of WhatsApp that do not own it: the groups, the batches, find, and send.
1043 type WhatsAppLink struct {
1045 device *store.Device
1046 client WhatsAppClient
1051 // WhatsAppRequest is a pair or unlink command for Run, with the function that
1052 // gives its answers to the client that asked. A pairing has the phone number.
1053 type WhatsAppRequest struct {
1056 answer func(text string)
1059 // whatsappSetDeviceProps sets the device properties that the library sends at
1060 // the pairing. They are global values of the library, so the daemon sets them
1061 // once before any client exists. The phone shows the linked device with the
1062 // name OneChat and a desktop icon only when the platform type is known.
1063 func whatsappSetDeviceProps() {
1064 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
1066 store.DeviceProps.PlatformType = waCompanionReg.DeviceProps_DESKTOP.Enum()
1069 // whatsappNewClient returns the client of the library for device, with handle
1070 // as its event handler. Run owns failed starting connections of linked devices,
1071 // so only an unlinked device enables the initial retry of the library for
1072 // pairing. The library still retries a lost connection. The client acknowledges
1073 // a message only after handle returns true, and downloads no old history.
1074 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
1075 client := whatsmeow.NewClient(device, waLog.Noop)
1076 client.InitialAutoReconnect = device.ID == nil
1077 client.SynchronousAck = true
1078 client.ManualHistorySyncDownload = true
1079 client.AddEventHandlerWithSuccessStatus(handle)
1084 // whatsappContactName returns the name of the person jid: the full name, the
1085 // first name, the business name, or the push name of the contact in the session
1086 // of device, then push, the push name of a message, then the phone number. A
1087 // LID gets its phone number from the LID map of the session.
1088 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
1090 candidates := []types.JID{jid}
1091 phone := types.EmptyJID
1093 case types.DefaultUserServer:
1095 case types.HiddenUserServer:
1096 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
1097 if err == nil && !mapped.IsEmpty() {
1099 candidates = append(candidates, mapped)
1103 for _, candidate := range candidates {
1104 contact, err := device.Contacts.GetContact(ctx, candidate)
1105 if err != nil || !contact.Found {
1109 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
1119 case !phone.IsEmpty():
1120 return "+" + phone.User
1126 // whatsappOwnIDs returns the own number and the own LID that are not empty.
1127 func whatsappOwnIDs(ids ...string) []string {
1130 for _, id := range ids {
1132 own = append(own, id)
1139 // whatsappRedact replaces each of the own IDs own in text with OWN.
1140 func whatsappRedact(own []string, text string) string {
1141 for _, id := range own {
1142 text = strings.ReplaceAll(text, id, "OWN")
1148 // whatsappSessionAddress returns the SQLite address of the session database at
1149 // path, with foreign keys on, as the library needs, and a wait for a busy
1151 func whatsappSessionAddress(path string) (string, error) {
1152 path, err := filepath.Abs(path)
1154 return "", fmt.Errorf("find WhatsApp session: %w", err)
1160 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
1163 return address.String(), nil
1166 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
1167 // command, or false for any other line.
1168 func whatsappCommandArgs(line string) (string, bool) {
1169 line = strings.TrimSpace(line)
1170 if line == whatsappCommand {
1174 args, found := strings.CutPrefix(line, whatsappCommand+" ")
1179 return strings.TrimSpace(args), true
1182 // whatsappPhone returns the digits of phone, a number with its country code and
1183 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
1184 // digits, with no 0 first.
1185 func whatsappPhone(phone string) (string, bool) {
1186 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
1187 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
1192 // whatsappItemError returns the error of a pairing item that is not a code, a
1193 // success, or a timeout.
1194 func whatsappItemError(item whatsmeow.QRChannelItem) string {
1195 if item.Error != nil {
1196 return item.Error.Error()