all repos — fsrv @ de1dfeb667f0ed81e9acfc66198f7ba42b311bd3

filehost server for x.icyphox.sh

hooks.go (view raw)

 1package main
 2
 3import (
 4	"bufio"
 5	"fmt"
 6	"log"
 7	"os"
 8	"os/exec"
 9	"path/filepath"
10
11	"github.com/h2non/filetype"
12)
13
14func runHooks(file string) {
15	hooks, err := os.ReadDir("hooks")
16	if err != nil {
17		log.Println(err)
18	}
19	for _, h := range hooks {
20		hookFile := getHook(file)
21		if h.Name() == hookFile {
22			log.Println("running hook:", hookFile)
23			cmd := exec.Command(filepath.Join("hooks", h.Name()), file)
24			stdout, _ := cmd.StdoutPipe()
25			cmd.Start()
26			s := bufio.NewScanner(stdout)
27			for s.Scan() {
28				fmt.Println(s.Text())
29			}
30		}
31	}
32}
33
34// Checks the MIME type of file and returns
35// the corresponding hook file.
36func getHook(file string) string {
37	// Not sure how many bytes the magic number takes, but 16
38	// is a good guess. I think.
39	magic := make([]byte, 16)
40
41	f, err := os.Open(file)
42	if err != nil {
43		log.Println(err)
44	}
45	defer f.Close()
46
47	_, err = f.Read(magic)
48	if err != nil {
49		log.Println(err)
50	}
51
52	t, err := filetype.Match(magic)
53	if err != nil {
54		log.Println(err)
55	}
56	return t.Extension + ".sh"
57}