content_rewrite_functions.go 13 KB

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