url.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package mediaproxy // import "miniflux.app/v2/internal/mediaproxy"
  4. import (
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "fmt"
  9. "net/url"
  10. "miniflux.app/v2/internal/config"
  11. )
  12. func ProxifyRelativeURL(mediaURL string) string {
  13. if mediaURL == "" {
  14. return ""
  15. }
  16. if customProxyURL := config.Opts.MediaCustomProxyURL(); customProxyURL != nil {
  17. return proxifyURLWithCustomProxy(mediaURL, customProxyURL)
  18. }
  19. mediaURLBytes := []byte(mediaURL)
  20. mac := hmac.New(sha256.New, config.Opts.MediaProxyPrivateKey())
  21. mac.Write(mediaURLBytes)
  22. digest := mac.Sum(nil)
  23. // Preserve the configured base path so proxied URLs still work when Miniflux is served from a subfolder.
  24. return fmt.Sprintf("%s/proxy/%s/%s", config.Opts.BasePath(), base64.URLEncoding.EncodeToString(digest), base64.URLEncoding.EncodeToString(mediaURLBytes))
  25. }
  26. func ProxifyAbsoluteURL(mediaURL string) string {
  27. if mediaURL == "" {
  28. return ""
  29. }
  30. if customProxyURL := config.Opts.MediaCustomProxyURL(); customProxyURL != nil {
  31. return proxifyURLWithCustomProxy(mediaURL, customProxyURL)
  32. }
  33. // Note that the proxyified URL is relative to the root URL.
  34. proxifiedUrl := ProxifyRelativeURL(mediaURL)
  35. absoluteURL, err := url.JoinPath(config.Opts.RootURL(), proxifiedUrl)
  36. if err != nil {
  37. return mediaURL
  38. }
  39. return absoluteURL
  40. }
  41. func proxifyURLWithCustomProxy(mediaURL string, customProxyURL *url.URL) string {
  42. if customProxyURL == nil {
  43. return mediaURL
  44. }
  45. absoluteURL := customProxyURL.JoinPath(base64.URLEncoding.EncodeToString([]byte(mediaURL)))
  46. return absoluteURL.String()
  47. }