urlpreview.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/json"
  21. "image"
  22. "net/http"
  23. "strings"
  24. "time"
  25. "github.com/tidwall/gjson"
  26. "google.golang.org/protobuf/proto"
  27. "maunium.net/go/mautrix/appservice"
  28. "maunium.net/go/mautrix/crypto/attachment"
  29. "maunium.net/go/mautrix/event"
  30. "maunium.net/go/mautrix/id"
  31. "go.mau.fi/whatsmeow"
  32. waProto "go.mau.fi/whatsmeow/binary/proto"
  33. )
  34. type BeeperLinkPreview struct {
  35. MatchedURL string `json:"matched_url"`
  36. CanonicalURL string `json:"og:url,omitempty"`
  37. Title string `json:"og:title,omitempty"`
  38. Type string `json:"og:type,omitempty"`
  39. Description string `json:"og:description,omitempty"`
  40. ImageURL id.ContentURIString `json:"og:image,omitempty"`
  41. ImageEncryption *event.EncryptedFileInfo `json:"beeper:image:encryption,omitempty"`
  42. ImageSize int `json:"matrix:image:size,omitempty"`
  43. ImageWidth int `json:"og:image:width,omitempty"`
  44. ImageHeight int `json:"og:image:height,omitempty"`
  45. ImageType string `json:"og:image:type,omitempty"`
  46. }
  47. func (portal *Portal) convertURLPreviewToBeeper(intent *appservice.IntentAPI, source *User, msg *waProto.ExtendedTextMessage) []*BeeperLinkPreview {
  48. if msg.GetMatchedText() == "" {
  49. return []*BeeperLinkPreview{}
  50. }
  51. output := &BeeperLinkPreview{
  52. MatchedURL: msg.GetMatchedText(),
  53. CanonicalURL: msg.GetCanonicalUrl(),
  54. Title: msg.GetTitle(),
  55. Description: msg.GetDescription(),
  56. }
  57. if len(output.CanonicalURL) == 0 {
  58. output.CanonicalURL = output.MatchedURL
  59. }
  60. var thumbnailData []byte
  61. if msg.ThumbnailDirectPath != nil {
  62. var err error
  63. thumbnailData, err = source.Client.DownloadThumbnail(msg)
  64. if err != nil {
  65. portal.log.Warnfln("Failed to download thumbnail for link preview: %v", err)
  66. }
  67. }
  68. if thumbnailData == nil && msg.JpegThumbnail != nil {
  69. thumbnailData = msg.JpegThumbnail
  70. }
  71. if thumbnailData != nil {
  72. output.ImageHeight = int(msg.GetThumbnailHeight())
  73. output.ImageWidth = int(msg.GetThumbnailWidth())
  74. if output.ImageHeight == 0 || output.ImageWidth == 0 {
  75. src, _, err := image.Decode(bytes.NewReader(thumbnailData))
  76. if err == nil {
  77. imageBounds := src.Bounds()
  78. output.ImageWidth, output.ImageHeight = imageBounds.Max.X, imageBounds.Max.Y
  79. }
  80. }
  81. output.ImageSize = len(thumbnailData)
  82. output.ImageType = http.DetectContentType(thumbnailData)
  83. uploadData, uploadMime := thumbnailData, output.ImageType
  84. if portal.Encrypted {
  85. crypto := attachment.NewEncryptedFile()
  86. uploadData = crypto.Encrypt(uploadData)
  87. uploadMime = "application/octet-stream"
  88. output.ImageEncryption = &event.EncryptedFileInfo{EncryptedFile: *crypto}
  89. }
  90. resp, err := intent.UploadBytes(uploadData, uploadMime)
  91. if err != nil {
  92. portal.log.Warnfln("Failed to reupload thumbnail for link preview: %v", err)
  93. } else {
  94. if output.ImageEncryption != nil {
  95. output.ImageEncryption.URL = resp.ContentURI.CUString()
  96. } else {
  97. output.ImageURL = resp.ContentURI.CUString()
  98. }
  99. }
  100. }
  101. if msg.GetPreviewType() == waProto.ExtendedTextMessage_VIDEO {
  102. output.Type = "video.other"
  103. }
  104. return []*BeeperLinkPreview{output}
  105. }
  106. func (portal *Portal) convertURLPreviewToWhatsApp(sender *User, evt *event.Event, dest *waProto.ExtendedTextMessage) {
  107. rawPreview := gjson.GetBytes(evt.Content.VeryRaw, `com\.beeper\.linkpreviews`)
  108. if !rawPreview.Exists() || !rawPreview.IsArray() {
  109. return
  110. }
  111. var previews []BeeperLinkPreview
  112. if err := json.Unmarshal([]byte(rawPreview.Raw), &previews); err != nil || len(previews) == 0 {
  113. return
  114. }
  115. // WhatsApp only supports a single preview.
  116. preview := previews[0]
  117. if len(preview.MatchedURL) == 0 {
  118. return
  119. }
  120. dest.MatchedText = &preview.MatchedURL
  121. if len(preview.CanonicalURL) > 0 {
  122. dest.CanonicalUrl = &preview.CanonicalURL
  123. }
  124. if len(preview.Description) > 0 {
  125. dest.Description = &preview.Description
  126. }
  127. if len(preview.Title) > 0 {
  128. dest.Title = &preview.Title
  129. }
  130. if strings.HasPrefix(preview.Type, "video.") {
  131. dest.PreviewType = waProto.ExtendedTextMessage_VIDEO.Enum()
  132. }
  133. imageMXC := preview.ImageURL.ParseOrIgnore()
  134. if preview.ImageEncryption != nil {
  135. imageMXC = preview.ImageEncryption.URL.ParseOrIgnore()
  136. }
  137. if !imageMXC.IsEmpty() {
  138. data, err := portal.MainIntent().DownloadBytes(imageMXC)
  139. if err != nil {
  140. portal.log.Errorfln("Failed to download URL preview image %s in %s: %v", preview.ImageURL, evt.ID, err)
  141. return
  142. }
  143. if preview.ImageEncryption != nil {
  144. data, err = preview.ImageEncryption.Decrypt(data)
  145. if err != nil {
  146. portal.log.Errorfln("Failed to decrypt URL preview image in %s: %v", evt.ID, err)
  147. return
  148. }
  149. }
  150. dest.MediaKeyTimestamp = proto.Int64(time.Now().Unix())
  151. uploadResp, err := sender.Client.Upload(context.Background(), data, whatsmeow.MediaLinkThumbnail)
  152. if err != nil {
  153. portal.log.Errorfln("Failed to upload URL preview thumbnail in %s: %v", evt.ID, err)
  154. return
  155. }
  156. dest.ThumbnailSha256 = uploadResp.FileSHA256
  157. dest.ThumbnailEncSha256 = uploadResp.FileEncSHA256
  158. dest.ThumbnailDirectPath = &uploadResp.DirectPath
  159. dest.MediaKey = uploadResp.MediaKey
  160. var width, height int
  161. dest.JpegThumbnail, width, height, err = createJPEGThumbnailAndGetSize(data)
  162. if err != nil {
  163. portal.log.Warnfln("Failed to create JPEG thumbnail for URL preview in %s: %v", evt.ID, err)
  164. }
  165. if preview.ImageHeight > 0 && preview.ImageWidth > 0 {
  166. dest.ThumbnailWidth = proto.Uint32(uint32(preview.ImageWidth))
  167. dest.ThumbnailHeight = proto.Uint32(uint32(preview.ImageHeight))
  168. } else if width > 0 && height > 0 {
  169. dest.ThumbnailWidth = proto.Uint32(uint32(width))
  170. dest.ThumbnailHeight = proto.Uint32(uint32(height))
  171. }
  172. }
  173. }