portal_convert.go 24 KB

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