package document // import "twos.dev/winter/document" import ( "errors" "fmt" "image" "io" "log/slog" "math" "os" "path/filepath" "strconv" "strings" "time" "github.com/nickalie/go-webpbin" "github.com/rwcarlsen/goexif/exif" "github.com/rwcarlsen/goexif/mknote" "github.com/rwcarlsen/goexif/tiff" ) type EXIF struct { Aperture float64 Camera *Gear FocalLength float64 ISO string // Lens holds information about the lens used for the photo. // If the photo EXIF data has no or insufficient lens information, // Lens is nil. Lens *Gear ShutterSpeed string TakenAt time.Time } type img struct { EXIF Alt string // PurchaseURL is an optional external URL where the image can be purchased. PurchaseURL string Thumbnails thumbnails // SourcePath is the path to the image this gallery document was built around. // It is relative to the repository root. SourcePath string // WebPath is the path component of the URL to the image as it will exist after building. WebPath string cfg *Config configuredPurchaseURL string hasConfiguredPurchaseURL bool } type thumbnail struct { // Height is the height of the thumbnail. Height int // Width is the width of the thumbnail. Width int // WebPath is the path component of the URL where the thumbnail will ultimately be placed. // It is equivalent to the thumbnail's path relative to dist. WebPath string } type thumbnails []*thumbnail func (t thumbnails) Len() int { return len(t) } func (t thumbnails) Less(i, j int) bool { return t[i].Width < t[j].Width } func (t thumbnails) Swap(i, j int) { t[i], t[j] = t[j], t[i] } // NewIMG returns a struct that represents an image to be built. // The returned value implements [Document]. func NewIMG(src string, cfg *Config) (*img, error) { relpath, err := filepath.Rel("src", src) if err != nil { return nil, fmt.Errorf("cannot get relative path for photo: %w", err) } purchaseURL, hasPurchaseURL := cfg.PurchaseURLs[filepath.ToSlash(relpath)] return &img{ PurchaseURL: purchaseURL, SourcePath: src, configuredPurchaseURL: purchaseURL, hasConfiguredPurchaseURL: hasPurchaseURL, WebPath: fmt.Sprintf( "%s.webp", strings.TrimSuffix(relpath, filepath.Ext(relpath)), ), cfg: cfg, }, nil } // LoadEXIF populates im's EXIF information without decoding the entire image. // // Calling [Render] also implicitly loads EXIF data, // so calling both is redundant. func (im *img) LoadEXIF() error { f, err := os.Open(im.SourcePath) if err != nil { return fmt.Errorf("can't read %q: %w", im.SourcePath, err) } defer f.Close() if err := im.loadEXIF(f); err != nil { return wrapErrorf(err, "cannot get camera for %q", im.SourcePath) } return nil } // loadMetadataFromSource reloads all metadata Winter exposes for im. // // Purchase URLs configured in winter.yml explicitly override embedded XMP. func (im *img) loadMetadataFromSource() error { f, err := os.Open(im.SourcePath) if err != nil { return fmt.Errorf("can't read %q: %w", im.SourcePath, err) } defer f.Close() if err := im.loadEXIF(f); err != nil { return wrapErrorf(err, "cannot get camera for %q", im.SourcePath) } if _, err := f.Seek(0, io.SeekStart); err != nil { return fmt.Errorf("cannot rewind %q to read XMP: %w", im.SourcePath, err) } metadata, err := loadPhotoXMP(f) if err != nil { return wrapErrorf(err, "cannot read photo metadata from %q", im.SourcePath) } im.applyPhotoXMP(metadata) return nil } func (im *img) applyPhotoXMP(metadata photoXMP) { im.Alt = metadata.Alt im.PurchaseURL = metadata.PurchaseURL if im.hasConfiguredPurchaseURL { im.PurchaseURL = im.configuredPurchaseURL } } func (im *img) thumbnailDir() string { return filepath.Dir(strings.Replace( filepath.Join(im.cfg.Dist, im.WebPath), filepath.FromSlash("/img/"), filepath.FromSlash("/img/thumb/"), 1, )) } func (im *img) Load(r io.Reader) error { if err := im.loadMetadataFromSource(); err != nil { return err } cfg, _, err := image.DecodeConfig(r) if err != nil { return fmt.Errorf( "cannot decode photo dimensions for %q (maybe not an image?): %w", im.SourcePath, err, ) } return im.populateThumbnails( im.SourcePath, im.thumbnailDir(), cfg.Width, cfg.Height, ) } func (im *img) loadThumbnailMetadata() error { srcf, err := os.Open(im.SourcePath) if err != nil { return fmt.Errorf("cannot read %q to infer thumbnails: %w", im.SourcePath, err) } defer srcf.Close() cfg, _, err := image.DecodeConfig(srcf) if err != nil { return fmt.Errorf("cannot decode %q to infer thumbnails: %w", im.SourcePath, err) } if cfg.Width <= 0 || cfg.Height <= 0 { return fmt.Errorf("cannot determine dimensions for %q", im.SourcePath) } return im.populateThumbnails(im.SourcePath, im.thumbnailDir(), cfg.Width, cfg.Height) } func (im *img) Render(w io.Writer) error { if err := webpbin.NewCWebP(). Quality(75). InputFile(im.SourcePath). Output(w). Run(); err != nil { return fmt.Errorf( "cannot encode source image %q to WebP: %w", im.SourcePath, err, ) } if err := im.thumbnails(im.SourcePath); err != nil { return fmt.Errorf("can't generate thumbnails: %w", err) } return nil } func exifFractionToDecimal( x *exif.Exif, field exif.FieldName, ) (float64, error) { fraction, err := x.Get(field) if err != nil { return 0, fmt.Errorf("can't get field %s: %w", field, err) } return exifFractionStringToDecimal(field, fraction.String()) } func exifFractionStringToDecimal( field exif.FieldName, fraction string, ) (float64, error) { parts := strings.Split( strings.Replace(fraction, "\"", "", 2), "/", ) numer, err := strconv.Atoi(parts[0]) if err != nil { return 0, fmt.Errorf( "can't convert %s (numerator of %s, %s) to int: %w", parts[0], field, fraction, err, ) } denom, err := strconv.Atoi(parts[1]) if err != nil { return 0, fmt.Errorf( "can't convert %s (denominator of %s, %s) to int: %w", parts[1], field, fraction, err, ) } return math.Round((float64(numer)/float64(denom))*10) / 10, nil } // loadEXIF extracts the EXIF string // (including lens, etc.) // and timestamp from the image at the given path. func (im *img) loadEXIF(r io.Reader) error { exif.RegisterParsers(mknote.All...) x, err := exif.Decode(r) if err != nil { return fmt.Errorf("cannot read exif data: %w", err) } camera, err := im.findGear(x, exif.Make, exif.Model) if err != nil { return wrapErrorf(err, "cannot get camera") } exposure, err := x.Get(exif.ExposureTime) if err != nil { return fmt.Errorf("cannot get exposure: %w", err) } fnum, err := exifFractionToDecimal(x, exif.FNumber) if err != nil { return fmt.Errorf("cannot get focal length: %w", err) } focalLength, err := exifFractionToDecimal(x, exif.FocalLength) if err != nil { return fmt.Errorf("cannot get focal length: %w", err) } iso, err := x.Get(exif.ISOSpeedRatings) if err != nil { return fmt.Errorf("cannot get ISO: %w", err) } lens, err := im.findGear(x, exif.LensMake, exif.LensModel) if err != nil { return wrapErrorf(err, "cannot get lens") } timestamp, err := x.DateTime() if err != nil { if errors.Is(err, exif.TagNotPresentError("")) { return fmt.Errorf( "photo has no EXIF timestamp... what do?", ) } return fmt.Errorf("cannot get photo datetime: %w", err) } _, err = x.Get(exif.GPSInfoIFDPointer) if err == nil { // location data is set! no no no! panic( fmt.Sprintf( "photo %s has location data! please strip it.", im.SourcePath, ), ) } im.EXIF = EXIF{ Aperture: fnum, Camera: camera, FocalLength: focalLength, ISO: iso.String(), Lens: lens, ShutterSpeed: strings.Replace(exposure.String(), "\"", "", 2), TakenAt: timestamp, } return nil } // thumbnails makes WebP thumbnails of the photo srcPhoto located at srcPath. // The thumbnails made are based on the specifications already in im.Thumbnails at call time. // // The file at src is read at least once every time this function is called, // but the thumbnails are only regenerated if src has changed since their last generation. func (im *img) thumbnails(srcPath string) error { slog.Debug(fmt.Sprintf("Creating thumbnails for %s.", srcPath)) for _, thmb := range im.Thumbnails { if thmb.Width <= 0 || thmb.Height <= 0 { continue } slog.Debug( fmt.Sprintf( "Created %dx%d thumbnail for %s.", thmb.Width, thmb.Height, srcPath, ), ) path := filepath.Join(im.cfg.Dist, thmb.WebPath) if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return fmt.Errorf( "cannot make thumbnail directory %q: %w", filepath.Dir(thmb.WebPath), err, ) } destinationFile, err := os.Create(path) if err != nil { return fmt.Errorf( "cannot create thumbnail for %q: %w", srcPath, err, ) } encoder := webpbin.NewCWebP(). Quality(75). InputFile(srcPath). Output(destinationFile) encoder.Arg("-resize", strconv.Itoa(thmb.Width), strconv.Itoa(thmb.Height)) encodeErr := encoder.Run() closeErr := destinationFile.Close() if encodeErr != nil { return fmt.Errorf( "cannot encode WebP thumbnail to %q: %w", thmb.WebPath, encodeErr, ) } if closeErr != nil { return fmt.Errorf("cannot close WebP thumbnail %q: %w", thmb.WebPath, closeErr) } } return nil } func (im *img) populateThumbnails( srcPath, thumbdir string, srcWidth, srcHeight int, ) error { var thmbs thumbnails if srcWidth <= 0 || srcHeight <= 0 { return fmt.Errorf("cannot generate thumbnails for %q with dimensions %dx%d", srcPath, srcWidth, srcHeight) } for height := 1; height < srcWidth; height *= 2 { width := (height * srcWidth / srcHeight) & -1 if width <= 0 || height <= 0 { continue } destPath := filepath.Join( thumbdir, fmt.Sprintf( "%s.%dx%d.webp", strings.TrimSuffix(filepath.Base(srcPath), filepath.Ext(srcPath)), width, height, ), ) webPath, err := filepath.Rel(im.cfg.Dist, destPath) if err != nil { return fmt.Errorf( "cannot get relative path for thumbnail %q: %w", thumbdir, err, ) } thmbs = append(thmbs, &thumbnail{ Height: height, WebPath: webPath, Width: width, }) } im.Thumbnails = thmbs return nil } // findGear returns a Gear built from the given EXIF data. // // If the EXIF data contains no or insufficient info, // (nil, nil) is returned. // // If the EXIF data is present but winter.yml does not index it, // an error is returned. func (im *img) findGear( x *exif.Exif, make, model exif.FieldName, ) (*Gear, error) { gearMake, err := x.Get(make) if err != nil { if errors.Is(err, exif.TagNotPresentError(make)) { return nil, nil } return nil, fmt.Errorf("can't get gear make: %w", err) } gearModel, err := x.Get(model) if err != nil { if errors.Is(err, exif.TagNotPresentError(model)) { return nil, nil } return nil, fmt.Errorf("can't get gear model: %w", err) } gearMakeStr := sanitizeEXIFField(gearMake) gearModelStr := sanitizeEXIFField(gearModel) g, ok := im.cfg.GearByString(gearMakeStr, gearModelStr) if !ok { return nil, errors.New(formatMissingGearError( im.SourcePath, gearMakeStr, gearModelStr, im.cfg.Gear, )) } return g, nil } func formatMissingGearError( sourcePath, gearMake, gearModel string, configuredGear []Gear, ) string { var b strings.Builder fmt.Fprintf( &b, "no matching gear entry in winter.yml for photo %q\n", sourcePath, ) fmt.Fprintf(&b, "wanted EXIF match:\n") fmt.Fprintf(&b, " make: %s\n", gearMake) fmt.Fprintf(&b, " model: %s\n", gearModel) if len(configuredGear) == 0 { b.WriteString("configured gear: none\n") b.WriteString("add a matching item under gear: in winter.yml") return b.String() } b.WriteString("configured gear:\n") for _, gear := range configuredGear { fmt.Fprintf( &b, " - %s %s (exif.make=%s, exif.model=%s)\n", gear.Make, gear.Model, formatEXIFValue(gear.EXIF.Make), formatEXIFValue(gear.EXIF.Model), ) } b.WriteString("add a matching item under gear: in winter.yml") return b.String() } func formatEXIFValue(value string) string { if value == "" { return "" } return strconv.Quote(value) } type wrappedError struct { msg string err error } func wrapErrorf(err error, format string, args ...any) error { if err == nil { return nil } return wrappedError{ msg: fmt.Sprintf(format, args...), err: err, } } func (e wrappedError) Error() string { if strings.Contains(e.err.Error(), "\n") { return e.msg + ":\n" + indentLines(e.err.Error(), " ") } return e.msg + ": " + e.err.Error() } func (e wrappedError) Unwrap() error { return e.err } func indentLines(s, prefix string) string { lines := strings.Split(s, "\n") for i, line := range lines { lines[i] = prefix + line } return strings.Join(lines, "\n") } // exifCutSet is a string containing all the individual characters, // in no specific order, // that should be cut from both ends of an EXIF field before processing it. const exifCutSet = " \"" // sanitizeEXIFField pulls the value out of the given EXIF field, // strips whitespace and quotes from its ends, // and returns the result. func sanitizeEXIFField(field *tiff.Tag) string { fieldVal := field.String() fieldVal = strings.Trim(fieldVal, exifCutSet) return fieldVal }