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 // whatsappNotLinked is the answer of a WhatsApp tool without a link.
81 whatsappNotLinked = "WhatsApp is not linked. Tell the user to run /whatsapp pair PHONE in the terminal or in Telegram."
84 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
85 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
87 type WhatsAppClient interface {
88 ConnectContext(ctx context.Context) error
90 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
91 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
92 Logout(ctx context.Context) error
93 GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error)
94 Download(ctx context.Context, message whatsmeow.DownloadableMessage) ([]byte, error)
95 GenerateMessageID() types.MessageID
96 SendMessage(ctx context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error)
99 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
100 // the session file, WhatsApp is not linked. The session gives full access to
101 // the account, so a file that another user can read is an error. The clock
102 // gives the times of the status, logger gets the failures, and newClient makes
103 // the client of a device with its event handler.
104 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) {
107 dir: filepath.Join(dir, whatsappDirName),
110 newClient: newClient,
111 requests: make(chan WhatsAppRequest, whatsappRequests),
112 logouts: make(chan struct{}, 1),
113 groups: newWhatsAppGroups(logger),
118 w.state, err = openWhatsAppState(filepath.Join(w.dir, whatsappStateFileName))
123 w.inbox = newWhatsAppInbox(w.state, clock, w.groups, &ImageStore{dir: filepath.Join(dir, imageDirName)}, logger)
125 info, err := os.Stat(w.sessionPath())
126 if errors.Is(err, os.ErrNotExist) {
131 return nil, fmt.Errorf("read WhatsApp session: %w", err)
134 if info.Mode().Perm()&0o077 != 0 {
135 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
138 err = w.openSession(ctx)
143 if w.device.ID != nil {
145 w.inbox.waitForCatchup()
147 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
153 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as a
154 // linked device. The session database of the library in dir holds the keys of
155 // the device. Run keeps a linked device connected, and the library connects
156 // again by itself after a network failure.
158 // The commands pair and unlink go to Run as requests, and Run runs one at a
159 // time. A pairing runs in its own goroutine until its code expires, and a new
160 // pairing ends the one before. Its phone number and code go only to the answer
161 // of the client that asked. A logout from the phone comes as an event of the
162 // library, and Run deletes the session. The mutex protects the session, the
163 // client, and the state of the connection, which the event handler of the
164 // library changes from its own goroutines. The sessionMutex serializes session
165 // creation, close, removal, and snapshots. It is held before mutex, and stays
166 // held when removal releases mutex for client callbacks.
168 // ctx is the caller context until Run sets its context for library callbacks.
169 // The mutex protects it, so callbacks follow daemon cancellation.
171 // The inbox puts messages into batches and logs them, and groups holds the
172 // names of the groups. Both get a WhatsAppLink from link for each call, so they
173 // 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 {
185 clock func() time.Time
187 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
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 {
232 timer := time.NewTimer(whatsappRetryDelay)
236 var retry <-chan time.Time
238 delay := whatsappRetryDelay
245 delay = min(2*delay, whatsappRetryLimit)
249 stopRetry := func() {
260 var pairing sync.WaitGroup
274 err := w.inbox.deliver(ctx, l, w.link(), false)
282 case err = <-w.inbox.failures:
285 case <-w.inbox.due():
291 err = w.loggedOut(ctx, l)
295 case request := <-w.requests:
305 err = w.unlink(ctx, l, request.answer)
310 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
312 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
317 w.pair(pairCtx, ctx, l, request.phone, request.answer)
324 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
325 // each answer to answer. The answers go only to the client that sent the
327 func (w *WhatsApp) Command(args string, answer func(text string)) {
328 fields := strings.Fields(args)
329 request := WhatsAppRequest{
334 case len(fields) == 1 && fields[0] == "status":
338 case len(fields) == 1 && fields[0] == "unlink":
339 request.unlink = true
340 case len(fields) >= 2 && fields[0] == "pair":
341 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
343 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
348 request.phone = phone
350 answer(whatsappUsage)
356 case w.requests <- request:
358 answer("Too many WhatsApp commands wait. Try again in a minute.")
362 // Status returns the state of the link: not linked, linked and connected, or
363 // linked and disconnected, with the times of the connection and the routes.
364 // Route source IDs can hold the phone numbers of other chats.
365 func (w *WhatsApp) Status() string {
367 defer w.mutex.Unlock()
371 listed := w.routes.List()
372 if listed != "No routes." {
373 routes = "\nWhatsApp routes:\n" + listed
379 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it." + routes
381 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "." + routes
382 case w.disconnectedAt.IsZero():
383 return "WhatsApp is linked and not connected yet." + routes
384 case w.connectedAt.IsZero():
385 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "." + routes
387 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "." + routes
391 // BackupSession writes a consistent SQLite snapshot to path while the session
392 // cannot be created, closed, or removed. The source opens without creation
393 // permission. No session file means no linked state to copy.
394 func (w *WhatsApp) BackupSession(ctx context.Context, path string) (err error) {
395 w.sessionMutex.Lock()
396 defer w.sessionMutex.Unlock()
399 defer w.mutex.Unlock()
401 _, err = os.Stat(w.sessionPath())
402 if errors.Is(err, os.ErrNotExist) {
407 return fmt.Errorf("read session file: %w", err)
410 err = os.MkdirAll(filepath.Dir(path), 0o700)
412 return fmt.Errorf("create session snapshot directory: %w", err)
415 address, err := whatsappSessionAddress(w.sessionPath())
417 return fmt.Errorf("find session database: %w", err)
420 database, err := sql.Open("sqlite", address+"&mode=rw")
422 return fmt.Errorf("open session snapshot source: %w", err)
426 err = errors.Join(err, database.Close())
429 _, err = database.ExecContext(ctx, "VACUUM INTO ?", path)
431 return fmt.Errorf("snapshot session database: %w", err)
434 err = os.Chmod(path, 0o600)
436 return fmt.Errorf("set session snapshot mode: %w", err)
442 // Close closes the session database.
443 func (w *WhatsApp) Close() error {
444 w.sessionMutex.Lock()
445 defer w.sessionMutex.Unlock()
448 defer w.mutex.Unlock()
450 if w.container == nil {
454 err := w.container.Close()
460 // Find returns the answer of whatsapp_find for name, as whatsappFind says.
461 func (w *WhatsApp) Find(ctx context.Context, name string) (string, error) {
462 return whatsappFind(ctx, w.link(), w.groups, name)
465 // Send returns the answer of whatsapp_send for the send id of text to chat, as
466 // whatsappSend says.
467 func (w *WhatsApp) Send(ctx context.Context, id, chat, text string) (string, error) {
468 return whatsappSend(ctx, w.link(), w.groups, w.state, w.clock, id, chat, text)
471 func (w *WhatsApp) sessionPath() string {
472 return filepath.Join(w.dir, whatsappSessionFileName)
475 // openSession opens the session database and its first device. The caller holds
476 // the mutex, or no other goroutine uses w yet.
477 func (w *WhatsApp) openSession(ctx context.Context) error {
478 address, err := whatsappSessionAddress(w.sessionPath())
483 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
485 return fmt.Errorf("open WhatsApp session: %w", err)
488 device, err := container.GetFirstDevice(ctx)
490 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
493 w.container = container
499 func (w *WhatsApp) isLinked() bool {
501 defer w.mutex.Unlock()
506 // link returns a copy of the link of the device: whether it is linked, the
507 // device, the client, whether it is connected, and the own IDs.
508 func (w *WhatsApp) link() WhatsAppLink {
510 defer w.mutex.Unlock()
516 connected: w.connected,
517 own: slices.Clone(w.own),
521 // connect tries the starting connection of the linked device with one client.
522 // It returns whether Run must retry. A failed call starts the shared outage
523 // state and logs its redacted cause once, because a returned ConnectContext
524 // error does not emit Disconnected. Connected logs recovery after
526 func (w *WhatsApp) connect(ctx context.Context) bool {
529 if ctx.Err() != nil || !w.linked || !w.retrying || w.closed {
536 w.client = w.newClient(w.device, w.handle)
542 err := client.ConnectContext(ctx)
546 if err == nil || ctx.Err() != nil || !w.retrying || !w.linked {
553 first := w.startOutage()
554 cause := whatsappRedact(w.own, err.Error())
558 w.logger.Warn("first connect failed, retrying", "err", cause)
564 // startOutage starts the shared outage time and notice timer once. The caller
565 // holds the mutex. Its result tells whether this is the first failure.
566 func (w *WhatsApp) startOutage() bool {
567 first := w.linked && (w.connected || w.disconnectedAt.IsZero())
569 w.disconnectedAt = w.clock()
571 disconnections := w.disconnections
572 w.timer = time.AfterFunc(whatsappNoticeDelay, func() {
573 w.disconnectedLong(disconnections)
582 // close ends the connection and the timer of the notice, and stops all notices.
583 func (w *WhatsApp) close() {
602 // loggedOut logs the open batches, deletes the session after a logout from the
603 // phone, notes it in the log of l, and tells all clients one time.
604 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
609 w.logger.Error("logged out by the phone, run /whatsapp pair PHONE")
611 err := w.inbox.deliver(ctx, l, w.link(), true)
616 err = w.removeSession()
618 w.logger.Error("session delete failed", "err", err)
621 err = l.note("WhatsApp was unlinked from the phone.")
623 w.logger.Error("chat note failed", "err", err)
626 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
631 // unlink logs the open batches, logs out the linked device, and deletes the
632 // session. When the logout call fails, as it does while WhatsApp is
633 // disconnected, the session is deleted all the same, and answer tells the user
634 // to remove the device in the phone. Its error is one of the log or the state
636 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
644 answer("WhatsApp is not linked.")
649 err := w.inbox.deliver(ctx, l, w.link(), true)
657 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
660 logoutErr = client.Logout(ctx)
663 err = w.removeSession()
665 answer("The unlink failed: " + w.redact(err.Error()))
670 w.logger.Info("unlinked")
672 err = l.note("WhatsApp is unlinked.")
674 w.logger.Error("chat note failed", "err", err)
677 if client == nil || logoutErr != nil {
678 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.")
683 answer("WhatsApp is unlinked.")
688 // removeSession ends the connection, closes the session database, and deletes
689 // its files. The session lock covers the cleanup after mutex is released, so a
690 // snapshot or a new session cannot open files that cleanup removes.
691 func (w *WhatsApp) removeSession() error {
692 w.sessionMutex.Lock()
693 defer w.sessionMutex.Unlock()
703 w.disconnectedAt = time.Time{}
709 container := w.container
714 w.inbox.stopCatchup()
722 if container != nil {
723 err = container.Close()
726 for _, suffix := range []string{"", "-wal", "-shm"} {
727 removeErr := os.Remove(w.sessionPath() + suffix)
728 if !errors.Is(removeErr, os.ErrNotExist) {
729 err = errors.Join(err, removeErr)
736 // pair links a new device to the account of phone with a pairing code. It gives
737 // the steps and the code to answer, and then the end of the pairing: the linked
738 // number, an expired code, or a failure. A pairing that a new one ends gives no
739 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
740 // The client of a pairing that does not link is disconnected.
742 // ctx limits the pairing, but the connection uses runCtx, the context of Run.
743 // The library keeps the context of the connection for its keep-alive, its event
744 // handler, and its reconnections, and after the link the server ends the stream
745 // and the library connects again. With ctx, the end of the pairing would stop
746 // that reconnection, and the linked device would never connect.
747 func (w *WhatsApp) pair(ctx, runCtx context.Context, l *TurnLoop, phone string, answer func(text string)) {
748 device, err := w.newDevice(ctx)
750 answer("The pairing failed: " + err.Error())
755 client := w.newClient(device, w.handle)
763 qr, err := client.GetQRChannel(ctx)
765 err = client.ConnectContext(runCtx)
769 answer("The connection to WhatsApp failed: " + err.Error())
775 case item, open := <-qr:
776 if !open || item.Event != whatsmeow.QRChannelEventCode {
777 answer("WhatsApp did not start the pairing. Try again later.")
782 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
783 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
789 // The server accepts only a display name of the form "Browser (OS)"
790 // with a common browser and OS, and refuses the pairing otherwise.
791 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
793 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
798 answer(whatsappPairSteps)
802 var item whatsmeow.QRChannelItem
806 case item, open = <-qr:
808 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
809 answer(whatsappPairExpired)
816 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
817 answer(whatsappPairExpired)
820 case item.Event == whatsmeow.QRChannelEventCode:
822 case item.Event == whatsmeow.QRChannelSuccess.Event:
826 w.logger.Info("linked")
828 err = l.note("WhatsApp is linked.")
830 w.logger.Error("chat note failed", "err", err)
833 answer("WhatsApp is linked to +" + phone + ".")
837 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
844 // newDevice returns a new device in the session database. It makes the
845 // directory and the file of the session first, with their modes, when they do
847 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
848 w.sessionMutex.Lock()
849 defer w.sessionMutex.Unlock()
852 defer w.mutex.Unlock()
854 if w.container == nil {
855 err := os.MkdirAll(w.dir, 0o700)
857 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
860 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
862 return nil, fmt.Errorf("create WhatsApp session: %w", err)
867 return nil, fmt.Errorf("create WhatsApp session: %w", err)
870 err = w.openSession(ctx)
876 w.device = w.container.NewDevice()
881 // linkedBy makes client the client of the linked device.
882 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
884 defer w.mutex.Unlock()
890 // handle takes one event of the library and tells if it was handled. A message
891 // goes to the inbox. The names of the groups follow the events of the groups. A
892 // connection starts a catch-up of the inbox, which ends at OfflineSyncCompleted
893 // or after whatsappCatchupLimit. A disconnection keeps the time of its start
894 // while Run or the library tries again. After whatsappNoticeDelay of a
895 // disconnection, all clients get one notice, and they get one more when the
896 // connection comes back. A disconnection that the library does not try again
897 // gives a notice at once.
899 // The log of the daemon gets one line for each change of the connection of the
900 // linked device: connected, a failed first connection, a lost connection, and
901 // connected again with the length of the outage. The retries of the library and
902 // Run between them log nothing.
903 func (w *WhatsApp) handle(event any) bool {
909 switch event := event.(type) {
910 case *events.Message:
911 return w.inbox.receive(ctx, w.link(), event)
912 case *events.GroupInfo:
913 if event.Name != nil {
914 w.groups.set(event.JID.String(), event.Name.Name)
918 case *events.JoinedGroup:
919 w.groups.set(event.JID.String(), event.Name)
922 case *events.OfflineSyncCompleted:
926 case *events.Connected:
927 w.inbox.startCatchup()
930 var notice, line string
932 level := slog.LevelInfo
938 switch event := event.(type) {
939 case *events.PairSuccess:
940 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
941 case *events.Connected:
943 case !w.linked || w.connected:
944 case w.disconnectedAt.IsZero():
947 line = "connected again"
948 attrs = append(attrs, "after", w.clock().Sub(w.disconnectedAt))
953 w.connectedAt = w.clock()
960 notice = "WhatsApp is connected again."
962 case *events.Disconnected:
963 connected := w.connected
965 level = slog.LevelWarn
966 line = "disconnected, retrying"
968 line = "first connect failed, retrying"
971 case *events.LoggedOut:
974 case w.logouts <- struct{}{}:
977 case events.PermanentDisconnect:
982 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
983 level = slog.LevelError
984 line = "disconnected for good, restart to retry"
985 attrs = append(attrs, "err", whatsappRedact(w.own, event.PermanentDisconnectDescription()))
996 w.logger.Log(ctx, level, line, attrs...)
1006 // disconnectedLong gives the notice of a long disconnection, unless the
1007 // disconnection with the number disconnections ended.
1008 func (w *WhatsApp) disconnectedLong(disconnections int) {
1011 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
1016 since := w.disconnectedAt
1020 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
1024 // broadcast gives text as a notice to all clients.
1025 func (w *WhatsApp) broadcast(text string) {
1032 if notify != nil && !closed {
1040 // redact replaces the own number and the own LID in text with OWN.
1041 func (w *WhatsApp) redact(text string) string {
1043 defer w.mutex.Unlock()
1045 return whatsappRedact(w.own, text)
1048 // WhatsAppLink is a copy of the link of the device at one time, for the parts
1049 // of WhatsApp that do not own it: the groups, the batches, find, and send.
1050 type WhatsAppLink struct {
1052 device *store.Device
1053 client WhatsAppClient
1058 // WhatsAppRequest is a pair or unlink command for Run, with the function that
1059 // gives its answers to the client that asked. A pairing has the phone number.
1060 type WhatsAppRequest struct {
1063 answer func(text string)
1066 // whatsappSetDeviceProps sets the device properties that the library sends at
1067 // the pairing. They are global values of the library, so the daemon sets them
1068 // once before any client exists. The phone shows the linked device with the
1069 // name OneChat and a desktop icon only when the platform type is known.
1070 func whatsappSetDeviceProps() {
1071 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
1073 store.DeviceProps.PlatformType = waCompanionReg.DeviceProps_DESKTOP.Enum()
1076 // whatsappNewClient returns the client of the library for device, with handle
1077 // as its event handler. Run owns failed starting connections of linked devices,
1078 // so only an unlinked device enables the initial retry of the library for
1079 // pairing. The library still retries a lost connection. The client acknowledges
1080 // a message only after handle returns true, and downloads no old history.
1081 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
1082 client := whatsmeow.NewClient(device, waLog.Noop)
1083 client.InitialAutoReconnect = device.ID == nil
1084 client.SynchronousAck = true
1085 client.ManualHistorySyncDownload = true
1086 client.AddEventHandlerWithSuccessStatus(handle)
1091 // whatsappContactName returns the name of the person jid: the full name, the
1092 // first name, the business name, or the push name of the contact in the session
1093 // of device, then push, the push name of a message, then the phone number. A
1094 // LID gets its phone number from the LID map of the session.
1095 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
1097 candidates := []types.JID{jid}
1098 phone := types.EmptyJID
1100 case types.DefaultUserServer:
1102 case types.HiddenUserServer:
1103 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
1104 if err == nil && !mapped.IsEmpty() {
1106 candidates = append(candidates, mapped)
1110 for _, candidate := range candidates {
1111 contact, err := device.Contacts.GetContact(ctx, candidate)
1112 if err != nil || !contact.Found {
1116 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
1126 case !phone.IsEmpty():
1127 return "+" + phone.User
1133 // whatsappOwnIDs returns the own number and the own LID that are not empty.
1134 func whatsappOwnIDs(ids ...string) []string {
1137 for _, id := range ids {
1139 own = append(own, id)
1146 // whatsappRedact replaces each of the own IDs own in text with OWN.
1147 func whatsappRedact(own []string, text string) string {
1148 for _, id := range own {
1149 text = strings.ReplaceAll(text, id, "OWN")
1155 // whatsappSessionAddress returns the SQLite address of the session database at
1156 // path, with foreign keys on, as the library needs, and a wait for a busy
1158 func whatsappSessionAddress(path string) (string, error) {
1159 path, err := filepath.Abs(path)
1161 return "", fmt.Errorf("find WhatsApp session: %w", err)
1167 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
1170 return address.String(), nil
1173 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
1174 // command, or false for any other line.
1175 func whatsappCommandArgs(line string) (string, bool) {
1176 line = strings.TrimSpace(line)
1177 if line == whatsappCommand {
1181 args, found := strings.CutPrefix(line, whatsappCommand+" ")
1186 return strings.TrimSpace(args), true
1189 // whatsappPhone returns the digits of phone, a number with its country code and
1190 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
1191 // digits, with no 0 first.
1192 func whatsappPhone(phone string) (string, bool) {
1193 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
1194 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
1199 // whatsappItemError returns the error of a pairing item that is not a code, a
1200 // success, or a timeout.
1201 func whatsappItemError(item whatsmeow.QRChannelItem) string {
1202 if item.Error != nil {
1203 return item.Error.Error()