content_rewrite_functions.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. videoPlayerHTML := ""
  261. for _, match := range matches {
  262. if len(match) == 2 {
  263. videoPlayerHTML += buildVideoPlayerIframe(config.Opts.YouTubeEmbedUrlOverride()+match[1]) + "<br>"
  264. }
  265. }
  266. return videoPlayerHTML + entryContent
  267. }
  268. func addInvidiousVideo(entryURL, entryContent string) string {
  269. u, err := url.Parse(entryURL)
  270. if err != nil {
  271. return entryContent
  272. }
  273. if u.Path != "/watch" {
  274. return entryContent
  275. }
  276. qs := u.Query()
  277. videoID := qs.Get("v")
  278. if videoID == "" {
  279. return entryContent
  280. }
  281. qs.Del("v")
  282. embedVideoURL := "https://" + u.Hostname() + `/embed/` + videoID
  283. if len(qs) > 0 {
  284. embedVideoURL += "?" + qs.Encode()
  285. }
  286. return addVideoPlayerIframe(embedVideoURL, entryContent)
  287. }
  288. func addPDFLink(entryURL, entryContent string) string {
  289. if strings.HasSuffix(entryURL, ".pdf") {
  290. return fmt.Sprintf(`<a href=%q>PDF</a><br>%s`, entryURL, entryContent)
  291. }
  292. return entryContent
  293. }
  294. func replaceTextLinks(input string) string {
  295. return textLinkRegex.ReplaceAllString(input, `<a href="${1}">${1}</a>`)
  296. }
  297. func replaceCustom(entryContent string, searchTerm string, replaceTerm string) string {
  298. re, err := regexp.Compile(searchTerm)
  299. if err == nil {
  300. return re.ReplaceAllString(entryContent, replaceTerm)
  301. }
  302. return entryContent
  303. }
  304. func removeCustom(entryContent string, selector string) string {
  305. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  306. if err != nil {
  307. return entryContent
  308. }
  309. doc.Find(selector).Remove()
  310. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  311. return output
  312. }
  313. func addCastopodEpisode(entryURL, entryContent string) string {
  314. player := `<iframe width="650" frameborder="0" src="` + entryURL + `/embed/light"></iframe>`
  315. return player + `<br>` + entryContent
  316. }
  317. func applyFuncOnTextContent(entryContent string, selector string, repl func(string) string) string {
  318. var treatChildren func(i int, s *goquery.Selection)
  319. treatChildren = func(i int, s *goquery.Selection) {
  320. if s.Nodes[0].Type == nethtml.TextNode {
  321. s.ReplaceWithHtml(repl(s.Nodes[0].Data))
  322. } else {
  323. s.Contents().Each(treatChildren)
  324. }
  325. }
  326. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  327. if err != nil {
  328. return entryContent
  329. }
  330. doc.Find(selector).Each(treatChildren)
  331. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  332. return output
  333. }
  334. func decodeBase64Content(entryContent string) string {
  335. if ret, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entryContent)); err != nil {
  336. return entryContent
  337. } else {
  338. return html.EscapeString(string(ret))
  339. }
  340. }
  341. func addHackerNewsLinksUsing(entryContent, app string) string {
  342. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  343. if err != nil {
  344. return entryContent
  345. }
  346. hn_prefix := "https://news.ycombinator.com/"
  347. matches := doc.Find(`a[href^="` + hn_prefix + `"]`)
  348. if matches.Length() > 0 {
  349. matches.Each(func(i int, a *goquery.Selection) {
  350. hrefAttr, _ := a.Attr("href")
  351. hn_uri, err := url.Parse(hrefAttr)
  352. if err != nil {
  353. return
  354. }
  355. switch app {
  356. case "opener":
  357. params := url.Values{}
  358. params.Add("url", hn_uri.String())
  359. url := url.URL{
  360. Scheme: "opener",
  361. Host: "x-callback-url",
  362. Path: "show-options",
  363. RawQuery: params.Encode(),
  364. }
  365. open_with_opener := `<a href="` + url.String() + `">Open with Opener</a>`
  366. a.Parent().AppendHtml(" " + open_with_opener)
  367. case "hack":
  368. url := strings.Replace(hn_uri.String(), hn_prefix, "hack://", 1)
  369. open_with_hack := `<a href="` + url + `">Open with HACK</a>`
  370. a.Parent().AppendHtml(" " + open_with_hack)
  371. default:
  372. slog.Warn("Unknown app provided for openHackerNewsLinksWith rewrite rule",
  373. slog.String("app", app),
  374. )
  375. return
  376. }
  377. })
  378. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  379. return output
  380. }
  381. return entryContent
  382. }
  383. func removeTables(entryContent string) string {
  384. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  385. if err != nil {
  386. return entryContent
  387. }
  388. selectors := []string{"table", "tbody", "thead", "td", "th", "td"}
  389. var loopElement *goquery.Selection
  390. for _, selector := range selectors {
  391. for {
  392. loopElement = doc.FindMatcher(goquery.Single(selector))
  393. if loopElement.Length() == 0 {
  394. break
  395. }
  396. innerHtml, err := loopElement.Html()
  397. if err != nil {
  398. break
  399. }
  400. loopElement.Parent().AppendHtml(innerHtml)
  401. loopElement.Remove()
  402. }
  403. }
  404. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  405. return output
  406. }
  407. func fixGhostCards(entryContent string) string {
  408. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  409. if err != nil {
  410. return entryContent
  411. }
  412. const cardSelector = "figure.kg-card"
  413. var currentList *goquery.Selection
  414. doc.Find(cardSelector).Each(func(i int, s *goquery.Selection) {
  415. title := s.Find(".kg-bookmark-title").First().Text()
  416. author := s.Find(".kg-bookmark-author").First().Text()
  417. href := s.Find("a.kg-bookmark-container").First().AttrOr("href", "")
  418. // if there is no link or title, skip processing
  419. if href == "" || title == "" {
  420. return
  421. }
  422. link := ""
  423. if author == "" || strings.HasSuffix(title, author) {
  424. link = fmt.Sprintf("<a href=\"%s\">%s</a>", href, title)
  425. } else {
  426. link = fmt.Sprintf("<a href=\"%s\">%s - %s</a>", href, title, author)
  427. }
  428. next := s.Next()
  429. // if the next element is also a card, start a list
  430. if next.Is(cardSelector) && currentList == nil {
  431. currentList = s.BeforeHtml("<ul></ul>").Prev()
  432. }
  433. if currentList != nil {
  434. // add this card to the list, then delete it
  435. currentList.AppendHtml("<li>" + link + "</li>")
  436. s.Remove()
  437. } else {
  438. // replace single card
  439. s.ReplaceWithHtml(link)
  440. }
  441. // if the next element is not a card, start a new list
  442. if !next.Is(cardSelector) && currentList != nil {
  443. currentList = nil
  444. }
  445. })
  446. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  447. return strings.TrimSpace(output)
  448. }
  449. func removeImgBlurParams(entryContent string) string {
  450. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  451. if err != nil {
  452. return entryContent
  453. }
  454. changed := false
  455. doc.Find("img[src]").Each(func(i int, img *goquery.Selection) {
  456. srcAttr, exists := img.Attr("src")
  457. if !exists {
  458. return
  459. }
  460. parsedURL, err := url.Parse(srcAttr)
  461. if err != nil {
  462. return
  463. }
  464. // Only strip query parameters if this is a blurry placeholder image
  465. if parsedURL.RawQuery != "" {
  466. // Check if there's a blur parameter with a non-zero value
  467. if blurValue := parsedURL.Query().Get("blur"); blurValue != "" {
  468. if blurInt, err := strconv.Atoi(blurValue); err == nil && blurInt > 0 {
  469. parsedURL.RawQuery = ""
  470. img.SetAttr("src", parsedURL.String())
  471. changed = true
  472. }
  473. }
  474. }
  475. })
  476. if changed {
  477. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  478. return output
  479. }
  480. return entryContent
  481. }