photoprism/converter.go

92 lines
1.8 KiB
Go
Raw Normal View History

2018-02-04 17:34:07 +01:00
package photoprism
import (
2018-02-28 10:08:49 +01:00
"errors"
"log"
2018-02-04 17:34:07 +01:00
"os"
"os/exec"
"path/filepath"
2018-02-04 17:34:07 +01:00
)
type Converter struct {
darktableCli string
}
func NewConverter(darktableCli string) *Converter {
if stat, err := os.Stat(darktableCli); err != nil {
log.Print("Darktable CLI binary could not be found at " + darktableCli)
} else if stat.IsDir() {
log.Print("Darktable CLI must be a file, not a directory")
}
return &Converter{darktableCli: darktableCli}
}
func (c *Converter) ConvertAll(path string) {
err := filepath.Walk(path, func(filename string, fileInfo os.FileInfo, err error) error {
if err != nil {
log.Print(err.Error())
return nil
}
if fileInfo.IsDir() {
return nil
}
mediaFile := NewMediaFile(filename)
if !mediaFile.Exists() || !mediaFile.IsRaw() {
return nil
}
if _, err := c.ConvertToJpeg(mediaFile); err != nil {
log.Print(err.Error())
}
return nil
})
if err != nil {
log.Print(err.Error())
}
}
func (c *Converter) ConvertToJpeg(image *MediaFile) (*MediaFile, error) {
if !image.Exists() {
return nil, errors.New("can not convert, file does not exist")
}
2018-02-04 17:34:07 +01:00
if image.IsJpeg() {
return image, nil
}
extension := image.GetExtension()
2018-02-28 10:08:49 +01:00
baseFilename := image.filename[0 : len(image.filename)-len(extension)]
2018-02-04 17:34:07 +01:00
jpegFilename := baseFilename + ".jpg"
if _, err := os.Stat(jpegFilename); err == nil {
return NewMediaFile(jpegFilename), nil
}
2018-06-16 14:19:18 +02:00
log.Printf("Converting %s to %s \n", image.filename, jpegFilename)
2018-02-04 17:34:07 +01:00
xmpFilename := baseFilename + ".xmp"
var convertCommand *exec.Cmd
if _, err := os.Stat(xmpFilename); err == nil {
convertCommand = exec.Command(c.darktableCli, image.filename, xmpFilename, jpegFilename)
2018-02-04 17:34:07 +01:00
} else {
convertCommand = exec.Command(c.darktableCli, image.filename, jpegFilename)
2018-02-04 17:34:07 +01:00
}
if err := convertCommand.Run(); err != nil {
return nil, err
}
return NewMediaFile(jpegFilename), nil
}