download.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "crypto/tls"
  7. "errors"
  8. "fmt"
  9. "image"
  10. "io"
  11. "io/ioutil"
  12. "net/http"
  13. "sync"
  14. "time"
  15. _ "image/gif"
  16. _ "image/jpeg"
  17. _ "image/png"
  18. _ "golang.org/x/image/webp"
  19. )
  20. var (
  21. downloadClient *http.Client
  22. imageTypeCtxKey = ctxKey("imageType")
  23. imageDataCtxKey = ctxKey("imageData")
  24. errSourceDimensionsTooBig = errors.New("Source image dimensions are too big")
  25. errSourceResolutionTooBig = errors.New("Source image resolution are too big")
  26. errSourceImageTypeNotSupported = errors.New("Source image type not supported")
  27. )
  28. var downloadBufPool = sync.Pool{
  29. New: func() interface{} {
  30. return new(bytes.Buffer)
  31. },
  32. }
  33. type netReader struct {
  34. reader *bufio.Reader
  35. buf *bytes.Buffer
  36. }
  37. func newNetReader(r io.Reader, buf *bytes.Buffer) *netReader {
  38. return &netReader{
  39. reader: bufio.NewReader(r),
  40. buf: buf,
  41. }
  42. }
  43. func (r *netReader) Read(p []byte) (n int, err error) {
  44. n, err = r.reader.Read(p)
  45. if err == nil {
  46. r.buf.Write(p[:n])
  47. }
  48. return
  49. }
  50. func (r *netReader) Peek(n int) ([]byte, error) {
  51. return r.reader.Peek(n)
  52. }
  53. func (r *netReader) ReadAll() error {
  54. if _, err := r.buf.ReadFrom(r.reader); err != nil {
  55. return err
  56. }
  57. return nil
  58. }
  59. func initDownloading() {
  60. transport := &http.Transport{
  61. Proxy: http.ProxyFromEnvironment,
  62. }
  63. if conf.IgnoreSslVerification {
  64. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  65. }
  66. if conf.LocalFileSystemRoot != "" {
  67. transport.RegisterProtocol("local", http.NewFileTransport(http.Dir(conf.LocalFileSystemRoot)))
  68. }
  69. if conf.S3Enabled {
  70. transport.RegisterProtocol("s3", newS3Transport())
  71. }
  72. downloadClient = &http.Client{
  73. Timeout: time.Duration(conf.DownloadTimeout) * time.Second,
  74. Transport: transport,
  75. }
  76. }
  77. func checkTypeAndDimensions(r io.Reader) (imageType, error) {
  78. imgconf, imgtypeStr, err := image.DecodeConfig(r)
  79. imgtype, imgtypeOk := imageTypes[imgtypeStr]
  80. if err != nil {
  81. return imageTypeUnknown, err
  82. }
  83. if imgconf.Width > conf.MaxSrcDimension || imgconf.Height > conf.MaxSrcDimension {
  84. return imageTypeUnknown, errSourceDimensionsTooBig
  85. }
  86. if imgconf.Width*imgconf.Height > conf.MaxSrcResolution {
  87. return imageTypeUnknown, errSourceResolutionTooBig
  88. }
  89. if !imgtypeOk || !vipsTypeSupportLoad[imgtype] {
  90. return imageTypeUnknown, errSourceImageTypeNotSupported
  91. }
  92. return imgtype, nil
  93. }
  94. func readAndCheckImage(ctx context.Context, res *http.Response) (context.Context, context.CancelFunc, error) {
  95. buf := downloadBufPool.Get().(*bytes.Buffer)
  96. cancel := func() {
  97. buf.Reset()
  98. downloadBufPool.Put(buf)
  99. }
  100. nr := newNetReader(res.Body, buf)
  101. imgtype, err := checkTypeAndDimensions(nr)
  102. if err != nil {
  103. return ctx, cancel, err
  104. }
  105. if err = nr.ReadAll(); err == nil {
  106. ctx = context.WithValue(ctx, imageTypeCtxKey, imgtype)
  107. ctx = context.WithValue(ctx, imageDataCtxKey, nr.buf)
  108. }
  109. return ctx, cancel, err
  110. }
  111. func downloadImage(ctx context.Context) (context.Context, context.CancelFunc, error) {
  112. url := fmt.Sprintf("%s%s", conf.BaseURL, getImageURL(ctx))
  113. res, err := downloadClient.Get(url)
  114. if err != nil {
  115. return ctx, func() {}, err
  116. }
  117. defer res.Body.Close()
  118. if res.StatusCode != 200 {
  119. body, _ := ioutil.ReadAll(res.Body)
  120. return ctx, func() {}, fmt.Errorf("Can't download image; Status: %d; %s", res.StatusCode, string(body))
  121. }
  122. return readAndCheckImage(ctx, res)
  123. }
  124. func getImageType(ctx context.Context) imageType {
  125. return ctx.Value(imageTypeCtxKey).(imageType)
  126. }
  127. func getImageData(ctx context.Context) *bytes.Buffer {
  128. return ctx.Value(imageDataCtxKey).(*bytes.Buffer)
  129. }