attachments.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package bridge
  2. import (
  3. "bytes"
  4. "image"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. "github.com/bwmarrin/discordgo"
  9. "maunium.net/go/mautrix/appservice"
  10. "maunium.net/go/mautrix/event"
  11. )
  12. func (p *Portal) downloadDiscordAttachment(url string) ([]byte, error) {
  13. // We might want to make this save to disk in the future. Discord defaults
  14. // to 8mb for all attachments to a messages for non-nitro users and
  15. // non-boosted servers.
  16. //
  17. // If the user has nitro classic, their limit goes up to 50mb but if a user
  18. // has regular nitro the limit is increased to 100mb.
  19. //
  20. // Servers boosted to level 2 will have the limit bumped to 50mb.
  21. req, err := http.NewRequest(http.MethodGet, url, nil)
  22. if err != nil {
  23. return nil, err
  24. }
  25. req.Header.Set("User-Agent", discordgo.DroidBrowserUserAgent)
  26. resp, err := http.DefaultClient.Do(req)
  27. if err != nil {
  28. return nil, err
  29. }
  30. defer resp.Body.Close()
  31. return ioutil.ReadAll(resp.Body)
  32. }
  33. func (p *Portal) uploadMatrixAttachment(intent *appservice.IntentAPI, data []byte, content *event.MessageEventContent) error {
  34. uploaded, err := intent.UploadBytes(data, content.Info.MimeType)
  35. if err != nil {
  36. return err
  37. }
  38. content.URL = uploaded.ContentURI.CUString()
  39. content.Info.Size = len(data)
  40. if content.Info.Width == 0 && content.Info.Height == 0 && strings.HasPrefix(content.Info.MimeType, "image/") {
  41. cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
  42. content.Info.Width = cfg.Width
  43. content.Info.Height = cfg.Height
  44. }
  45. return nil
  46. }