1
0
Fork 0

Add rewrite rule replace for custom search and replace

This commit is contained in:
Pacman99 2020-11-25 14:51:54 -08:00 committed by fguillot
parent de7a613098
commit b8b6c74d86
3 changed files with 34 additions and 1 deletions

View file

@ -221,3 +221,12 @@ func replaceTextLinks(input string) string {
func replaceLineFeeds(input string) string {
return strings.Replace(input, "\n", "<br>", -1)
}
func replaceCustom(entryContent string, searchTerm string, replaceTerm string) string {
re, err := regexp.Compile(searchTerm)
if err == nil {
return re.ReplaceAllString(entryContent, replaceTerm)
}
return entryContent
}

View file

@ -6,11 +6,14 @@ package rewrite // import "miniflux.app/reader/rewrite"
import (
"strings"
"regexp"
"miniflux.app/logger"
"miniflux.app/url"
)
var customReplaceRuleRegex = regexp.MustCompile(`replace\("(.*)"\|"(.*)"\)`)
// Rewriter modify item contents with a set of rewriting rules.
func Rewriter(entryURL, entryContent, customRewriteRules string) string {
rulesList := getPredefinedRewriteRules(entryURL)
@ -24,7 +27,8 @@ func Rewriter(entryURL, entryContent, customRewriteRules string) string {
logger.Debug(`[Rewrite] Applying rules %v for %q`, rules, entryURL)
for _, rule := range rules {
switch strings.TrimSpace(rule) {
rule := strings.TrimSpace(rule)
switch rule {
case "add_image_title":
entryContent = addImageTitle(entryURL, entryContent)
case "add_mailto_subject":
@ -47,6 +51,16 @@ func Rewriter(entryURL, entryContent, customRewriteRules string) string {
entryContent = fixMediumImages(entryURL, entryContent)
case "use_noscript_figure_images":
entryContent = useNoScriptImages(entryURL, entryContent)
default:
if strings.Contains(rule, "replace") {
// Format: replace("search-term"|"replace-term")
args := customReplaceRuleRegex.FindStringSubmatch(rule)
if len(args) >= 3 {
entryContent = replaceCustom(entryContent, args[1], args[2])
} else {
logger.Debug("[Rewrite] Cannot find search and replace terms for replace rule %s", rule)
}
}
}
}

View file

@ -230,3 +230,13 @@ func TestRewriteNoScriptImageWithNoScriptTag(t *testing.T) {
t.Errorf(`Not expected output: %s`, output)
}
}
func TestRewriteReplaceCustom(t *testing.T) {
content := `<img src="http://example.org/logo.svg"><img src="https://example.org/article/picture.svg">`
expected := `<img src="http://example.org/logo.svg"><img src="https://example.org/article/picture.png">`
output := Rewriter("https://example.org/artcle", content, `replace("article/(.*).svg"|"article/$1.png")`)
if expected != output {
t.Errorf(`Not expected output: %s`, output)
}
}