rewrite_functions.go 11 KB

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