17 "go.mau.fi/whatsmeow/store"
18 "go.mau.fi/whatsmeow/store/sqlstore"
19 "go.mau.fi/whatsmeow/types"
20 "go.mau.fi/whatsmeow/types/events"
21 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 // whatsappSource is the source of the work events of the batches.
72 whatsappSource = "whatsapp"
74 // whatsappLookupTime is the longest time of a read of the names in the
75 // session database or of the groups from WhatsApp.
76 whatsappLookupTime = 10 * time.Second
78 // whatsappGroupsRefresh is the shortest time between two reads of the
79 // groups from WhatsApp for a group with no name.
80 whatsappGroupsRefresh = time.Minute
82 // whatsappUnknownGroup is the name of a group whose name is not known.
83 whatsappUnknownGroup = "A group with no known name"
86 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
87 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
89 type WhatsAppClient interface {
90 ConnectContext(ctx context.Context) error
92 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
93 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
94 Logout(ctx context.Context) error
95 GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, error)
98 // openWhatsApp opens the WhatsApp session in the data directory dir. Without
99 // the session file, WhatsApp is not linked. The session gives full access to
100 // the account, so a file that another user can read is an error. The clock
101 // gives the times of the status, logger gets the failures, and newClient makes
102 // the client of a device with its event handler.
103 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) {
105 dir: filepath.Join(dir, whatsappDirName),
108 newClient: newClient,
109 noticeDelay: whatsappNoticeDelay,
110 requests: make(chan WhatsAppRequest, whatsappRequests),
111 logouts: make(chan struct{}, 1),
112 wake: make(chan struct{}, 1),
113 failures: make(chan error, 1),
114 groupNames: make(map[string]string),
118 w.batches, err = openWhatsAppBatches(filepath.Join(w.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
123 info, err := os.Stat(w.sessionPath())
124 if errors.Is(err, os.ErrNotExist) {
129 return nil, fmt.Errorf("read WhatsApp session: %w", err)
132 if info.Mode().Perm()&0o077 != 0 {
133 return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName))
136 err = w.openSession(ctx)
141 if w.device.ID != nil {
143 w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User)
149 // WhatsApp is the link of the daemon to the WhatsApp account of the user, as a
150 // linked device. The session database of the library in dir holds the keys of
151 // the device. Run keeps a linked device connected, and the library connects
152 // again by itself after a network failure.
154 // The commands pair and unlink go to Run as requests, and Run runs one at a
155 // time. A pairing runs in its own goroutine until its code expires, and a new
156 // pairing ends the one before. Its phone number and code go only to the answer
157 // of the client that asked. A logout from the phone comes as an event of the
158 // library, and Run deletes the session. The mutex protects the session, the
159 // client, and the state of the connection, which the event handler of the
160 // library changes from its own goroutines.
162 // The text messages go into batches, one chat at a time, as WhatsAppBatches
163 // says. Run logs each closed batch as a work message that starts with
164 // [WhatsApp], and a batch that needs the user wakes the turn loop. The event
165 // handler acknowledges a message only after the state file holds it, so the
166 // servers send again a message that a crash lost. A batch leaves the state file
167 // only after its work message is durable in the log. A crash between the two
168 // makes the batch repeat once.
170 // The library logs nothing, because its log lines hold the ID of the own
171 // account, which is the phone number of the user. The own number and the own
172 // LID never go to the log of the agent or to the log of the daemon: redact
173 // removes them from the errors, and a batch shows the messages of the user as
174 // You and a mention of the user as @you. The IDs of the other chats go to the
175 // log, and those of private chats hold phone numbers, because the agent needs
177 type WhatsApp struct {
179 clock func() time.Time
181 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
182 noticeDelay time.Duration
183 requests chan WhatsAppRequest
184 logouts chan struct{}
187 batches *WhatsAppBatches
190 container *sqlstore.Container
192 client WhatsAppClient
197 connectedAt time.Time
198 disconnectedAt time.Time
203 groupNames map[string]string
207 // Run connects a linked device, logs the closed batches in l, runs the pair and
208 // unlink commands, and handles a logout from the phone, until ctx ends. Its
209 // notes go to the log of l, and notify gets the notices for all clients. A
210 // failed first connection is logged, and the library tries again when the
211 // failure is one of the network. Run returns the error of a write of the log or
212 // of the state file, which stops the daemon, because then messages would be
214 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) error {
224 var pairing sync.WaitGroup
233 err := w.deliver(ctx, l)
238 var due <-chan time.Time
239 wait, open := w.batches.Wait(time.Now())
241 due = time.After(wait)
247 case err = <-w.failures:
252 err = w.loggedOut(ctx, l)
256 case request := <-w.requests:
263 err = w.unlink(ctx, l, request.answer)
268 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
270 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
275 w.pair(pairCtx, l, request.phone, request.answer)
282 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
283 // each answer to answer. The answers go only to the client that sent the
285 func (w *WhatsApp) Command(args string, answer func(text string)) {
286 fields := strings.Fields(args)
287 request := WhatsAppRequest{
292 case len(fields) == 1 && fields[0] == "status":
295 case len(fields) == 1 && fields[0] == "unlink":
296 request.unlink = true
297 case len(fields) >= 2 && fields[0] == "pair":
298 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
300 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
304 request.phone = phone
306 answer(whatsappUsage)
311 case w.requests <- request:
313 answer("Too many WhatsApp commands wait. Try again in a minute.")
317 // Status returns the state of the link: not linked, linked and connected, or
318 // linked and disconnected, with the times of the connection. It never holds the
320 func (w *WhatsApp) Status() string {
322 defer w.mutex.Unlock()
326 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it."
328 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "."
329 case w.disconnectedAt.IsZero():
330 return "WhatsApp is linked and not connected yet."
331 case w.connectedAt.IsZero():
332 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "."
334 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "."
338 // Close closes the session database.
339 func (w *WhatsApp) Close() error {
341 defer w.mutex.Unlock()
343 if w.container == nil {
347 err := w.container.Close()
353 func (w *WhatsApp) sessionPath() string {
354 return filepath.Join(w.dir, whatsappSessionFileName)
357 // openSession opens the session database and its first device. The caller holds
358 // the mutex, or no other goroutine uses w yet.
359 func (w *WhatsApp) openSession(ctx context.Context) error {
360 address, err := whatsappSessionAddress(w.sessionPath())
365 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
367 return fmt.Errorf("open WhatsApp session: %w", err)
370 device, err := container.GetFirstDevice(ctx)
372 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
375 w.container = container
381 func (w *WhatsApp) isLinked() bool {
383 defer w.mutex.Unlock()
388 // connect makes the client of the linked device and connects it.
389 func (w *WhatsApp) connect(ctx context.Context) {
391 w.client = w.newClient(w.device, w.handle)
395 err := client.ConnectContext(ctx)
397 w.logger.Printf("connect: %s", w.redact(err.Error()))
401 // close ends the connection and the timer of the notice, and stops all notices.
402 func (w *WhatsApp) close() {
418 // loggedOut logs the open batches, deletes the session after a logout from the
419 // phone, notes it in the log of l, and tells all clients one time.
420 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
425 err := w.deliverAll(ctx, l)
430 err = w.removeSession()
432 w.logger.Printf("delete the session after the logout: %v", err)
435 err = l.note("WhatsApp was unlinked from the phone.")
437 w.logger.Printf("note the logout: %v", err)
440 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
445 // unlink logs the open batches, logs out the linked device, and deletes the
446 // session. When the logout call fails, as it does while WhatsApp is
447 // disconnected, the session is deleted all the same, and answer tells the user
448 // to remove the device in the phone. Its error is one of the log or the state
450 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
457 answer("WhatsApp is not linked.")
461 err := w.deliverAll(ctx, l)
468 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
471 logoutErr = client.Logout(ctx)
474 err = w.removeSession()
476 answer("The unlink failed: " + w.redact(err.Error()))
480 err = l.note("WhatsApp is unlinked.")
482 w.logger.Printf("note the unlink: %v", err)
485 if client == nil || logoutErr != nil {
486 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.")
490 answer("WhatsApp is unlinked.")
495 // deliver logs the closed batches in l in order, each as a work message of
496 // whatsappSource that wakes the loop when the batch starts a turn. A batch
497 // leaves the state file after its message is durable in the log. A group with
498 // no name gets its name from WhatsApp first.
499 func (w *WhatsApp) deliver(ctx context.Context, l *TurnLoop) error {
500 _, err := w.batches.CloseDue(time.Now())
505 for _, batch := range w.batches.Closed() {
506 if batch.Chat.Group && batch.Chat.Name == "" {
507 batch.Chat.Name = w.groupName(ctx, batch.Chat.ID)
510 _, err = l.Work(whatsappSource, batch.Text(w.clock().Location()), "", batch.Turn())
512 return fmt.Errorf("log a WhatsApp batch: %w", err)
515 // A stop of the daemon during the flush is no failure: the
516 // batch stays in the state file and repeats once at the next
519 if ctx.Err() != nil {
524 return fmt.Errorf("log a WhatsApp batch: %w", err)
527 err = w.batches.Remove(batch.Number)
536 // deliverAll closes every open batch and logs all of them.
537 func (w *WhatsApp) deliverAll(ctx context.Context, l *TurnLoop) error {
538 err := w.batches.CloseAll()
543 return w.deliver(ctx, l)
546 // groupName returns the name of the group id, or whatsappUnknownGroup. A group
547 // that is not in the names of the groups reads the groups from WhatsApp again,
548 // at most once in whatsappGroupsRefresh.
549 func (w *WhatsApp) groupName(ctx context.Context, id string) string {
551 name, found := w.groupNames[id]
553 fresh := time.Since(w.groupsAt) < whatsappGroupsRefresh
560 if client == nil || fresh {
561 return whatsappUnknownGroup
564 ctx, cancel := context.WithTimeout(ctx, whatsappLookupTime)
567 groups, err := client.GetJoinedGroups(ctx)
569 w.logger.Printf("read the groups: %s", w.redact(err.Error()))
573 defer w.mutex.Unlock()
575 w.groupsAt = time.Now()
576 for _, group := range groups {
577 w.groupNames[group.JID.String()] = group.Name
580 name, found = w.groupNames[id]
581 if !found || name == "" {
582 return whatsappUnknownGroup
588 // removeSession ends the connection, closes the session database, and deletes
590 func (w *WhatsApp) removeSession() error {
602 container := w.container
612 if container != nil {
613 err = container.Close()
616 for _, suffix := range []string{"", "-wal", "-shm"} {
617 removeErr := os.Remove(w.sessionPath() + suffix)
618 if !errors.Is(removeErr, os.ErrNotExist) {
619 err = errors.Join(err, removeErr)
626 // pair links a new device to the account of phone with a pairing code. It gives
627 // the steps and the code to answer, and then the end of the pairing: the linked
628 // number, an expired code, or a failure. A pairing that a new one ends gives no
629 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
630 // The client of a pairing that does not link is disconnected.
631 func (w *WhatsApp) pair(ctx context.Context, l *TurnLoop, phone string, answer func(text string)) {
632 device, err := w.newDevice(ctx)
634 answer("The pairing failed: " + err.Error())
638 client := w.newClient(device, w.handle)
646 qr, err := client.GetQRChannel(ctx)
648 err = client.ConnectContext(ctx)
652 answer("The connection to WhatsApp failed: " + err.Error())
657 case item, open := <-qr:
658 if !open || item.Event != whatsmeow.QRChannelEventCode {
659 answer("WhatsApp did not start the pairing. Try again later.")
663 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
664 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
670 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
672 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
676 answer(whatsappPairSteps)
680 var item whatsmeow.QRChannelItem
683 case item, open = <-qr:
685 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
686 answer(whatsappPairExpired)
693 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
694 answer(whatsappPairExpired)
696 case item.Event == whatsmeow.QRChannelEventCode:
698 case item.Event == whatsmeow.QRChannelSuccess.Event:
702 err = l.note("WhatsApp is linked.")
704 w.logger.Printf("note the link: %v", err)
707 answer("WhatsApp is linked to +" + phone + ".")
711 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
717 // newDevice returns a new device in the session database. It makes the
718 // directory and the file of the session first, with their modes, when they do
720 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
722 defer w.mutex.Unlock()
724 if w.container == nil {
725 err := os.MkdirAll(w.dir, 0o700)
727 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
730 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
732 return nil, fmt.Errorf("create WhatsApp session: %w", err)
737 return nil, fmt.Errorf("create WhatsApp session: %w", err)
740 err = w.openSession(ctx)
746 w.device = w.container.NewDevice()
751 // linkedBy makes client the client of the linked device.
752 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
754 defer w.mutex.Unlock()
760 // handle takes one event of the library and tells if it was handled. A message
761 // goes to receive. The names of the groups follow the events of the groups. A
762 // disconnection keeps the time of its start while the library tries again.
763 // After noticeDelay of a disconnection, all clients get one notice, and they
764 // get one more when the connection comes back. A disconnection that the library
765 // does not try again gives a notice at once.
766 func (w *WhatsApp) handle(event any) bool {
767 message, isMessage := event.(*events.Message)
769 return w.receive(message)
774 switch event := event.(type) {
775 case *events.GroupInfo:
776 if event.Name != nil {
777 w.groupNames[event.JID.String()] = event.Name.Name
779 case *events.JoinedGroup:
780 w.groupNames[event.JID.String()] = event.Name
781 case *events.PairSuccess:
782 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
783 case *events.Connected:
785 w.connectedAt = w.clock()
792 notice = "WhatsApp is connected again."
794 case *events.Disconnected:
795 if w.linked && (w.connected || w.disconnectedAt.IsZero()) {
796 w.disconnectedAt = w.clock()
798 disconnections := w.disconnections
799 w.timer = time.AfterFunc(w.noticeDelay, func() {
800 w.disconnectedLong(disconnections)
805 case *events.LoggedOut:
807 case w.logouts <- struct{}{}:
810 case events.PermanentDisconnect:
814 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
826 // receive puts the text of event into its batch and wakes Run. It returns false
827 // when the state file cannot hold the message, so that the library does not
828 // acknowledge it, and Run stops the daemon. A message that is not text, or that
829 // the batches do not take, is handled with nothing to do.
830 func (w *WhatsApp) receive(event *events.Message) bool {
831 ctx, cancel := context.WithTimeout(context.Background(), whatsappLookupTime)
834 chat, message, found := w.message(ctx, event)
839 _, err := w.batches.Add(chat, message, time.Now())
842 case w.failures <- err:
850 case w.wake <- struct{}{}:
857 // message returns the chat and the batch message of event, or false when the
858 // batches do not take it. They take the text of a private chat or a group, from
859 // another person or from the user. They do not take media, reactions, edits,
860 // deletions, view-once and disappearing messages, old history, status
861 // broadcasts, channels, and the chat of the user with itself.
863 // A mention of the user becomes @you, another mention @NAME when the name is
864 // known, and the own number and LID become OWN, so that they never go to the
866 func (w *WhatsApp) message(ctx context.Context, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
869 own := slices.Clone(w.own)
873 chatJID := info.Chat.ToNonAD()
876 case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.SourceWebMsg != nil:
877 case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
878 case slices.Contains(own, chatJID.User):
880 return w.text(ctx, device, own, event)
883 return WhatsAppChat{}, WhatsAppMessage{}, false
886 // text returns the chat and the batch message of event, a message that the
887 // batches take when it has text.
888 func (w *WhatsApp) text(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
890 text := event.Message.GetConversation()
891 extended := event.Message.GetExtendedTextMessage()
893 text = extended.GetText()
896 if strings.TrimSpace(text) == "" {
897 return WhatsAppChat{}, WhatsAppMessage{}, false
900 contextInfo := extended.GetContextInfo()
901 message := WhatsAppMessage{
903 Time: info.Timestamp,
908 message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
911 for _, mentioned := range contextInfo.GetMentionedJID() {
912 jid, err := types.ParseJID(mentioned)
915 case slices.Contains(own, jid.User):
916 message.Mention = true
917 text = strings.ReplaceAll(text, "@"+jid.User, "@you")
919 text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
923 participant, err := types.ParseJID(contextInfo.GetParticipant())
924 message.Reply = err == nil && slices.Contains(own, participant.User)
926 for _, id := range own {
927 text = strings.ReplaceAll(text, id, "OWN")
931 chatJID := info.Chat.ToNonAD()
932 chat := WhatsAppChat{
933 ID: chatJID.String(),
934 Group: chatJID.Server == types.GroupServer,
938 push := info.PushName
943 chat.Name = whatsappContactName(ctx, device, chatJID, push)
946 return chat, message, true
949 // disconnectedLong gives the notice of a long disconnection, unless the
950 // disconnection with the number disconnections ended.
951 func (w *WhatsApp) disconnectedLong(disconnections int) {
953 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
958 since := w.disconnectedAt
962 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
966 // broadcast gives text as a notice to all clients.
967 func (w *WhatsApp) broadcast(text string) {
973 if notify != nil && !closed {
981 // redact replaces the own number and the own LID in text with OWN.
982 func (w *WhatsApp) redact(text string) string {
984 defer w.mutex.Unlock()
986 for _, id := range w.own {
987 text = strings.ReplaceAll(text, id, "OWN")
993 // WhatsAppRequest is a pair or unlink command for Run, with the function that
994 // gives its answers to the client that asked. A pairing has the phone number.
995 type WhatsAppRequest struct {
998 answer func(text string)
1001 // whatsappNewClient returns the client of the library for device, with handle
1002 // as its event handler. The client tries again after a failed first connection,
1003 // acknowledges a message only after handle returns true, and downloads no old
1004 // history. The phone shows the device with the name OneChat.
1005 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
1006 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
1007 client := whatsmeow.NewClient(device, waLog.Noop)
1008 client.InitialAutoReconnect = true
1009 client.SynchronousAck = true
1010 client.ManualHistorySyncDownload = true
1011 client.AddEventHandlerWithSuccessStatus(handle)
1016 // whatsappContactName returns the name of the person jid: the full name, the
1017 // first name, the business name, or the push name of the contact in the session
1018 // of device, then push, the push name of a message, then the phone number. A
1019 // LID gets its phone number from the LID map of the session.
1020 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
1022 candidates := []types.JID{jid}
1023 phone := types.EmptyJID
1025 case types.DefaultUserServer:
1027 case types.HiddenUserServer:
1028 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
1029 if err == nil && !mapped.IsEmpty() {
1031 candidates = append(candidates, mapped)
1035 for _, candidate := range candidates {
1036 contact, err := device.Contacts.GetContact(ctx, candidate)
1037 if err != nil || !contact.Found {
1041 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
1051 case !phone.IsEmpty():
1052 return "+" + phone.User
1058 // whatsappOwnIDs returns the own number and the own LID that are not empty.
1059 func whatsappOwnIDs(ids ...string) []string {
1061 for _, id := range ids {
1063 own = append(own, id)
1070 // whatsappSessionAddress returns the SQLite address of the session database at
1071 // path, with foreign keys on, as the library needs, and a wait for a busy
1073 func whatsappSessionAddress(path string) (string, error) {
1074 path, err := filepath.Abs(path)
1076 return "", fmt.Errorf("find WhatsApp session: %w", err)
1082 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
1085 return address.String(), nil
1088 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
1089 // command, or false for any other line.
1090 func whatsappCommandArgs(line string) (string, bool) {
1091 line = strings.TrimSpace(line)
1092 if line == whatsappCommand {
1096 args, found := strings.CutPrefix(line, whatsappCommand+" ")
1101 return strings.TrimSpace(args), true
1104 // whatsappPhone returns the digits of phone, a number with its country code and
1105 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
1106 // digits, with no 0 first.
1107 func whatsappPhone(phone string) (string, bool) {
1108 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
1109 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
1114 // whatsappItemError returns the error of a pairing item that is not a code, a
1115 // success, or a timeout.
1116 func whatsappItemError(item whatsmeow.QRChannelItem) string {
1117 if item.Error != nil {
1118 return item.Error.Error()