rewrite_functions.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package rewrite // import "miniflux.app/reader/rewrite"
  5. import (
  6. "encoding/base64"
  7. "fmt"
  8. "html"
  9. "net/url"
  10. "regexp"
  11. "strings"
  12. "miniflux.app/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-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 fixMediumImages(entryURL, entryContent string) string {
  135. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  136. if err != nil {
  137. return entryContent
  138. }
  139. doc.Find("figure.paragraph-image").Each(func(i int, paragraphImage *goquery.Selection) {
  140. noscriptElement := paragraphImage.Find("noscript")
  141. if noscriptElement.Length() > 0 {
  142. paragraphImage.ReplaceWithHtml(noscriptElement.Text())
  143. }
  144. })
  145. output, _ := doc.Find("body").First().Html()
  146. return output
  147. }
  148. func useNoScriptImages(entryURL, entryContent string) string {
  149. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  150. if err != nil {
  151. return entryContent
  152. }
  153. doc.Find("figure").Each(func(i int, figureElement *goquery.Selection) {
  154. imgElement := figureElement.Find("img")
  155. if imgElement.Length() > 0 {
  156. noscriptElement := figureElement.Find("noscript")
  157. if noscriptElement.Length() > 0 {
  158. figureElement.PrependHtml(noscriptElement.Text())
  159. imgElement.Remove()
  160. noscriptElement.Remove()
  161. }
  162. }
  163. })
  164. output, _ := doc.Find("body").First().Html()
  165. return output
  166. }
  167. func addYoutubeVideo(entryURL, entryContent string) string {
  168. matches := youtubeRegex.FindStringSubmatch(entryURL)
  169. if len(matches) == 2 {
  170. video := `<iframe width="650" height="350" frameborder="0" src="https://www.youtube-nocookie.com/embed/` + matches[1] + `" allowfullscreen></iframe>`
  171. return video + `<br>` + entryContent
  172. }
  173. return entryContent
  174. }
  175. func addYoutubeVideoUsingInvidiousPlayer(entryURL, entryContent string) string {
  176. matches := youtubeRegex.FindStringSubmatch(entryURL)
  177. if len(matches) == 2 {
  178. video := `<iframe width="650" height="350" frameborder="0" src="https://` + config.Opts.InvidiousInstance() + `/embed/` + matches[1] + `" allowfullscreen></iframe>`
  179. return video + `<br>` + entryContent
  180. }
  181. return entryContent
  182. }
  183. func addYoutubeVideoFromId(entryContent string) string {
  184. matches := youtubeIdRegex.FindAllStringSubmatch(entryContent, -1)
  185. if matches == nil {
  186. return entryContent
  187. }
  188. sb := strings.Builder{}
  189. for _, match := range matches {
  190. if len(match) == 2 {
  191. sb.WriteString(`<iframe width="650" height="350" frameborder="0" src="https://www.youtube-nocookie.com/embed/`)
  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. }