imguploader.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. username := webdavSec.Key("username").String()
  40. password := webdavSec.Key("password").String()
  41. return NewWebdavImageUploader(url, username, password)
  42. }
  43. return NopImageUploader{}, nil
  44. }
  45. type s3Info struct {
  46. region string
  47. bucket string
  48. }
  49. func getRegionAndBucketFromUrl(url string) (*s3Info, error) {
  50. info := &s3Info{}
  51. urlRegex := regexp.MustCompile(`https?:\/\/(.*)\.s3(-([^.]+))?\.amazonaws\.com\/?`)
  52. matches := urlRegex.FindStringSubmatch(url)
  53. if len(matches) > 0 {
  54. info.bucket = matches[1]
  55. if matches[3] != "" {
  56. info.region = matches[3]
  57. } else {
  58. info.region = "us-east-1"
  59. }
  60. return info, nil
  61. }
  62. urlRegex2 := regexp.MustCompile(`https?:\/\/s3(-([^.]+))?\.amazonaws\.com\/(.*)?`)
  63. matches2 := urlRegex2.FindStringSubmatch(url)
  64. if len(matches2) > 0 {
  65. info.bucket = matches2[3]
  66. if matches2[2] != "" {
  67. info.region = matches2[2]
  68. } else {
  69. info.region = "us-east-1"
  70. }
  71. return info, nil
  72. }
  73. return nil, fmt.Errorf("Could not find bucket setting for image.uploader.s3")
  74. }