rewrite_functions.go 13 KB

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