aboutsummaryrefslogtreecommitdiffhomepage
path: root/filter/image_proxy_filter.go
blob: 01ae59173ec362bd573aa70710fa782393a6a906 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

package filter // import "miniflux.app/filter"

import (
	"encoding/base64"
	"strings"

	"miniflux.app/config"
	"miniflux.app/http/route"
	"miniflux.app/url"

	"github.com/PuerkitoBio/goquery"
	"github.com/gorilla/mux"
)

// ImageProxyFilter rewrites image tag URLs to local proxy URL (by default only non-HTTPS URLs)
func ImageProxyFilter(router *mux.Router, cfg *config.Config, data string) string {
	proxyImages := cfg.ProxyImages()
	if proxyImages == "none" {
		return data
	}

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(data))
	if err != nil {
		return data
	}

	doc.Find("img").Each(func(i int, img *goquery.Selection) {
		if srcAttr, ok := img.Attr("src"); ok {
			if proxyImages == "all" || !url.IsHTTPS(srcAttr) {
				img.SetAttr("src", Proxify(router, srcAttr))
			}
		}
	})

	output, _ := doc.Find("body").First().Html()
	return output
}

// Proxify returns a proxified link.
func Proxify(router *mux.Router, link string) string {
	// We use base64 url encoding to avoid slash in the URL.
	return route.Path(router, "proxy", "encodedURL", base64.URLEncoding.EncodeToString([]byte(link)))
}