// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2018 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 $2$3",
}
func (portal *Portal) ParseWhatsAppFormat(input string) string {
output := html.EscapeString(input)
for regex, replacement := range whatsAppFormat {
output = regex.ReplaceAllString(output, replacement)
}
output = codeBlockRegex.ReplaceAllStringFunc(output, func(str string) string {
str = str[3 : len(str)-3]
if strings.ContainsRune(str, '\n') {
return fmt.Sprintf("
%s
", str)
}
return fmt.Sprintf("%s
", str)
})
return output
}
func (portal *Portal) HandleTextMessage(message whatsapp.TextMessage) {
if portal.IsDuplicate(message.Info.Id) {
return
}
err := portal.CreateMatrixRoom()
if err != nil {
portal.log.Errorln("Failed to create portal room:", err)
return
}
intent := portal.GetMessageIntent(message.Info)
if intent == nil {
return
}
content := gomatrix.Content{
Body: message.Text,
MsgType: gomatrix.MsgText,
}
htmlBody := portal.ParseWhatsAppFormat(message.Text)
if htmlBody != message.Text {
content.FormattedBody = htmlBody
content.Format = gomatrix.FormatHTML
}
portal.SetReply(&content, message.Info)
intent.UserTyping(portal.MXID, false, 0)
resp, err := intent.SendMassagedMessageEvent(portal.MXID, gomatrix.EventMessage, content, int64(message.Info.Timestamp*1000))
if err != nil {
portal.log.Errorfln("Failed to handle message %s: %v", message.Info.Id, err)
return
}
portal.MarkHandled(message.Info.Id, resp.EventID)
portal.log.Debugln("Handled message", message.Info.Id, "->", resp.EventID)
}
func (portal *Portal) HandleMediaMessage(download func() ([]byte, error), thumbnail []byte, info whatsapp.MessageInfo, mimeType, caption string) {
if portal.IsDuplicate(info.Id) {
return
}
err := portal.CreateMatrixRoom()
if err != nil {
portal.log.Errorln("Failed to create portal room:", err)
return
}
intent := portal.GetMessageIntent(info)
if intent == nil {
return
}
data, err := download()
if err != nil {
portal.log.Errorln("Failed to download media:", err)
return
}
uploaded, err := intent.UploadBytes(data, mimeType)
if err != nil {
portal.log.Errorln("Failed to upload media:", err)
return
}
if len(caption) == 0 {
caption = info.Id
exts, _ := mime.ExtensionsByType(mimeType)
if exts != nil && len(exts) > 0 {
caption += exts[0]
}
}
content := gomatrix.Content{
Body: caption,
URL: uploaded.ContentURI,
Info: &gomatrix.FileInfo{
Size: len(data),
MimeType: mimeType,
},
}
portal.SetReply(&content, info)
if thumbnail != nil {
thumbnailMime := http.DetectContentType(thumbnail)
uploadedThumbnail, _ := intent.UploadBytes(thumbnail, thumbnailMime)
if uploadedThumbnail != nil {
content.Info.ThumbnailURL = uploadedThumbnail.ContentURI
cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
content.Info.ThumbnailInfo = &gomatrix.FileInfo{
Size: len(thumbnail),
Width: cfg.Width,
Height: cfg.Height,
MimeType: thumbnailMime,
}
}
}
switch strings.ToLower(strings.Split(mimeType, "/")[0]) {
case "image":
content.MsgType = gomatrix.MsgImage
cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
content.Info.Width = cfg.Width
content.Info.Height = cfg.Height
case "video":
content.MsgType = gomatrix.MsgVideo
case "audio":
content.MsgType = gomatrix.MsgAudio
default:
content.MsgType = gomatrix.MsgFile
}
intent.UserTyping(portal.MXID, false, 0)
resp, err := intent.SendMassagedMessageEvent(portal.MXID, gomatrix.EventMessage, content, int64(info.Timestamp*1000))
if err != nil {
portal.log.Errorfln("Failed to handle message %s: %v", info.Id, err)
return
}
portal.MarkHandled(info.Id, resp.EventID)
portal.log.Debugln("Handled message", info.Id, "->", resp.EventID)
}
var htmlParser = format.HTMLParser{
TabsToSpaces: 4,
Newline: "\n",
PillConverter: func(mxid, eventID string) string {
return mxid
},
BoldConverter: func(text string) string {
return fmt.Sprintf("*%s*", text)
},
ItalicConverter: func(text string) string {
return fmt.Sprintf("_%s_", text)
},
StrikethroughConverter: func(text string) string {
return fmt.Sprintf("~%s~", text)
},
MonospaceConverter: func(text string) string {
return fmt.Sprintf("```%s```", text)
},
MonospaceBlockConverter: func(text string) string {
return fmt.Sprintf("```%s```", text)
},
}
func makeMessageID() string {
b := make([]byte, 10)
rand.Read(b)
return strings.ToUpper(hex.EncodeToString(b))
}
func (portal *Portal) PreprocessMatrixMedia(evt *gomatrix.Event) (string, io.ReadCloser, []byte) {
if evt.Content.Info == nil {
evt.Content.Info = &gomatrix.FileInfo{}
}
caption := evt.Content.Body
exts, err := mime.ExtensionsByType(evt.Content.Info.MimeType)
for _, ext := range exts {
if strings.HasSuffix(caption, ext) {
caption = ""
break
}
}
content, err := portal.MainIntent().Download(evt.Content.URL)
if err != nil {
portal.log.Errorln("Failed to download media in %s: %v", evt.ID, err)
return "", nil, nil
}
thumbnail, err := portal.MainIntent().DownloadBytes(evt.Content.Info.ThumbnailURL)
return caption, content, thumbnail
}
func (portal *Portal) HandleMatrixMessage(evt *gomatrix.Event) {
info := whatsapp.MessageInfo{
Id: makeMessageID(),
RemoteJid: portal.JID,
}
var err error
switch evt.Content.MsgType {
case gomatrix.MsgText, gomatrix.MsgEmote:
text := evt.Content.Body
if evt.Content.Format == gomatrix.FormatHTML {
text = htmlParser.Parse(evt.Content.FormattedBody)
}
if evt.Content.MsgType == gomatrix.MsgEmote {
text = "/me " + text
}
err = portal.user.Conn.Send(whatsapp.TextMessage{
Text: text,
Info: info,
})
case gomatrix.MsgImage:
caption, content, thumbnail := portal.PreprocessMatrixMedia(evt)
if content == nil {
return
}
err = portal.user.Conn.Send(whatsapp.ImageMessage{
Caption: caption,
Content: content,
Thumbnail: thumbnail,
Type: evt.Content.Info.MimeType,
Info: info,
})
case gomatrix.MsgVideo:
caption, content, thumbnail := portal.PreprocessMatrixMedia(evt)
if content == nil {
return
}
err = portal.user.Conn.Send(whatsapp.VideoMessage{
Caption: caption,
Content: content,
Thumbnail: thumbnail,
Type: evt.Content.Info.MimeType,
Info: info,
})
case gomatrix.MsgAudio:
_, content, _ := portal.PreprocessMatrixMedia(evt)
if content == nil {
return
}
err = portal.user.Conn.Send(whatsapp.AudioMessage{
Content: content,
Type: evt.Content.Info.MimeType,
Info: info,
})
case gomatrix.MsgFile:
_, content, thumbnail := portal.PreprocessMatrixMedia(evt)
if content == nil {
return
}
err = portal.user.Conn.Send(whatsapp.DocumentMessage{
Content: content,
Thumbnail: thumbnail,
Type: evt.Content.Info.MimeType,
Info: info,
})
default:
portal.log.Debugln("Unhandled Matrix event:", evt)
return
}
portal.MarkHandled(info.Id, evt.ID)
if err != nil {
portal.log.Errorfln("Error handling Matrix event %s: %v", evt.ID, err)
} else {
portal.log.Debugln("Handled Matrix event:", evt)
}
}