content_rewrite_functions.go 14 KB

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