portal_convert.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. // mautrix-discord - A Matrix-Discord puppeting bridge.
  2. // Copyright (C) 2023 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. "context"
  19. "fmt"
  20. "html"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/bwmarrin/discordgo"
  25. "github.com/rs/zerolog"
  26. "golang.org/x/exp/slices"
  27. "maunium.net/go/mautrix/id"
  28. "maunium.net/go/mautrix"
  29. "maunium.net/go/mautrix/appservice"
  30. "maunium.net/go/mautrix/event"
  31. "maunium.net/go/mautrix/format"
  32. )
  33. type ConvertedMessage struct {
  34. AttachmentID string
  35. Type event.Type
  36. Content *event.MessageEventContent
  37. Extra map[string]any
  38. }
  39. func (portal *Portal) createMediaFailedMessage(bridgeErr error) *event.MessageEventContent {
  40. return &event.MessageEventContent{
  41. Body: fmt.Sprintf("Failed to bridge media: %v", bridgeErr),
  42. MsgType: event.MsgNotice,
  43. }
  44. }
  45. const DiscordStickerSize = 160
  46. func (portal *Portal) convertDiscordFile(ctx context.Context, typeName string, intent *appservice.IntentAPI, id, url string, content *event.MessageEventContent) *event.MessageEventContent {
  47. meta := AttachmentMeta{AttachmentID: id, MimeType: content.Info.MimeType}
  48. if typeName == "sticker" && content.Info.MimeType == "application/json" {
  49. meta.Converter = portal.bridge.convertLottie
  50. }
  51. dbFile, err := portal.bridge.copyAttachmentToMatrix(intent, url, portal.Encrypted, meta)
  52. if err != nil {
  53. zerolog.Ctx(ctx).Err(err).Msg("Failed to copy attachment to Matrix")
  54. return portal.createMediaFailedMessage(err)
  55. }
  56. if typeName == "sticker" && content.Info.MimeType == "application/json" {
  57. content.Info.MimeType = dbFile.MimeType
  58. }
  59. content.Info.Size = dbFile.Size
  60. if content.Info.Width == 0 && content.Info.Height == 0 {
  61. content.Info.Width = dbFile.Width
  62. content.Info.Height = dbFile.Height
  63. }
  64. if dbFile.DecryptionInfo != nil {
  65. content.File = &event.EncryptedFileInfo{
  66. EncryptedFile: *dbFile.DecryptionInfo,
  67. URL: dbFile.MXC.CUString(),
  68. }
  69. } else {
  70. content.URL = dbFile.MXC.CUString()
  71. }
  72. return content
  73. }
  74. func (portal *Portal) cleanupConvertedStickerInfo(content *event.MessageEventContent) {
  75. if content.Info == nil {
  76. return
  77. }
  78. if content.Info.Width == 0 && content.Info.Height == 0 {
  79. content.Info.Width = DiscordStickerSize
  80. content.Info.Height = DiscordStickerSize
  81. } else if content.Info.Width > DiscordStickerSize || content.Info.Height > DiscordStickerSize {
  82. if content.Info.Width > content.Info.Height {
  83. content.Info.Height /= content.Info.Width / DiscordStickerSize
  84. content.Info.Width = DiscordStickerSize
  85. } else if content.Info.Width < content.Info.Height {
  86. content.Info.Width /= content.Info.Height / DiscordStickerSize
  87. content.Info.Height = DiscordStickerSize
  88. } else {
  89. content.Info.Width = DiscordStickerSize
  90. content.Info.Height = DiscordStickerSize
  91. }
  92. }
  93. }
  94. func (portal *Portal) convertDiscordSticker(ctx context.Context, intent *appservice.IntentAPI, sticker *discordgo.Sticker) *ConvertedMessage {
  95. var mime, ext string
  96. switch sticker.FormatType {
  97. case discordgo.StickerFormatTypePNG:
  98. mime = "image/png"
  99. ext = "png"
  100. case discordgo.StickerFormatTypeAPNG:
  101. mime = "image/apng"
  102. ext = "png"
  103. case discordgo.StickerFormatTypeLottie:
  104. mime = "application/json"
  105. ext = "json"
  106. case discordgo.StickerFormatTypeGIF:
  107. mime = "image/gif"
  108. ext = "gif"
  109. default:
  110. zerolog.Ctx(ctx).Warn().
  111. Int("sticker_format", int(sticker.FormatType)).
  112. Str("sticker_id", sticker.ID).
  113. Msg("Unknown sticker format")
  114. }
  115. content := &event.MessageEventContent{
  116. Body: sticker.Name, // TODO find description from somewhere?
  117. Info: &event.FileInfo{
  118. MimeType: mime,
  119. },
  120. }
  121. mxc := portal.bridge.Config.Bridge.MediaPatterns.Sticker(sticker.ID, ext)
  122. if mxc.IsEmpty() {
  123. content = portal.convertDiscordFile(ctx, "sticker", intent, sticker.ID, sticker.URL(), content)
  124. } else {
  125. content.URL = mxc.CUString()
  126. }
  127. portal.cleanupConvertedStickerInfo(content)
  128. return &ConvertedMessage{
  129. AttachmentID: sticker.ID,
  130. Type: event.EventSticker,
  131. Content: content,
  132. }
  133. }
  134. func (portal *Portal) convertDiscordAttachment(ctx context.Context, intent *appservice.IntentAPI, att *discordgo.MessageAttachment) *ConvertedMessage {
  135. content := &event.MessageEventContent{
  136. Body: att.Filename,
  137. Info: &event.FileInfo{
  138. Height: att.Height,
  139. MimeType: att.ContentType,
  140. Width: att.Width,
  141. // This gets overwritten later after the file is uploaded to the homeserver
  142. Size: att.Size,
  143. },
  144. }
  145. if att.Description != "" {
  146. content.Body = att.Description
  147. content.FileName = att.Filename
  148. }
  149. var extra map[string]any
  150. switch strings.ToLower(strings.Split(att.ContentType, "/")[0]) {
  151. case "audio":
  152. content.MsgType = event.MsgAudio
  153. if att.Waveform != nil {
  154. // TODO convert waveform
  155. extra = map[string]any{
  156. "org.matrix.1767.audio": map[string]any{
  157. "duration": int(att.DurationSeconds * 1000),
  158. },
  159. "org.matrix.msc3245.voice": map[string]any{},
  160. }
  161. }
  162. case "image":
  163. content.MsgType = event.MsgImage
  164. case "video":
  165. content.MsgType = event.MsgVideo
  166. default:
  167. content.MsgType = event.MsgFile
  168. }
  169. mxc := portal.bridge.Config.Bridge.MediaPatterns.Attachment(portal.Key.ChannelID, att.ID, att.Filename)
  170. if mxc.IsEmpty() {
  171. content = portal.convertDiscordFile(ctx, "attachment", intent, att.ID, att.URL, content)
  172. } else {
  173. content.URL = mxc.CUString()
  174. }
  175. return &ConvertedMessage{
  176. AttachmentID: att.ID,
  177. Type: event.EventMessage,
  178. Content: content,
  179. Extra: extra,
  180. }
  181. }
  182. func (portal *Portal) convertDiscordVideoEmbed(ctx context.Context, intent *appservice.IntentAPI, embed *discordgo.MessageEmbed) *ConvertedMessage {
  183. attachmentID := fmt.Sprintf("video_%s", embed.URL)
  184. var proxyURL string
  185. if embed.Video != nil {
  186. proxyURL = embed.Video.ProxyURL
  187. } else {
  188. proxyURL = embed.Thumbnail.ProxyURL
  189. }
  190. dbFile, err := portal.bridge.copyAttachmentToMatrix(intent, proxyURL, portal.Encrypted, NoMeta)
  191. if err != nil {
  192. zerolog.Ctx(ctx).Err(err).Msg("Failed to copy video embed to Matrix")
  193. return &ConvertedMessage{
  194. AttachmentID: attachmentID,
  195. Type: event.EventMessage,
  196. Content: portal.createMediaFailedMessage(err),
  197. }
  198. }
  199. content := &event.MessageEventContent{
  200. Body: embed.URL,
  201. Info: &event.FileInfo{
  202. MimeType: dbFile.MimeType,
  203. Size: dbFile.Size,
  204. },
  205. }
  206. if embed.Video != nil {
  207. content.MsgType = event.MsgVideo
  208. content.Info.Width = embed.Video.Width
  209. content.Info.Height = embed.Video.Height
  210. } else {
  211. content.MsgType = event.MsgImage
  212. content.Info.Width = embed.Thumbnail.Width
  213. content.Info.Height = embed.Thumbnail.Height
  214. }
  215. if content.Info.Width == 0 && content.Info.Height == 0 {
  216. content.Info.Width = dbFile.Width
  217. content.Info.Height = dbFile.Height
  218. }
  219. if dbFile.DecryptionInfo != nil {
  220. content.File = &event.EncryptedFileInfo{
  221. EncryptedFile: *dbFile.DecryptionInfo,
  222. URL: dbFile.MXC.CUString(),
  223. }
  224. } else {
  225. content.URL = dbFile.MXC.CUString()
  226. }
  227. extra := map[string]any{}
  228. if content.MsgType == event.MsgVideo && embed.Type == discordgo.EmbedTypeGifv {
  229. extra["info"] = map[string]any{
  230. "fi.mau.discord.gifv": true,
  231. "fi.mau.loop": true,
  232. "fi.mau.autoplay": true,
  233. "fi.mau.hide_controls": true,
  234. "fi.mau.no_audio": true,
  235. }
  236. }
  237. return &ConvertedMessage{
  238. AttachmentID: attachmentID,
  239. Type: event.EventMessage,
  240. Content: content,
  241. Extra: extra,
  242. }
  243. }
  244. func (portal *Portal) convertDiscordMessage(ctx context.Context, puppet *Puppet, intent *appservice.IntentAPI, msg *discordgo.Message) []*ConvertedMessage {
  245. predictedLength := len(msg.Attachments) + len(msg.StickerItems)
  246. if msg.Content != "" {
  247. predictedLength++
  248. }
  249. parts := make([]*ConvertedMessage, 0, predictedLength)
  250. if textPart := portal.convertDiscordTextMessage(ctx, intent, msg); textPart != nil {
  251. parts = append(parts, textPart)
  252. }
  253. log := zerolog.Ctx(ctx)
  254. handledIDs := make(map[string]struct{})
  255. for _, att := range msg.Attachments {
  256. if _, handled := handledIDs[att.ID]; handled {
  257. continue
  258. }
  259. handledIDs[att.ID] = struct{}{}
  260. log := log.With().Str("attachment_id", att.ID).Logger()
  261. if part := portal.convertDiscordAttachment(log.WithContext(ctx), intent, att); part != nil {
  262. parts = append(parts, part)
  263. }
  264. }
  265. for _, sticker := range msg.StickerItems {
  266. if _, handled := handledIDs[sticker.ID]; handled {
  267. continue
  268. }
  269. handledIDs[sticker.ID] = struct{}{}
  270. log := log.With().Str("sticker_id", sticker.ID).Logger()
  271. if part := portal.convertDiscordSticker(log.WithContext(ctx), intent, sticker); part != nil {
  272. parts = append(parts, part)
  273. }
  274. }
  275. for i, embed := range msg.Embeds {
  276. // Ignore non-video embeds, they're handled in convertDiscordTextMessage
  277. if getEmbedType(msg, embed) != EmbedVideo {
  278. continue
  279. }
  280. // Discord deduplicates embeds by URL. It makes things easier for us too.
  281. if _, handled := handledIDs[embed.URL]; handled {
  282. continue
  283. }
  284. handledIDs[embed.URL] = struct{}{}
  285. log := log.With().
  286. Str("computed_embed_type", "video").
  287. Str("embed_type", string(embed.Type)).
  288. Int("embed_index", i).
  289. Logger()
  290. part := portal.convertDiscordVideoEmbed(log.WithContext(ctx), intent, embed)
  291. if part != nil {
  292. parts = append(parts, part)
  293. }
  294. }
  295. if len(parts) == 0 && msg.Thread != nil {
  296. parts = append(parts, &ConvertedMessage{Type: event.EventMessage, Content: &event.MessageEventContent{
  297. MsgType: event.MsgText,
  298. Body: fmt.Sprintf("Created a thread: %s", msg.Thread.Name),
  299. }})
  300. }
  301. for _, part := range parts {
  302. puppet.addWebhookMeta(part, msg)
  303. puppet.addMemberMeta(part, msg)
  304. }
  305. return parts
  306. }
  307. func (puppet *Puppet) addMemberMeta(part *ConvertedMessage, msg *discordgo.Message) {
  308. if msg.Member == nil {
  309. return
  310. }
  311. if part.Extra == nil {
  312. part.Extra = make(map[string]any)
  313. }
  314. var avatarURL id.ContentURI
  315. var discordAvatarURL string
  316. if msg.Member.Avatar != "" {
  317. var err error
  318. avatarURL, discordAvatarURL, err = puppet.bridge.reuploadUserAvatar(puppet.DefaultIntent(), msg.GuildID, msg.Author.ID, msg.Author.Avatar)
  319. if err != nil {
  320. puppet.log.Warn().Err(err).
  321. Str("avatar_id", msg.Author.Avatar).
  322. Msg("Failed to reupload guild user avatar")
  323. }
  324. }
  325. part.Extra["fi.mau.discord.guild_member_metadata"] = map[string]any{
  326. "nick": msg.Member.Nick,
  327. "avatar_id": msg.Member.Avatar,
  328. "avatar_url": discordAvatarURL,
  329. "avatar_mxc": avatarURL.String(),
  330. }
  331. if msg.Member.Nick != "" || !avatarURL.IsEmpty() {
  332. perMessageProfile := map[string]any{
  333. "is_multiple_users": false,
  334. "displayname": msg.Member.Nick,
  335. "avatar_url": avatarURL.String(),
  336. }
  337. if msg.Member.Nick == "" {
  338. perMessageProfile["displayname"] = puppet.Name
  339. }
  340. if avatarURL.IsEmpty() {
  341. perMessageProfile["avatar_url"] = puppet.AvatarURL.String()
  342. }
  343. part.Extra["com.beeper.per_message_profile"] = perMessageProfile
  344. }
  345. }
  346. func (puppet *Puppet) addWebhookMeta(part *ConvertedMessage, msg *discordgo.Message) {
  347. if msg.WebhookID == "" {
  348. return
  349. }
  350. if part.Extra == nil {
  351. part.Extra = make(map[string]any)
  352. }
  353. var avatarURL id.ContentURI
  354. if msg.Author.Avatar != "" {
  355. var err error
  356. avatarURL, _, err = puppet.bridge.reuploadUserAvatar(puppet.DefaultIntent(), "", msg.Author.ID, msg.Author.Avatar)
  357. if err != nil {
  358. puppet.log.Warn().Err(err).
  359. Str("avatar_id", msg.Author.Avatar).
  360. Msg("Failed to reupload webhook avatar")
  361. }
  362. }
  363. part.Extra["fi.mau.discord.webhook_metadata"] = map[string]any{
  364. "id": msg.WebhookID,
  365. "name": msg.Author.Username,
  366. "avatar_id": msg.Author.Avatar,
  367. "avatar_url": msg.Author.AvatarURL(""),
  368. "avatar_mxc": avatarURL.String(),
  369. }
  370. part.Extra["com.beeper.per_message_profile"] = map[string]any{
  371. "is_multiple_users": true,
  372. "avatar_url": avatarURL.String(),
  373. "displayname": msg.Author.Username,
  374. }
  375. }
  376. const (
  377. embedHTMLWrapper = `<blockquote class="discord-embed">%s</blockquote>`
  378. embedHTMLWrapperColor = `<blockquote class="discord-embed" background-color="#%06X">%s</blockquote>`
  379. embedHTMLAuthorWithImage = `<p class="discord-embed-author"><img data-mx-emoticon height="24" src="%s" title="Author icon" alt="">&nbsp;<span>%s</span></p>`
  380. embedHTMLAuthorPlain = `<p class="discord-embed-author"><span>%s</span></p>`
  381. embedHTMLAuthorLink = `<a href="%s">%s</a>`
  382. embedHTMLTitleWithLink = `<p class="discord-embed-title"><a href="%s"><strong>%s</strong></a></p>`
  383. embedHTMLTitlePlain = `<p class="discord-embed-title"><strong>%s</strong></p>`
  384. embedHTMLDescription = `<p class="discord-embed-description">%s</p>`
  385. embedHTMLFieldName = `<th>%s</th>`
  386. embedHTMLFieldValue = `<td>%s</td>`
  387. embedHTMLFields = `<table class="discord-embed-fields"><tr>%s</tr><tr>%s</tr></table>`
  388. embedHTMLLinearField = `<p class="discord-embed-field" x-inline="%s"><strong>%s</strong><br><span>%s</span></p>`
  389. embedHTMLImage = `<p class="discord-embed-image"><img src="%s" alt="" title="Embed image"></p>`
  390. embedHTMLFooterWithImage = `<p class="discord-embed-footer"><sub><img data-mx-emoticon height="20" src="%s" title="Footer icon" alt="">&nbsp;<span>%s</span>%s</sub></p>`
  391. embedHTMLFooterPlain = `<p class="discord-embed-footer"><sub><span>%s</span>%s</sub></p>`
  392. embedHTMLFooterOnlyDate = `<p class="discord-embed-footer"><sub>%s</sub></p>`
  393. embedHTMLDate = `<time datetime="%s">%s</time>`
  394. embedFooterDateSeparator = ` • `
  395. )
  396. func (portal *Portal) convertDiscordRichEmbed(ctx context.Context, intent *appservice.IntentAPI, embed *discordgo.MessageEmbed, msgID string, index int) string {
  397. log := zerolog.Ctx(ctx)
  398. var htmlParts []string
  399. if embed.Author != nil {
  400. var authorHTML string
  401. authorNameHTML := html.EscapeString(embed.Author.Name)
  402. if embed.Author.URL != "" {
  403. authorNameHTML = fmt.Sprintf(embedHTMLAuthorLink, embed.Author.URL, authorNameHTML)
  404. }
  405. authorHTML = fmt.Sprintf(embedHTMLAuthorPlain, authorNameHTML)
  406. if embed.Author.ProxyIconURL != "" {
  407. dbFile, err := portal.bridge.copyAttachmentToMatrix(intent, embed.Author.ProxyIconURL, false, NoMeta)
  408. if err != nil {
  409. log.Warn().Err(err).Msg("Failed to reupload author icon in embed")
  410. } else {
  411. authorHTML = fmt.Sprintf(embedHTMLAuthorWithImage, dbFile.MXC, authorNameHTML)
  412. }
  413. }
  414. htmlParts = append(htmlParts, authorHTML)
  415. }
  416. if embed.Title != "" {
  417. var titleHTML string
  418. baseTitleHTML := portal.renderDiscordMarkdownOnlyHTML(embed.Title, false)
  419. if embed.URL != "" {
  420. titleHTML = fmt.Sprintf(embedHTMLTitleWithLink, html.EscapeString(embed.URL), baseTitleHTML)
  421. } else {
  422. titleHTML = fmt.Sprintf(embedHTMLTitlePlain, baseTitleHTML)
  423. }
  424. htmlParts = append(htmlParts, titleHTML)
  425. }
  426. if embed.Description != "" {
  427. htmlParts = append(htmlParts, fmt.Sprintf(embedHTMLDescription, portal.renderDiscordMarkdownOnlyHTML(embed.Description, true)))
  428. }
  429. for i := 0; i < len(embed.Fields); i++ {
  430. item := embed.Fields[i]
  431. if portal.bridge.Config.Bridge.EmbedFieldsAsTables {
  432. splitItems := []*discordgo.MessageEmbedField{item}
  433. if item.Inline && len(embed.Fields) > i+1 && embed.Fields[i+1].Inline {
  434. splitItems = append(splitItems, embed.Fields[i+1])
  435. i++
  436. if len(embed.Fields) > i+1 && embed.Fields[i+1].Inline {
  437. splitItems = append(splitItems, embed.Fields[i+1])
  438. i++
  439. }
  440. }
  441. headerParts := make([]string, len(splitItems))
  442. contentParts := make([]string, len(splitItems))
  443. for j, splitItem := range splitItems {
  444. headerParts[j] = fmt.Sprintf(embedHTMLFieldName, portal.renderDiscordMarkdownOnlyHTML(splitItem.Name, false))
  445. contentParts[j] = fmt.Sprintf(embedHTMLFieldValue, portal.renderDiscordMarkdownOnlyHTML(splitItem.Value, true))
  446. }
  447. htmlParts = append(htmlParts, fmt.Sprintf(embedHTMLFields, strings.Join(headerParts, ""), strings.Join(contentParts, "")))
  448. } else {
  449. htmlParts = append(htmlParts, fmt.Sprintf(embedHTMLLinearField,
  450. strconv.FormatBool(item.Inline),
  451. portal.renderDiscordMarkdownOnlyHTML(item.Name, false),
  452. portal.renderDiscordMarkdownOnlyHTML(item.Value, true),
  453. ))
  454. }
  455. }
  456. if embed.Image != nil {
  457. dbFile, err := portal.bridge.copyAttachmentToMatrix(intent, embed.Image.ProxyURL, false, NoMeta)
  458. if err != nil {
  459. log.Warn().Err(err).Msg("Failed to reupload image in embed")
  460. } else {
  461. htmlParts = append(htmlParts, fmt.Sprintf(embedHTMLImage, dbFile.MXC))
  462. }
  463. }
  464. var embedDateHTML string
  465. if embed.Timestamp != "" {
  466. formattedTime := embed.Timestamp
  467. parsedTS, err := time.Parse(time.RFC3339, embed.Timestamp)
  468. if err != nil {
  469. log.Warn().Err(err).Msg("Failed to parse timestamp in embed")
  470. } else {
  471. formattedTime = parsedTS.Format(discordTimestampStyle('F').Format())
  472. }
  473. embedDateHTML = fmt.Sprintf(embedHTMLDate, embed.Timestamp, formattedTime)
  474. }
  475. if embed.Footer != nil {
  476. var footerHTML string
  477. var datePart string
  478. if embedDateHTML != "" {
  479. datePart = embedFooterDateSeparator + embedDateHTML
  480. }
  481. footerHTML = fmt.Sprintf(embedHTMLFooterPlain, html.EscapeString(embed.Footer.Text), datePart)
  482. if embed.Footer.ProxyIconURL != "" {
  483. dbFile, err := portal.bridge.copyAttachmentToMatrix(intent, embed.Footer.ProxyIconURL, false, NoMeta)
  484. if err != nil {
  485. log.Warn().Err(err).Msg("Failed to reupload footer icon in embed")
  486. } else {
  487. footerHTML = fmt.Sprintf(embedHTMLFooterWithImage, dbFile.MXC, html.EscapeString(embed.Footer.Text), datePart)
  488. }
  489. }
  490. htmlParts = append(htmlParts, footerHTML)
  491. } else if embed.Timestamp != "" {
  492. htmlParts = append(htmlParts, fmt.Sprintf(embedHTMLFooterOnlyDate, embedDateHTML))
  493. }
  494. if len(htmlParts) == 0 {
  495. return ""
  496. }
  497. compiledHTML := strings.Join(htmlParts, "")
  498. if embed.Color != 0 {
  499. compiledHTML = fmt.Sprintf(embedHTMLWrapperColor, embed.Color, compiledHTML)
  500. } else {
  501. compiledHTML = fmt.Sprintf(embedHTMLWrapper, compiledHTML)
  502. }
  503. return compiledHTML
  504. }
  505. type BeeperLinkPreview struct {
  506. mautrix.RespPreviewURL
  507. MatchedURL string `json:"matched_url"`
  508. ImageEncryption *event.EncryptedFileInfo `json:"beeper:image:encryption,omitempty"`
  509. }
  510. func (portal *Portal) convertDiscordLinkEmbedImage(ctx context.Context, intent *appservice.IntentAPI, url string, width, height int, preview *BeeperLinkPreview) {
  511. dbFile, err := portal.bridge.copyAttachmentToMatrix(intent, url, portal.Encrypted, NoMeta)
  512. if err != nil {
  513. zerolog.Ctx(ctx).Warn().Err(err).Msg("Failed to reupload image in URL preview")
  514. return
  515. }
  516. if width != 0 || height != 0 {
  517. preview.ImageWidth = width
  518. preview.ImageHeight = height
  519. } else {
  520. preview.ImageWidth = dbFile.Width
  521. preview.ImageHeight = dbFile.Height
  522. }
  523. preview.ImageSize = dbFile.Size
  524. preview.ImageType = dbFile.MimeType
  525. if dbFile.Encrypted {
  526. preview.ImageEncryption = &event.EncryptedFileInfo{
  527. EncryptedFile: *dbFile.DecryptionInfo,
  528. URL: dbFile.MXC.CUString(),
  529. }
  530. } else {
  531. preview.ImageURL = dbFile.MXC.CUString()
  532. }
  533. }
  534. func (portal *Portal) convertDiscordLinkEmbedToBeeper(ctx context.Context, intent *appservice.IntentAPI, embed *discordgo.MessageEmbed) *BeeperLinkPreview {
  535. var preview BeeperLinkPreview
  536. preview.MatchedURL = embed.URL
  537. preview.Title = embed.Title
  538. preview.Description = embed.Description
  539. if embed.Image != nil {
  540. portal.convertDiscordLinkEmbedImage(ctx, intent, embed.Image.ProxyURL, embed.Image.Width, embed.Image.Height, &preview)
  541. } else if embed.Thumbnail != nil {
  542. portal.convertDiscordLinkEmbedImage(ctx, intent, embed.Thumbnail.ProxyURL, embed.Thumbnail.Width, embed.Thumbnail.Height, &preview)
  543. }
  544. return &preview
  545. }
  546. const msgInteractionTemplateHTML = `<blockquote>
  547. <a href="https://matrix.to/#/%s">%s</a> used <font color="#3771bb">/%s</font>
  548. </blockquote>`
  549. const msgComponentTemplateHTML = `<p>This message contains interactive elements. Use the Discord app to interact with the message.</p>`
  550. type BridgeEmbedType int
  551. const (
  552. EmbedUnknown BridgeEmbedType = iota
  553. EmbedRich
  554. EmbedLinkPreview
  555. EmbedVideo
  556. )
  557. func isActuallyLinkPreview(embed *discordgo.MessageEmbed) bool {
  558. // Sending YouTube links creates a video embed, but we want to bridge it as a URL preview,
  559. // so this is a hacky way to detect those.
  560. return embed.Video != nil && embed.Video.ProxyURL == ""
  561. }
  562. func getEmbedType(msg *discordgo.Message, embed *discordgo.MessageEmbed) BridgeEmbedType {
  563. switch embed.Type {
  564. case discordgo.EmbedTypeLink, discordgo.EmbedTypeArticle:
  565. return EmbedLinkPreview
  566. case discordgo.EmbedTypeVideo:
  567. if isActuallyLinkPreview(embed) {
  568. return EmbedLinkPreview
  569. }
  570. return EmbedVideo
  571. case discordgo.EmbedTypeGifv:
  572. return EmbedVideo
  573. case discordgo.EmbedTypeImage:
  574. if msg != nil && isPlainGifMessage(msg) {
  575. return EmbedVideo
  576. } else if embed.Image == nil && embed.Thumbnail != nil {
  577. return EmbedLinkPreview
  578. }
  579. return EmbedRich
  580. case discordgo.EmbedTypeRich:
  581. return EmbedRich
  582. default:
  583. return EmbedUnknown
  584. }
  585. }
  586. func isPlainGifMessage(msg *discordgo.Message) bool {
  587. if len(msg.Embeds) != 1 {
  588. return false
  589. }
  590. embed := msg.Embeds[0]
  591. isGifVideo := embed.Type == discordgo.EmbedTypeGifv && embed.Video != nil
  592. isGifImage := embed.Type == discordgo.EmbedTypeImage && embed.Image == nil && embed.Thumbnail != nil
  593. contentIsOnlyURL := msg.Content == embed.URL || discordLinkRegexFull.MatchString(msg.Content)
  594. return contentIsOnlyURL && (isGifVideo || isGifImage)
  595. }
  596. func (portal *Portal) convertDiscordMentions(msg *discordgo.Message, syncGhosts bool) *event.Mentions {
  597. var matrixMentions event.Mentions
  598. for _, mention := range msg.Mentions {
  599. puppet := portal.bridge.GetPuppetByID(mention.ID)
  600. if syncGhosts {
  601. puppet.UpdateInfo(nil, mention, nil)
  602. }
  603. user := portal.bridge.GetUserByID(mention.ID)
  604. if user != nil {
  605. matrixMentions.UserIDs = append(matrixMentions.UserIDs, user.MXID)
  606. } else {
  607. matrixMentions.UserIDs = append(matrixMentions.UserIDs, puppet.MXID)
  608. }
  609. }
  610. slices.Sort(matrixMentions.UserIDs)
  611. matrixMentions.UserIDs = slices.Compact(matrixMentions.UserIDs)
  612. if msg.MentionEveryone {
  613. matrixMentions.Room = true
  614. }
  615. return &matrixMentions
  616. }
  617. func (portal *Portal) convertDiscordTextMessage(ctx context.Context, intent *appservice.IntentAPI, msg *discordgo.Message) *ConvertedMessage {
  618. log := zerolog.Ctx(ctx)
  619. if msg.Type == discordgo.MessageTypeCall {
  620. return &ConvertedMessage{Type: event.EventMessage, Content: &event.MessageEventContent{
  621. MsgType: event.MsgEmote,
  622. Body: "started a call",
  623. }}
  624. } else if msg.Type == discordgo.MessageTypeGuildMemberJoin {
  625. return &ConvertedMessage{Type: event.EventMessage, Content: &event.MessageEventContent{
  626. MsgType: event.MsgEmote,
  627. Body: "joined the server",
  628. }}
  629. }
  630. var htmlParts []string
  631. if msg.Interaction != nil {
  632. puppet := portal.bridge.GetPuppetByID(msg.Interaction.User.ID)
  633. puppet.UpdateInfo(nil, msg.Interaction.User, nil)
  634. htmlParts = append(htmlParts, fmt.Sprintf(msgInteractionTemplateHTML, puppet.MXID, puppet.Name, msg.Interaction.Name))
  635. }
  636. if msg.Content != "" && !isPlainGifMessage(msg) {
  637. htmlParts = append(htmlParts, portal.renderDiscordMarkdownOnlyHTML(msg.Content, true))
  638. }
  639. previews := make([]*BeeperLinkPreview, 0)
  640. for i, embed := range msg.Embeds {
  641. if i == 0 && msg.MessageReference == nil && isReplyEmbed(embed) {
  642. continue
  643. }
  644. with := log.With().
  645. Str("embed_type", string(embed.Type)).
  646. Int("embed_index", i)
  647. switch getEmbedType(msg, embed) {
  648. case EmbedRich:
  649. log := with.Str("computed_embed_type", "rich").Logger()
  650. htmlParts = append(htmlParts, portal.convertDiscordRichEmbed(log.WithContext(ctx), intent, embed, msg.ID, i))
  651. case EmbedLinkPreview:
  652. log := with.Str("computed_embed_type", "link preview").Logger()
  653. previews = append(previews, portal.convertDiscordLinkEmbedToBeeper(log.WithContext(ctx), intent, embed))
  654. case EmbedVideo:
  655. // Ignore video embeds, they're handled as separate messages
  656. default:
  657. log := with.Logger()
  658. log.Warn().Msg("Unknown embed type in message")
  659. }
  660. }
  661. if len(msg.Components) > 0 {
  662. htmlParts = append(htmlParts, msgComponentTemplateHTML)
  663. }
  664. if len(htmlParts) == 0 {
  665. return nil
  666. }
  667. fullHTML := strings.Join(htmlParts, "\n")
  668. if !msg.MentionEveryone {
  669. fullHTML = strings.ReplaceAll(fullHTML, "@room", "@\u2063ro\u2063om")
  670. }
  671. content := format.HTMLToContent(fullHTML)
  672. extraContent := map[string]any{
  673. "com.beeper.linkpreviews": previews,
  674. }
  675. if msg.WebhookID != "" && msg.ApplicationID == "" && portal.bridge.Config.Bridge.PrefixWebhookMessages {
  676. content.EnsureHasHTML()
  677. content.Body = fmt.Sprintf("%s: %s", msg.Author.Username, content.Body)
  678. content.FormattedBody = fmt.Sprintf("<strong>%s</strong>: %s", html.EscapeString(msg.Author.Username), content.FormattedBody)
  679. }
  680. return &ConvertedMessage{Type: event.EventMessage, Content: &content, Extra: extraContent}
  681. }