content_rewrite_functions.go 13 KB

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