+// whatsappMessage returns the chat and the batch message of event, or false
+// when the batches do not take it. device is the linked device, and own holds
+// the own IDs. The batches take the text of a private chat or a group, from
+// another person or from the user. They do not take media, reactions, edits,
+// deletions, view-once and disappearing messages, old history, status
+// broadcasts, channels, and the chat of the user with itself.
+//
+// A mention of the user becomes @you, another mention @NAME when the name is
+// known, and the own number and LID become OWN, so that they never go to the
+// log.
+func whatsappMessage(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
+ info := event.Info
+ chatJID := info.Chat.ToNonAD()
+ switch {
+ case device == nil:
+ case event.IsEdit, info.Edit != "", event.IsEphemeral, event.IsViewOnce, event.SourceWebMsg != nil:
+ case chatJID.Server != types.DefaultUserServer && chatJID.Server != types.HiddenUserServer && chatJID.Server != types.GroupServer:
+ case slices.Contains(own, chatJID.User):
+ default:
+ return whatsappText(ctx, device, own, event)
+ }
+
+ return WhatsAppChat{}, WhatsAppMessage{}, false
+}
+
+// whatsappText returns the chat and the batch message of event, a message that
+// the batches take when it has text.
+func whatsappText(ctx context.Context, device *store.Device, own []string, event *events.Message) (WhatsAppChat, WhatsAppMessage, bool) {
+ info := event.Info
+ text := event.Message.GetConversation()
+ extended := event.Message.GetExtendedTextMessage()
+ if text == "" {
+ text = extended.GetText()
+ }
+
+ if strings.TrimSpace(text) == "" {
+ return WhatsAppChat{}, WhatsAppMessage{}, false
+ }
+
+ contextInfo := extended.GetContextInfo()
+ message := WhatsAppMessage{
+ ID: info.ID,
+ Time: info.Timestamp,
+ Mine: info.IsFromMe,
+ }
+
+ if !message.Mine {
+ message.Sender = whatsappContactName(ctx, device, info.Sender, info.PushName)
+ }
+
+ for _, mentioned := range contextInfo.GetMentionedJID() {
+ jid, err := types.ParseJID(mentioned)
+ switch {
+ case err != nil:
+ case slices.Contains(own, jid.User):
+ message.Mention = true
+ text = strings.ReplaceAll(text, "@"+jid.User, "@you")
+ default:
+ text = strings.ReplaceAll(text, "@"+jid.User, "@"+whatsappContactName(ctx, device, jid, ""))
+ }
+ }
+
+ participant, err := types.ParseJID(contextInfo.GetParticipant())
+ message.Reply = err == nil && slices.Contains(own, participant.User)
+
+ message.Text = whatsappRedact(own, text)
+ chatJID := info.Chat.ToNonAD()
+ chat := WhatsAppChat{
+ ID: chatJID.String(),
+ Group: chatJID.Server == types.GroupServer,
+ }
+
+ if !chat.Group {
+ push := info.PushName
+ if message.Mine {
+ push = ""
+ }
+
+ chat.Name = whatsappContactName(ctx, device, chatJID, push)
+ }
+
+ return chat, message, true
+}
+
+// whatsappContactName returns the name of the person jid: the full name, the
+// first name, the business name, or the push name of the contact in the session
+// of device, then push, the push name of a message, then the phone number. A
+// LID gets its phone number from the LID map of the session.
+func whatsappContactName(ctx context.Context, device *store.Device, jid types.JID, push string) string {
+ jid = jid.ToNonAD()
+ candidates := []types.JID{jid}
+ phone := types.EmptyJID
+ switch jid.Server {
+ case types.DefaultUserServer:
+ phone = jid
+ case types.HiddenUserServer:
+ mapped, err := device.LIDs.GetPNForLID(ctx, jid)
+ if err == nil && !mapped.IsEmpty() {
+ phone = mapped
+ candidates = append(candidates, mapped)
+ }
+ }
+
+ for _, candidate := range candidates {
+ contact, err := device.Contacts.GetContact(ctx, candidate)
+ if err != nil || !contact.Found {
+ continue
+ }
+
+ for _, name := range []string{contact.FullName, contact.FirstName, contact.BusinessName, contact.PushName} {
+ if name != "" {
+ return name
+ }
+ }
+ }
+
+ switch {
+ case push != "":
+ return push
+ case !phone.IsEmpty():
+ return "+" + phone.User
+ default:
+ return jid.User
+ }
+}
+
+// whatsappFold returns text in lower case with no accents and no space at its
+// ends, so that names match with no regard to case and accents.
+func whatsappFold(text string) string {
+ folded, _, err := transform.String(transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC), text)
+ if err != nil {
+ folded = text
+ }
+
+ return strings.ToLower(strings.TrimSpace(folded))
+}
+
+// whatsappFindAnswer returns the answer of Find for name with matches. Without
+// groups, the answer says that it has no groups.
+func whatsappFindAnswer(name string, matches []WhatsAppMatch, groups bool) string {
+ slices.SortFunc(matches, func(a, b WhatsAppMatch) int {
+ return cmp.Or(strings.Compare(whatsappFold(a.name), whatsappFold(b.name)), strings.Compare(a.id, b.id))
+ })
+
+ var lines []string
+ for _, match := range matches[:min(len(matches), whatsappFindMatches)] {
+ lines = append(lines, match.id+" | "+match.name+" | "+match.kind)
+ }
+
+ if len(matches) == 0 {
+ lines = append(lines, "No contact or group has a name with \""+name+"\".")
+ }
+
+ if len(matches) > whatsappFindMatches {
+ lines = append(lines, fmt.Sprintf("%d more: give a longer part of the name.", len(matches)-whatsappFindMatches))
+ }
+
+ if !groups {
+ lines = append(lines, "The groups are not in this answer, because WhatsApp is disconnected.")
+ }
+
+ return strings.Join(lines, "\n")
+}
+
+// whatsappSendCheck returns the JID of chat, and an error when id, chat, or
+// text cannot go to a send. The chat is a private chat or a group, and not the
+// chat of the user with itself.
+func whatsappSendCheck(id, chat, text string, own []string) (types.JID, error) {
+ jid, err := types.ParseJID(chat)
+ switch {
+ case strings.TrimSpace(id) == "" || len(id) > whatsappSendIDBytes:
+ return types.EmptyJID, fmt.Errorf("the id must have 1 to %d bytes", whatsappSendIDBytes)
+ case strings.TrimSpace(text) == "" || len(text) > whatsappSendBytes:
+ return types.EmptyJID, fmt.Errorf("the text must have 1 to %d bytes", whatsappSendBytes)
+ case err != nil || jid.User == "" || jid != jid.ToNonAD() || jid.String() != chat:
+ return types.EmptyJID, fmt.Errorf("%q is not the ID of a WhatsApp chat: find the ID with whatsapp_find", chat)
+ case jid.Server != types.DefaultUserServer && jid.Server != types.HiddenUserServer && jid.Server != types.GroupServer:
+ return types.EmptyJID, fmt.Errorf("%q is not a private chat or a group", chat)
+ case slices.Contains(own, jid.User):
+ return types.EmptyJID, errors.New("this is the chat of the user with itself: send to another chat")
+ }
+
+ return jid, nil
+}
+