filebrowser/runner/runner.go
Henrique Dias 12b2c21522 feat: v2 (#599)
Read https://github.com/filebrowser/filebrowser/pull/575.

Former-commit-id: 7aedcaaf72b863033e3f089d6df308d41a3fd00c [formerly bdbe4d49161b901c4adf9c245895a1be2d62e4a7] [formerly acfc1ec67c423e0b3e065a8c1f8897c5249af65b [formerly d309066def]]
Former-commit-id: 0c7d925a38a68ccabdf2c4bbd8c302ee89b93509 [formerly a6173925a1382955d93b334ded93f70d6dddd694]
Former-commit-id: e032e0804dd051df86f42962de2b39caec5318b7
2019-01-05 22:44:33 +00:00

82 lines
1.8 KiB
Go

package runner
import (
"fmt"
"log"
"os"
"os/exec"
"strings"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/users"
)
// Runner is a commands runner.
type Runner struct {
*settings.Settings
}
// RunHook runs the hooks for the before and after event.
func (r *Runner) RunHook(fn func() error, evt, path, dst string, user *users.User) error {
path = user.FullPath(path)
dst = user.FullPath(dst)
if val, ok := r.Commands["before_"+evt]; ok {
for _, command := range val {
err := r.exec(command, "before_"+evt, path, dst, user)
if err != nil {
return err
}
}
}
err := fn()
if err != nil {
return err
}
if val, ok := r.Commands["after_"+evt]; ok {
for _, command := range val {
err := r.exec(command, "after_"+evt, path, dst, user)
if err != nil {
return err
}
}
}
return nil
}
func (r *Runner) exec(raw, evt, path, dst string, user *users.User) error {
blocking := true
if strings.HasSuffix(raw, "&") {
blocking = false
raw = strings.TrimSpace(strings.TrimSuffix(raw, "&"))
}
command, err := ParseCommand(r.Settings, raw)
if err != nil {
return err
}
cmd := exec.Command(command[0], command[1:]...)
cmd.Env = append(os.Environ(), fmt.Sprintf("FILE=%s", path))
cmd.Env = append(cmd.Env, fmt.Sprintf("SCOPE=%s", user.Scope))
cmd.Env = append(cmd.Env, fmt.Sprintf("TRIGGER=%s", evt))
cmd.Env = append(cmd.Env, fmt.Sprintf("USERNAME=%s", user.Username))
cmd.Env = append(cmd.Env, fmt.Sprintf("DESTINATION=%s", dst))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if !blocking {
log.Printf("[INFO] Nonblocking Command: \"%s\"", strings.Join(command, " "))
return cmd.Start()
}
log.Printf("[INFO] Blocking Command: \"%s\"", strings.Join(command, " "))
return cmd.Run()
}