rewrite_functions.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. "net/url"
  9. "regexp"
  10. "strings"
  11. "miniflux.app/v2/internal/config"
  12. "github.com/PuerkitoBio/goquery"
  13. "github.com/yuin/goldmark"
  14. goldmarkhtml "github.com/yuin/goldmark/renderer/html"
  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-2000src",
  80. "data-1000src",
  81. "data-800src",
  82. "data-655src",
  83. "data-500src",
  84. "data-380src",
  85. }
  86. candidateSrcsetAttrs := []string{
  87. "data-srcset",
  88. }
  89. changed := false
  90. doc.Find("img,div").Each(func(i int, img *goquery.Selection) {
  91. // Src-linked candidates
  92. for _, candidateAttr := range candidateAttrs {
  93. if srcAttr, found := img.Attr(candidateAttr); found {
  94. changed = true
  95. if img.Is("img") {
  96. img.SetAttr("src", srcAttr)
  97. } else {
  98. altAttr := img.AttrOr("alt", "")
  99. img.ReplaceWithHtml(`<img src="` + srcAttr + `" alt="` + altAttr + `"/>`)
  100. }
  101. break
  102. }
  103. }
  104. // Srcset-linked candidates
  105. for _, candidateAttr := range candidateSrcsetAttrs {
  106. if srcAttr, found := img.Attr(candidateAttr); found {
  107. changed = true
  108. if img.Is("img") {
  109. img.SetAttr("srcset", srcAttr)
  110. } else {
  111. altAttr := img.AttrOr("alt", "")
  112. img.ReplaceWithHtml(`<img srcset="` + srcAttr + `" alt="` + altAttr + `"/>`)
  113. }
  114. break
  115. }
  116. }
  117. })
  118. if !changed {
  119. doc.Find("noscript").Each(func(i int, noscript *goquery.Selection) {
  120. matches := imgRegex.FindAllString(noscript.Text(), 2)
  121. if len(matches) == 1 {
  122. changed = true
  123. noscript.ReplaceWithHtml(matches[0])
  124. }
  125. })
  126. }
  127. if changed {
  128. output, _ := doc.Find("body").First().Html()
  129. return output
  130. }
  131. return entryContent
  132. }
  133. func fixMediumImages(entryURL, entryContent string) string {
  134. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  135. if err != nil {
  136. return entryContent
  137. }
  138. doc.Find("figure.paragraph-image").Each(func(i int, paragraphImage *goquery.Selection) {
  139. noscriptElement := paragraphImage.Find("noscript")
  140. if noscriptElement.Length() > 0 {
  141. paragraphImage.ReplaceWithHtml(noscriptElement.Text())
  142. }
  143. })
  144. output, _ := doc.Find("body").First().Html()
  145. return output
  146. }
  147. func useNoScriptImages(entryURL, entryContent string) string {
  148. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  149. if err != nil {
  150. return entryContent
  151. }
  152. doc.Find("figure").Each(func(i int, figureElement *goquery.Selection) {
  153. imgElement := figureElement.Find("img")
  154. if imgElement.Length() > 0 {
  155. noscriptElement := figureElement.Find("noscript")
  156. if noscriptElement.Length() > 0 {
  157. figureElement.PrependHtml(noscriptElement.Text())
  158. imgElement.Remove()
  159. noscriptElement.Remove()
  160. }
  161. }
  162. })
  163. output, _ := doc.Find("body").First().Html()
  164. return output
  165. }
  166. func addYoutubeVideo(entryURL, entryContent string) string {
  167. matches := youtubeRegex.FindStringSubmatch(entryURL)
  168. if len(matches) == 2 {
  169. video := `<iframe width="650" height="350" frameborder="0" src="` + config.Opts.YouTubeEmbedUrlOverride() + matches[1] + `" allowfullscreen></iframe>`
  170. return video + `<br>` + entryContent
  171. }
  172. return entryContent
  173. }
  174. func addYoutubeVideoUsingInvidiousPlayer(entryURL, entryContent string) string {
  175. matches := youtubeRegex.FindStringSubmatch(entryURL)
  176. if len(matches) == 2 {
  177. video := `<iframe width="650" height="350" frameborder="0" src="https://` + config.Opts.InvidiousInstance() + `/embed/` + matches[1] + `" allowfullscreen></iframe>`
  178. return video + `<br>` + entryContent
  179. }
  180. return entryContent
  181. }
  182. func addYoutubeVideoFromId(entryContent string) string {
  183. matches := youtubeIdRegex.FindAllStringSubmatch(entryContent, -1)
  184. if matches == nil {
  185. return entryContent
  186. }
  187. sb := strings.Builder{}
  188. for _, match := range matches {
  189. if len(match) == 2 {
  190. sb.WriteString(`<iframe width="650" height="350" frameborder="0" src="`)
  191. sb.WriteString(config.Opts.YouTubeEmbedUrlOverride())
  192. sb.WriteString(match[1])
  193. sb.WriteString(`" allowfullscreen></iframe><br>`)
  194. }
  195. }
  196. sb.WriteString(entryContent)
  197. return sb.String()
  198. }
  199. func addInvidiousVideo(entryURL, entryContent string) string {
  200. matches := invidioRegex.FindStringSubmatch(entryURL)
  201. if len(matches) == 3 {
  202. video := `<iframe width="650" height="350" frameborder="0" src="https://` + matches[1] + `/embed/` + matches[2] + `" allowfullscreen></iframe>`
  203. return video + `<br>` + entryContent
  204. }
  205. return entryContent
  206. }
  207. func addPDFLink(entryURL, entryContent string) string {
  208. if strings.HasSuffix(entryURL, ".pdf") {
  209. return fmt.Sprintf(`<a href="%s">PDF</a><br>%s`, entryURL, entryContent)
  210. }
  211. return entryContent
  212. }
  213. func replaceTextLinks(input string) string {
  214. return textLinkRegex.ReplaceAllString(input, `<a href="${1}">${1}</a>`)
  215. }
  216. func replaceLineFeeds(input string) string {
  217. return strings.Replace(input, "\n", "<br>", -1)
  218. }
  219. func replaceCustom(entryContent string, searchTerm string, replaceTerm string) string {
  220. re, err := regexp.Compile(searchTerm)
  221. if err == nil {
  222. return re.ReplaceAllString(entryContent, replaceTerm)
  223. }
  224. return entryContent
  225. }
  226. func removeCustom(entryContent string, selector string) string {
  227. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  228. if err != nil {
  229. return entryContent
  230. }
  231. doc.Find(selector).Remove()
  232. output, _ := doc.Find("body").First().Html()
  233. return output
  234. }
  235. func addCastopodEpisode(entryURL, entryContent string) string {
  236. player := `<iframe width="650" frameborder="0" src="` + entryURL + `/embed/light"></iframe>`
  237. return player + `<br>` + entryContent
  238. }
  239. func applyFuncOnTextContent(entryContent string, selector string, repl func(string) string) string {
  240. var treatChildren func(i int, s *goquery.Selection)
  241. treatChildren = func(i int, s *goquery.Selection) {
  242. if s.Nodes[0].Type == 1 {
  243. s.ReplaceWithHtml(repl(s.Nodes[0].Data))
  244. } else {
  245. s.Contents().Each(treatChildren)
  246. }
  247. }
  248. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  249. if err != nil {
  250. return entryContent
  251. }
  252. doc.Find(selector).Each(treatChildren)
  253. output, _ := doc.Find("body").First().Html()
  254. return output
  255. }
  256. func decodeBase64Content(entryContent string) string {
  257. if ret, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entryContent)); err != nil {
  258. return entryContent
  259. } else {
  260. return html.EscapeString(string(ret))
  261. }
  262. }
  263. func parseMarkdown(entryContent string) string {
  264. var sb strings.Builder
  265. md := goldmark.New(
  266. goldmark.WithRendererOptions(
  267. goldmarkhtml.WithUnsafe(),
  268. ),
  269. )
  270. if err := md.Convert([]byte(entryContent), &sb); err != nil {
  271. return entryContent
  272. }
  273. return sb.String()
  274. }
  275. func removeTables(entryContent string) string {
  276. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  277. if err != nil {
  278. return entryContent
  279. }
  280. selectors := []string{"table", "tbody", "thead", "td", "th", "td"}
  281. var loopElement *goquery.Selection
  282. for _, selector := range selectors {
  283. for {
  284. loopElement = doc.Find(selector).First()
  285. if loopElement.Length() == 0 {
  286. break
  287. }
  288. innerHtml, err := loopElement.Html()
  289. if err != nil {
  290. break
  291. }
  292. loopElement.Parent().AppendHtml(innerHtml)
  293. loopElement.Remove()
  294. }
  295. }
  296. output, _ := doc.Find("body").First().Html()
  297. return output
  298. }
  299. func removeClickbait(entryTitle string) string {
  300. titleWords := []string{}
  301. for _, word := range strings.Fields(entryTitle) {
  302. runes := []rune(word)
  303. if len(runes) > 1 {
  304. // keep first rune as is to keep the first capital letter
  305. titleWords = append(titleWords, string([]rune{runes[0]})+strings.ToLower(string(runes[1:])))
  306. } else {
  307. titleWords = append(titleWords, word)
  308. }
  309. }
  310. return strings.Join(titleWords, " ")
  311. }