// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2021 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see
%s", url, name, msg.GetAddress()),
GeoURI: fmt.Sprintf("geo:%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude()),
}
if len(msg.GetJpegThumbnail()) > 0 {
thumbnailMime := http.DetectContentType(msg.GetJpegThumbnail())
uploadedThumbnail, _ := intent.UploadBytes(msg.GetJpegThumbnail(), thumbnailMime)
if uploadedThumbnail != nil {
cfg, _, _ := image.DecodeConfig(bytes.NewReader(msg.GetJpegThumbnail()))
content.Info = &event.FileInfo{
ThumbnailInfo: &event.FileInfo{
Size: len(msg.GetJpegThumbnail()),
Width: cfg.Width,
Height: cfg.Height,
MimeType: thumbnailMime,
},
ThumbnailURL: uploadedThumbnail.ContentURI.CUString(),
}
}
}
return &ConvertedMessage{
Intent: intent,
Type: event.EventMessage,
Content: content,
ReplyTo: GetReply(msg.GetContextInfo()),
ExpiresIn: msg.GetContextInfo().GetExpiration(),
}
}
const inviteMsg = `%s
!wa accept
to accept the invite.`
const inviteMetaField = "fi.mau.whatsapp.invite"
const escapedInviteMetaField = `fi\.mau\.whatsapp\.invite`
type InviteMeta struct {
JID types.JID `json:"jid"`
Code string `json:"code"`
Expiration int64 `json:"expiration,string"`
Inviter types.JID `json:"inviter"`
}
func (portal *Portal) convertGroupInviteMessage(intent *appservice.IntentAPI, info *types.MessageInfo, msg *waProto.GroupInviteMessage) *ConvertedMessage {
expiry := time.Unix(msg.GetInviteExpiration(), 0)
htmlMessage := fmt.Sprintf(inviteMsg, event.TextToHTML(msg.GetCaption()), msg.GetGroupName(), expiry)
content := &event.MessageEventContent{
MsgType: event.MsgText,
Body: format.HTMLToText(htmlMessage),
Format: event.FormatHTML,
FormattedBody: htmlMessage,
}
groupJID, err := types.ParseJID(msg.GetGroupJid())
if err != nil {
portal.log.Errorfln("Failed to parse invite group JID: %v", err)
}
extraAttrs := map[string]interface{}{
inviteMetaField: InviteMeta{
JID: groupJID,
Code: msg.GetInviteCode(),
Expiration: msg.GetInviteExpiration(),
Inviter: info.Sender.ToNonAD(),
},
}
return &ConvertedMessage{
Intent: intent,
Type: event.EventMessage,
Content: content,
Extra: extraAttrs,
ReplyTo: GetReply(msg.GetContextInfo()),
ExpiresIn: msg.GetContextInfo().GetExpiration(),
}
}
func (portal *Portal) convertContactMessage(intent *appservice.IntentAPI, msg *waProto.ContactMessage) *ConvertedMessage {
fileName := fmt.Sprintf("%s.vcf", msg.GetDisplayName())
data := []byte(msg.GetVcard())
mimeType := "text/vcard"
uploadMimeType, file := portal.encryptFileInPlace(data, mimeType)
uploadResp, err := intent.UploadBytesWithName(data, uploadMimeType, fileName)
if err != nil {
portal.log.Errorfln("Failed to upload vcard of %s: %v", msg.GetDisplayName(), err)
return nil
}
content := &event.MessageEventContent{
Body: fileName,
MsgType: event.MsgFile,
File: file,
Info: &event.FileInfo{
MimeType: mimeType,
Size: len(msg.GetVcard()),
},
}
if content.File != nil {
content.File.URL = uploadResp.ContentURI.CUString()
} else {
content.URL = uploadResp.ContentURI.CUString()
}
return &ConvertedMessage{
Intent: intent,
Type: event.EventMessage,
Content: content,
ReplyTo: GetReply(msg.GetContextInfo()),
ExpiresIn: msg.GetContextInfo().GetExpiration(),
}
}
func (portal *Portal) convertContactsArrayMessage(intent *appservice.IntentAPI, msg *waProto.ContactsArrayMessage) *ConvertedMessage {
name := msg.GetDisplayName()
if len(name) == 0 {
name = fmt.Sprintf("%d contacts", len(msg.GetContacts()))
}
contacts := make([]*event.MessageEventContent, 0, len(msg.GetContacts()))
for _, contact := range msg.GetContacts() {
converted := portal.convertContactMessage(intent, contact)
if converted != nil {
contacts = append(contacts, converted.Content)
}
}
return &ConvertedMessage{
Intent: intent,
Type: event.EventMessage,
Content: &event.MessageEventContent{
MsgType: event.MsgNotice,
Body: fmt.Sprintf("Sent %s", name),
},
ReplyTo: GetReply(msg.GetContextInfo()),
ExpiresIn: msg.GetContextInfo().GetExpiration(),
MultiEvent: contacts,
}
}
func (portal *Portal) tryKickUser(userID id.UserID, intent *appservice.IntentAPI) error {
_, err := intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
if err != nil {
httpErr, ok := err.(mautrix.HTTPError)
if ok && httpErr.RespError != nil && httpErr.RespError.ErrCode == "M_FORBIDDEN" {
_, err = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
}
}
return err
}
func (portal *Portal) removeUser(isSameUser bool, kicker *appservice.IntentAPI, target id.UserID, targetIntent *appservice.IntentAPI) {
if !isSameUser || targetIntent == nil {
err := portal.tryKickUser(target, kicker)
if err != nil {
portal.log.Warnfln("Failed to kick %s from %s: %v", target, portal.MXID, err)
if targetIntent != nil {
_, _ = targetIntent.LeaveRoom(portal.MXID)
}
}
} else {
_, err := targetIntent.LeaveRoom(portal.MXID)
if err != nil {
portal.log.Warnfln("Failed to leave portal as %s: %v", target, err)
_, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: target})
}
}
portal.CleanupIfEmpty()
}
func (portal *Portal) HandleWhatsAppKick(source *User, senderJID types.JID, jids []types.JID) {
sender := portal.bridge.GetPuppetByJID(senderJID)
senderIntent := sender.IntentFor(portal)
for _, jid := range jids {
//if source != nil && source.JID.User == jid.User {
// portal.log.Debugln("Ignoring self-kick by", source.MXID)
// continue
//}
puppet := portal.bridge.GetPuppetByJID(jid)
portal.removeUser(puppet.JID == sender.JID, senderIntent, puppet.MXID, puppet.DefaultIntent())
if !portal.IsBroadcastList() {
user := portal.bridge.GetUserByJID(jid)
if user != nil {
var customIntent *appservice.IntentAPI
if puppet.CustomMXID == user.MXID {
customIntent = puppet.CustomIntent()
}
portal.removeUser(puppet.JID == sender.JID, senderIntent, user.MXID, customIntent)
}
}
}
}
func (portal *Portal) HandleWhatsAppInvite(source *User, senderJID *types.JID, jids []types.JID) (evtID id.EventID) {
intent := portal.MainIntent()
if senderJID != nil && !senderJID.IsEmpty() {
sender := portal.bridge.GetPuppetByJID(*senderJID)
intent = sender.IntentFor(portal)
}
for _, jid := range jids {
puppet := portal.bridge.GetPuppetByJID(jid)
puppet.SyncContact(source, true, false, "handling whatsapp invite")
resp, err := intent.SendStateEvent(portal.MXID, event.StateMember, puppet.MXID.String(), &event.MemberEventContent{
Membership: event.MembershipInvite,
Displayname: puppet.Displayname,
AvatarURL: puppet.AvatarURL.CUString(),
})
if err != nil {
portal.log.Warnfln("Failed to invite %s as %s: %v", puppet.MXID, intent.UserID, err)
_ = portal.MainIntent().EnsureInvited(portal.MXID, puppet.MXID)
} else {
evtID = resp.EventID
}
err = puppet.DefaultIntent().EnsureJoined(portal.MXID)
if err != nil {
portal.log.Errorfln("Failed to ensure %s is joined: %v", puppet.MXID, err)
}
}
return
}
func (portal *Portal) HandleWhatsAppDeleteChat(user *User) {
matrixUsers, err := portal.GetMatrixUsers()
if err != nil {
portal.log.Errorln("Failed to get Matrix users to see if DeleteChat should be handled:", err)
return
}
if len(matrixUsers) > 1 {
portal.log.Infoln("Portal contains more than one Matrix user, so deleteChat will not be handled.")
return
} else if (len(matrixUsers) == 1 && matrixUsers[0] == user.MXID) || len(matrixUsers) < 1 {
portal.log.Debugln("User deleted chat and there are no other Matrix users using it, deleting portal...")
portal.Delete()
portal.Cleanup(false)
}
}
const failedMediaField = "fi.mau.whatsapp.failed_media"
type FailedMediaKeys struct {
Key []byte `json:"key"`
Length int `json:"length"`
Type whatsmeow.MediaType `json:"type"`
SHA256 []byte `json:"sha256"`
EncSHA256 []byte `json:"enc_sha256"`
}
type FailedMediaMeta struct {
Type event.Type `json:"type"`
Content *event.MessageEventContent `json:"content"`
ExtraContent map[string]interface{} `json:"extra_content,omitempty"`
Media FailedMediaKeys `json:"whatsapp_media"`
}
func shallowCopyMap(data map[string]interface{}) map[string]interface{} {
newMap := make(map[string]interface{}, len(data))
for key, value := range data {
newMap[key] = value
}
return newMap
}
func (portal *Portal) makeMediaBridgeFailureMessage(info *types.MessageInfo, bridgeErr error, converted *ConvertedMessage, keys *FailedMediaKeys, userFriendlyError string) *ConvertedMessage {
if errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith410) {
portal.log.Debugfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
} else {
portal.log.Errorfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
}
if keys != nil {
if portal.bridge.Config.Bridge.CaptionInMessage {
converted.MergeCaption()
}
meta := &FailedMediaMeta{
Type: converted.Type,
Content: converted.Content,
ExtraContent: shallowCopyMap(converted.Extra),
Media: *keys,
}
converted.Extra[failedMediaField] = meta
portal.mediaErrorCache[info.ID] = meta
}
converted.Type = event.EventMessage
body := userFriendlyError
if body == "" {
body = fmt.Sprintf("Failed to bridge media: %v", bridgeErr)
}
converted.Content = &event.MessageEventContent{
MsgType: event.MsgNotice,
Body: body,
}
return converted
}
func (portal *Portal) encryptFileInPlace(data []byte, mimeType string) (string, *event.EncryptedFileInfo) {
if !portal.Encrypted {
return mimeType, nil
}
file := &event.EncryptedFileInfo{
EncryptedFile: *attachment.NewEncryptedFile(),
URL: "",
}
file.EncryptInPlace(data)
return "application/octet-stream", file
}
type MediaMessage interface {
whatsmeow.DownloadableMessage
GetContextInfo() *waProto.ContextInfo
GetFileLength() uint64
GetMimetype() string
}
type MediaMessageWithThumbnail interface {
MediaMessage
GetJpegThumbnail() []byte
}
type MediaMessageWithCaption interface {
MediaMessage
GetCaption() string
}
type MediaMessageWithDimensions interface {
MediaMessage
GetHeight() uint32
GetWidth() uint32
}
type MediaMessageWithFileName interface {
MediaMessage
GetFileName() string
}
type MediaMessageWithDuration interface {
MediaMessage
GetSeconds() uint32
}
const WhatsAppStickerSize = 190
func (portal *Portal) convertMediaMessageContent(intent *appservice.IntentAPI, msg MediaMessage) *ConvertedMessage {
content := &event.MessageEventContent{
Info: &event.FileInfo{
MimeType: msg.GetMimetype(),
Size: int(msg.GetFileLength()),
},
}
extraContent := map[string]interface{}{}
messageWithDimensions, ok := msg.(MediaMessageWithDimensions)
if ok {
content.Info.Width = int(messageWithDimensions.GetWidth())
content.Info.Height = int(messageWithDimensions.GetHeight())
}
msgWithName, ok := msg.(MediaMessageWithFileName)
if ok && len(msgWithName.GetFileName()) > 0 {
content.Body = msgWithName.GetFileName()
} else {
mimeClass := strings.Split(msg.GetMimetype(), "/")[0]
switch mimeClass {
case "application":
content.Body = "file"
default:
content.Body = mimeClass
}
content.Body += util.ExtensionFromMimetype(msg.GetMimetype())
}
msgWithDuration, ok := msg.(MediaMessageWithDuration)
if ok {
content.Info.Duration = int(msgWithDuration.GetSeconds()) * 1000
}
videoMessage, ok := msg.(*waProto.VideoMessage)
var isGIF bool
if ok && videoMessage.GetGifPlayback() {
isGIF = true
extraContent["info"] = map[string]interface{}{
"fi.mau.loop": true,
"fi.mau.autoplay": true,
"fi.mau.hide_controls": true,
"fi.mau.no_audio": true,
}
}
messageWithThumbnail, ok := msg.(MediaMessageWithThumbnail)
if ok && messageWithThumbnail.GetJpegThumbnail() != nil && (portal.bridge.Config.Bridge.WhatsappThumbnail || isGIF) {
thumbnailData := messageWithThumbnail.GetJpegThumbnail()
thumbnailMime := http.DetectContentType(thumbnailData)
thumbnailCfg, _, _ := image.DecodeConfig(bytes.NewReader(thumbnailData))
thumbnailSize := len(thumbnailData)
thumbnailUploadMime, thumbnailFile := portal.encryptFileInPlace(thumbnailData, thumbnailMime)
uploadedThumbnail, err := intent.UploadBytes(thumbnailData, thumbnailUploadMime)
if err != nil {
portal.log.Warnfln("Failed to upload thumbnail: %v", err)
} else if uploadedThumbnail != nil {
if thumbnailFile != nil {
thumbnailFile.URL = uploadedThumbnail.ContentURI.CUString()
content.Info.ThumbnailFile = thumbnailFile
} else {
content.Info.ThumbnailURL = uploadedThumbnail.ContentURI.CUString()
}
content.Info.ThumbnailInfo = &event.FileInfo{
Size: thumbnailSize,
Width: thumbnailCfg.Width,
Height: thumbnailCfg.Height,
MimeType: thumbnailMime,
}
}
}
eventType := event.EventMessage
switch msg.(type) {
case *waProto.ImageMessage:
content.MsgType = event.MsgImage
case *waProto.StickerMessage:
eventType = event.EventSticker
if content.Info.Width > content.Info.Height {
content.Info.Height /= content.Info.Width / WhatsAppStickerSize
content.Info.Width = WhatsAppStickerSize
} else if content.Info.Width < content.Info.Height {
content.Info.Width /= content.Info.Height / WhatsAppStickerSize
content.Info.Height = WhatsAppStickerSize
} else {
content.Info.Width = WhatsAppStickerSize
content.Info.Height = WhatsAppStickerSize
}
case *waProto.VideoMessage:
content.MsgType = event.MsgVideo
case *waProto.AudioMessage:
content.MsgType = event.MsgAudio
case *waProto.DocumentMessage:
content.MsgType = event.MsgFile
default:
portal.log.Warnfln("Unexpected media type %T in convertMediaMessageContent", msg)
content.MsgType = event.MsgFile
}
audioMessage, ok := msg.(*waProto.AudioMessage)
if ok {
var waveform []int
if audioMessage.Waveform != nil {
waveform = make([]int, len(audioMessage.Waveform))
max := 0
for i, part := range audioMessage.Waveform {
waveform[i] = int(part)
if waveform[i] > max {
max = waveform[i]
}
}
multiplier := 0
if max > 0 {
multiplier = 1024 / max
}
if multiplier > 32 {
multiplier = 32
}
for i := range waveform {
waveform[i] *= multiplier
}
}
extraContent["org.matrix.msc1767.audio"] = map[string]interface{}{
"duration": int(audioMessage.GetSeconds()) * 1000,
"waveform": waveform,
}
if audioMessage.GetPtt() {
extraContent["org.matrix.msc3245.voice"] = map[string]interface{}{}
}
}
messageWithCaption, ok := msg.(MediaMessageWithCaption)
var captionContent *event.MessageEventContent
if ok && len(messageWithCaption.GetCaption()) > 0 {
captionContent = &event.MessageEventContent{
Body: messageWithCaption.GetCaption(),
MsgType: event.MsgNotice,
}
portal.bridge.Formatter.ParseWhatsApp(portal.MXID, captionContent, msg.GetContextInfo().GetMentionedJid(), false, false)
}
return &ConvertedMessage{
Intent: intent,
Type: eventType,
Content: content,
Caption: captionContent,
ReplyTo: GetReply(msg.GetContextInfo()),
ExpiresIn: msg.GetContextInfo().GetExpiration(),
Extra: extraContent,
}
}
func (portal *Portal) uploadMedia(intent *appservice.IntentAPI, data []byte, content *event.MessageEventContent) error {
uploadMimeType, file := portal.encryptFileInPlace(data, content.Info.MimeType)
req := mautrix.ReqUploadMedia{
ContentBytes: data,
ContentType: uploadMimeType,
}
var mxc id.ContentURI
if portal.bridge.Config.Homeserver.AsyncMedia {
uploaded, err := intent.UnstableUploadAsync(req)
if err != nil {
return err
}
mxc = uploaded.ContentURI
} else {
uploaded, err := intent.UploadMedia(req)
if err != nil {
return err
}
mxc = uploaded.ContentURI
}
if file != nil {
file.URL = mxc.CUString()
content.File = file
} else {
content.URL = mxc.CUString()
}
content.Info.Size = len(data)
if content.Info.Width == 0 && content.Info.Height == 0 && strings.HasPrefix(content.Info.MimeType, "image/") {
cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
content.Info.Width, content.Info.Height = cfg.Width, cfg.Height
}
return nil
}
func (portal *Portal) convertMediaMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, msg MediaMessage, typeName string, isBackfill bool) *ConvertedMessage {
converted := portal.convertMediaMessageContent(intent, msg)
if msg.GetFileLength() > uint64(portal.bridge.MediaConfig.UploadSize) {
return portal.makeMediaBridgeFailureMessage(info, errors.New("file is too large"), converted, nil, fmt.Sprintf("Large %s not bridged - please use WhatsApp app to view", typeName))
}
data, err := source.Client.Download(msg)
if errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith410) {
converted.Error = database.MsgErrMediaNotFound
converted.MediaKey = msg.GetMediaKey()
errorText := fmt.Sprintf("Old %s.", typeName)
if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia && isBackfill {
errorText += " Media will be automatically requested from your phone later."
} else {
errorText += " React with the \u267b (recycle) emoji to request this media from your phone."
}
return portal.makeMediaBridgeFailureMessage(info, err, converted, &FailedMediaKeys{
Key: msg.GetMediaKey(),
Length: int(msg.GetFileLength()),
Type: whatsmeow.GetMediaType(msg),
SHA256: msg.GetFileSha256(),
EncSHA256: msg.GetFileEncSha256(),
}, errorText)
} else if errors.Is(err, whatsmeow.ErrNoURLPresent) {
portal.log.Debugfln("No URL present error for media message %s, ignoring...", info.ID)
return nil
} else if errors.Is(err, whatsmeow.ErrFileLengthMismatch) || errors.Is(err, whatsmeow.ErrInvalidMediaSHA256) {
portal.log.Warnfln("Mismatching media checksums in %s: %v. Ignoring because WhatsApp seems to ignore them too", info.ID, err)
} else if err != nil {
return portal.makeMediaBridgeFailureMessage(info, err, converted, nil, "")
}
err = portal.uploadMedia(intent, data, converted.Content)
if err != nil {
if errors.Is(err, mautrix.MTooLarge) {
return portal.makeMediaBridgeFailureMessage(info, errors.New("homeserver rejected too large file"), converted, nil, "")
} else if httpErr, ok := err.(mautrix.HTTPError); ok && httpErr.IsStatus(413) {
return portal.makeMediaBridgeFailureMessage(info, errors.New("proxy rejected too large file"), converted, nil, "")
} else {
return portal.makeMediaBridgeFailureMessage(info, fmt.Errorf("failed to upload media: %w", err), converted, nil, "")
}
}
return converted
}
func (portal *Portal) fetchMediaRetryEvent(msg *database.Message) (*FailedMediaMeta, error) {
errorMeta, ok := portal.mediaErrorCache[msg.JID]
if ok {
return errorMeta, nil
}
evt, err := portal.MainIntent().GetEvent(portal.MXID, msg.MXID)
if err != nil {
return nil, fmt.Errorf("failed to fetch event %s: %w", msg.MXID, err)
}
if evt.Type == event.EventEncrypted {
err = evt.Content.ParseRaw(evt.Type)
if err != nil {
return nil, fmt.Errorf("failed to parse encrypted content in %s: %w", msg.MXID, err)
}
evt, err = portal.bridge.Crypto.Decrypt(evt)
if err != nil {
return nil, fmt.Errorf("failed to decrypt event %s: %w", msg.MXID, err)
}
}
errorMetaResult := gjson.GetBytes(evt.Content.VeryRaw, strings.ReplaceAll(failedMediaField, ".", "\\."))
if !errorMetaResult.Exists() || !errorMetaResult.IsObject() {
return nil, fmt.Errorf("didn't find failed media metadata in %s", msg.MXID)
}
var errorMetaBytes []byte
if errorMetaResult.Index > 0 {
errorMetaBytes = evt.Content.VeryRaw[errorMetaResult.Index : errorMetaResult.Index+len(errorMetaResult.Raw)]
} else {
errorMetaBytes = []byte(errorMetaResult.Raw)
}
err = json.Unmarshal(errorMetaBytes, &errorMeta)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal failed media metadata in %s: %w", msg.MXID, err)
}
return errorMeta, nil
}
func (portal *Portal) sendMediaRetryFailureEdit(intent *appservice.IntentAPI, msg *database.Message, err error) {
content := event.MessageEventContent{
MsgType: event.MsgNotice,
Body: fmt.Sprintf("Failed to bridge media after re-requesting it from your phone: %v", err),
}
contentCopy := content
content.NewContent = &contentCopy
content.RelatesTo = &event.RelatesTo{
EventID: msg.MXID,
Type: event.RelReplace,
}
resp, sendErr := portal.sendMessage(intent, event.EventMessage, &content, nil, time.Now().UnixMilli())
if sendErr != nil {
portal.log.Warnfln("Failed to edit %s after retry failure for %s: %v", msg.MXID, msg.JID, sendErr)
} else {
portal.log.Debugfln("Successfully edited %s -> %s after retry failure for %s", msg.MXID, resp.EventID, msg.JID)
}
}
func (portal *Portal) handleMediaRetry(retry *events.MediaRetry, source *User) {
msg := portal.bridge.DB.Message.GetByJID(portal.Key, retry.MessageID)
if msg == nil {
portal.log.Warnfln("Dropping media retry notification for unknown message %s", retry.MessageID)
return
} else if msg.Error != database.MsgErrMediaNotFound {
portal.log.Warnfln("Dropping media retry notification for non-errored message %s / %s", retry.MessageID, msg.MXID)
return
}
meta, err := portal.fetchMediaRetryEvent(msg)
if err != nil {
portal.log.Warnfln("Can't handle media retry notification for %s: %v", retry.MessageID, err)
return
}
var puppet *Puppet
if retry.FromMe {
puppet = portal.bridge.GetPuppetByJID(source.JID)
} else if retry.ChatID.Server == types.DefaultUserServer {
puppet = portal.bridge.GetPuppetByJID(retry.ChatID)
} else {
puppet = portal.bridge.GetPuppetByJID(retry.SenderID)
}
intent := puppet.IntentFor(portal)
retryData, err := whatsmeow.DecryptMediaRetryNotification(retry, meta.Media.Key)
if err != nil {
portal.log.Warnfln("Failed to handle media retry notification for %s: %v", retry.MessageID, err)
portal.sendMediaRetryFailureEdit(intent, msg, err)
return
} else if retryData.GetResult() != waProto.MediaRetryNotification_SUCCESS {
errorName := waProto.MediaRetryNotification_ResultType_name[int32(retryData.GetResult())]
if retryData.GetDirectPath() == "" {
portal.log.Warnfln("Got error response in media retry notification for %s: %s", retry.MessageID, errorName)
portal.log.Debugfln("Error response contents: %+v", retryData)
if retryData.GetResult() == waProto.MediaRetryNotification_NOT_FOUND {
portal.sendMediaRetryFailureEdit(intent, msg, whatsmeow.ErrMediaNotAvailableOnPhone)
} else {
portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("phone sent error response: %s", errorName))
}
return
} else {
portal.log.Debugfln("Got error response %s in media retry notification for %s, but response also contains a new download URL - trying to download", retry.MessageID, errorName)
}
}
data, err := source.Client.DownloadMediaWithPath(retryData.GetDirectPath(), meta.Media.EncSHA256, meta.Media.SHA256, meta.Media.Key, meta.Media.Length, meta.Media.Type, "")
if err != nil {
portal.log.Warnfln("Failed to download media in %s after retry notification: %v", retry.MessageID, err)
portal.sendMediaRetryFailureEdit(intent, msg, err)
return
}
err = portal.uploadMedia(intent, data, meta.Content)
if err != nil {
portal.log.Warnfln("Failed to re-upload media for %s after retry notification: %v", retry.MessageID, err)
portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("re-uploading media failed: %v", err))
return
}
replaceContent := &event.MessageEventContent{
MsgType: meta.Content.MsgType,
Body: "* " + meta.Content.Body,
NewContent: meta.Content,
RelatesTo: &event.RelatesTo{
EventID: msg.MXID,
Type: event.RelReplace,
},
}
// Move the extra content into m.new_content too
meta.ExtraContent = map[string]interface{}{
"m.new_content": shallowCopyMap(meta.ExtraContent),
}
resp, err := portal.sendMessage(intent, meta.Type, replaceContent, meta.ExtraContent, time.Now().UnixMilli())
if err != nil {
portal.log.Warnfln("Failed to edit %s after retry notification for %s: %v", msg.MXID, retry.MessageID, err)
return
}
portal.log.Debugfln("Successfully edited %s -> %s after retry notification for %s", msg.MXID, resp.EventID, retry.MessageID)
msg.UpdateMXID(nil, resp.EventID, database.MsgNormal, database.MsgNoError)
}
func (portal *Portal) requestMediaRetry(user *User, eventID id.EventID, mediaKey []byte) (bool, error) {
msg := portal.bridge.DB.Message.GetByMXID(eventID)
if msg == nil {
err := errors.New(fmt.Sprintf("%s requested a media retry for unknown event %s", user.MXID, eventID))
portal.log.Debugfln(err.Error())
return false, err
} else if msg.Error != database.MsgErrMediaNotFound {
err := errors.New(fmt.Sprintf("%s requested a media retry for non-errored event %s", user.MXID, eventID))
portal.log.Debugfln(err.Error())
return false, err
}
// If the media key is not provided, grab it from the event in Matrix
if mediaKey == nil {
evt, err := portal.fetchMediaRetryEvent(msg)
if err != nil {
portal.log.Warnfln("Can't send media retry request for %s: %v", msg.JID, err)
return true, nil
}
mediaKey = evt.Media.Key
}
err := user.Client.SendMediaRetryReceipt(&types.MessageInfo{
ID: msg.JID,
MessageSource: types.MessageSource{
IsFromMe: msg.Sender.User == user.JID.User,
IsGroup: !portal.IsPrivateChat(),
Sender: msg.Sender,
Chat: portal.Key.JID,
},
}, mediaKey)
if err != nil {
portal.log.Warnfln("Failed to send media retry request for %s: %v", msg.JID, err)
} else {
portal.log.Debugfln("Sent media retry request for %s", msg.JID)
}
return true, err
}
const thumbnailMaxSize = 72
const thumbnailMinSize = 24
func createThumbnailAndGetSize(source []byte, pngThumbnail bool) ([]byte, int, int, error) {
src, _, err := image.Decode(bytes.NewReader(source))
if err != nil {
return nil, 0, 0, fmt.Errorf("failed to decode thumbnail: %w", err)
}
imageBounds := src.Bounds()
width, height := imageBounds.Max.X, imageBounds.Max.Y
var img image.Image
if width <= thumbnailMaxSize && height <= thumbnailMaxSize {
// No need to resize
img = src
} else {
if width == height {
width = thumbnailMaxSize
height = thumbnailMaxSize
} else if width < height {
width /= height / thumbnailMaxSize
height = thumbnailMaxSize
} else {
height /= width / thumbnailMaxSize
width = thumbnailMaxSize
}
if width < thumbnailMinSize {
width = thumbnailMinSize
}
if height < thumbnailMinSize {
height = thumbnailMinSize
}
dst := image.NewRGBA(image.Rect(0, 0, width, height))
draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
img = dst
}
var buf bytes.Buffer
if pngThumbnail {
err = png.Encode(&buf, img)
} else {
err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: jpeg.DefaultQuality})
}
if err != nil {
return nil, width, height, fmt.Errorf("failed to re-encode thumbnail: %w", err)
}
return buf.Bytes(), width, height, nil
}
func createThumbnail(source []byte, png bool) ([]byte, error) {
data, _, _, err := createThumbnailAndGetSize(source, png)
return data, err
}
func (portal *Portal) downloadThumbnail(ctx context.Context, original []byte, thumbnailURL id.ContentURIString, eventID id.EventID, png bool) ([]byte, error) {
if len(thumbnailURL) == 0 {
// just fall back to making thumbnail of original
} else if mxc, err := thumbnailURL.Parse(); err != nil {
portal.log.Warnfln("Malformed thumbnail URL in %s: %v (falling back to generating thumbnail from source)", eventID, err)
} else if thumbnail, err := portal.MainIntent().DownloadBytesContext(ctx, mxc); err != nil {
portal.log.Warnfln("Failed to download thumbnail in %s: %v (falling back to generating thumbnail from source)", eventID, err)
} else {
return createThumbnail(thumbnail, png)
}
return createThumbnail(original, png)
}
func (portal *Portal) convertWebPtoPNG(webpImage []byte) ([]byte, error) {
webpDecoded, err := webp.Decode(bytes.NewReader(webpImage))
if err != nil {
return nil, fmt.Errorf("failed to decode webp image: %w", err)
}
var pngBuffer bytes.Buffer
if err = png.Encode(&pngBuffer, webpDecoded); err != nil {
return nil, fmt.Errorf("failed to encode png image: %w", err)
}
return pngBuffer.Bytes(), nil
}
type PaddedImage struct {
image.Image
Size int
OffsetX int
OffsetY int
}
func (img *PaddedImage) Bounds() image.Rectangle {
return image.Rect(0, 0, img.Size, img.Size)
}
func (img *PaddedImage) At(x, y int) color.Color {
return img.Image.At(x+img.OffsetX, y+img.OffsetY)
}
func (portal *Portal) convertToWebP(img []byte) ([]byte, error) {
decodedImg, _, err := image.Decode(bytes.NewReader(img))
if err != nil {
return img, fmt.Errorf("failed to decode image: %w", err)
}
bounds := decodedImg.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width != height {
paddedImg := &PaddedImage{
Image: decodedImg,
OffsetX: bounds.Min.Y,
OffsetY: bounds.Min.X,
}
if width > height {
paddedImg.Size = width
paddedImg.OffsetY -= (paddedImg.Size - height) / 2
} else {
paddedImg.Size = height
paddedImg.OffsetX -= (paddedImg.Size - width) / 2
}
decodedImg = paddedImg
}
var webpBuffer bytes.Buffer
if err = webp.Encode(&webpBuffer, decodedImg, nil); err != nil {
return img, fmt.Errorf("failed to encode webp image: %w", err)
}
return webpBuffer.Bytes(), nil
}
func (portal *Portal) preprocessMatrixMedia(ctx context.Context, sender *User, relaybotFormatted bool, content *event.MessageEventContent, eventID id.EventID, mediaType whatsmeow.MediaType) (*MediaUpload, error) {
fileName := content.Body
var caption string
var mentionedJIDs []string
var hasHTMLCaption bool
isSticker := string(content.MsgType) == event.EventSticker.Type
if content.FileName != "" && content.Body != content.FileName {
fileName = content.FileName
caption = content.Body
hasHTMLCaption = content.Format == event.FormatHTML
}
if relaybotFormatted || hasHTMLCaption {
caption, mentionedJIDs = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
}
var file *event.EncryptedFileInfo
rawMXC := content.URL
if content.File != nil {
file = content.File
rawMXC = file.URL
}
mxc, err := rawMXC.Parse()
if err != nil {
return nil, err
}
data, err := portal.MainIntent().DownloadBytesContext(ctx, mxc)
if err != nil {
return nil, util.NewDualError(errMediaDownloadFailed, err)
}
if file != nil {
err = file.DecryptInPlace(data)
if err != nil {
return nil, util.NewDualError(errMediaDecryptFailed, err)
}
}
mimeType := content.GetInfo().MimeType
var convertErr error
// Allowed mime types from https://developers.facebook.com/docs/whatsapp/on-premises/reference/media
switch {
case isSticker:
if mimeType != "image/webp" || content.Info.Width != content.Info.Height {
data, convertErr = portal.convertToWebP(data)
content.Info.MimeType = "image/webp"
}
case mediaType == whatsmeow.MediaVideo:
switch mimeType {
case "video/mp4", "video/3gpp":
// Allowed
case "image/gif":
data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "gif"}, []string{
"-pix_fmt", "yuv420p", "-c:v", "libx264", "-movflags", "+faststart",
"-filter:v", "crop='floor(in_w/2)*2:floor(in_h/2)*2'",
}, mimeType)
content.Info.MimeType = "video/mp4"
case "video/webm":
data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "webm"}, []string{
"-pix_fmt", "yuv420p", "-c:v", "libx264",
}, mimeType)
content.Info.MimeType = "video/mp4"
default:
return nil, fmt.Errorf("%w %q in video message", errMediaUnsupportedType, mimeType)
}
case mediaType == whatsmeow.MediaImage:
switch mimeType {
case "image/jpeg", "image/png":
// Allowed
case "image/webp":
data, convertErr = portal.convertWebPtoPNG(data)
content.Info.MimeType = "image/png"
default:
return nil, fmt.Errorf("%w %q in image message", errMediaUnsupportedType, mimeType)
}
case mediaType == whatsmeow.MediaAudio:
switch mimeType {
case "audio/aac", "audio/mp4", "audio/amr", "audio/mpeg", "audio/ogg; codecs=opus":
// Allowed
case "audio/ogg":
// Hopefully it's opus already
content.Info.MimeType = "audio/ogg; codecs=opus"
default:
return nil, fmt.Errorf("%w %q in audio message", errMediaUnsupportedType, mimeType)
}
case mediaType == whatsmeow.MediaDocument:
// Everything is allowed
}
if convertErr != nil {
if content.Info.MimeType != mimeType || data == nil {
return nil, util.NewDualError(fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, content.Info.MimeType), convertErr)
} else {
// If the mime type didn't change and the errored conversion function returned the original data, just log a warning and continue
portal.log.Warnfln("Failed to re-encode %s media: %v, continuing with original file", mimeType, convertErr)
}
}
uploadResp, err := sender.Client.Upload(ctx, data, mediaType)
if err != nil {
return nil, util.NewDualError(errMediaWhatsAppUploadFailed, err)
}
// Audio doesn't have thumbnails
var thumbnail []byte
if mediaType != whatsmeow.MediaAudio {
thumbnail, err = portal.downloadThumbnail(ctx, data, content.GetInfo().ThumbnailURL, eventID, isSticker)
// Ignore format errors for non-image files, we don't care about those thumbnails
if err != nil && (!errors.Is(err, image.ErrFormat) || mediaType == whatsmeow.MediaImage) {
portal.log.Warnfln("Failed to generate thumbnail for %s: %v", eventID, err)
}
}
return &MediaUpload{
UploadResponse: uploadResp,
FileName: fileName,
Caption: caption,
MentionedJIDs: mentionedJIDs,
Thumbnail: thumbnail,
FileLength: len(data),
}, nil
}
type MediaUpload struct {
whatsmeow.UploadResponse
Caption string
FileName string
MentionedJIDs []string
Thumbnail []byte
FileLength int
}
func (portal *Portal) addRelaybotFormat(sender *User, content *event.MessageEventContent) bool {
member := portal.MainIntent().Member(portal.MXID, sender.MXID)
if member == nil {
member = &event.MemberEventContent{}
}
content.EnsureHasHTML()
data, err := portal.bridge.Config.Bridge.Relay.FormatMessage(content, sender.MXID, *member)
if err != nil {
portal.log.Errorln("Failed to apply relaybot format:", err)
}
content.FormattedBody = data
return true
}
func addCodecToMime(mimeType, codec string) string {
mediaType, params, err := mime.ParseMediaType(mimeType)
if err != nil {
return mimeType
}
if _, ok := params["codecs"]; !ok {
params["codecs"] = codec
}
return mime.FormatMediaType(mediaType, params)
}
func parseGeoURI(uri string) (lat, long float64, err error) {
if !strings.HasPrefix(uri, "geo:") {
err = fmt.Errorf("uri doesn't have geo: prefix")
return
}
// Remove geo: prefix and anything after ;
coordinates := strings.Split(strings.TrimPrefix(uri, "geo:"), ";")[0]
if splitCoordinates := strings.Split(coordinates, ","); len(splitCoordinates) != 2 {
err = fmt.Errorf("didn't find exactly two numbers separated by a comma")
} else if lat, err = strconv.ParseFloat(splitCoordinates[0], 64); err != nil {
err = fmt.Errorf("latitude is not a number: %w", err)
} else if long, err = strconv.ParseFloat(splitCoordinates[1], 64); err != nil {
err = fmt.Errorf("longitude is not a number: %w", err)
}
return
}
func getUnstableWaveform(content map[string]interface{}) []byte {
audioInfo, ok := content["org.matrix.msc1767.audio"].(map[string]interface{})
if !ok {
return nil
}
waveform, ok := audioInfo["waveform"].([]interface{})
if !ok {
return nil
}
output := make([]byte, len(waveform))
var val float64
for i, part := range waveform {
val, ok = part.(float64)
if ok {
output[i] = byte(val / 4)
}
}
return output
}
func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, error) {
content, ok := evt.Content.Parsed.(*event.MessageEventContent)
if !ok {
return nil, sender, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
}
var editRootMsg *database.Message
if editEventID := content.RelatesTo.GetReplaceID(); editEventID != "" && portal.bridge.Config.Bridge.SendWhatsAppEdits {
editRootMsg = portal.bridge.DB.Message.GetByMXID(editEventID)
if editRootMsg == nil || editRootMsg.Type != database.MsgNormal || editRootMsg.IsFakeJID() || editRootMsg.Sender.User != sender.JID.User {
return nil, sender, fmt.Errorf("edit rejected") // TODO more specific error message
}
if content.NewContent != nil {
content = content.NewContent
}
}
msg := &waProto.Message{}
var ctxInfo waProto.ContextInfo
replyToID := content.GetReplyTo()
if len(replyToID) > 0 {
replyToMsg := portal.bridge.DB.Message.GetByMXID(replyToID)
if replyToMsg != nil && !replyToMsg.IsFakeJID() && replyToMsg.Type == database.MsgNormal {
ctxInfo.StanzaId = &replyToMsg.JID
ctxInfo.Participant = proto.String(replyToMsg.Sender.ToNonAD().String())
// Using blank content here seems to work fine on all official WhatsApp apps.
//
// We could probably invent a slightly more accurate version of the quoted message
// by fetching the Matrix event and converting it to the WhatsApp format, but that's
// a lot of work and this works fine.
ctxInfo.QuotedMessage = &waProto.Message{Conversation: proto.String("")}
}
}
if portal.ExpirationTime != 0 {
ctxInfo.Expiration = proto.Uint32(portal.ExpirationTime)
}
relaybotFormatted := false
if !sender.IsLoggedIn() || (portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User) {
if !portal.HasRelaybot() {
return nil, sender, errUserNotLoggedIn
}
relaybotFormatted = portal.addRelaybotFormat(sender, content)
sender = portal.GetRelayUser()
}
if evt.Type == event.EventSticker {
if relaybotFormatted {
// Stickers can't have captions, so force relaybot stickers to be images
content.MsgType = event.MsgImage
} else {
content.MsgType = event.MessageType(event.EventSticker.Type)
}
}
if content.MsgType == event.MsgImage && content.GetInfo().MimeType == "image/gif" {
content.MsgType = event.MsgVideo
}
switch content.MsgType {
case event.MsgText, event.MsgEmote, event.MsgNotice:
text := content.Body
if content.MsgType == event.MsgNotice && !portal.bridge.Config.Bridge.BridgeNotices {
return nil, sender, errMNoticeDisabled
}
if content.Format == event.FormatHTML {
text, ctxInfo.MentionedJid = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
}
if content.MsgType == event.MsgEmote && !relaybotFormatted {
text = "/me " + text
}
msg.ExtendedTextMessage = &waProto.ExtendedTextMessage{
Text: &text,
ContextInfo: &ctxInfo,
}
hasPreview := portal.convertURLPreviewToWhatsApp(ctx, sender, evt, msg.ExtendedTextMessage)
if ctx.Err() != nil {
return nil, nil, ctx.Err()
}
if ctxInfo.StanzaId == nil && ctxInfo.MentionedJid == nil && ctxInfo.Expiration == nil && !hasPreview {
// No need for extended message
msg.ExtendedTextMessage = nil
msg.Conversation = &text
}
case event.MsgImage:
media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
if media == nil {
return nil, sender, err
}
ctxInfo.MentionedJid = media.MentionedJIDs
msg.ImageMessage = &waProto.ImageMessage{
ContextInfo: &ctxInfo,
Caption: &media.Caption,
JpegThumbnail: media.Thumbnail,
Url: &media.URL,
MediaKey: media.MediaKey,
Mimetype: &content.GetInfo().MimeType,
FileEncSha256: media.FileEncSHA256,
FileSha256: media.FileSHA256,
FileLength: proto.Uint64(uint64(media.FileLength)),
}
case event.MessageType(event.EventSticker.Type):
media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
if media == nil {
return nil, sender, err
}
ctxInfo.MentionedJid = media.MentionedJIDs
msg.StickerMessage = &waProto.StickerMessage{
ContextInfo: &ctxInfo,
PngThumbnail: media.Thumbnail,
Url: &media.URL,
MediaKey: media.MediaKey,
Mimetype: &content.GetInfo().MimeType,
FileEncSha256: media.FileEncSHA256,
FileSha256: media.FileSHA256,
FileLength: proto.Uint64(uint64(media.FileLength)),
}
case event.MsgVideo:
gifPlayback := content.GetInfo().MimeType == "image/gif"
media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaVideo)
if media == nil {
return nil, sender, err
}
duration := uint32(content.GetInfo().Duration / 1000)
ctxInfo.MentionedJid = media.MentionedJIDs
msg.VideoMessage = &waProto.VideoMessage{
ContextInfo: &ctxInfo,
Caption: &media.Caption,
JpegThumbnail: media.Thumbnail,
Url: &media.URL,
MediaKey: media.MediaKey,
Mimetype: &content.GetInfo().MimeType,
GifPlayback: &gifPlayback,
Seconds: &duration,
FileEncSha256: media.FileEncSHA256,
FileSha256: media.FileSHA256,
FileLength: proto.Uint64(uint64(media.FileLength)),
}
case event.MsgAudio:
media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaAudio)
if media == nil {
return nil, sender, err
}
duration := uint32(content.GetInfo().Duration / 1000)
msg.AudioMessage = &waProto.AudioMessage{
ContextInfo: &ctxInfo,
Url: &media.URL,
MediaKey: media.MediaKey,
Mimetype: &content.GetInfo().MimeType,
Seconds: &duration,
FileEncSha256: media.FileEncSHA256,
FileSha256: media.FileSHA256,
FileLength: proto.Uint64(uint64(media.FileLength)),
}
_, isMSC3245Voice := evt.Content.Raw["org.matrix.msc3245.voice"]
if isMSC3245Voice {
msg.AudioMessage.Waveform = getUnstableWaveform(evt.Content.Raw)
msg.AudioMessage.Ptt = proto.Bool(true)
// hacky hack to add the codecs param that whatsapp seems to require
msg.AudioMessage.Mimetype = proto.String(addCodecToMime(content.GetInfo().MimeType, "opus"))
}
case event.MsgFile:
media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaDocument)
if media == nil {
return nil, sender, err
}
msg.DocumentMessage = &waProto.DocumentMessage{
ContextInfo: &ctxInfo,
Caption: &media.Caption,
JpegThumbnail: media.Thumbnail,
Url: &media.URL,
Title: &media.FileName,
FileName: &media.FileName,
MediaKey: media.MediaKey,
Mimetype: &content.GetInfo().MimeType,
FileEncSha256: media.FileEncSHA256,
FileSha256: media.FileSHA256,
FileLength: proto.Uint64(uint64(media.FileLength)),
}
if media.Caption != "" {
msg.DocumentWithCaptionMessage = &waProto.FutureProofMessage{
Message: &waProto.Message{
DocumentMessage: msg.DocumentMessage,
},
}
msg.DocumentMessage = nil
}
case event.MsgLocation:
lat, long, err := parseGeoURI(content.GeoURI)
if err != nil {
return nil, sender, fmt.Errorf("%w: %v", errInvalidGeoURI, err)
}
msg.LocationMessage = &waProto.LocationMessage{
DegreesLatitude: &lat,
DegreesLongitude: &long,
Comment: &content.Body,
ContextInfo: &ctxInfo,
}
default:
return nil, sender, fmt.Errorf("%w %q", errUnknownMsgType, content.MsgType)
}
if editRootMsg != nil {
msg = &waProto.Message{
EditedMessage: &waProto.FutureProofMessage{
Message: &waProto.Message{
ProtocolMessage: &waProto.ProtocolMessage{
Key: &waProto.MessageKey{
FromMe: proto.Bool(true),
Id: proto.String(editRootMsg.JID),
RemoteJid: proto.String(portal.Key.JID.String()),
},
Type: waProto.ProtocolMessage_MESSAGE_EDIT.Enum(),
EditedMessage: msg,
TimestampMs: proto.Int64(evt.Timestamp),
},
},
},
}
}
return msg, sender, nil
}
func (portal *Portal) generateMessageInfo(sender *User) *types.MessageInfo {
return &types.MessageInfo{
ID: whatsmeow.GenerateMessageID(),
Timestamp: time.Now(),
MessageSource: types.MessageSource{
Sender: sender.JID,
Chat: portal.Key.JID,
IsFromMe: true,
IsGroup: portal.Key.JID.Server == types.GroupServer || portal.Key.JID.Server == types.BroadcastServer,
},
}
}
func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event, timings messageTimings) {
start := time.Now()
ms := metricSender{portal: portal, timings: &timings}
if err := portal.canBridgeFrom(sender, true); err != nil {
go ms.sendMessageMetrics(evt, err, "Ignoring", true)
return
} else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
go ms.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", true)
return
}
messageAge := timings.totalReceive
origEvtID := evt.ID
var dbMsg *database.Message
if retryMeta := evt.Content.AsMessage().MessageSendRetry; retryMeta != nil {
origEvtID = retryMeta.OriginalEventID
dbMsg = portal.bridge.DB.Message.GetByMXID(origEvtID)
if dbMsg != nil && dbMsg.Sent {
portal.log.Debugfln("Ignoring retry request %s (#%d, age: %s) for %s/%s from %s as message was already sent", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
go ms.sendMessageMetrics(evt, nil, "", true)
return
} else if dbMsg != nil {
portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s/%s from %s", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
} else {
portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s from %s (original message not known)", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, evt.Sender)
}
} else {
portal.log.Debugfln("Received message %s from %s (age: %s)", evt.ID, evt.Sender, messageAge)
}
errorAfter := portal.bridge.Config.Bridge.MessageHandlingTimeout.ErrorAfter
deadline := portal.bridge.Config.Bridge.MessageHandlingTimeout.Deadline
isScheduled, _ := evt.Content.Raw["com.beeper.scheduled"].(bool)
if isScheduled {
portal.log.Debugfln("%s is a scheduled message, extending handling timeouts", evt.ID)
errorAfter *= 10
deadline *= 10
}
if errorAfter > 0 {
remainingTime := errorAfter - messageAge
if remainingTime < 0 {
go ms.sendMessageMetrics(evt, errTimeoutBeforeHandling, "Timeout handling", true)
return
} else if remainingTime < 1*time.Second {
portal.log.Warnfln("Message %s was delayed before reaching the bridge, only have %s (of %s timeout) until delay warning", evt.ID, remainingTime, errorAfter)
}
go func() {
time.Sleep(remainingTime)
ms.sendMessageMetrics(evt, errMessageTakingLong, "Timeout handling", false)
}()
}
ctx := context.Background()
if deadline > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, deadline)
defer cancel()
}
timings.preproc = time.Since(start)
start = time.Now()
msg, sender, err := portal.convertMatrixMessage(ctx, sender, evt)
timings.convert = time.Since(start)
if msg == nil {
go ms.sendMessageMetrics(evt, err, "Error converting", true)
return
}
dbMsgType := database.MsgNormal
if msg.EditedMessage == nil {
portal.MarkDisappearing(nil, origEvtID, portal.ExpirationTime, true)
} else {
dbMsgType = database.MsgEdit
}
info := portal.generateMessageInfo(sender)
if dbMsg == nil {
dbMsg = portal.markHandled(nil, nil, info, evt.ID, false, true, dbMsgType, database.MsgNoError)
} else {
info.ID = dbMsg.JID
}
portal.log.Debugln("Sending event", evt.ID, "to WhatsApp", info.ID)
start = time.Now()
resp, err := sender.Client.SendMessage(ctx, portal.Key.JID, info.ID, msg)
timings.totalSend = time.Since(start)
timings.whatsmeow = resp.DebugTimings
go ms.sendMessageMetrics(evt, err, "Error sending", true)
if err == nil {
dbMsg.MarkSent(resp.Timestamp)
}
}
func (portal *Portal) HandleMatrixReaction(sender *User, evt *event.Event) {
if err := portal.canBridgeFrom(sender, false); err != nil {
go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
return
} else if portal.Key.JID.Server == types.BroadcastServer {
// TODO implement this, probably by only sending the reaction to the sender of the status message?
// (whatsapp hasn't published the feature yet)
go portal.sendMessageMetrics(evt, errBroadcastReactionNotSupported, "Ignoring", nil)
return
}
content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
if ok && strings.Contains(content.RelatesTo.Key, "retry") || strings.HasPrefix(content.RelatesTo.Key, "\u267b") { // ♻️
if retryRequested, _ := portal.requestMediaRetry(sender, content.RelatesTo.EventID, nil); retryRequested {
_, _ = portal.MainIntent().RedactEvent(portal.MXID, evt.ID, mautrix.ReqRedact{
Reason: "requested media from phone",
})
// Errored media, don't try to send as reaction
return
}
}
portal.log.Debugfln("Received reaction event %s from %s", evt.ID, evt.Sender)
err := portal.handleMatrixReaction(sender, evt)
go portal.sendMessageMetrics(evt, err, "Error sending", nil)
}
func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) error {
content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
if !ok {
return fmt.Errorf("unexpected parsed content type %T", evt.Content.Parsed)
}
target := portal.bridge.DB.Message.GetByMXID(content.RelatesTo.EventID)
if target == nil || target.Type == database.MsgReaction {
return fmt.Errorf("unknown target event %s", content.RelatesTo.EventID)
}
info := portal.generateMessageInfo(sender)
dbMsg := portal.markHandled(nil, nil, info, evt.ID, false, true, database.MsgReaction, database.MsgNoError)
portal.upsertReaction(nil, nil, target.JID, sender.JID, evt.ID, info.ID)
portal.log.Debugln("Sending reaction", evt.ID, "to WhatsApp", info.ID)
resp, err := portal.sendReactionToWhatsApp(sender, info.ID, target, content.RelatesTo.Key, evt.Timestamp)
if err == nil {
dbMsg.MarkSent(resp.Timestamp)
}
return err
}
func (portal *Portal) sendReactionToWhatsApp(sender *User, id types.MessageID, target *database.Message, key string, timestamp int64) (whatsmeow.SendResponse, error) {
var messageKeyParticipant *string
if !portal.IsPrivateChat() {
messageKeyParticipant = proto.String(target.Sender.ToNonAD().String())
}
key = variationselector.Remove(key)
return sender.Client.SendMessage(context.TODO(), portal.Key.JID, id, &waProto.Message{
ReactionMessage: &waProto.ReactionMessage{
Key: &waProto.MessageKey{
RemoteJid: proto.String(portal.Key.JID.String()),
FromMe: proto.Bool(target.Sender.User == sender.JID.User),
Id: proto.String(target.JID),
Participant: messageKeyParticipant,
},
Text: proto.String(key),
SenderTimestampMs: proto.Int64(timestamp),
},
})
}
func (portal *Portal) upsertReaction(txn dbutil.Transaction, intent *appservice.IntentAPI, targetJID types.MessageID, senderJID types.JID, mxid id.EventID, jid types.MessageID) {
dbReaction := portal.bridge.DB.Reaction.GetByTargetJID(portal.Key, targetJID, senderJID)
if dbReaction == nil {
dbReaction = portal.bridge.DB.Reaction.New()
dbReaction.Chat = portal.Key
dbReaction.TargetJID = targetJID
dbReaction.Sender = senderJID
} else if intent != nil {
portal.log.Debugfln("Redacting old Matrix reaction %s after new one (%s) was sent", dbReaction.MXID, mxid)
var err error
if intent != nil {
_, err = intent.RedactEvent(portal.MXID, dbReaction.MXID)
}
if intent == nil || errors.Is(err, mautrix.MForbidden) {
_, err = portal.MainIntent().RedactEvent(portal.MXID, dbReaction.MXID)
}
if err != nil {
portal.log.Warnfln("Failed to remove old reaction %s: %v", dbReaction.MXID, err)
}
}
dbReaction.MXID = mxid
dbReaction.JID = jid
dbReaction.Upsert(txn)
}
func (portal *Portal) HandleMatrixRedaction(sender *User, evt *event.Event) {
if err := portal.canBridgeFrom(sender, true); err != nil {
go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
return
}
portal.log.Debugfln("Received redaction %s from %s", evt.ID, evt.Sender)
senderLogIdentifier := sender.MXID
if !sender.HasSession() {
sender = portal.GetRelayUser()
senderLogIdentifier += " (through relaybot)"
}
msg := portal.bridge.DB.Message.GetByMXID(evt.Redacts)
if msg == nil {
go portal.sendMessageMetrics(evt, errTargetNotFound, "Ignoring", nil)
} else if msg.IsFakeJID() {
go portal.sendMessageMetrics(evt, errTargetIsFake, "Ignoring", nil)
} else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
go portal.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", nil)
} else if msg.Type == database.MsgReaction {
if msg.Sender.User != sender.JID.User {
go portal.sendMessageMetrics(evt, errReactionSentBySomeoneElse, "Ignoring", nil)
} else if reaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts); reaction == nil {
go portal.sendMessageMetrics(evt, errReactionDatabaseNotFound, "Ignoring", nil)
} else if reactionTarget := reaction.GetTarget(); reactionTarget == nil {
go portal.sendMessageMetrics(evt, errReactionTargetNotFound, "Ignoring", nil)
} else {
portal.log.Debugfln("Sending redaction reaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
_, err := portal.sendReactionToWhatsApp(sender, "", reactionTarget, "", evt.Timestamp)
go portal.sendMessageMetrics(evt, err, "Error sending", nil)
}
} else {
key := &waProto.MessageKey{
FromMe: proto.Bool(true),
Id: proto.String(msg.JID),
RemoteJid: proto.String(portal.Key.JID.String()),
}
if msg.Sender.User != sender.JID.User {
if portal.IsPrivateChat() {
go portal.sendMessageMetrics(evt, errDMSentByOtherUser, "Ignoring", nil)
return
}
key.FromMe = proto.Bool(false)
key.Participant = proto.String(msg.Sender.ToNonAD().String())
}
portal.log.Debugfln("Sending redaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
_, err := sender.Client.SendMessage(context.TODO(), portal.Key.JID, "", &waProto.Message{
ProtocolMessage: &waProto.ProtocolMessage{
Type: waProto.ProtocolMessage_REVOKE.Enum(),
Key: key,
},
})
go portal.sendMessageMetrics(evt, err, "Error sending", nil)
}
}
func (portal *Portal) HandleMatrixReadReceipt(sender bridge.User, eventID id.EventID, receipt event.ReadReceipt) {
portal.handleMatrixReadReceipt(sender.(*User), eventID, receipt.Timestamp, true)
}
func (portal *Portal) handleMatrixReadReceipt(sender *User, eventID id.EventID, receiptTimestamp time.Time, isExplicit bool) {
if !sender.IsLoggedIn() {
if isExplicit {
portal.log.Debugfln("Ignoring read receipt by %s/%s: user is not connected to WhatsApp", sender.MXID, sender.JID)
}
return
}
maxTimestamp := receiptTimestamp
// Implicit read receipts don't have an event ID that's already bridged
if isExplicit {
if message := portal.bridge.DB.Message.GetByMXID(eventID); message != nil {
maxTimestamp = message.Timestamp
}
}
prevTimestamp := sender.GetLastReadTS(portal.Key)
lastReadIsZero := false
if prevTimestamp.IsZero() {
prevTimestamp = maxTimestamp.Add(-2 * time.Second)
lastReadIsZero = true
}
messages := portal.bridge.DB.Message.GetMessagesBetween(portal.Key, prevTimestamp, maxTimestamp)
if len(messages) > 0 {
sender.SetLastReadTS(portal.Key, messages[len(messages)-1].Timestamp)
}
groupedMessages := make(map[types.JID][]types.MessageID)
for _, msg := range messages {
var key types.JID
if msg.IsFakeJID() || msg.Sender.User == sender.JID.User {
// Don't send read receipts for own messages or fake messages
continue
} else if !portal.IsPrivateChat() {
key = msg.Sender
} else if !msg.BroadcastListJID.IsEmpty() {
key = msg.BroadcastListJID
} // else: blank key (participant field isn't needed in direct chat read receipts)
groupedMessages[key] = append(groupedMessages[key], msg.JID)
}
// For explicit read receipts, log even if there are no targets. For implicit ones only log when there are targets
if len(groupedMessages) > 0 || isExplicit {
portal.log.Debugfln("Sending read receipts by %s (last read: %d, was zero: %t, explicit: %t): %v",
sender.JID, prevTimestamp.Unix(), lastReadIsZero, isExplicit, groupedMessages)
}
for messageSender, ids := range groupedMessages {
chatJID := portal.Key.JID
if messageSender.Server == types.BroadcastServer {
chatJID = messageSender
messageSender = portal.Key.JID
}
err := sender.Client.MarkRead(ids, receiptTimestamp, chatJID, messageSender)
if err != nil {
portal.log.Warnfln("Failed to mark %v as read by %s: %v", ids, sender.JID, err)
}
}
if isExplicit {
portal.ScheduleDisappearing()
}
}
func typingDiff(prev, new []id.UserID) (started, stopped []id.UserID) {
OuterNew:
for _, userID := range new {
for _, previousUserID := range prev {
if userID == previousUserID {
continue OuterNew
}
}
started = append(started, userID)
}
OuterPrev:
for _, userID := range prev {
for _, previousUserID := range new {
if userID == previousUserID {
continue OuterPrev
}
}
stopped = append(stopped, userID)
}
return
}
func (portal *Portal) setTyping(userIDs []id.UserID, state types.ChatPresence) {
for _, userID := range userIDs {
user := portal.bridge.GetUserByMXIDIfExists(userID)
if user == nil || !user.IsLoggedIn() {
continue
}
portal.log.Debugfln("Bridging typing change from %s to chat presence %s", state, user.MXID)
err := user.Client.SendChatPresence(portal.Key.JID, state, types.ChatPresenceMediaText)
if err != nil {
portal.log.Warnln("Error sending chat presence:", err)
}
if portal.bridge.Config.Bridge.SendPresenceOnTyping {
err = user.Client.SendPresence(types.PresenceAvailable)
if err != nil {
user.log.Warnln("Failed to set presence:", err)
}
}
}
}
func (portal *Portal) HandleMatrixTyping(newTyping []id.UserID) {
portal.currentlyTypingLock.Lock()
defer portal.currentlyTypingLock.Unlock()
startedTyping, stoppedTyping := typingDiff(portal.currentlyTyping, newTyping)
portal.currentlyTyping = newTyping
portal.setTyping(startedTyping, types.ChatPresenceComposing)
portal.setTyping(stoppedTyping, types.ChatPresencePaused)
}
func (portal *Portal) canBridgeFrom(sender *User, allowRelay bool) error {
if !sender.IsLoggedIn() {
if allowRelay && portal.HasRelaybot() {
return nil
} else if sender.Session != nil {
return errUserNotConnected
} else {
return errUserNotLoggedIn
}
} else if portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User && (!allowRelay || !portal.HasRelaybot()) {
return errDifferentUser
}
return nil
}
func (portal *Portal) Delete() {
portal.Portal.Delete()
portal.bridge.portalsLock.Lock()
delete(portal.bridge.portalsByJID, portal.Key)
if len(portal.MXID) > 0 {
delete(portal.bridge.portalsByMXID, portal.MXID)
}
portal.bridge.portalsLock.Unlock()
}
func (portal *Portal) GetMatrixUsers() ([]id.UserID, error) {
members, err := portal.MainIntent().JoinedMembers(portal.MXID)
if err != nil {
return nil, fmt.Errorf("failed to get member list: %w", err)
}
var users []id.UserID
for userID := range members.Joined {
_, isPuppet := portal.bridge.ParsePuppetMXID(userID)
if !isPuppet && userID != portal.bridge.Bot.UserID {
users = append(users, userID)
}
}
return users, nil
}
func (portal *Portal) CleanupIfEmpty() {
users, err := portal.GetMatrixUsers()
if err != nil {
portal.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
return
}
if len(users) == 0 {
portal.log.Infoln("Room seems to be empty, cleaning up...")
portal.Delete()
portal.Cleanup(false)
}
}
func (portal *Portal) Cleanup(puppetsOnly bool) {
if len(portal.MXID) == 0 {
return
}
intent := portal.MainIntent()
members, err := intent.JoinedMembers(portal.MXID)
if err != nil {
portal.log.Errorln("Failed to get portal members for cleanup:", err)
return
}
for member := range members.Joined {
if member == intent.UserID {
continue
}
puppet := portal.bridge.GetPuppetByMXID(member)
if puppet != nil {
_, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
if err != nil {
portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
}
} else if !puppetsOnly {
_, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
if err != nil {
portal.log.Errorln("Error kicking user while cleaning up portal:", err)
}
}
}
_, err = intent.LeaveRoom(portal.MXID)
if err != nil {
portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
}
}
func (portal *Portal) HandleMatrixLeave(brSender bridge.User) {
sender := brSender.(*User)
if portal.IsPrivateChat() {
portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
portal.Delete()
portal.Cleanup(false)
return
} else if portal.bridge.Config.Bridge.BridgeMatrixLeave {
err := sender.Client.LeaveGroup(portal.Key.JID)
if err != nil {
portal.log.Errorfln("Failed to leave group as %s: %v", sender.MXID, err)
return
}
//portal.log.Infoln("Leave response:", <-resp)
}
portal.CleanupIfEmpty()
}
func (portal *Portal) HandleMatrixKick(brSender bridge.User, brTarget bridge.Ghost) {
sender := brSender.(*User)
target := brTarget.(*Puppet)
_, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
target.JID: whatsmeow.ParticipantChangeRemove,
})
if err != nil {
portal.log.Errorfln("Failed to kick %s from group as %s: %v", target.JID, sender.MXID, err)
return
}
//portal.log.Infoln("Kick %s response: %s", puppet.JID, <-resp)
}
func (portal *Portal) HandleMatrixInvite(brSender bridge.User, brTarget bridge.Ghost) {
sender := brSender.(*User)
target := brTarget.(*Puppet)
_, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
target.JID: whatsmeow.ParticipantChangeAdd,
})
if err != nil {
portal.log.Errorfln("Failed to add %s to group as %s: %v", target.JID, sender.MXID, err)
return
}
//portal.log.Infofln("Add %s response: %s", puppet.JID, <-resp)
}
func (portal *Portal) HandleMatrixMeta(brSender bridge.User, evt *event.Event) {
sender := brSender.(*User)
if !sender.Whitelisted || !sender.IsLoggedIn() {
return
}
switch content := evt.Content.Parsed.(type) {
case *event.RoomNameEventContent:
if content.Name == portal.Name {
return
}
portal.Name = content.Name
err := sender.Client.SetGroupName(portal.Key.JID, content.Name)
if err != nil {
portal.log.Errorln("Failed to update group name:", err)
}
case *event.TopicEventContent:
if content.Topic == portal.Topic {
return
}
portal.Topic = content.Topic
err := sender.Client.SetGroupTopic(portal.Key.JID, "", "", content.Topic)
if err != nil {
portal.log.Errorln("Failed to update group description:", err)
}
case *event.RoomAvatarEventContent:
portal.avatarLock.Lock()
defer portal.avatarLock.Unlock()
if content.URL == portal.AvatarURL || (content.URL.IsEmpty() && portal.Avatar == "remove") {
return
}
var data []byte
var err error
if !content.URL.IsEmpty() {
data, err = portal.MainIntent().DownloadBytes(content.URL)
if err != nil {
portal.log.Errorfln("Failed to download updated avatar %s: %v", content.URL, err)
return
}
portal.log.Debugfln("%s set the group avatar to %s", sender.MXID, content.URL)
} else {
portal.log.Debugfln("%s removed the group avatar", sender.MXID)
}
newID, err := sender.Client.SetGroupPhoto(portal.Key.JID, data)
if err != nil {
portal.log.Errorfln("Failed to update group avatar: %v", err)
return
}
portal.log.Debugfln("Successfully updated group avatar to %s", newID)
portal.Avatar = newID
portal.AvatarURL = content.URL
portal.UpdateBridgeInfo()
portal.Update(nil)
}
}