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"
85 // whatsappCatchupLimit is the longest wait for the end of the catch-up
86 // after a connection.
87 whatsappCatchupLimit = time.Minute
90 // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The
91 // real one is a *whatsmeow.Client from whatsappNewClient, and the tests use a
93 type WhatsAppClient interface {
94 ConnectContext(ctx context.Context) error
96 GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error)
97 PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)
98 Logout(ctx context.Context) error
99 GetJoinedGroups(ctx context.Context) ([]*types.GroupInfo, 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 *log.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 catchupLimit: whatsappCatchupLimit,
115 requests: make(chan WhatsAppRequest, whatsappRequests),
116 logouts: make(chan struct{}, 1),
117 wake: make(chan struct{}, 1),
118 failures: make(chan error, 1),
119 groupNames: make(map[string]string),
123 w.batches, err = openWhatsAppBatches(filepath.Join(w.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
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 {
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.
168 // The text messages go into batches, one chat at a time, as WhatsAppBatches
169 // says. Run logs each closed batch as a work message that starts with
170 // [WhatsApp], and a batch that needs the user wakes the turn loop.
172 // After each connection, the servers send the messages that came while the
173 // daemon was away, and then OfflineSyncCompleted. Until then, or until
174 // catchupLimit passes, the closed batches wait in the state file. At the end of
175 // the catch-up, Run closes all batches, logs them, and wakes the turn loop
176 // once, so the whole catch-up gives one turn and not one turn for each chat.
177 // The batches of the state file at the start wait for the first catch-up in the
178 // same way. The event handler acknowledges a message only after the state file
179 // holds it, so the servers send again a message that a crash lost. A batch
180 // leaves the state file only after its work message is durable in the log. A
181 // crash between the two makes the batch repeat once.
183 // The library logs nothing, because its log lines hold the ID of the own
184 // account, which is the phone number of the user. The own number and the own
185 // LID never go to the log of the agent or to the log of the daemon: redact
186 // removes them from the errors, and a batch shows the messages of the user as
187 // You and a mention of the user as @you. The IDs of the other chats go to the
188 // log, and those of private chats hold phone numbers, because the agent needs
190 type WhatsApp struct {
192 clock func() time.Time
194 newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient
195 noticeDelay time.Duration
196 catchupLimit time.Duration
197 requests chan WhatsAppRequest
198 logouts chan struct{}
201 batches *WhatsAppBatches
204 container *sqlstore.Container
206 client WhatsAppClient
211 connectedAt time.Time
212 disconnectedAt time.Time
217 groupNames map[string]string
222 catchupTimer *time.Timer
225 // Run connects a linked device, logs the closed batches in l, runs the pair and
226 // unlink commands, and handles a logout from the phone, until ctx ends. Its
227 // notes go to the log of l, and notify gets the notices for all clients. A
228 // failed first connection is logged, and the library tries again when the
229 // failure is one of the network. Run returns the error of a write of the log or
230 // of the state file, which stops the daemon, because then messages would be
232 func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) error {
242 var pairing sync.WaitGroup
251 err := w.deliver(ctx, l, false)
256 var due <-chan time.Time
257 wait, open := w.batches.Wait(time.Now())
259 due = time.After(wait)
265 case err = <-w.failures:
270 err = w.loggedOut(ctx, l)
274 case request := <-w.requests:
281 err = w.unlink(ctx, l, request.answer)
286 request.answer("WhatsApp is linked already. Run /whatsapp unlink first.")
288 pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime)
293 w.pair(pairCtx, l, request.phone, request.answer)
300 // Command runs the WhatsApp command args, the text after /whatsapp, and gives
301 // each answer to answer. The answers go only to the client that sent the
303 func (w *WhatsApp) Command(args string, answer func(text string)) {
304 fields := strings.Fields(args)
305 request := WhatsAppRequest{
310 case len(fields) == 1 && fields[0] == "status":
313 case len(fields) == 1 && fields[0] == "unlink":
314 request.unlink = true
315 case len(fields) >= 2 && fields[0] == "pair":
316 phone, valid := whatsappPhone(strings.Join(fields[1:], ""))
318 answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.")
322 request.phone = phone
324 answer(whatsappUsage)
329 case w.requests <- request:
331 answer("Too many WhatsApp commands wait. Try again in a minute.")
335 // Status returns the state of the link: not linked, linked and connected, or
336 // linked and disconnected, with the times of the connection. It never holds the
338 func (w *WhatsApp) Status() string {
340 defer w.mutex.Unlock()
344 return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it."
346 return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "."
347 case w.disconnectedAt.IsZero():
348 return "WhatsApp is linked and not connected yet."
349 case w.connectedAt.IsZero():
350 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + "."
352 return "WhatsApp is linked and disconnected since " + w.disconnectedAt.Format(whatsappTimeLayout) + ". The last connection started at " + w.connectedAt.Format(whatsappTimeLayout) + "."
356 // Close closes the session database.
357 func (w *WhatsApp) Close() error {
359 defer w.mutex.Unlock()
361 if w.container == nil {
365 err := w.container.Close()
371 func (w *WhatsApp) sessionPath() string {
372 return filepath.Join(w.dir, whatsappSessionFileName)
375 // openSession opens the session database and its first device. The caller holds
376 // the mutex, or no other goroutine uses w yet.
377 func (w *WhatsApp) openSession(ctx context.Context) error {
378 address, err := whatsappSessionAddress(w.sessionPath())
383 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
385 return fmt.Errorf("open WhatsApp session: %w", err)
388 device, err := container.GetFirstDevice(ctx)
390 return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close())
393 w.container = container
399 func (w *WhatsApp) isLinked() bool {
401 defer w.mutex.Unlock()
406 // connect makes the client of the linked device and connects it.
407 func (w *WhatsApp) connect(ctx context.Context) {
409 w.client = w.newClient(w.device, w.handle)
413 err := client.ConnectContext(ctx)
415 w.logger.Printf("connect: %s", w.redact(err.Error()))
419 // close ends the connection and the timer of the notice, and stops all notices.
420 func (w *WhatsApp) close() {
427 if w.catchupTimer != nil {
428 w.catchupTimer.Stop()
440 // loggedOut logs the open batches, deletes the session after a logout from the
441 // phone, notes it in the log of l, and tells all clients one time.
442 func (w *WhatsApp) loggedOut(ctx context.Context, l *TurnLoop) error {
447 err := w.deliver(ctx, l, true)
452 err = w.removeSession()
454 w.logger.Printf("delete the session after the logout: %v", err)
457 err = l.note("WhatsApp was unlinked from the phone.")
459 w.logger.Printf("note the logout: %v", err)
462 w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.")
467 // unlink logs the open batches, logs out the linked device, and deletes the
468 // session. When the logout call fails, as it does while WhatsApp is
469 // disconnected, the session is deleted all the same, and answer tells the user
470 // to remove the device in the phone. Its error is one of the log or the state
472 func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) error {
479 answer("WhatsApp is not linked.")
483 err := w.deliver(ctx, l, true)
490 ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime)
493 logoutErr = client.Logout(ctx)
496 err = w.removeSession()
498 answer("The unlink failed: " + w.redact(err.Error()))
502 err = l.note("WhatsApp is unlinked.")
504 w.logger.Printf("note the unlink: %v", err)
507 if client == nil || logoutErr != nil {
508 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.")
512 answer("WhatsApp is unlinked.")
517 // deliver logs the closed batches in l in order, each as a work message of
518 // whatsappSource, and wakes the loop once with the batches that start a turn. A
519 // batch leaves the state file after its message is durable in the log. A group
520 // with no name gets its name from WhatsApp first. During a catch-up it logs
521 // nothing, and at its end it closes all batches first. With all, it closes and
522 // logs all batches also during a catch-up.
523 func (w *WhatsApp) deliver(ctx context.Context, l *TurnLoop, all bool) error {
525 catchingUp := w.catchingUp
526 caughtUp := w.caughtUp
532 case all || caughtUp:
533 err = w.batches.CloseAll()
537 _, err = w.batches.CloseDue(time.Now())
545 for _, batch := range w.batches.Closed() {
546 if batch.Chat.Group && batch.Chat.Name == "" {
547 batch.Chat.Name = w.groupName(ctx, batch.Chat.ID)
550 message, err := l.Work(whatsappSource, batch.Text(w.clock().Location()), "")
552 return fmt.Errorf("log a WhatsApp batch: %w", err)
555 // A stop of the daemon during the flush is no failure: the
556 // batch stays in the state file and repeats once at the next
559 if ctx.Err() != nil {
564 return fmt.Errorf("log a WhatsApp batch: %w", err)
567 err = w.batches.Remove(batch.Number)
573 turns = append(turns, message)
582 // groupName returns the name of the group id, or whatsappUnknownGroup. A group
583 // that is not in the names of the groups reads the groups from WhatsApp again,
584 // at most once in whatsappGroupsRefresh.
585 func (w *WhatsApp) groupName(ctx context.Context, id string) string {
587 name, found := w.groupNames[id]
589 fresh := time.Since(w.groupsAt) < whatsappGroupsRefresh
596 if client == nil || fresh {
597 return whatsappUnknownGroup
600 ctx, cancel := context.WithTimeout(ctx, whatsappLookupTime)
603 groups, err := client.GetJoinedGroups(ctx)
605 w.logger.Printf("read the groups: %s", w.redact(err.Error()))
609 defer w.mutex.Unlock()
611 w.groupsAt = time.Now()
612 for _, group := range groups {
613 w.groupNames[group.JID.String()] = group.Name
616 name, found = w.groupNames[id]
617 if !found || name == "" {
618 return whatsappUnknownGroup
624 // removeSession ends the connection, closes the session database, and deletes
626 func (w *WhatsApp) removeSession() error {
639 container := w.container
649 if container != nil {
650 err = container.Close()
653 for _, suffix := range []string{"", "-wal", "-shm"} {
654 removeErr := os.Remove(w.sessionPath() + suffix)
655 if !errors.Is(removeErr, os.ErrNotExist) {
656 err = errors.Join(err, removeErr)
663 // pair links a new device to the account of phone with a pairing code. It gives
664 // the steps and the code to answer, and then the end of the pairing: the linked
665 // number, an expired code, or a failure. A pairing that a new one ends gives no
666 // answer. A link notes "WhatsApp is linked." in the log of l, with no number.
667 // The client of a pairing that does not link is disconnected.
668 func (w *WhatsApp) pair(ctx context.Context, l *TurnLoop, phone string, answer func(text string)) {
669 device, err := w.newDevice(ctx)
671 answer("The pairing failed: " + err.Error())
675 client := w.newClient(device, w.handle)
683 qr, err := client.GetQRChannel(ctx)
685 err = client.ConnectContext(ctx)
689 answer("The connection to WhatsApp failed: " + err.Error())
694 case item, open := <-qr:
695 if !open || item.Event != whatsmeow.QRChannelEventCode {
696 answer("WhatsApp did not start the pairing. Try again later.")
700 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
701 answer("The connection to WhatsApp did not start the pairing in time. Try again later.")
707 code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
709 answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.")
713 answer(whatsappPairSteps)
717 var item whatsmeow.QRChannelItem
720 case item, open = <-qr:
722 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
723 answer(whatsappPairExpired)
730 case !open || item.Event == whatsmeow.QRChannelTimeout.Event:
731 answer(whatsappPairExpired)
733 case item.Event == whatsmeow.QRChannelEventCode:
735 case item.Event == whatsmeow.QRChannelSuccess.Event:
739 err = l.note("WhatsApp is linked.")
741 w.logger.Printf("note the link: %v", err)
744 answer("WhatsApp is linked to +" + phone + ".")
748 answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.")
754 // newDevice returns a new device in the session database. It makes the
755 // directory and the file of the session first, with their modes, when they do
757 func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) {
759 defer w.mutex.Unlock()
761 if w.container == nil {
762 err := os.MkdirAll(w.dir, 0o700)
764 return nil, fmt.Errorf("create WhatsApp directory: %w", err)
767 file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600)
769 return nil, fmt.Errorf("create WhatsApp session: %w", err)
774 return nil, fmt.Errorf("create WhatsApp session: %w", err)
777 err = w.openSession(ctx)
783 w.device = w.container.NewDevice()
788 // linkedBy makes client the client of the linked device.
789 func (w *WhatsApp) linkedBy(client WhatsAppClient) {
791 defer w.mutex.Unlock()
797 // handle takes one event of the library and tells if it was handled. A message
798 // goes to receive. The names of the groups follow the events of the groups. A
799 // connection starts a catch-up, which ends at OfflineSyncCompleted or after
800 // catchupLimit. A disconnection keeps the time of its start while the library
801 // tries again. After noticeDelay of a disconnection, all clients get one
802 // notice, and they get one more when the connection comes back. A disconnection
803 // that the library does not try again gives a notice at once.
804 func (w *WhatsApp) handle(event any) bool {
805 message, isMessage := event.(*events.Message)
807 return w.receive(message)
812 switch event := event.(type) {
813 case *events.GroupInfo:
814 if event.Name != nil {
815 w.groupNames[event.JID.String()] = event.Name.Name
817 case *events.JoinedGroup:
818 w.groupNames[event.JID.String()] = event.Name
819 case *events.PairSuccess:
820 w.own = whatsappOwnIDs(event.ID.User, event.LID.User)
821 case *events.Connected:
823 w.connectedAt = w.clock()
826 catchups := w.catchups
827 if w.catchupTimer != nil {
828 w.catchupTimer.Stop()
831 w.catchupTimer = time.AfterFunc(w.catchupLimit, func() {
832 w.caughtUpBy(catchups)
840 notice = "WhatsApp is connected again."
842 case *events.Disconnected:
843 if w.linked && (w.connected || w.disconnectedAt.IsZero()) {
844 w.disconnectedAt = w.clock()
846 disconnections := w.disconnections
847 w.timer = time.AfterFunc(w.noticeDelay, func() {
848 w.disconnectedLong(disconnections)
853 case *events.OfflineSyncCompleted:
855 case *events.LoggedOut:
857 case w.logouts <- struct{}{}:
860 case events.PermanentDisconnect:
864 notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again."
876 // receive puts the text of event into its batch and wakes Run. It returns false
877 // when the state file cannot hold the message, so that the library does not
878 // acknowledge it, and Run stops the daemon. A message that is not text, or that
879 // the batches do not take, is handled with nothing to do.
880 func (w *WhatsApp) receive(event *events.Message) bool {
881 ctx, cancel := context.WithTimeout(context.Background(), whatsappLookupTime)
884 chat, message, found := w.message(ctx, event)
889 _, err := w.batches.Add(chat, message, time.Now())
892 case w.failures <- err:
900 case w.wake <- struct{}{}:
907 // message returns the chat and the batch message of event, or false when the
908 // batches do not take it. They take the text of a private chat or a group, from
909 // another person or from the user. They do not take media, reactions, edits,
910 // deletions, view-once and disappearing messages, old history, status
911 // broadcasts, channels, and the chat of the user with itself.
913 // A mention of the user becomes @you, another mention @NAME when the name is
914 // known, and the own number and LID become OWN, so that they never go to the
916 func (w *WhatsApp) message(ctx context.Context, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
919 own := slices.Clone(w.own)
923 chatJID := info.Chat.ToNonAD()
926 case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.SourceWebMsg != nil:
927 case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
928 case slices.Contains(own, chatJID.User):
930 return w.text(ctx, device, own, event)
933 return WhatsAppChat{}, WhatsAppMessage{}, false
936 // text returns the chat and the batch message of event, a message that the
937 // batches take when it has text.
938 func (w *WhatsApp) text(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
940 text := event.Message.GetConversation()
941 extended := event.Message.GetExtendedTextMessage()
943 text = extended.GetText()
946 if strings.TrimSpace(text) == "" {
947 return WhatsAppChat{}, WhatsAppMessage{}, false
950 contextInfo := extended.GetContextInfo()
951 message := WhatsAppMessage{
953 Time: info.Timestamp,
958 message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
961 for _, mentioned := range contextInfo.GetMentionedJID() {
962 jid, err := types.ParseJID(mentioned)
965 case slices.Contains(own, jid.User):
966 message.Mention = true
967 text = strings.ReplaceAll(text, "@"+jid.User, "@you")
969 text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
973 participant, err := types.ParseJID(contextInfo.GetParticipant())
974 message.Reply = err == nil && slices.Contains(own, participant.User)
976 for _, id := range own {
977 text = strings.ReplaceAll(text, id, "OWN")
981 chatJID := info.Chat.ToNonAD()
982 chat := WhatsAppChat{
983 ID: chatJID.String(),
984 Group: chatJID.Server == types.GroupServer,
988 push := info.PushName
993 chat.Name = whatsappContactName(ctx, device, chatJID, push)
996 return chat, message, true
999 // caughtUpBy ends the catch-up of the connection with the number catchups, when
1000 // no later connection started a new one.
1001 func (w *WhatsApp) caughtUpBy(catchups int) {
1003 defer w.mutex.Unlock()
1005 if w.catchups == catchups {
1010 // endCatchup ends a running catch-up and wakes Run, which logs all batches. The
1011 // caller holds the mutex.
1012 func (w *WhatsApp) endCatchup() {
1017 w.catchingUp = false
1019 if w.catchupTimer != nil {
1020 w.catchupTimer.Stop()
1024 case w.wake <- struct{}{}:
1029 // disconnectedLong gives the notice of a long disconnection, unless the
1030 // disconnection with the number disconnections ended.
1031 func (w *WhatsApp) disconnectedLong(disconnections int) {
1033 long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections
1038 since := w.disconnectedAt
1042 w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.")
1046 // broadcast gives text as a notice to all clients.
1047 func (w *WhatsApp) broadcast(text string) {
1053 if notify != nil && !closed {
1061 // redact replaces the own number and the own LID in text with OWN.
1062 func (w *WhatsApp) redact(text string) string {
1064 defer w.mutex.Unlock()
1066 for _, id := range w.own {
1067 text = strings.ReplaceAll(text, id, "OWN")
1073 // WhatsAppRequest is a pair or unlink command for Run, with the function that
1074 // gives its answers to the client that asked. A pairing has the phone number.
1075 type WhatsAppRequest struct {
1078 answer func(text string)
1081 // whatsappNewClient returns the client of the library for device, with handle
1082 // as its event handler. The client tries again after a failed first connection,
1083 // acknowledges a message only after handle returns true, and downloads no old
1084 // history. The phone shows the device with the name OneChat.
1085 func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient {
1086 store.SetOSInfo("OneChat", [3]uint32{0, 1, 0})
1087 client := whatsmeow.NewClient(device, waLog.Noop)
1088 client.InitialAutoReconnect = true
1089 client.SynchronousAck = true
1090 client.ManualHistorySyncDownload = true
1091 client.AddEventHandlerWithSuccessStatus(handle)
1096 // whatsappContactName returns the name of the person jid: the full name, the
1097 // first name, the business name, or the push name of the contact in the session
1098 // of device, then push, the push name of a message, then the phone number. A
1099 // LID gets its phone number from the LID map of the session.
1100 func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
1102 candidates := []types.JID{jid}
1103 phone := types.EmptyJID
1105 case types.DefaultUserServer:
1107 case types.HiddenUserServer:
1108 mapped, err := device.LIDs.GetPNForLID(ctx, jid)
1109 if err == nil && !mapped.IsEmpty() {
1111 candidates = append(candidates, mapped)
1115 for _, candidate := range candidates {
1116 contact, err := device.Contacts.GetContact(ctx, candidate)
1117 if err != nil || !contact.Found {
1121 for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
1131 case !phone.IsEmpty():
1132 return "+" + phone.User
1138 // whatsappOwnIDs returns the own number and the own LID that are not empty.
1139 func whatsappOwnIDs(ids ...string) []string {
1141 for _, id := range ids {
1143 own = append(own, id)
1150 // whatsappSessionAddress returns the SQLite address of the session database at
1151 // path, with foreign keys on, as the library needs, and a wait for a busy
1153 func whatsappSessionAddress(path string) (string, error) {
1154 path, err := filepath.Abs(path)
1156 return "", fmt.Errorf("find WhatsApp session: %w", err)
1162 RawQuery: "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)",
1165 return address.String(), nil
1168 // whatsappCommandArgs returns the text after /whatsapp of a line of a WhatsApp
1169 // command, or false for any other line.
1170 func whatsappCommandArgs(line string) (string, bool) {
1171 line = strings.TrimSpace(line)
1172 if line == whatsappCommand {
1176 args, found := strings.CutPrefix(line, whatsappCommand+" ")
1181 return strings.TrimSpace(args), true
1184 // whatsappPhone returns the digits of phone, a number with its country code and
1185 // an optional + and dashes, and tells if it has the form of a number: 7 to 15
1186 // digits, with no 0 first.
1187 func whatsappPhone(phone string) (string, bool) {
1188 phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "")
1189 valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == ""
1194 // whatsappItemError returns the error of a pairing item that is not a code, a
1195 // success, or a timeout.
1196 func whatsappItemError(item whatsmeow.QRChannelItem) string {
1197 if item.Error != nil {
1198 return item.Error.Error()