all repos — fsrv @ b00f8f23450ac8f362a2eaa234199b820fbd17a3

filehost server for x.icyphox.sh

Add filetype hooks
Anirudh Oppiliappan x@icyphox.sh
Sat, 14 Aug 2021 18:06:59 +0530
commit

b00f8f23450ac8f362a2eaa234199b820fbd17a3

parent

935cd56cdb007397f802d5f870f1c08496d87d19

5 files changed, 73 insertions(+), 2 deletions(-)

jump to
M go.modgo.mod

@@ -1,3 +1,5 @@

module git.icyphox.sh/fsrv go 1.16 + +require github.com/h2non/filetype v1.1.1
A go.sum

@@ -0,0 +1,2 @@

+github.com/h2non/filetype v1.1.1 h1:xvOwnXKAckvtLWsN398qS9QhlxlnVXBjXBydK2/UFB4= +github.com/h2non/filetype v1.1.1/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
A hooks.go

@@ -0,0 +1,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" +}
A hooks/7z.sh

@@ -0,0 +1,6 @@

+#!/bin/sh + +mkdir tmp +7z x "$1" -otmp +rsync -avz tmp/* jade:/mnt/music +rm -rf tmp
M main.gomain.go

@@ -36,13 +36,12 @@ switch r.Method {

case "POST": key := r.FormValue("key") useragent := r.Header.Get("User-Agent") - fmt.Println(key) if key != s.key { fmt.Fprintf(w, "incorrect key") log.Printf("incorrect key: %+v", key) return } - r.ParseMultipartForm(20 << 20) + r.ParseMultipartForm(512 << 20) file, handler, err := r.FormFile("file") if err != nil { log.Println(err)

@@ -61,6 +60,11 @@ newFile := randName(5) + ext

diskFile := filepath.Join(s.storepath, newFile) os.WriteFile(diskFile, fileBytes, 0644) log.Printf("wrote: %+v", diskFile) + abs, err := filepath.Abs(diskFile) + if err != nil { + log.Println(err) + } + runHooks(abs) fileUrl := s.url + "/" + newFile if strings.Contains(useragent, "curl/") {