content_rewrite_functions.go 15 KB

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