sorting images by date; acquiring metadata

pull/12/head
Stephen Searles 7 years ago
parent b62a7a7a28
commit 450923be2f
  1. 4
      media.go
  2. 69
      media/media.go

@ -77,13 +77,13 @@ func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int
<div style="display: inline-block; width: 100%; height: 10vh;"></div>
`)
if ch.Media != nil {
media, err := ch.Media.Walk()
mm, err := ch.Media.Walk()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return 500, nil
}
for _, m := range media {
for _, m := range media.Set(mm).ByDate() {
src, size, err := ch.Media.ThumbMax(*m, 100)
if err != nil {

@ -9,18 +9,23 @@ import (
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"time"
// for processing images
_ "image/gif"
_ "image/png"
"github.com/nfnt/resize"
"github.com/tajtiattila/metadata"
)
type MediaSource struct {
StorageDir string
ThumbDir string
set Set
}
func (ms *MediaSource) LocationOrig(m Media) string {
@ -49,6 +54,8 @@ func (ms *MediaSource) ThumbFilename(m Media, size image.Rectangle) string {
}
func (ms *MediaSource) ReceiveNewMedia(name string, r io.Reader) error {
ms.set = nil
dest := path.Join(ms.StorageDir, name)
f, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
@ -67,6 +74,47 @@ type Media struct {
Type string
Name string
Size image.Rectangle
FullName string
metadata *metadata.Metadata
}
func (m *Media) Date() time.Time {
m.getMetadata()
if m.metadata != nil {
raw := m.metadata.Get(metadata.DateTimeOriginal)
if raw != "" {
d, err := time.Parse("2006-01-02T15:04:05", raw)
if err == nil {
return d
}
}
}
fi, err := os.Stat(m.FullName)
if err == nil {
return fi.ModTime()
}
return time.Time{}
}
func (m *Media) getMetadata() error {
if m.metadata != nil {
return nil
}
f, err := os.Open(m.FullName)
if err != nil {
return err
}
md, err := metadata.Parse(f)
if err != nil {
return err
}
m.metadata = md
return nil
}
func (ms *MediaSource) Size(name string) (image.Rectangle, error) {
@ -136,11 +184,13 @@ func (ms *MediaSource) HasThumb(m Media, size image.Rectangle) bool {
func (ms *MediaSource) ByName(name string) *Media {
size, _ := ms.Size(path.Join(ms.StorageDir, name))
return &Media{
m := Media{
Type: "image",
Name: name,
Size: size,
}
m.FullName = ms.LocationOrig(m)
return &m
}
func (ms *MediaSource) Thumb(m Media, size image.Rectangle) (string, error) {
@ -187,6 +237,7 @@ func (ms *MediaSource) ThumbImage(img image.Image, m Media, size image.Rectangle
}
func (ms *MediaSource) Walk() ([]*Media, error) {
if ms.set == nil {
var media []*Media
err := filepath.Walk(ms.StorageDir, func(name string, fi os.FileInfo, err error) error {
@ -200,7 +251,23 @@ func (ms *MediaSource) Walk() ([]*Media, error) {
return nil
})
if err != nil {
return media, err
}
ms.set = media
}
return ms.set, nil
}
type Set []*Media
func (s Set) ByDate() Set {
sort.Slice(s, func(i, j int) bool {
return s[i].Date().After(s[j].Date())
})
return s
}
var (

Loading…
Cancel
Save