4
0

rewrite_functions.go 12 KB

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