rewrite_functions.go 11 KB

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