attachment_image.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package run
  2. import (
  3. "image"
  4. _ "image/jpeg"
  5. _ "image/png"
  6. "net/http"
  7. "github.com/ayn2op/discordo/config"
  8. "github.com/diamondburned/arikawa/v3/discord"
  9. "github.com/gdamore/tcell/v2"
  10. "github.com/rivo/tview"
  11. )
  12. type AttachmentImage struct {
  13. *tview.Image
  14. }
  15. func newAttachmentImage(a discord.Attachment) (*AttachmentImage, error) {
  16. ai := &AttachmentImage{
  17. Image: tview.NewImage(),
  18. }
  19. ai.SetInputCapture(ai.onInputCapture)
  20. ai.SetBackgroundColor(tcell.GetColor(config.Current.Theme.BackgroundColor))
  21. ai.SetTitleColor(tcell.GetColor(config.Current.Theme.TitleColor))
  22. ai.SetTitleAlign(tview.AlignLeft)
  23. p := config.Current.Theme.BorderPadding
  24. ai.SetBorder(config.Current.Theme.Border)
  25. ai.SetBorderColor(tcell.GetColor(config.Current.Theme.BorderColor))
  26. ai.SetBorderPadding(p[0], p[1], p[2], p[3])
  27. resp, err := http.Get(a.URL)
  28. if err != nil {
  29. return nil, err
  30. }
  31. defer resp.Body.Close()
  32. i, _, err := image.Decode(resp.Body)
  33. if err != nil {
  34. return nil, err
  35. }
  36. ai.SetTitle(a.Filename)
  37. ai.SetImage(i)
  38. return ai, nil
  39. }
  40. func (ai *AttachmentImage) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  41. if event.Name() == config.Current.Keys.Cancel {
  42. app.SetRoot(mainFlex, true)
  43. app.SetFocus(mainFlex.messagesText)
  44. return nil
  45. }
  46. return event
  47. }