rewrite_functions.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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
  5. import (
  6. "fmt"
  7. "regexp"
  8. "strings"
  9. "github.com/PuerkitoBio/goquery"
  10. )
  11. var (
  12. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)`)
  13. )
  14. func addImageTitle(entryURL, entryContent string) string {
  15. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  16. if err != nil {
  17. return entryContent
  18. }
  19. matches := doc.Find("img[src][title]")
  20. if matches.Length() > 0 {
  21. matches.Each(func(i int, img *goquery.Selection) {
  22. altAttr := img.AttrOr("alt", "")
  23. srcAttr, _ := img.Attr("src")
  24. titleAttr, _ := img.Attr("title")
  25. img.ReplaceWithHtml(`<figure><img src="` + srcAttr + `" alt="` + altAttr + `"/><figcaption><p>` + titleAttr + `</p></figcaption></figure>`)
  26. })
  27. output, _ := doc.Find("body").First().Html()
  28. return output
  29. }
  30. return entryContent
  31. }
  32. func addYoutubeVideo(entryURL, entryContent string) string {
  33. matches := youtubeRegex.FindStringSubmatch(entryURL)
  34. if len(matches) == 2 {
  35. video := `<iframe width="650" height="350" frameborder="0" src="https://www.youtube-nocookie.com/embed/` + matches[1] + `" allowfullscreen></iframe>`
  36. return video + "<p>" + entryContent + "</p>"
  37. }
  38. return entryContent
  39. }
  40. func addPDFLink(entryURL, entryContent string) string {
  41. if strings.HasSuffix(entryURL, ".pdf") {
  42. return fmt.Sprintf(`<a href="%s">PDF</a><br>%s`, entryURL, entryContent)
  43. }
  44. return entryContent
  45. }