including counts of how many pages media is referenced on

pull/16/head
Stephen Searles 7 years ago
parent fb93746ba6
commit e75784599e
  1. 49
      media.go

@ -1,13 +1,48 @@
package caddyhugo
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"path"
"github.com/PuerkitoBio/goquery"
"github.com/gohugoio/hugo/hugolib"
"git.stephensearles.com/stephen/caddy-hugo2/media"
)
func (ch *CaddyHugo) ReferencedMedia() map[string]map[*hugolib.Page]struct{} {
found := map[string]map[*hugolib.Page]struct{}{}
for _, page := range ch.HugoSites.Pages() {
r := bytes.NewBufferString(string(page.Render()))
doc, err := goquery.NewDocumentFromReader(r)
if err != nil {
continue
}
doc.Find("img,video").Map(func(i int, s *goquery.Selection) string {
u, ok := s.Attr("src")
if ok {
u = path.Base(u)
if ud, err := url.QueryUnescape(u); err == nil {
u = ud
}
if m := found[u]; m == nil {
found[u] = make(map[*hugolib.Page]struct{})
}
found[u][page] = struct{}{}
}
return ""
})
}
return found
}
func (ch *CaddyHugo) uploadMedia(w http.ResponseWriter, r *http.Request) (int, error) {
if ch.Media == nil {
http.NotFound(w, r)
@ -49,6 +84,8 @@ func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int
return 404, nil
}
referenced := ch.ReferencedMedia()
io.WriteString(w, `<html>
<head><style>
iframe { height: 100%; }
@ -87,12 +124,20 @@ func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int
fmt.Fprintf(w, `<div class="img">error rendering %q: %v</div>`, m.Name, err)
continue
}
refs := len(referenced[m.Name])
plural := "s"
if refs == 1 {
plural = ""
}
refLine := fmt.Sprintf("included on %d page%s", refs, plural)
switch m.Type {
case media.TypeImage:
fmt.Fprintf(w, `<div class="img"><img width=%d height=%d src=%q data-filename=%q /><br /><input type="text" readonly value=%q /><span class="copy">&#x1F4CB;</span></div>`, size.Dx(), size.Dy(), m.ThumbPath(size), m.Name, m.ThumbPath(size))
fmt.Fprintf(w, `<div class="img"><img width=%d height=%d src=%q data-filename=%q /><br /><input type="text" readonly value=%q /><span class="copy">&#x1F4CB;</span><br />%s</div>`, size.Dx(), size.Dy(), m.ThumbPath(size), m.Name, m.ThumbPath(size), refLine)
case media.TypeVideo:
// TODO: onmouseover sucks for mobile
fmt.Fprintf(w, `<div class="img"><video width=%d height=%d src=%q data-filename=%q onmouseover="this.play()" onmouseout="this.pause();this.currentTime=0;"></video><br /><input type="text" readonly value=%q /><span class="copy">&#x1F4CB;</span></div>`, size.Dx(), size.Dy(), m.ThumbPath(size), m.Name, m.ThumbPath(size))
fmt.Fprintf(w, `<div class="img"><video width=%d height=%d src=%q data-filename=%q onmouseover="this.play()" onmouseout="this.pause();this.currentTime=0;"></video><br /><input type="text" readonly value=%q /><span class="copy">&#x1F4CB;</span><br />%s</div>`, size.Dx(), size.Dy(), m.ThumbPath(size), m.Name, m.ThumbPath(size), refLine)
}
}
}

Loading…
Cancel
Save