Add support for on-demand thumbnail generation via github.com/mutschler/mt

This commit is contained in:
James Mills 2020-03-21 10:46:03 +10:00
parent 4dae45a68f
commit 84cba43724
No known key found for this signature in database
GPG key ID: AC4C014F1440EBD6
2 changed files with 70 additions and 0 deletions

56
media/utils.go Normal file
View file

@ -0,0 +1,56 @@
package media
import (
"bytes"
"fmt"
"os/exec"
"time"
)
func cmdExists(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
}
func runCmd(timeout int, command string, args ...string) error {
// instantiate new command
cmd := exec.Command(command, args...)
// get pipe to standard output
stdout, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("cmd.StdoutPipe() error: %w", err)
}
// start process via command
if err := cmd.Start(); err != nil {
return fmt.Errorf("cmd.Start() error: %w", err)
}
// setup a buffer to capture standard output
var buf bytes.Buffer
// create a channel to capture any errors from wait
done := make(chan error)
go func() {
if _, err := buf.ReadFrom(stdout); err != nil {
panic("buf.Read(stdout) error: " + err.Error())
}
done <- cmd.Wait()
}()
// block on select, and switch based on actions received
select {
case <-time.After(time.Duration(timeout) * time.Second):
if err := cmd.Process.Kill(); err != nil {
return fmt.Errorf("failed to kill: %w", err)
}
return fmt.Errorf("timeout reached, process killed")
case err := <-done:
if err != nil {
close(done)
return fmt.Errorf("process done, with error: %w", err)
}
return nil
}
}

View file

@ -1,8 +1,11 @@
package media package media
import ( import (
"fmt"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath"
"strings" "strings"
"time" "time"
@ -72,6 +75,17 @@ func ParseVideo(p *Path, name string) (*Video, error) {
if pic != nil { if pic != nil {
v.Thumb = pic.Data v.Thumb = pic.Data
v.ThumbType = pic.MIMEType v.ThumbType = pic.MIMEType
} else if cmdExists("mt") {
if err := runCmd(3, "mt", "-s", "-n", "1", pth); err != nil {
return nil, err
} }
data, err := ioutil.ReadFile(fmt.Sprintf("%s.jpg", strings.TrimSuffix(pth, filepath.Ext(pth))))
if err != nil {
return nil, err
}
v.Thumb = data
v.ThumbType = "image/jpeg"
}
return v, nil return v, nil
} }