nori/cmd/cory-bin/main.go

121 lines
2.5 KiB
Go
Raw Normal View History

2022-03-25 22:20:50 +00:00
package main
import (
"bytes"
"flag"
"fmt"
2024-08-06 03:35:53 +00:00
"log"
"log/slog"
2022-03-25 22:20:50 +00:00
"net/http"
"os"
"time"
2024-08-06 03:35:53 +00:00
"anime.bike/slogutil/slogenv"
"anime.bike/stint"
2022-12-19 09:09:29 +00:00
"git.tuxpa.in/a/nori/renderer"
2022-03-25 22:33:48 +00:00
"git.tuxpa.in/a/nori"
"git.tuxpa.in/a/nori/utils"
2022-03-25 22:20:50 +00:00
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
var (
servePtr = flag.Bool("serve", false, "launch web server")
dumpPtr = flag.Bool("d", false, "dump nri file to zip")
silentPtr = flag.Bool("s", false, "silent")
filePtr = flag.String("f", "example.nri", "file to load")
outputPtr = flag.String("o", "output.zip", "output zip file")
)
2024-08-06 03:35:53 +00:00
func init() {
slog.SetDefault(slog.New(stint.NewHandler(os.Stderr, &stint.Options{
AddSource: true,
Level: slogenv.EnvLevel(),
})))
}
2022-03-25 22:20:50 +00:00
func main() {
flag.Parse()
if *servePtr {
serve()
return
}
if *dumpPtr {
filename := *filePtr
output := *outputPtr
if _, err := os.Stat(filename); err != nil {
printIf("could not find file %s\n", filename)
return
}
dump(filename, output)
return
}
flag.PrintDefaults()
}
func printIf(s string, args ...interface{}) {
if !*silentPtr {
fmt.Printf(s, args...)
}
}
func dump(filename string, output string) {
start := time.Now()
printIf("reading file '%s'\n", filename)
n, err := nori.FromFile(filename)
if err != nil {
2022-12-19 09:09:29 +00:00
log.Panicf("decode: %s", err)
2022-03-25 22:20:50 +00:00
}
out := new(bytes.Buffer)
printIf("rendering %d animation(s)\n", n.AnimationCount)
animations, err := renderer.RenderAnimationsApng(n)
2022-03-25 22:20:50 +00:00
if err != nil {
2024-08-06 03:35:53 +00:00
log.Panicf("animation: %s\n", err)
2022-03-25 22:20:50 +00:00
}
printIf("saving to %s \n", output)
2022-03-25 22:27:42 +00:00
if err := utils.ZipApngs(out, animations); err != nil {
2024-08-06 03:35:53 +00:00
log.Panicf("zipping: %s\n", err)
2022-03-25 22:20:50 +00:00
}
printIf("done in %v \n", time.Now().Sub(start))
os.WriteFile(output, out.Bytes(), 0740)
}
func serve() {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(60 * time.Second))
r.Post("/animations", func(w http.ResponseWriter, r *http.Request) {
output_type := chi.URLParam(r, "format")
switch output_type {
case "":
output_type = "apng"
case "apng":
default:
http.Error(w, "output type not supported", 500)
return
}
n := nori.New()
if err := n.Decode(r.Body); err != nil {
http.Error(w, err.Error(), 500)
}
frames, err := renderer.RenderAnimationsApng(n)
2022-03-25 22:20:50 +00:00
if err != nil {
http.Error(w, err.Error(), 500)
}
if err := utils.ZipApngs(w, frames); err != nil {
http.Error(w, err.Error(), 500)
}
w.WriteHeader(200)
})
log.Println("listening on 3333")
http.ListenAndServe(":3333", r)
}