content_rewrite_functions.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. "strconv"
  12. "strings"
  13. "unicode"
  14. "miniflux.app/v2/internal/config"
  15. nethtml "golang.org/x/net/html"
  16. "github.com/PuerkitoBio/goquery"
  17. )
  18. var (
  19. youtubeIdRegex = regexp.MustCompile(`youtube_id"?\s*[:=]\s*"([a-zA-Z0-9_-]{11})"`)
  20. textLinkRegex = regexp.MustCompile(`(?mi)(\bhttps?:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])`)
  21. )
  22. // titlelize returns a copy of the string s with all Unicode letters that begin words
  23. // mapped to their Unicode title case.
  24. func titlelize(s string) string {
  25. // A closure is used here to remember the previous character
  26. // so that we can check if there is a space preceding the current
  27. // character.
  28. previous := ' '
  29. return strings.Map(
  30. func(current rune) rune {
  31. if unicode.IsSpace(previous) {
  32. previous = current
  33. return unicode.ToTitle(current)
  34. }
  35. previous = current
  36. return current
  37. }, strings.ToLower(s))
  38. }
  39. func addImageTitle(entryContent string) string {
  40. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  41. if err != nil {
  42. return entryContent
  43. }
  44. matches := doc.Find("img[src][title]")
  45. if matches.Length() > 0 {
  46. matches.Each(func(i int, img *goquery.Selection) {
  47. altAttr := img.AttrOr("alt", "")
  48. srcAttr, _ := img.Attr("src")
  49. titleAttr, _ := img.Attr("title")
  50. img.ReplaceWithHtml(`<figure><img src="` + srcAttr + `" alt="` + altAttr + `"/><figcaption><p>` + html.EscapeString(titleAttr) + `</p></figcaption></figure>`)
  51. })
  52. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  53. return output
  54. }
  55. return entryContent
  56. }
  57. func addMailtoSubject(entryContent string) string {
  58. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  59. if err != nil {
  60. return entryContent
  61. }
  62. matches := doc.Find(`a[href^="mailto:"]`)
  63. if matches.Length() > 0 {
  64. matches.Each(func(i int, a *goquery.Selection) {
  65. hrefAttr, _ := a.Attr("href")
  66. mailto, err := url.Parse(hrefAttr)
  67. if err != nil {
  68. return
  69. }
  70. subject := mailto.Query().Get("subject")
  71. if subject == "" {
  72. return
  73. }
  74. a.AppendHtml(" [" + html.EscapeString(subject) + "]")
  75. })
  76. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  77. return output
  78. }
  79. return entryContent
  80. }
  81. func addDynamicImage(entryContent string) string {
  82. parserHtml, err := nethtml.ParseWithOptions(strings.NewReader(entryContent), nethtml.ParseOptionEnableScripting(false))
  83. if err != nil {
  84. return entryContent
  85. }
  86. doc := goquery.NewDocumentFromNode(parserHtml)
  87. // Ordered most preferred to least preferred.
  88. candidateAttrs := [...]string{
  89. "data-src",
  90. "data-original",
  91. "data-orig",
  92. "data-url",
  93. "data-orig-file",
  94. "data-large-file",
  95. "data-medium-file",
  96. "data-original-mos",
  97. "data-2000src",
  98. "data-1000src",
  99. "data-800src",
  100. "data-655src",
  101. "data-500src",
  102. "data-380src",
  103. }
  104. candidateSrcsetAttrs := [...]string{
  105. "data-srcset",
  106. }
  107. changed := false
  108. doc.Find("img,div").Each(func(i int, img *goquery.Selection) {
  109. // Src-linked candidates
  110. for _, candidateAttr := range candidateAttrs {
  111. if srcAttr, found := img.Attr(candidateAttr); found {
  112. changed = true
  113. if img.Is("img") {
  114. img.SetAttr("src", srcAttr)
  115. } else {
  116. altAttr := img.AttrOr("alt", "")
  117. img.ReplaceWithHtml(`<img src="` + srcAttr + `" alt="` + altAttr + `"/>`)
  118. }
  119. break
  120. }
  121. }
  122. // Srcset-linked candidates
  123. for _, candidateAttr := range candidateSrcsetAttrs {
  124. if srcAttr, found := img.Attr(candidateAttr); found {
  125. changed = true
  126. if img.Is("img") {
  127. img.SetAttr("srcset", srcAttr)
  128. } else {
  129. altAttr := img.AttrOr("alt", "")
  130. img.ReplaceWithHtml(`<img srcset="` + srcAttr + `" alt="` + altAttr + `"/>`)
  131. }
  132. break
  133. }
  134. }
  135. })
  136. if !changed {
  137. doc.Find("noscript").Each(func(i int, noscript *goquery.Selection) {
  138. if img := noscript.Find("img"); img.Length() == 1 {
  139. img.Unwrap()
  140. changed = true
  141. }
  142. })
  143. }
  144. if changed {
  145. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  146. return output
  147. }
  148. return entryContent
  149. }
  150. func addDynamicIframe(entryContent string) string {
  151. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  152. if err != nil {
  153. return entryContent
  154. }
  155. // Ordered most preferred to least preferred.
  156. candidateAttrs := []string{
  157. "data-src",
  158. "data-original",
  159. "data-orig",
  160. "data-url",
  161. "data-lazy-src",
  162. }
  163. changed := false
  164. doc.Find("iframe").Each(func(i int, iframe *goquery.Selection) {
  165. for _, candidateAttr := range candidateAttrs {
  166. if srcAttr, found := iframe.Attr(candidateAttr); found {
  167. changed = true
  168. iframe.SetAttr("src", srcAttr)
  169. break
  170. }
  171. }
  172. })
  173. if changed {
  174. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  175. return output
  176. }
  177. return entryContent
  178. }
  179. func fixMediumImages(entryContent string) string {
  180. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  181. if err != nil {
  182. return entryContent
  183. }
  184. doc.Find("figure.paragraph-image").Each(func(i int, paragraphImage *goquery.Selection) {
  185. noscriptElement := paragraphImage.Find("noscript")
  186. if noscriptElement.Length() > 0 {
  187. paragraphImage.ReplaceWithHtml(noscriptElement.Text())
  188. }
  189. })
  190. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  191. return output
  192. }
  193. func useNoScriptImages(entryContent string) string {
  194. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  195. if err != nil {
  196. return entryContent
  197. }
  198. doc.Find("figure").Each(func(i int, figureElement *goquery.Selection) {
  199. imgElement := figureElement.Find("img")
  200. if imgElement.Length() > 0 {
  201. noscriptElement := figureElement.Find("noscript")
  202. if noscriptElement.Length() > 0 {
  203. figureElement.PrependHtml(noscriptElement.Text())
  204. imgElement.Remove()
  205. noscriptElement.Remove()
  206. }
  207. }
  208. })
  209. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  210. return output
  211. }
  212. func getYoutubVideoIDFromURL(entryURL string) string {
  213. u, err := url.Parse(entryURL)
  214. if err != nil {
  215. return ""
  216. }
  217. if !strings.HasSuffix(u.Hostname(), "youtube.com") {
  218. return ""
  219. }
  220. if u.Path == "/watch" {
  221. if v := u.Query().Get("v"); v != "" {
  222. return v
  223. }
  224. return ""
  225. }
  226. if id, found := strings.CutPrefix(u.Path, "/shorts/"); found {
  227. if len(id) == 11 {
  228. // youtube shorts id are always 11 chars.
  229. return id
  230. }
  231. }
  232. return ""
  233. }
  234. func buildVideoPlayerIframe(absoluteVideoURL string) string {
  235. // Note: the referrerpolicy seems to be required to avoid YouTube error 153 video player configuration error
  236. // See https://developers.google.com/youtube/terms/required-minimum-functionality#embedded-player-api-client-identity
  237. return `<iframe width="650" height="350" frameborder="0" src="` + absoluteVideoURL + `" allowfullscreen referrerpolicy="strict-origin-when-cross-origin"></iframe>`
  238. }
  239. func addVideoPlayerIframe(absoluteVideoURL, entryContent string) string {
  240. return buildVideoPlayerIframe(absoluteVideoURL) + `<br>` + entryContent
  241. }
  242. func addYoutubeVideoRewriteRule(entryURL, entryContent string) string {
  243. if videoURL := getYoutubVideoIDFromURL(entryURL); videoURL != "" {
  244. return addVideoPlayerIframe(config.Opts.YouTubeEmbedUrlOverride()+videoURL, entryContent)
  245. }
  246. return entryContent
  247. }
  248. func addYoutubeVideoUsingInvidiousPlayer(entryURL, entryContent string) string {
  249. if videoURL := getYoutubVideoIDFromURL(entryURL); videoURL != "" {
  250. return addVideoPlayerIframe(`https://`+config.Opts.InvidiousInstance()+`/embed/`+videoURL, entryContent)
  251. }
  252. return entryContent
  253. }
  254. // For reference: https://github.com/miniflux/v2/pull/1314
  255. func addYoutubeVideoFromId(entryContent string) string {
  256. matches := youtubeIdRegex.FindAllStringSubmatch(entryContent, -1)
  257. if matches == nil {
  258. return entryContent
  259. }
  260. var videoPlayerHTML strings.Builder
  261. for _, match := range matches {
  262. if len(match) == 2 {
  263. videoPlayerHTML.WriteString(buildVideoPlayerIframe(config.Opts.YouTubeEmbedUrlOverride() + match[1]))
  264. videoPlayerHTML.WriteString("<br>")
  265. }
  266. }
  267. return videoPlayerHTML.String() + entryContent
  268. }
  269. func addInvidiousVideo(entryURL, entryContent string) string {
  270. u, err := url.Parse(entryURL)
  271. if err != nil {
  272. return entryContent
  273. }
  274. if u.Path != "/watch" {
  275. return entryContent
  276. }
  277. qs := u.Query()
  278. videoID := qs.Get("v")
  279. if videoID == "" {
  280. return entryContent
  281. }
  282. qs.Del("v")
  283. embedVideoURL := "https://" + u.Hostname() + `/embed/` + videoID
  284. if len(qs) > 0 {
  285. embedVideoURL += "?" + qs.Encode()
  286. }
  287. return addVideoPlayerIframe(embedVideoURL, entryContent)
  288. }
  289. func addPDFLink(entryURL, entryContent string) string {
  290. if strings.HasSuffix(entryURL, ".pdf") {
  291. return fmt.Sprintf(`<a href=%q>PDF</a><br>%s`, entryURL, entryContent)
  292. }
  293. return entryContent
  294. }
  295. func replaceTextLinks(input string) string {
  296. return textLinkRegex.ReplaceAllString(input, `<a href="${1}">${1}</a>`)
  297. }
  298. func replaceCustom(entryContent string, searchTerm string, replaceTerm string) string {
  299. re, err := regexp.Compile(searchTerm)
  300. if err == nil {
  301. return re.ReplaceAllString(entryContent, replaceTerm)
  302. }
  303. return entryContent
  304. }
  305. func removeCustom(entryContent string, selector string) string {
  306. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  307. if err != nil {
  308. return entryContent
  309. }
  310. doc.Find(selector).Remove()
  311. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  312. return output
  313. }
  314. func addCastopodEpisode(entryURL, entryContent string) string {
  315. player := `<iframe width="650" frameborder="0" src="` + entryURL + `/embed/light"></iframe>`
  316. return player + `<br>` + entryContent
  317. }
  318. func applyFuncOnTextContent(entryContent string, selector string, repl func(string) string) string {
  319. var treatChildren func(i int, s *goquery.Selection)
  320. treatChildren = func(i int, s *goquery.Selection) {
  321. if s.Nodes[0].Type == nethtml.TextNode {
  322. s.ReplaceWithHtml(repl(s.Nodes[0].Data))
  323. } else {
  324. s.Contents().Each(treatChildren)
  325. }
  326. }
  327. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  328. if err != nil {
  329. return entryContent
  330. }
  331. doc.Find(selector).Each(treatChildren)
  332. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  333. return output
  334. }
  335. func decodeBase64Content(entryContent string) string {
  336. if ret, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entryContent)); err != nil {
  337. return entryContent
  338. } else {
  339. return html.EscapeString(string(ret))
  340. }
  341. }
  342. func addHackerNewsLinksUsing(entryContent, app string) string {
  343. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  344. if err != nil {
  345. return entryContent
  346. }
  347. hn_prefix := "https://news.ycombinator.com/"
  348. matches := doc.Find(`a[href^="` + hn_prefix + `"]`)
  349. if matches.Length() > 0 {
  350. matches.Each(func(i int, a *goquery.Selection) {
  351. hrefAttr, _ := a.Attr("href")
  352. hn_uri, err := url.Parse(hrefAttr)
  353. if err != nil {
  354. return
  355. }
  356. switch app {
  357. case "opener":
  358. params := url.Values{}
  359. params.Add("url", hn_uri.String())
  360. url := url.URL{
  361. Scheme: "opener",
  362. Host: "x-callback-url",
  363. Path: "show-options",
  364. RawQuery: params.Encode(),
  365. }
  366. open_with_opener := `<a href="` + url.String() + `">Open with Opener</a>`
  367. a.Parent().AppendHtml(" " + open_with_opener)
  368. case "hack":
  369. url := strings.Replace(hn_uri.String(), hn_prefix, "hack://", 1)
  370. open_with_hack := `<a href="` + url + `">Open with HACK</a>`
  371. a.Parent().AppendHtml(" " + open_with_hack)
  372. default:
  373. slog.Warn("Unknown app provided for openHackerNewsLinksWith rewrite rule",
  374. slog.String("app", app),
  375. )
  376. return
  377. }
  378. })
  379. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  380. return output
  381. }
  382. return entryContent
  383. }
  384. func removeTables(entryContent string) string {
  385. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  386. if err != nil {
  387. return entryContent
  388. }
  389. selectors := []string{"table", "tbody", "thead", "td", "th", "td"}
  390. var loopElement *goquery.Selection
  391. for _, selector := range selectors {
  392. for {
  393. loopElement = doc.FindMatcher(goquery.Single(selector))
  394. if loopElement.Length() == 0 {
  395. break
  396. }
  397. innerHtml, err := loopElement.Html()
  398. if err != nil {
  399. break
  400. }
  401. loopElement.Parent().AppendHtml(innerHtml)
  402. loopElement.Remove()
  403. }
  404. }
  405. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  406. return output
  407. }
  408. func fixGhostCards(entryContent string) string {
  409. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  410. if err != nil {
  411. return entryContent
  412. }
  413. const cardSelector = "figure.kg-card"
  414. var currentList *goquery.Selection
  415. doc.Find(cardSelector).Each(func(i int, s *goquery.Selection) {
  416. title := s.Find(".kg-bookmark-title").First().Text()
  417. author := s.Find(".kg-bookmark-author").First().Text()
  418. href := s.Find("a.kg-bookmark-container").First().AttrOr("href", "")
  419. // if there is no link or title, skip processing
  420. if href == "" || title == "" {
  421. return
  422. }
  423. link := ""
  424. if author == "" || strings.HasSuffix(title, author) {
  425. link = fmt.Sprintf("<a href=\"%s\">%s</a>", href, title)
  426. } else {
  427. link = fmt.Sprintf("<a href=\"%s\">%s - %s</a>", href, title, author)
  428. }
  429. next := s.Next()
  430. // if the next element is also a card, start a list
  431. if next.Is(cardSelector) && currentList == nil {
  432. currentList = s.BeforeHtml("<ul></ul>").Prev()
  433. }
  434. if currentList != nil {
  435. // add this card to the list, then delete it
  436. currentList.AppendHtml("<li>" + link + "</li>")
  437. s.Remove()
  438. } else {
  439. // replace single card
  440. s.ReplaceWithHtml(link)
  441. }
  442. // if the next element is not a card, start a new list
  443. if !next.Is(cardSelector) && currentList != nil {
  444. currentList = nil
  445. }
  446. })
  447. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  448. return strings.TrimSpace(output)
  449. }
  450. func removeImgBlurParams(entryContent string) string {
  451. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  452. if err != nil {
  453. return entryContent
  454. }
  455. changed := false
  456. doc.Find("img[src]").Each(func(i int, img *goquery.Selection) {
  457. srcAttr, exists := img.Attr("src")
  458. if !exists {
  459. return
  460. }
  461. parsedURL, err := url.Parse(srcAttr)
  462. if err != nil {
  463. return
  464. }
  465. // Only strip query parameters if this is a blurry placeholder image
  466. if parsedURL.RawQuery != "" {
  467. // Check if there's a blur parameter with a non-zero value
  468. if blurValue := parsedURL.Query().Get("blur"); blurValue != "" {
  469. if blurInt, err := strconv.Atoi(blurValue); err == nil && blurInt > 0 {
  470. parsedURL.RawQuery = ""
  471. img.SetAttr("src", parsedURL.String())
  472. changed = true
  473. }
  474. }
  475. }
  476. })
  477. if changed {
  478. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  479. return output
  480. }
  481. return entryContent
  482. }