miniflux-v2/internal/mediaproxy/url.go

71 lines
1.8 KiB
Go
Raw Normal View History

// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
2020-10-08 07:21:45 +02:00
package mediaproxy // import "miniflux.app/v2/internal/mediaproxy"
2020-10-08 07:21:45 +02:00
import (
2022-10-15 08:17:17 +02:00
"crypto/hmac"
"crypto/sha256"
2020-10-08 07:21:45 +02:00
"encoding/base64"
"log/slog"
2022-08-30 05:33:47 +02:00
"net/url"
"path"
2020-10-08 07:21:45 +02:00
"miniflux.app/v2/internal/http/route"
2020-10-08 07:21:45 +02:00
"github.com/gorilla/mux"
2022-08-30 05:33:47 +02:00
"miniflux.app/v2/internal/config"
2020-10-08 07:21:45 +02:00
)
func ProxifyRelativeURL(router *mux.Router, mediaURL string) string {
if mediaURL == "" {
return ""
}
2022-10-15 08:17:17 +02:00
if customProxyURL := config.Opts.MediaCustomProxyURL(); customProxyURL != "" {
return proxifyURLWithCustomProxy(mediaURL, customProxyURL)
2022-10-15 08:17:17 +02:00
}
mac := hmac.New(sha256.New, config.Opts.MediaProxyPrivateKey())
mac.Write([]byte(mediaURL))
digest := mac.Sum(nil)
return route.Path(router, "proxy", "encodedDigest", base64.URLEncoding.EncodeToString(digest), "encodedURL", base64.URLEncoding.EncodeToString([]byte(mediaURL)))
2022-10-15 08:17:17 +02:00
}
func ProxifyAbsoluteURL(router *mux.Router, host, mediaURL string) string {
if mediaURL == "" {
return ""
}
2022-08-30 05:33:47 +02:00
if customProxyURL := config.Opts.MediaCustomProxyURL(); customProxyURL != "" {
return proxifyURLWithCustomProxy(mediaURL, customProxyURL)
}
proxifiedUrl := ProxifyRelativeURL(router, mediaURL)
scheme := "http"
if config.Opts.HTTPS {
scheme = "https"
}
return scheme + "://" + host + proxifiedUrl
}
func proxifyURLWithCustomProxy(mediaURL, customProxyURL string) string {
if customProxyURL == "" {
return mediaURL
2022-07-06 06:13:40 +02:00
}
proxyUrl, err := url.Parse(customProxyURL)
if err != nil {
slog.Error("Incorrect custom media proxy URL",
slog.String("custom_proxy_url", customProxyURL),
slog.Any("error", err),
)
return mediaURL
}
proxyUrl.Path = path.Join(proxyUrl.Path, base64.URLEncoding.EncodeToString([]byte(mediaURL)))
return proxyUrl.String()
2020-10-08 07:21:45 +02:00
}