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. "net/url"
  9. "github.com/gorilla/mux"
  10. "miniflux.app/v2/internal/config"
  11. "miniflux.app/v2/internal/http/route"
  12. )
  13. func ProxifyRelativeURL(router *mux.Router, mediaURL string) string {
  14. if mediaURL == "" {
  15. return ""
  16. }
  17. if customProxyURL := config.Opts.MediaCustomProxyURL(); customProxyURL != nil {
  18. return proxifyURLWithCustomProxy(mediaURL, customProxyURL)
  19. }
  20. mediaURLBytes := []byte(mediaURL)
  21. mac := hmac.New(sha256.New, config.Opts.MediaProxyPrivateKey())
  22. mac.Write(mediaURLBytes)
  23. digest := mac.Sum(nil)
  24. return route.Path(router, "proxy", "encodedDigest", base64.URLEncoding.EncodeToString(digest), "encodedURL", base64.URLEncoding.EncodeToString(mediaURLBytes))
  25. }
  26. func ProxifyAbsoluteURL(router *mux.Router, 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(router, 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. }