content_rewrite_functions.go 14 KB

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