emoji.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "github.com/bwmarrin/discordgo"
  6. "maunium.net/go/mautrix/appservice"
  7. "maunium.net/go/mautrix/id"
  8. )
  9. func (portal *Portal) getEmojiMXCByDiscordID(emojiID, name string, animated bool) id.ContentURI {
  10. dbEmoji := portal.bridge.DB.Emoji.GetByDiscordID(emojiID)
  11. if dbEmoji == nil {
  12. data, mimeType, err := portal.downloadDiscordEmoji(emojiID, animated)
  13. if err != nil {
  14. portal.log.Warnfln("Failed to download emoji %s from discord: %v", emojiID, err)
  15. return id.ContentURI{}
  16. }
  17. uri, err := portal.uploadMatrixEmoji(portal.MainIntent(), data, mimeType)
  18. if err != nil {
  19. portal.log.Warnfln("Failed to upload discord emoji %s to homeserver: %v", emojiID, err)
  20. return id.ContentURI{}
  21. }
  22. dbEmoji = portal.bridge.DB.Emoji.New()
  23. dbEmoji.DiscordID = emojiID
  24. dbEmoji.DiscordName = name
  25. dbEmoji.MatrixURL = uri
  26. dbEmoji.Insert()
  27. }
  28. return dbEmoji.MatrixURL
  29. }
  30. func (portal *Portal) downloadDiscordEmoji(id string, animated bool) ([]byte, string, error) {
  31. var url string
  32. var mimeType string
  33. if animated {
  34. // This url requests a gif, so that's what we set the mimetype to.
  35. url = discordgo.EndpointEmojiAnimated(id)
  36. mimeType = "image/gif"
  37. } else {
  38. // This url requests a png, so that's what we set the mimetype to.
  39. url = discordgo.EndpointEmoji(id)
  40. mimeType = "image/png"
  41. }
  42. req, err := http.NewRequest(http.MethodGet, url, nil)
  43. if err != nil {
  44. return nil, mimeType, err
  45. }
  46. req.Header.Set("User-Agent", discordgo.DroidBrowserUserAgent)
  47. resp, err := http.DefaultClient.Do(req)
  48. if err != nil {
  49. return nil, mimeType, err
  50. }
  51. defer resp.Body.Close()
  52. data, err := ioutil.ReadAll(resp.Body)
  53. return data, mimeType, err
  54. }
  55. func (portal *Portal) uploadMatrixEmoji(intent *appservice.IntentAPI, data []byte, mimeType string) (id.ContentURI, error) {
  56. uploaded, err := intent.UploadBytes(data, mimeType)
  57. if err != nil {
  58. return id.ContentURI{}, err
  59. }
  60. return uploaded.ContentURI, nil
  61. }