collage-maker/main.go

157 lines
3.9 KiB
Go
Raw Normal View History

2023-08-01 19:16:46 -04:00
package main
import (
2023-09-11 12:37:44 -04:00
"context"
"crypto/rand"
2023-08-31 20:27:43 -04:00
"embed"
"encoding/json"
"flag"
2023-08-01 19:16:46 -04:00
"fmt"
"io"
2023-08-31 20:27:43 -04:00
"io/fs"
"net/http"
2023-08-01 19:16:46 -04:00
"os"
"path"
"sync/atomic"
"time"
2023-08-03 19:33:05 -04:00
"log/slog"
2023-09-08 12:45:46 -04:00
"go.balki.me/anyhttp"
2023-09-11 12:37:44 -04:00
"go.balki.me/anyhttp/idle"
"go.balki.me/collage-maker/collage"
2023-08-01 19:16:46 -04:00
)
var (
2023-09-01 15:13:54 -04:00
imagesDir string
collageDir string
localAssets bool
collageNameGen *nameGen
imagesDirFs fs.FS
2023-09-08 12:45:46 -04:00
listenAddr string
2023-09-01 15:13:54 -04:00
// go:embed web/*
webFS embed.FS
)
2023-08-03 19:33:05 -04:00
2023-08-01 19:16:46 -04:00
func main() {
flag.StringVar(&imagesDir, "images-dir", "images", "Sets the images dir")
flag.StringVar(&collageDir, "collages-dir", "collages", "Sets the collages dir")
2023-08-31 20:27:43 -04:00
flag.BoolVar(&localAssets, "local-assets", false, "Serve local assets for testing")
2023-09-08 12:45:46 -04:00
flag.StringVar(&listenAddr, "addr", "127.0.0.1:8767", "Sets the collages dir")
2023-08-31 20:27:43 -04:00
flag.Parse()
2023-09-01 15:13:54 -04:00
collageNameGen = NewNameGen()
imagesDirFs = os.DirFS(imagesDir)
2023-08-31 20:27:43 -04:00
imagesURLPath := "images"
collagesPath := "collages"
addFileServer := func(path, dir string) {
httpFileServer := http.FileServer(http.Dir(dir))
http.Handle("/"+path+"/", http.StripPrefix("/"+path, httpFileServer))
}
addFileServer(imagesURLPath, imagesDir)
addFileServer(collagesPath, collageDir)
if localAssets {
httpFileServer := http.FileServer(http.Dir("web"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Cache-Control", "no-cache")
httpFileServer.ServeHTTP(w, r)
})
2023-08-31 20:27:43 -04:00
} else {
fs, err := fs.Sub(webFS, "web")
if err != nil {
panic(err)
}
httpFileServer := http.FileServer(http.FS(fs))
http.Handle("/", httpFileServer)
}
2023-08-01 19:16:46 -04:00
http.HandleFunc("/make-collage", func(w http.ResponseWriter, r *http.Request) {
collageReq := collage.Request{}
body, err := io.ReadAll(r.Body)
if err != nil {
slog.Error("failed to read request body", "error", err)
2023-09-01 15:13:54 -04:00
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := json.Unmarshal(body, &collageReq); err != nil {
slog.Error("failed to unmarshal json request", "error", err)
2023-09-01 15:13:54 -04:00
w.WriteHeader(http.StatusInternalServerError)
return
}
2023-09-01 15:13:54 -04:00
collageFile, err := MakeCollage(&collageReq)
if err != nil {
slog.Error("failed to make collage", "error", err)
2023-09-01 15:13:54 -04:00
w.WriteHeader(http.StatusInternalServerError)
return
}
2023-09-11 12:37:44 -04:00
if _, err := w.Write([]byte(collageFile)); err != nil {
slog.Error("Failed to write collageFile", "error", err)
}
2023-08-03 19:33:05 -04:00
})
2023-09-11 21:09:12 -04:00
addrType, server, done, err := anyhttp.Serve(listenAddr, idle.WrapHandler(nil))
2023-09-11 12:37:44 -04:00
if err != nil {
2023-09-11 21:09:12 -04:00
slog.Error("anyhttp Serve failed", "error", err)
2023-09-11 12:37:44 -04:00
}
if addrType == anyhttp.SystemdFD {
2023-09-11 21:09:12 -04:00
if err := idle.Wait(30 * time.Minute); err != nil {
2023-09-11 12:37:44 -04:00
slog.Error("Failed to wait for idler", "error", err)
}
ctx, _ := context.WithTimeout(context.Background(), 1*time.Minute) // Don't want any stuck connections
if err := server.Shutdown(ctx); err != nil {
slog.Error("http server Shutdown failed", "error", err)
}
} else {
2023-09-11 21:09:12 -04:00
<-done
2023-08-03 19:33:05 -04:00
}
}
2023-08-03 19:33:05 -04:00
type nameGen struct {
prefix string
counter atomic.Uint64
}
2023-08-03 19:33:05 -04:00
func NewNameGen() *nameGen {
currentTime := time.Now().Unix()
randBytes := make([]byte, 8)
_, err := rand.Read(randBytes)
2023-08-03 19:33:05 -04:00
if err != nil {
panic(err)
}
alpha := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
uniqRunID := ""
for _, b := range randBytes {
uniqRunID += string(alpha[int(b)%len(alpha)])
2023-08-01 19:16:46 -04:00
}
return &nameGen{
prefix: fmt.Sprintf("%d-%s", currentTime, uniqRunID),
counter: atomic.Uint64{},
}
}
2023-08-01 19:16:46 -04:00
func (n *nameGen) Next() string {
return fmt.Sprintf("%s-%d", n.prefix, n.counter.Add(1))
2023-08-01 19:16:46 -04:00
}
2023-09-01 15:13:54 -04:00
func MakeCollage(req *collage.Request) (string, error) {
collageFile := fmt.Sprintf("collage-%s.jpg", collageNameGen.Next())
out, err := os.Create(path.Join(collageDir, collageFile))
if err != nil {
return "", fmt.Errorf("failed to create collage output file, err: %w", err)
}
if err := collage.Make(req, imagesDirFs, out); err != nil {
return "", fmt.Errorf("failed to make collage, err: %w", err)
}
return collageFile, nil
}
// curl -D - --json @req.json http://localhost:8767/make-collage