4
0

content_rewrite_functions.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. "strings"
  12. "unicode"
  13. "miniflux.app/v2/internal/config"
  14. nethtml "golang.org/x/net/html"
  15. "github.com/PuerkitoBio/goquery"
  16. )
  17. var (
  18. youtubeIdRegex = regexp.MustCompile(`youtube_id"?\s*[:=]\s*"([a-zA-Z0-9_-]{11})"`)
  19. textLinkRegex = regexp.MustCompile(`(?mi)(\bhttps?:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])`)
  20. )
  21. // titlelize returns a copy of the string s with all Unicode letters that begin words
  22. // mapped to their Unicode title case.
  23. func titlelize(s string) string {
  24. // A closure is used here to remember the previous character
  25. // so that we can check if there is a space preceding the current
  26. // character.
  27. previous := ' '
  28. return strings.Map(
  29. func(current rune) rune {
  30. if unicode.IsSpace(previous) {
  31. previous = current
  32. return unicode.ToTitle(current)
  33. }
  34. previous = current
  35. return current
  36. }, strings.ToLower(s))
  37. }
  38. func addImageTitle(entryContent string) string {
  39. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  40. if err != nil {
  41. return entryContent
  42. }
  43. matches := doc.Find("img[src][title]")
  44. if matches.Length() > 0 {
  45. matches.Each(func(i int, img *goquery.Selection) {
  46. altAttr := img.AttrOr("alt", "")
  47. srcAttr, _ := img.Attr("src")
  48. titleAttr, _ := img.Attr("title")
  49. img.ReplaceWithHtml(`<figure><img src="` + srcAttr + `" alt="` + altAttr + `"/><figcaption><p>` + html.EscapeString(titleAttr) + `</p></figcaption></figure>`)
  50. })
  51. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  52. return output
  53. }
  54. return entryContent
  55. }
  56. func addMailtoSubject(entryContent string) string {
  57. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  58. if err != nil {
  59. return entryContent
  60. }
  61. matches := doc.Find(`a[href^="mailto:"]`)
  62. if matches.Length() > 0 {
  63. matches.Each(func(i int, a *goquery.Selection) {
  64. hrefAttr, _ := a.Attr("href")
  65. mailto, err := url.Parse(hrefAttr)
  66. if err != nil {
  67. return
  68. }
  69. subject := mailto.Query().Get("subject")
  70. if subject == "" {
  71. return
  72. }
  73. a.AppendHtml(" [" + html.EscapeString(subject) + "]")
  74. })
  75. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  76. return output
  77. }
  78. return entryContent
  79. }
  80. func addDynamicImage(entryContent string) string {
  81. parserHtml, err := nethtml.ParseWithOptions(strings.NewReader(entryContent), nethtml.ParseOptionEnableScripting(false))
  82. if err != nil {
  83. return entryContent
  84. }
  85. doc := goquery.NewDocumentFromNode(parserHtml)
  86. // Ordered most preferred to least preferred.
  87. candidateAttrs := []string{
  88. "data-src",
  89. "data-original",
  90. "data-orig",
  91. "data-url",
  92. "data-orig-file",
  93. "data-large-file",
  94. "data-medium-file",
  95. "data-original-mos",
  96. "data-2000src",
  97. "data-1000src",
  98. "data-800src",
  99. "data-655src",
  100. "data-500src",
  101. "data-380src",
  102. }
  103. candidateSrcsetAttrs := []string{
  104. "data-srcset",
  105. }
  106. changed := false
  107. doc.Find("img,div").Each(func(i int, img *goquery.Selection) {
  108. // Src-linked candidates
  109. for _, candidateAttr := range candidateAttrs {
  110. if srcAttr, found := img.Attr(candidateAttr); found {
  111. changed = true
  112. if img.Is("img") {
  113. img.SetAttr("src", srcAttr)
  114. } else {
  115. altAttr := img.AttrOr("alt", "")
  116. img.ReplaceWithHtml(`<img src="` + srcAttr + `" alt="` + altAttr + `"/>`)
  117. }
  118. break
  119. }
  120. }
  121. // Srcset-linked candidates
  122. for _, candidateAttr := range candidateSrcsetAttrs {
  123. if srcAttr, found := img.Attr(candidateAttr); found {
  124. changed = true
  125. if img.Is("img") {
  126. img.SetAttr("srcset", srcAttr)
  127. } else {
  128. altAttr := img.AttrOr("alt", "")
  129. img.ReplaceWithHtml(`<img srcset="` + srcAttr + `" alt="` + altAttr + `"/>`)
  130. }
  131. break
  132. }
  133. }
  134. })
  135. if !changed {
  136. doc.Find("noscript").Each(func(i int, noscript *goquery.Selection) {
  137. if img := noscript.Find("img"); img.Length() == 1 {
  138. img.Unwrap()
  139. changed = true
  140. }
  141. })
  142. }
  143. if changed {
  144. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  145. return output
  146. }
  147. return entryContent
  148. }
  149. func addDynamicIframe(entryContent string) string {
  150. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  151. if err != nil {
  152. return entryContent
  153. }
  154. // Ordered most preferred to least preferred.
  155. candidateAttrs := []string{
  156. "data-src",
  157. "data-original",
  158. "data-orig",
  159. "data-url",
  160. "data-lazy-src",
  161. }
  162. changed := false
  163. doc.Find("iframe").Each(func(i int, iframe *goquery.Selection) {
  164. for _, candidateAttr := range candidateAttrs {
  165. if srcAttr, found := iframe.Attr(candidateAttr); found {
  166. changed = true
  167. iframe.SetAttr("src", srcAttr)
  168. break
  169. }
  170. }
  171. })
  172. if changed {
  173. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  174. return output
  175. }
  176. return entryContent
  177. }
  178. func fixMediumImages(entryContent string) string {
  179. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  180. if err != nil {
  181. return entryContent
  182. }
  183. doc.Find("figure.paragraph-image").Each(func(i int, paragraphImage *goquery.Selection) {
  184. noscriptElement := paragraphImage.Find("noscript")
  185. if noscriptElement.Length() > 0 {
  186. paragraphImage.ReplaceWithHtml(noscriptElement.Text())
  187. }
  188. })
  189. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  190. return output
  191. }
  192. func useNoScriptImages(entryContent string) string {
  193. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  194. if err != nil {
  195. return entryContent
  196. }
  197. doc.Find("figure").Each(func(i int, figureElement *goquery.Selection) {
  198. imgElement := figureElement.Find("img")
  199. if imgElement.Length() > 0 {
  200. noscriptElement := figureElement.Find("noscript")
  201. if noscriptElement.Length() > 0 {
  202. figureElement.PrependHtml(noscriptElement.Text())
  203. imgElement.Remove()
  204. noscriptElement.Remove()
  205. }
  206. }
  207. })
  208. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  209. return output
  210. }
  211. func getYoutubVideoIDFromURL(entryURL string) string {
  212. u, err := url.Parse(entryURL)
  213. if err != nil {
  214. return ""
  215. }
  216. if !strings.HasSuffix(u.Hostname(), "youtube.com") {
  217. return ""
  218. }
  219. if u.Path == "/watch" {
  220. if v := u.Query().Get("v"); v != "" {
  221. return v
  222. }
  223. return ""
  224. }
  225. if id, found := strings.CutPrefix(u.Path, "/shorts/"); found {
  226. if len(id) == 11 {
  227. // youtube shorts id are always 11 chars.
  228. return id
  229. }
  230. }
  231. return ""
  232. }
  233. func buildVideoPlayerIframe(absoluteVideoURL string) string {
  234. return `<iframe width="650" height="350" frameborder="0" src="` + absoluteVideoURL + `" allowfullscreen></iframe>`
  235. }
  236. func addVideoPlayerIframe(absoluteVideoURL, entryContent string) string {
  237. return buildVideoPlayerIframe(absoluteVideoURL) + `<br>` + entryContent
  238. }
  239. func addYoutubeVideoRewriteRule(entryURL, entryContent string) string {
  240. if videoURL := getYoutubVideoIDFromURL(entryURL); videoURL != "" {
  241. return addVideoPlayerIframe(config.Opts.YouTubeEmbedUrlOverride()+videoURL, entryContent)
  242. }
  243. return entryContent
  244. }
  245. func addYoutubeVideoUsingInvidiousPlayer(entryURL, entryContent string) string {
  246. if videoURL := getYoutubVideoIDFromURL(entryURL); videoURL != "" {
  247. return addVideoPlayerIframe(`https://`+config.Opts.InvidiousInstance()+`/embed/`+videoURL, entryContent)
  248. }
  249. return entryContent
  250. }
  251. // For reference: https://github.com/miniflux/v2/pull/1314
  252. func addYoutubeVideoFromId(entryContent string) string {
  253. matches := youtubeIdRegex.FindAllStringSubmatch(entryContent, -1)
  254. if matches == nil {
  255. return entryContent
  256. }
  257. videoPlayerHTML := ""
  258. for _, match := range matches {
  259. if len(match) == 2 {
  260. videoPlayerHTML += buildVideoPlayerIframe(config.Opts.YouTubeEmbedUrlOverride()+match[1]) + "<br>"
  261. }
  262. }
  263. return videoPlayerHTML + entryContent
  264. }
  265. func addInvidiousVideo(entryURL, entryContent string) string {
  266. u, err := url.Parse(entryURL)
  267. if err != nil {
  268. return entryContent
  269. }
  270. if u.Path != "/watch" {
  271. return entryContent
  272. }
  273. v := u.Query().Get("v")
  274. if v == "" {
  275. return entryContent
  276. }
  277. src := "https://" + u.Hostname() + `/embed/` + v
  278. for key, val := range u.Query() {
  279. if key == "v" || len(val) != 1 {
  280. continue
  281. }
  282. src += "&" + key + "=" + val[0]
  283. }
  284. return addVideoPlayerIframe(src, 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. }