Add an option to mdToHTML to strip links

This commit is contained in:
Daniele Tonon
2023-11-28 20:15:38 +01:00
parent 8a99017259
commit e4cd448c4c
3 changed files with 18 additions and 3 deletions

View File

@@ -2,6 +2,7 @@ package main
import (
"io"
"regexp"
"strings"
"github.com/gomarkdown/markdown"
@@ -21,6 +22,16 @@ var mdrenderer = html.NewRenderer(html.RendererOptions{
Flags: html.CommonFlags | html.HrefTargetBlank,
})
func stripLinksFromMarkdown(md string) string {
// Regular expression to match Markdown links and HTML links
linkRegex := regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)|<a[^>]*>(.*?)</a>`)
// Replace both Markdown and HTML links with just the link text
strippedMD := linkRegex.ReplaceAllString(md, "$1$2")
return strippedMD
}
var tgivmdrenderer = html.NewRenderer(html.RendererOptions{
Flags: html.CommonFlags | html.HrefTargetBlank,
RenderNodeHook: func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
@@ -46,7 +57,7 @@ var tgivmdrenderer = html.NewRenderer(html.RendererOptions{
},
})
func mdToHTML(md string, usingTelegramInstantView bool) string {
func mdToHTML(md string, usingTelegramInstantView bool, skipLinks bool) string {
md = strings.ReplaceAll(md, "\u00A0", " ")
md = replaceNostrURLsWithTags(nostrEveryMatcher, md)
@@ -61,6 +72,10 @@ func mdToHTML(md string, usingTelegramInstantView bool) string {
// create HTML renderer with extensions
output := string(markdown.Render(doc, renderer))
if skipLinks {
output = stripLinksFromMarkdown(output)
}
// sanitize content
output = sanitizeXSS(output)

View File

@@ -30,7 +30,7 @@ func renderEmbedded(w http.ResponseWriter, r *http.Request, code string) {
}
if data.event.Kind == 30023 || data.event.Kind == 30024 {
data.content = mdToHTML(data.content, data.templateId == TelegramInstantView)
data.content = mdToHTML(data.content, data.templateId == TelegramInstantView, true)
} else {
// first we run basicFormatting, which turns URLs into their appropriate HTML tags
data.content = basicFormatting(html.EscapeString(data.content), true, false, false)

View File

@@ -252,7 +252,7 @@ func renderEvent(w http.ResponseWriter, r *http.Request) {
data.content = strings.ReplaceAll(data.content, placeholderTag, "nostr:"+nreplace)
}
if data.event.Kind == 30023 || data.event.Kind == 30024 {
data.content = mdToHTML(data.content, data.templateId == TelegramInstantView)
data.content = mdToHTML(data.content, data.templateId == TelegramInstantView, false)
} else {
// first we run basicFormatting, which turns URLs into their appropriate HTML tags
data.content = basicFormatting(html.EscapeString(data.content), true, false, false)