rewrite_functions.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package rewrite // import "miniflux.app/v2/internal/reader/rewrite"
  4. import (
  5. "encoding/base64"
  6. "fmt"
  7. "html"
  8. "log/slog"
  9. "net/url"
  10. "regexp"
  11. "strings"
  12. "miniflux.app/v2/internal/config"
  13. "github.com/PuerkitoBio/goquery"
  14. "github.com/yuin/goldmark"
  15. goldmarkhtml "github.com/yuin/goldmark/renderer/html"
  16. )
  17. var (
  18. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)`)
  19. youtubeIdRegex = regexp.MustCompile(`youtube_id"?\s*[:=]\s*"([a-zA-Z0-9_-]{11})"`)
  20. invidioRegex = regexp.MustCompile(`https?:\/\/(.*)\/watch\?v=(.*)`)
  21. imgRegex = regexp.MustCompile(`<img [^>]+>`)
  22. textLinkRegex = regexp.MustCompile(`(?mi)(\bhttps?:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])`)
  23. )
  24. func addImageTitle(entryURL, entryContent string) string {
  25. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  26. if err != nil {
  27. return entryContent
  28. }
  29. matches := doc.Find("img[src][title]")
  30. if matches.Length() > 0 {
  31. matches.Each(func(i int, img *goquery.Selection) {
  32. altAttr := img.AttrOr("alt", "")
  33. srcAttr, _ := img.Attr("src")
  34. titleAttr, _ := img.Attr("title")
  35. img.ReplaceWithHtml(`<figure><img src="` + srcAttr + `" alt="` + altAttr + `"/><figcaption><p>` + html.EscapeString(titleAttr) + `</p></figcaption></figure>`)
  36. })
  37. output, _ := doc.Find("body").First().Html()
  38. return output
  39. }
  40. return entryContent
  41. }
  42. func addMailtoSubject(entryURL, entryContent string) string {
  43. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  44. if err != nil {
  45. return entryContent
  46. }
  47. matches := doc.Find(`a[href^="mailto:"]`)
  48. if matches.Length() > 0 {
  49. matches.Each(func(i int, a *goquery.Selection) {
  50. hrefAttr, _ := a.Attr("href")
  51. mailto, err := url.Parse(hrefAttr)
  52. if err != nil {
  53. return
  54. }
  55. subject := mailto.Query().Get("subject")
  56. if subject == "" {
  57. return
  58. }
  59. a.AppendHtml(" [" + html.EscapeString(subject) + "]")
  60. })
  61. output, _ := doc.Find("body").First().Html()
  62. return output
  63. }
  64. return entryContent
  65. }
  66. func addDynamicImage(entryURL, entryContent string) string {
  67. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  68. if err != nil {
  69. return entryContent
  70. }
  71. // Ordered most preferred to least preferred.
  72. candidateAttrs := []string{
  73. "data-src",
  74. "data-original",
  75. "data-orig",
  76. "data-url",
  77. "data-orig-file",
  78. "data-large-file",
  79. "data-medium-file",
  80. "data-2000src",
  81. "data-1000src",
  82. "data-800src",
  83. "data-655src",
  84. "data-500src",
  85. "data-380src",
  86. }
  87. candidateSrcsetAttrs := []string{
  88. "data-srcset",
  89. }
  90. changed := false
  91. doc.Find("img,div").Each(func(i int, img *goquery.Selection) {
  92. // Src-linked candidates
  93. for _, candidateAttr := range candidateAttrs {
  94. if srcAttr, found := img.Attr(candidateAttr); found {
  95. changed = true
  96. if img.Is("img") {
  97. img.SetAttr("src", srcAttr)
  98. } else {
  99. altAttr := img.AttrOr("alt", "")
  100. img.ReplaceWithHtml(`<img src="` + srcAttr + `" alt="` + altAttr + `"/>`)
  101. }
  102. break
  103. }
  104. }
  105. // Srcset-linked candidates
  106. for _, candidateAttr := range candidateSrcsetAttrs {
  107. if srcAttr, found := img.Attr(candidateAttr); found {
  108. changed = true
  109. if img.Is("img") {
  110. img.SetAttr("srcset", srcAttr)
  111. } else {
  112. altAttr := img.AttrOr("alt", "")
  113. img.ReplaceWithHtml(`<img srcset="` + srcAttr + `" alt="` + altAttr + `"/>`)
  114. }
  115. break
  116. }
  117. }
  118. })
  119. if !changed {
  120. doc.Find("noscript").Each(func(i int, noscript *goquery.Selection) {
  121. matches := imgRegex.FindAllString(noscript.Text(), 2)
  122. if len(matches) == 1 {
  123. changed = true
  124. noscript.ReplaceWithHtml(matches[0])
  125. }
  126. })
  127. }
  128. if changed {
  129. output, _ := doc.Find("body").First().Html()
  130. return output
  131. }
  132. return entryContent
  133. }
  134. func fixMediumImages(entryURL, entryContent string) string {
  135. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  136. if err != nil {
  137. return entryContent
  138. }
  139. doc.Find("figure.paragraph-image").Each(func(i int, paragraphImage *goquery.Selection) {
  140. noscriptElement := paragraphImage.Find("noscript")
  141. if noscriptElement.Length() > 0 {
  142. paragraphImage.ReplaceWithHtml(noscriptElement.Text())
  143. }
  144. })
  145. output, _ := doc.Find("body").First().Html()
  146. return output
  147. }
  148. func useNoScriptImages(entryURL, entryContent string) string {
  149. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  150. if err != nil {
  151. return entryContent
  152. }
  153. doc.Find("figure").Each(func(i int, figureElement *goquery.Selection) {
  154. imgElement := figureElement.Find("img")
  155. if imgElement.Length() > 0 {
  156. noscriptElement := figureElement.Find("noscript")
  157. if noscriptElement.Length() > 0 {
  158. figureElement.PrependHtml(noscriptElement.Text())
  159. imgElement.Remove()
  160. noscriptElement.Remove()
  161. }
  162. }
  163. })
  164. output, _ := doc.Find("body").First().Html()
  165. return output
  166. }
  167. func addYoutubeVideo(entryURL, entryContent string) string {
  168. matches := youtubeRegex.FindStringSubmatch(entryURL)
  169. if len(matches) == 2 {
  170. video := `<iframe width="650" height="350" frameborder="0" src="` + config.Opts.YouTubeEmbedUrlOverride() + matches[1] + `" allowfullscreen></iframe>`
  171. return video + `<br>` + entryContent
  172. }
  173. return entryContent
  174. }
  175. func addYoutubeVideoUsingInvidiousPlayer(entryURL, entryContent string) string {
  176. matches := youtubeRegex.FindStringSubmatch(entryURL)
  177. if len(matches) == 2 {
  178. video := `<iframe width="650" height="350" frameborder="0" src="https://` + config.Opts.InvidiousInstance() + `/embed/` + matches[1] + `" allowfullscreen></iframe>`
  179. return video + `<br>` + entryContent
  180. }
  181. return entryContent
  182. }
  183. func addYoutubeVideoFromId(entryContent string) string {
  184. matches := youtubeIdRegex.FindAllStringSubmatch(entryContent, -1)
  185. if matches == nil {
  186. return entryContent
  187. }
  188. sb := strings.Builder{}
  189. for _, match := range matches {
  190. if len(match) == 2 {
  191. sb.WriteString(`<iframe width="650" height="350" frameborder="0" src="`)
  192. sb.WriteString(config.Opts.YouTubeEmbedUrlOverride())
  193. sb.WriteString(match[1])
  194. sb.WriteString(`" allowfullscreen></iframe><br>`)
  195. }
  196. }
  197. sb.WriteString(entryContent)
  198. return sb.String()
  199. }
  200. func addInvidiousVideo(entryURL, entryContent string) string {
  201. matches := invidioRegex.FindStringSubmatch(entryURL)
  202. if len(matches) == 3 {
  203. video := `<iframe width="650" height="350" frameborder="0" src="https://` + matches[1] + `/embed/` + matches[2] + `" allowfullscreen></iframe>`
  204. return video + `<br>` + entryContent
  205. }
  206. return entryContent
  207. }
  208. func addPDFLink(entryURL, entryContent string) string {
  209. if strings.HasSuffix(entryURL, ".pdf") {
  210. return fmt.Sprintf(`<a href="%s">PDF</a><br>%s`, entryURL, entryContent)
  211. }
  212. return entryContent
  213. }
  214. func replaceTextLinks(input string) string {
  215. return textLinkRegex.ReplaceAllString(input, `<a href="${1}">${1}</a>`)
  216. }
  217. func replaceLineFeeds(input string) string {
  218. return strings.Replace(input, "\n", "<br>", -1)
  219. }
  220. func replaceCustom(entryContent string, searchTerm string, replaceTerm string) string {
  221. re, err := regexp.Compile(searchTerm)
  222. if err == nil {
  223. return re.ReplaceAllString(entryContent, replaceTerm)
  224. }
  225. return entryContent
  226. }
  227. func removeCustom(entryContent string, selector string) string {
  228. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  229. if err != nil {
  230. return entryContent
  231. }
  232. doc.Find(selector).Remove()
  233. output, _ := doc.Find("body").First().Html()
  234. return output
  235. }
  236. func addCastopodEpisode(entryURL, entryContent string) string {
  237. player := `<iframe width="650" frameborder="0" src="` + entryURL + `/embed/light"></iframe>`
  238. return player + `<br>` + entryContent
  239. }
  240. func applyFuncOnTextContent(entryContent string, selector string, repl func(string) string) string {
  241. var treatChildren func(i int, s *goquery.Selection)
  242. treatChildren = func(i int, s *goquery.Selection) {
  243. if s.Nodes[0].Type == 1 {
  244. s.ReplaceWithHtml(repl(s.Nodes[0].Data))
  245. } else {
  246. s.Contents().Each(treatChildren)
  247. }
  248. }
  249. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  250. if err != nil {
  251. return entryContent
  252. }
  253. doc.Find(selector).Each(treatChildren)
  254. output, _ := doc.Find("body").First().Html()
  255. return output
  256. }
  257. func decodeBase64Content(entryContent string) string {
  258. if ret, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entryContent)); err != nil {
  259. return entryContent
  260. } else {
  261. return html.EscapeString(string(ret))
  262. }
  263. }
  264. func addHackerNewsLinksUsing(entryContent, app string) string {
  265. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  266. if err != nil {
  267. return entryContent
  268. }
  269. hn_prefix := "https://news.ycombinator.com/"
  270. matches := doc.Find(`a[href^="` + hn_prefix + `"]`)
  271. if matches.Length() > 0 {
  272. matches.Each(func(i int, a *goquery.Selection) {
  273. hrefAttr, _ := a.Attr("href")
  274. hn_uri, err := url.Parse(hrefAttr)
  275. if err != nil {
  276. return
  277. }
  278. if app == "opener" {
  279. params := url.Values{}
  280. params.Add("url", hn_uri.String())
  281. url := url.URL{
  282. Scheme: "opener",
  283. Host: "x-callback-url",
  284. Path: "show-options",
  285. RawQuery: params.Encode(),
  286. }
  287. open_with_opener := `<a href="` + url.String() + `">Open with Opener</a>`
  288. a.Parent().AppendHtml(" " + open_with_opener)
  289. } else if app == "hack" {
  290. url := strings.Replace(hn_uri.String(), hn_prefix, "hack://", 1)
  291. open_with_hack := `<a href="` + url + `">Open with HACK</a>`
  292. a.Parent().AppendHtml(" " + open_with_hack)
  293. } else {
  294. slog.Warn("Unknown app provided for openHackerNewsLinksWith rewrite rule",
  295. slog.String("app", app),
  296. )
  297. return
  298. }
  299. })
  300. output, _ := doc.Find("body").First().Html()
  301. return output
  302. }
  303. return entryContent
  304. }
  305. func parseMarkdown(entryContent string) string {
  306. var sb strings.Builder
  307. md := goldmark.New(
  308. goldmark.WithRendererOptions(
  309. goldmarkhtml.WithUnsafe(),
  310. ),
  311. )
  312. if err := md.Convert([]byte(entryContent), &sb); err != nil {
  313. return entryContent
  314. }
  315. return sb.String()
  316. }
  317. func removeTables(entryContent string) string {
  318. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  319. if err != nil {
  320. return entryContent
  321. }
  322. selectors := []string{"table", "tbody", "thead", "td", "th", "td"}
  323. var loopElement *goquery.Selection
  324. for _, selector := range selectors {
  325. for {
  326. loopElement = doc.Find(selector).First()
  327. if loopElement.Length() == 0 {
  328. break
  329. }
  330. innerHtml, err := loopElement.Html()
  331. if err != nil {
  332. break
  333. }
  334. loopElement.Parent().AppendHtml(innerHtml)
  335. loopElement.Remove()
  336. }
  337. }
  338. output, _ := doc.Find("body").First().Html()
  339. return output
  340. }
  341. func removeClickbait(entryTitle string) string {
  342. titleWords := []string{}
  343. for _, word := range strings.Fields(entryTitle) {
  344. runes := []rune(word)
  345. if len(runes) > 1 {
  346. // keep first rune as is to keep the first capital letter
  347. titleWords = append(titleWords, string([]rune{runes[0]})+strings.ToLower(string(runes[1:])))
  348. } else {
  349. titleWords = append(titleWords, word)
  350. }
  351. }
  352. return strings.Join(titleWords, " ")
  353. }