19 "go.mau.fi/whatsmeow/proto/waCompanionReg"
20 "go.mau.fi/whatsmeow/proto/waE2E"
21 "go.mau.fi/whatsmeow/store"
22 "go.mau.fi/whatsmeow/store/sqlstore"
23 "go.mau.fi/whatsmeow/types"
24 "go.mau.fi/whatsmeow/types/events"
25 waLog "go.mau.fi/whatsmeow/util/log"
26 // The session store of the library opens SQLite with this pure Go
28 _ "modernc.org/sqlite"
32 // whatsappDirName is the directory of the WhatsApp files in the data
34 whatsappDirName = "whatsapp"
36 // whatsappSessionFileName is the session database of the library in
38 whatsappSessionFileName = "session.db"
40 // whatsappCommand starts the input lines of the WhatsApp commands, such
41 // as "/whatsapp status".
42 whatsappCommand = "/whatsapp"
44 // whatsappUsage is the answer to a WhatsApp command that does not
46 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."
48 // whatsappPairSteps tells the user what to do with the pairing code,
49 // which comes in the next message.
50 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."
52 // whatsappPairExpired is the answer when the pairing code expires.
53 whatsappPairExpired = "The pairing code expired. Run /whatsapp pair PHONE again for a new code."
55 // whatsappTimeLayout is the layout of the times in the answers.
56 whatsappTimeLayout = "2006-01-02 15:04"
58 // whatsappPairTimeout is the longest time of a pairing. The library
59 // closes the pairing connection after about 160 seconds.
60 whatsappPairTimeout = 3 * time.Minute
62 // whatsappLogoutTimeout is the longest time of the logout call of an
64 whatsappLogoutTimeout = 30 * time.Second
66 // whatsappOutageNoticeDelay is the delay from a disconnection to its
67 // notice to the user.
68 whatsappOutageNoticeDelay = 10 * time.Minute
70 // whatsappRetryDelay is the first wait after a failed starting
72 whatsappRetryDelay = 2 * time.Second
74 // whatsappRetryLimit is the longest wait between starting connections.
75 whatsappRetryLimit = 5 * time.Minute
77 // whatsappRequests is the number of pair and unlink commands that can
81 // whatsappNotLinked is the answer of a WhatsApp tool without a link.
82 whatsappNotLinked = "WhatsApp is not linked. Tell the user to run /whatsapp pair PHONE in the terminal or in Telegram."
85 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
86 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
88 type WhatsAppClient interface {
89 ConnectContext(ctx context.Context) error
91 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
92 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
93 Logout(ctx context.Context) error
94 GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error)
95 Download(ctx context.Context, message whatsmeow.DownloadableMessage) ([]byte, error)
96 Upload(ctx context.Context, data []byte, mediaType whatsmeow.MediaType) (whatsmeow.UploadResponse, error)
97 GenerateMessageID() types.MessageID
98 SendMessage(ctx context.Context, to types.JID, message *waE2E.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error)
101 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
102 // the session file, WhatsApp is not linked. The session gives full access to
103 // the account, so a file that another user can read is an error. The clock
104 // gives the times of the status, logger gets the failures, and newClient makes
105 // the client of a device with its event handler.
106 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 requests: make(chan WhatsAppRequest, whatsappRequests),
114 logouts: make(chan struct{}, 1),
115 groups: newWhatsAppGroups(logger),
120 w.state, err = openWhatsAppState(filepath.Join(w.dir, whatsappStateFileName))
125 w.inbox = newWhatsAppInbox(w.state, clock, w.groups, &ImageStore{dir: filepath.Join(dir, imageDirName)}, logger)
127 info, err := os.Stat(w.sessionPath())
128 if errors.Is(err, os.ErrNotExist) {
133 return nil, fmt.Errorf("read WhatsApp session: %w", err)
136 if info.Mode().Perm()&0o077 != 0 {
137 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
140 err = w.openSession(ctx)
145 if w.device.ID != nil {
147 w.inbox.waitForCatchup()
149 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
155 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as a
156 // linked device. The session database of the library in dir holds the keys of
157 // the device. Run keeps a linked device connected, and the library connects
158 // again by itself after a network failure.
160 // The commands pair and unlink go to Run as requests, and Run runs one at a
161 // time. A pairing runs in its own goroutine until its code expires, and a new
162 // pairing ends the one before. Its phone number and code go only to the answer
163 // of the client that asked. A logout from the phone comes as an event of the
164 // library, and Run deletes the session. The mutex protects the session, the
165 // client, and the state of the connection, which the event handler of the
166 // library changes from its own goroutines. The sessionMutex serializes session
167 // creation, close, removal, and snapshots. It is held before mutex, and stays
168 // held when removal releases mutex for client callbacks.
170 // ctx is the caller context until Run sets its context for library callbacks.
171 // The mutex protects it, so callbacks follow daemon cancellation.
173 // The inbox puts messages into batches and logs them, and groups holds the
174 // names of the groups. Both get a WhatsAppLink from link for each call, so they
175 // use the current device and client.
177 // The library logs nothing, because its log lines hold the ID of the own
178 // account, which is the phone number of the user. The own number and the own
179 // LID never go to the log of the agent or to the log of the daemon: redact
180 // removes them from the errors, and a batch shows the messages of the user as
181 // You and a mention of the user as @you. The IDs of the other chats go to the
182 // log, and those of private chats hold phone numbers, because the agent needs
184 type WhatsApp struct {
187 clock func() time.Time
189 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
190 requests chan WhatsAppRequest
191 logouts chan struct{}
193 groups *WhatsAppGroups
197 sessionMutex sync.Mutex
199 container *sqlstore.Container
201 client WhatsAppClient
207 connectedAt time.Time
208 disconnectedAt time.Time
215 // Run connects a linked device, logs the closed batches in l, runs the pair and
216 // unlink commands, and handles a logout from the phone, until ctx ends. Its
217 // notes go to the log of l, and notify gets the notices for all clients. A
218 // failed first connection starts the same outage notice as a lost connection. A
219 // timer in the select retries it with a doubled wait from 2 seconds to 5
220 // minutes, without a retry goroutine or a wait that blocks commands or the
221 // inbox. A connection, unlink, logout, or ctx end stops retries. The library
222 // owns retries after a connection opens. Run returns the error of a write of
223 // the log or of the state file, which stops the daemon, because then messages
225 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) error {
234 timer := time.NewTimer(whatsappRetryDelay)
238 var retry <-chan time.Time
240 delay := whatsappRetryDelay
247 delay = min(2*delay, whatsappRetryLimit)
251 stopRetry := func() {
262 var pairing sync.WaitGroup
276 err := w.inbox.deliver(ctx, l, w.link(), false)
284 case err = <-w.inbox.failures:
287 case <-w.inbox.due():
293 err = w.loggedOut(ctx, l)
297 case request := <-w.requests:
307 err = w.unlink(ctx, l, request.answer)
312 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
314 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTimeout)
319 w.pair(pairCtx, ctx, l, request.phone, request.answer)
326 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
327 // each answer to answer. The answers go only to the client that sent the
329 func (w *WhatsApp) Command(args string, answer func(text string)) {
330 fields := strings.Fields(args)
331 request := WhatsAppRequest{
336 case len(fields) == 1 && fields[0] == "status":
340 case len(fields) == 1 && fields[0] == "unlink":
341 request.unlink = true
342 case len(fields) >= 2 && fields[0] == "pair":
343 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
345 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
350 request.phone = phone
352 answer(whatsappUsage)
358 case w.requests <- request:
360 answer("Too many WhatsApp commands wait. Try again in a minute.")
364 // Status returns the state of the link: not linked, linked and connected, or
365 // linked and disconnected, with the times of the connection and the routes.
366 // Route source IDs can hold the phone numbers of other chats.
367 func (w *WhatsApp) Status() string {
369 defer w.mutex.Unlock()
373 listed := w.routes.List()
374 if listed != "No routes." {
375 routes = "\nWhatsApp routes:\n" + listed
381 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it." + routes
383 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "." + routes
384 case w.disconnectedAt.IsZero():
385 return "WhatsApp is linked and not connected yet." + routes
386 case w.connectedAt.IsZero():
387 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "." + routes
389 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "." + routes
393 // BackupSession writes a consistent SQLite snapshot to path while the session
394 // cannot be created, closed, or removed. The source opens without creation
395 // permission. No session file means no linked state to copy.
396 func (w *WhatsApp) BackupSession(ctx context.Context, path string) (err error) {
397 w.sessionMutex.Lock()
398 defer w.sessionMutex.Unlock()
401 defer w.mutex.Unlock()
403 _, err = os.Stat(w.sessionPath())
404 if errors.Is(err, os.ErrNotExist) {
409 return fmt.Errorf("read session file: %w", err)
412 err = os.MkdirAll(filepath.Dir(path), 0o700)
414 return fmt.Errorf("create session snapshot directory: %w", err)
417 address, err := whatsappSessionAddress(w.sessionPath())
419 return fmt.Errorf("find session database: %w", err)
422 database, err := sql.Open("sqlite", address+"&mode=rw")
424 return fmt.Errorf("open session snapshot source: %w", err)
428 err = errors.Join(err, database.Close())
431 _, err = database.ExecContext(ctx, "VACUUM INTO ?", path)
433 return fmt.Errorf("snapshot session database: %w", err)
436 err = os.Chmod(path, 0o600)
438 return fmt.Errorf("set session snapshot mode: %w", err)
444 // Close closes the session database.
445 func (w *WhatsApp) Close() error {
446 w.sessionMutex.Lock()
447 defer w.sessionMutex.Unlock()
450 defer w.mutex.Unlock()
452 if w.container == nil {
456 err := w.container.Close()
462 // Find returns the answer of whatsapp_find for name, as whatsappFind says.
463 func (w *WhatsApp) Find(ctx context.Context, name string) (string, error) {
464 return whatsappFind(ctx, w.link(), w.groups, name)
467 // Send returns the answer of whatsapp_send for text and an optional stored
468 // image to chat, with the durable send id that whatsappSend describes.
469 func (w *WhatsApp) Send(ctx context.Context, id, chat, text, image string) (string, error) {
470 return whatsappSend(ctx, w.link(), w.groups, w.state, w.inbox.images, w.logger, w.clock, id, chat, text, image)
473 func (w *WhatsApp) sessionPath() string {
474 return filepath.Join(w.dir, whatsappSessionFileName)
477 // openSession opens the session database and its first device. The caller holds
478 // the mutex, or no other goroutine uses w yet.
479 func (w *WhatsApp) openSession(ctx context.Context) error {
480 address, err := whatsappSessionAddress(w.sessionPath())
485 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
487 return fmt.Errorf("open WhatsApp session: %w", err)
490 device, err := container.GetFirstDevice(ctx)
492 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
495 w.container = container
501 func (w *WhatsApp) isLinked() bool {
503 defer w.mutex.Unlock()
508 // link returns a copy of the link of the device: whether it is linked, the
509 // device, the client, whether it is connected, and the own IDs.
510 func (w *WhatsApp) link() WhatsAppLink {
512 defer w.mutex.Unlock()
518 connected: w.connected,
519 own: slices.Clone(w.own),
523 // connect tries the starting connection of the linked device with one client.
524 // It returns whether Run must retry. A failed call starts the shared outage
525 // state and logs its redacted cause once, because a returned ConnectContext
526 // error does not emit Disconnected. Connected logs recovery after
528 func (w *WhatsApp) connect(ctx context.Context) bool {
531 if ctx.Err() != nil || !w.linked || !w.retrying || w.closed {
538 w.client = w.newClient(w.device, w.handle)
544 err := client.ConnectContext(ctx)
548 if err == nil || ctx.Err() != nil || !w.retrying || !w.linked {
555 first := w.startOutage()
556 cause := whatsappRedact(w.own, err.Error())
560 w.logger.Warn("first connect failed, retrying", "err", cause)
566 // startOutage starts the shared outage time and notice timer once. The caller
567 // holds the mutex. Its result tells whether this is the first failure.
568 func (w *WhatsApp) startOutage() bool {
569 first := w.linked && (w.connected || w.disconnectedAt.IsZero())
571 w.disconnectedAt = w.clock()
573 disconnections := w.disconnections
574 w.timer = time.AfterFunc(whatsappOutageNoticeDelay, func() {
575 w.disconnectedLong(disconnections)
584 // close ends the connection and the timer of the notice, and stops all notices.
585 func (w *WhatsApp) close() {
604 // loggedOut logs the open batches, deletes the session after a logout from the
605 // phone, notes it in the log of l, and tells all clients one time.
606 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
611 w.logger.Error("logged out by the phone, run /whatsapp pair PHONE")
613 err := w.inbox.deliver(ctx, l, w.link(), true)
618 err = w.removeSession()
620 w.logger.Error("session delete failed", "err", err)
623 err = l.note("WhatsApp was unlinked from the phone.")
625 w.logger.Error("chat note failed", "err", err)
628 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
633 // unlink logs the open batches, logs out the linked device, and deletes the
634 // session. When the logout call fails, as it does while WhatsApp is
635 // disconnected, the session is deleted all the same, and answer tells the user
636 // to remove the device in the phone. Its error is one of the log or the state
638 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
646 answer("WhatsApp is not linked.")
651 err := w.inbox.deliver(ctx, l, w.link(), true)
659 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTimeout)
662 logoutErr = client.Logout(ctx)
665 err = w.removeSession()
667 answer("The unlink failed: " + w.redact(err.Error()))
672 w.logger.Info("unlinked")
674 err = l.note("WhatsApp is unlinked.")
676 w.logger.Error("chat note failed", "err", err)
679 if client == nil || logoutErr != nil {
680 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.")
685 answer("WhatsApp is unlinked.")
690 // removeSession ends the connection, closes the session database, and deletes
691 // its files. The session lock covers the cleanup after mutex is released, so a
692 // snapshot or a new session cannot open files that cleanup removes.
693 func (w *WhatsApp) removeSession() error {
694 w.sessionMutex.Lock()
695 defer w.sessionMutex.Unlock()
705 w.disconnectedAt = time.Time{}
711 container := w.container
716 w.inbox.stopCatchup()
724 if container != nil {
725 err = container.Close()
728 for _, suffix := range []string{"", "-wal", "-shm"} {
729 removeErr := os.Remove(w.sessionPath() + suffix)
730 if !errors.Is(removeErr, os.ErrNotExist) {
731 err = errors.Join(err, removeErr)
738 // pair links a new device to the account of phone with a pairing code. It gives
739 // the steps and the code to answer, and then the end of the pairing: the linked
740 // number, an expired code, or a failure. A pairing that a new one ends gives no
741 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
742 // The client of a pairing that does not link is disconnected.
744 // ctx limits the pairing, but the connection uses runCtx, the context of Run.
745 // The library keeps the context of the connection for its keep-alive, its event
746 // handler, and its reconnections, and after the link the server ends the stream
747 // and the library connects again. With ctx, the end of the pairing would stop
748 // that reconnection, and the linked device would never connect.
749 func (w *WhatsApp) pair(ctx, runCtx context.Context, l *TurnLoop, phone string, answer func(text string)) {
750 device, err := w.newDevice(ctx)
752 answer("The pairing failed: " + err.Error())
757 client := w.newClient(device, w.handle)
765 qr, err := client.GetQRChannel(ctx)
767 err = client.ConnectContext(runCtx)
771 answer("The connection to WhatsApp failed: " + err.Error())
777 case item, open := <-qr:
778 if !open || item.Event != whatsmeow.QRChannelEventCode {
779 answer("WhatsApp did not start the pairing. Try again later.")
784 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
785 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
791 // The server accepts only a display name of the form "Browser (OS)"
792 // with a common browser and OS, and refuses the pairing otherwise.
793 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
795 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
800 answer(whatsappPairSteps)
804 var item whatsmeow.QRChannelItem
808 case item, open = <-qr:
810 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
811 answer(whatsappPairExpired)
818 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
819 answer(whatsappPairExpired)
822 case item.Event == whatsmeow.QRChannelEventCode:
824 case item.Event == whatsmeow.QRChannelSuccess.Event:
828 w.logger.Info("linked")
830 err = l.note("WhatsApp is linked.")
832 w.logger.Error("chat note failed", "err", err)
835 answer("WhatsApp is linked to +" + phone + ".")
839 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
846 // newDevice returns a new device in the session database. It makes the
847 // directory and the file of the session first, with their modes, when they do
849 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
850 w.sessionMutex.Lock()
851 defer w.sessionMutex.Unlock()
854 defer w.mutex.Unlock()
856 if w.container == nil {
857 err := os.MkdirAll(w.dir, 0o700)
859 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
862 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
864 return nil, fmt.Errorf("create WhatsApp session: %w", err)
869 return nil, fmt.Errorf("create WhatsApp session: %w", err)
872 err = w.openSession(ctx)
878 w.device = w.container.NewDevice()
883 // linkedBy makes client the client of the linked device.
884 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
886 defer w.mutex.Unlock()
892 // handle takes one event of the library and tells if it was handled. A message
893 // goes to the inbox. The names of the groups follow the events of the groups. A
894 // connection starts a catch-up of the inbox, which ends at OfflineSyncCompleted
895 // or after whatsappCatchupTimeout. A disconnection keeps the time of its start
896 // while Run or the library tries again. After whatsappOutageNoticeDelay of a
897 // disconnection, all clients get one notice, and they get one more when the
898 // connection comes back. A disconnection that the library does not try again
899 // gives a notice at once.
901 // The log of the daemon gets one line for each change of the connection of the
902 // linked device: connected, a failed first connection, a lost connection, and
903 // connected again with the length of the outage. The retries of the library and
904 // Run between them log nothing.
905 func (w *WhatsApp) handle(event any) bool {
911 switch event := event.(type) {
912 case *events.Message:
913 return w.inbox.receive(ctx, w.link(), event)
914 case *events.GroupInfo:
915 if event.Name != nil {
916 w.groups.set(event.JID.String(), event.Name.Name)
920 case *events.JoinedGroup:
921 w.groups.set(event.JID.String(), event.Name)
924 case *events.OfflineSyncCompleted:
928 case *events.Connected:
929 w.inbox.startCatchup()
932 var notice, line string
934 level := slog.LevelInfo
940 switch event := event.(type) {
941 case *events.PairSuccess:
942 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
943 case *events.Connected:
945 case !w.linked || w.connected:
946 case w.disconnectedAt.IsZero():
949 line = "connected again"
950 attrs = append(attrs, "after", w.clock().Sub(w.disconnectedAt))
955 w.connectedAt = w.clock()
962 notice = "WhatsApp is connected again."
964 case *events.Disconnected:
965 connected := w.connected
967 level = slog.LevelWarn
968 line = "disconnected, retrying"
970 line = "first connect failed, retrying"
973 case *events.LoggedOut:
976 case w.logouts <- struct{}{}:
979 case events.PermanentDisconnect:
984 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
985 level = slog.LevelError
986 line = "disconnected for good, restart to retry"
987 attrs = append(attrs, "err", whatsappRedact(w.own, event.PermanentDisconnectDescription()))
998 w.logger.Log(ctx, level, line, attrs...)
1008 // disconnectedLong gives the notice of a long disconnection, unless the
1009 // disconnection with the number disconnections ended.
1010 func (w *WhatsApp) disconnectedLong(disconnections int) {
1013 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
1018 since := w.disconnectedAt
1022 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
1026 // broadcast gives text as a notice to all clients.
1027 func (w *WhatsApp) broadcast(text string) {
1034 if notify != nil && !closed {
1042 // redact replaces the own number and the own LID in text with OWN.
1043 func (w *WhatsApp) redact(text string) string {
1045 defer w.mutex.Unlock()
1047 return whatsappRedact(w.own, text)
1050 // WhatsAppLink is a copy of the link of the device at one time, for the parts
1051 // of WhatsApp that do not own it: the groups, the batches, find, and send.
1052 type WhatsAppLink struct {
1054 device *store.Device
1055 client WhatsAppClient
1060 // WhatsAppRequest is a pair or unlink command for Run, with the function that
1061 // gives its answers to the client that asked. A pairing has the phone number.
1062 type WhatsAppRequest struct {
1065 answer func(text string)
1068 // whatsappSetDeviceProps sets the device properties that the library sends at
1069 // the pairing. They are global values of the library, so the daemon sets them
1070 // once before any client exists. The phone shows the linked device with the
1071 // name OneChat and a desktop icon only when the platform type is known.
1072 func whatsappSetDeviceProps() {
1073 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
1075 store.DeviceProps.PlatformType = waCompanionReg.DeviceProps_DESKTOP.Enum()
1078 // whatsappNewClient returns the client of the library for device, with handle
1079 // as its event handler. Run owns failed starting connections of linked devices,
1080 // so only an unlinked device enables the initial retry of the library for
1081 // pairing. The library still retries a lost connection. The client acknowledges
1082 // a message only after handle returns true, and downloads no old history.
1083 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
1084 client := whatsmeow.NewClient(device, waLog.Noop)
1085 client.InitialAutoReconnect = device.ID == nil
1086 client.SynchronousAck = true
1087 client.ManualHistorySyncDownload = true
1088 client.AddEventHandlerWithSuccessStatus(handle)
1093 // whatsappContactName returns the name of the person jid: the full name, the
1094 // first name, the business name, or the push name of the contact in the session
1095 // of device, then push, the push name of a message, then the phone number. A
1096 // LID gets its phone number from the LID map of the session.
1097 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
1099 candidates := []types.JID{jid}
1100 phone := types.EmptyJID
1102 case types.DefaultUserServer:
1104 case types.HiddenUserServer:
1105 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
1106 if err == nil && !mapped.IsEmpty() {
1108 candidates = append(candidates, mapped)
1112 for _, candidate := range candidates {
1113 contact, err := device.Contacts.GetContact(ctx, candidate)
1114 if err != nil || !contact.Found {
1118 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
1128 case !phone.IsEmpty():
1129 return "+" + phone.User
1135 // whatsappOwnIDs returns the own number and the own LID that are not empty.
1136 func whatsappOwnIDs(ids ...string) []string {
1139 for _, id := range ids {
1141 own = append(own, id)
1148 // whatsappChatHash returns a short hash of chat for the daemon log, so that a
1149 // log line can tell chats apart without a phone number.
1150 func whatsappChatHash(chat types.JID) string {
1151 digest := sha256.Sum256([]byte(chat.ToNonAD().String()))
1153 return fmt.Sprintf("%x", digest[:6])
1156 // whatsappRedact replaces each of the own IDs own in text with OWN.
1157 func whatsappRedact(own []string, text string) string {
1158 for _, id := range own {
1159 text = strings.ReplaceAll(text, id, "OWN")
1165 // whatsappSessionAddress returns the SQLite address of the session database at
1166 // path, with foreign keys on, as the library needs, and a wait for a busy
1168 func whatsappSessionAddress(path string) (string, error) {
1169 path, err := filepath.Abs(path)
1171 return "", fmt.Errorf("find WhatsApp session: %w", err)
1177 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
1180 return address.String(), nil
1183 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
1184 // command, or false for any other line.
1185 func whatsappCommandArgs(line string) (string, bool) {
1186 line = strings.TrimSpace(line)
1187 if line == whatsappCommand {
1191 args, found := strings.CutPrefix(line, whatsappCommand+" ")
1196 return strings.TrimSpace(args), true
1199 // whatsappPhone returns the digits of phone, a number with its country code and
1200 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
1201 // digits, with no 0 first.
1202 func whatsappPhone(phone string) (string, bool) {
1203 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
1204 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
1209 // whatsappItemError returns the error of a pairing item that is not a code, a
1210 // success, or a timeout.
1211 func whatsappItemError(item whatsmeow.QRChannelItem) string {
1212 if item.Error != nil {
1213 return item.Error.Error()