rewrite_functions.go 11 KB

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