2016-05-17 23:03:37 -07:00
|
|
|
package arrange
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
2026-10-22 13:59:09 -07:00
|
|
|
"log/slog"
|
2016-05-17 23:03:37 -07:00
|
|
|
"time"
|
|
|
|
|
|
2026-10-22 13:59:09 -07:00
|
|
|
"github.com/evanoberholster/imagemeta"
|
2016-05-17 23:03:37 -07:00
|
|
|
"github.com/rwcarlsen/goexif/exif"
|
|
|
|
|
)
|
|
|
|
|
|
2026-10-22 13:59:09 -07:00
|
|
|
func init() {
|
|
|
|
|
imagemeta.SetLogger(io.Discard, slog.LevelError)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// exifTime returns the capture time recorded in f, or the zero time if it
|
|
|
|
|
// can't find a believable one.
|
|
|
|
|
//
|
|
|
|
|
// imagemeta handles HEIC and camera RAW; goexif is kept as a fallback for
|
|
|
|
|
// jpegs because it copes with some damaged exif that imagemeta rejects.
|
|
|
|
|
func exifTime(f io.ReadSeeker, jpeg bool) time.Time {
|
|
|
|
|
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
|
|
|
|
return time.Time{}
|
|
|
|
|
}
|
|
|
|
|
if e, err := imagemeta.Decode(f); err == nil {
|
|
|
|
|
if t := e.SelectedDate(); plausible(t) {
|
|
|
|
|
// exif dates without an offset are camera wall-clock time,
|
|
|
|
|
// which imagemeta labels UTC; read them as local like goexif.
|
|
|
|
|
if t.Location() == time.UTC {
|
|
|
|
|
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local)
|
|
|
|
|
}
|
|
|
|
|
return t
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if !jpeg {
|
|
|
|
|
return time.Time{}
|
|
|
|
|
}
|
|
|
|
|
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
|
|
|
|
return time.Time{}
|
|
|
|
|
}
|
|
|
|
|
if t, err := parseExif(f); err == nil && plausible(t) {
|
|
|
|
|
return t
|
|
|
|
|
}
|
|
|
|
|
return time.Time{}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// plausible rejects zero and placeholder dates (e.g. "0000:00:00 00:00:00").
|
|
|
|
|
func plausible(t time.Time) bool {
|
|
|
|
|
return !t.IsZero() && t.Year() >= 1900
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-17 23:03:37 -07:00
|
|
|
func parseExif(f io.Reader) (time.Time, error) {
|
|
|
|
|
ti := time.Time{}
|
|
|
|
|
x, err := exif.Decode(f)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if exif.IsCriticalError(err) {
|
|
|
|
|
return ti, err
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-10-22 13:59:09 -07:00
|
|
|
if x == nil {
|
|
|
|
|
return ti, fmt.Errorf("no exif: %v", err)
|
|
|
|
|
}
|
2016-05-17 23:03:37 -07:00
|
|
|
tm, err := x.DateTime()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return ti, fmt.Errorf("no datetime in an ostensibly valid exif %v", err)
|
|
|
|
|
}
|
|
|
|
|
return tm, nil
|
|
|
|
|
}
|