all repos — fsrv @ daa1c66a38a7f414f2bc559bbae86605d4318722

filehost server for x.icyphox.sh

hooks.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/h2non/filetype"
)

func runHooks(file string) {
	hooks, err := os.ReadDir("hooks")
	if err != nil {
		log.Println(err)
	}
	for _, h := range hooks {
		hookFile := getHook(file)
		if h.Name() == hookFile {
			log.Println("running hook:", hookFile)
			cmd := exec.Command(filepath.Join("hooks", h.Name()), file)
			stdout, _ := cmd.StdoutPipe()
			cmd.Start()
			s := bufio.NewScanner(stdout)
			for s.Scan() {
				fmt.Println(s.Text())
			}
		}
	}
}

// Checks the MIME type of file and returns
// the corresponding hook file.
func getHook(file string) string {
	// Not sure how many bytes the magic number takes, but 16
	// is a good guess. I think.
	magic := make([]byte, 16)

	f, err := os.Open(file)
	if err != nil {
		log.Println(err)
	}
	defer f.Close()

	_, err = f.Read(magic)
	if err != nil {
		log.Println(err)
	}

	t, err := filetype.Match(magic)
	if err != nil {
		log.Println(err)
	}
	return t.Extension + ".sh"
}