imguploader.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package imguploader
  2. import (
  3. "fmt"
  4. "regexp"
  5. "github.com/grafana/grafana/pkg/setting"
  6. )
  7. type ImageUploader interface {
  8. Upload(path string) (string, error)
  9. }
  10. type NopImageUploader struct {
  11. }
  12. func (NopImageUploader) Upload(path string) (string, error) {
  13. return "", nil
  14. }
  15. func NewImageUploader() (ImageUploader, error) {
  16. switch setting.ImageUploadProvider {
  17. case "s3":
  18. s3sec, err := setting.Cfg.GetSection("external_image_storage.s3")
  19. if err != nil {
  20. return nil, err
  21. }
  22. bucketUrl := s3sec.Key("bucket_url").MustString("")
  23. accessKey := s3sec.Key("access_key").MustString("")
  24. secretKey := s3sec.Key("secret_key").MustString("")
  25. info, err := getRegionAndBucketFromUrl(bucketUrl)
  26. if err != nil {
  27. return nil, err
  28. }
  29. return NewS3Uploader(info.region, info.bucket, "public-read", accessKey, secretKey), nil
  30. case "webdav":
  31. webdavSec, err := setting.Cfg.GetSection("external_image_storage.webdav")
  32. if err != nil {
  33. return nil, err
  34. }
  35. url := webdavSec.Key("url").String()
  36. if url == "" {
  37. return nil, fmt.Errorf("Could not find url key for image.uploader.webdav")
  38. }
  39. public_url := webdavSec.Key("public_url").String()
  40. username := webdavSec.Key("username").String()
  41. password := webdavSec.Key("password").String()
  42. return NewWebdavImageUploader(url, username, password, public_url)
  43. }
  44. return NopImageUploader{}, nil
  45. }
  46. type s3Info struct {
  47. region string
  48. bucket string
  49. }
  50. func getRegionAndBucketFromUrl(url string) (*s3Info, error) {
  51. info := &s3Info{}
  52. urlRegex := regexp.MustCompile(`https?:\/\/(.*)\.s3(-([^.]+))?\.amazonaws\.com\/?`)
  53. matches := urlRegex.FindStringSubmatch(url)
  54. if len(matches) > 0 {
  55. info.bucket = matches[1]
  56. if matches[3] != "" {
  57. info.region = matches[3]
  58. } else {
  59. info.region = "us-east-1"
  60. }
  61. return info, nil
  62. }
  63. urlRegex2 := regexp.MustCompile(`https?:\/\/s3(-([^.]+))?\.amazonaws\.com\/(.*)?`)
  64. matches2 := urlRegex2.FindStringSubmatch(url)
  65. if len(matches2) > 0 {
  66. info.bucket = matches2[3]
  67. if matches2[2] != "" {
  68. info.region = matches2[2]
  69. } else {
  70. info.region = "us-east-1"
  71. }
  72. return info, nil
  73. }
  74. return nil, fmt.Errorf("Could not find bucket setting for image.uploader.s3")
  75. }