collage-maker/main.go

324 lines
8.1 KiB
Go

package main
import (
"bytes"
"context"
"embed"
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path"
"regexp"
"time"
"log/slog"
"go.balki.me/anyhttp"
"go.balki.me/anyhttp/idle"
"go.balki.me/collage-maker/collage"
)
var (
collageDir string
photosDir string
devMode bool
collageNameGen *nameGen
imagesDirFs fs.FS
listenAddr string
photoPrismURL *url.URL
photoPrismToken string
//go:embed web
webFS embed.FS
)
func main() {
var ppURL string
flag.StringVar(&collageDir, "collages-dir", "collages", "Sets the collages dir")
flag.StringVar(&photosDir, "photos-dir", "photos", "Cache directory for downloaded photos")
flag.BoolVar(&devMode, "dev", false, "Serve local assets during development")
flag.StringVar(&listenAddr, "addr", "127.0.0.1:8767", "Web listen address, see https://pkg.go.dev/go.balki.me/anyhttp#readme-address-syntax")
flag.StringVar(&ppURL, "pp-url", "", "Base url for photoprism")
flag.StringVar(&photoPrismToken, "pp-token", "", "API token for photoprism")
flag.Parse()
photoPrismURL = func() *url.URL {
photoPrismURL, err := url.Parse(ppURL)
if err != nil {
panic(err)
}
return photoPrismURL
}()
collageNameGen = NewNameGen()
imagesDirFs = os.DirFS(photosDir)
collagesPath := "collages"
photosPath := "photos"
addFileServer := func(path, dir string) {
httpFileServer := http.FileServer(http.Dir(dir))
http.Handle("/"+path+"/", http.StripPrefix("/"+path, httpFileServer))
}
addFileServer(collagesPath, collageDir)
addFileServer(photosPath, photosDir)
if devMode {
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)
})
} else {
indexModTime := time.Now()
indexHTML := func() io.ReadSeeker {
indexHTMLContent, err := webFS.ReadFile("web/index.html")
if err != nil {
panic(err)
}
devOnlyRegex := regexp.MustCompile("\n[^\n]*<!-- DEVONLY[^\n]*")
return bytes.NewReader(devOnlyRegex.ReplaceAllLiteral(indexHTMLContent, nil))
}()
httpFileServer := func() http.Handler {
webrootFs, err := fs.Sub(webFS, "web")
if err != nil {
panic(err)
}
return http.FileServer(http.FS(webrootFs))
}()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.ServeContent(w, r, "index.html", indexModTime, indexHTML)
} else {
httpFileServer.ServeHTTP(w, r)
}
})
}
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)
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := json.Unmarshal(body, &collageReq); err != nil {
slog.Error("failed to unmarshal json request", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
collageFilePath, err := MakeCollage(&collageReq)
if err != nil {
slog.Error("failed to make collage", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if _, err := w.Write([]byte(collageFilePath)); err != nil {
slog.Error("Failed to write collageFile", "error", err)
}
})
http.HandleFunc("/get-albums", func(w http.ResponseWriter, r *http.Request) {
albums, err := GetAlbums()
if err != nil {
slog.Error("failed to get albums", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
jData, err := json.Marshal(albums)
if err != nil {
slog.Error("failed to marshal albums", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
})
http.HandleFunc("/load-photos/{albumID}", func(w http.ResponseWriter, r *http.Request) {
albumID := r.PathValue("albumID")
photos, err := LoadPhotos(albumID)
if err != nil {
slog.Error("failed to load photos", "error", err, "album", albumID)
w.WriteHeader(http.StatusInternalServerError)
return
}
photoURLs := []string{}
for _, photo := range photos {
photoURLs = append(photoURLs, fmt.Sprintf("/%s/%s.jpg", photosPath, photo.FileUID))
}
go func() {
for _, photo := range photos {
_, err := DownloadPhoto(&photo)
if err != nil {
slog.Error("failed to download photo", "error", err, "album", albumID, "photoID", photo.FileUID)
}
}
}()
jData, err := json.Marshal(photoURLs)
if err != nil {
slog.Error("failed to marshal photoURLs", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
})
addrType, server, done, err := anyhttp.Serve(listenAddr, idle.WrapHandler(nil))
if err != nil {
slog.Error("anyhttp Serve failed", "error", err)
}
if addrType == anyhttp.SystemdFD {
if err := idle.Wait(30 * time.Minute); err != nil {
slog.Error("Failed to wait for idler", "error", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) // Don't want any stuck connections
defer cancel()
if err := server.Shutdown(ctx); err != nil {
slog.Error("http server Shutdown failed", "error", err)
}
} else {
<-done
}
}
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)
}
defer out.Close()
if err := collage.Make(req, imagesDirFs, out); err != nil {
return "", fmt.Errorf("failed to make collage, err: %w", err)
}
return collageFile, nil
}
type Album struct {
Title string `json:"Title"`
UID string `json:"UID"`
}
func GetAlbums() ([]Album, error) {
albumURL := func() string {
u := *photoPrismURL
u.Path = "/api/v1/albums"
v := url.Values{}
v.Add("count", "20")
v.Add("type", "album")
u.RawQuery = v.Encode()
return u.String()
}()
req, err := http.NewRequest("GET", albumURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", photoPrismToken))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
albums := []Album{}
err = json.Unmarshal(respBytes, &albums)
if err != nil {
return nil, err
}
return albums, nil
}
type Photo struct {
Hash string `json:"Hash"`
FileUID string `json:"FileUID"`
}
func LoadPhotos(albumID string) ([]Photo, error) {
loadPhotosURL := func() string {
u := *photoPrismURL
u.Path = "/api/v1/photos"
v := url.Values{}
v.Add("count", "50")
v.Add("s", albumID)
v.Add("merged", "true")
v.Add("video", "false")
u.RawQuery = v.Encode()
return u.String()
}()
req, err := http.NewRequest("GET", loadPhotosURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", photoPrismToken))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
photos := []Photo{}
err = json.Unmarshal(respBytes, &photos)
if err != nil {
return nil, err
}
return photos, nil
}
func DownloadPhoto(photo *Photo) (string, error) {
photoPath := path.Join(photosDir, fmt.Sprintf("%s.jpg", photo.FileUID))
_, err := os.Stat(photoPath)
if err == nil {
return photoPath, nil
} else if !os.IsNotExist(err) {
return "", err
}
out, err := os.Create(photoPath)
if err != nil {
return "", fmt.Errorf("failed to create collage output file, err: %w", err)
}
defer out.Close()
downloadPhotoURL := func() string {
u := *photoPrismURL
u.Path = fmt.Sprintf("/api/v1/dl/%s", photo.Hash)
return u.String()
}()
req, err := http.NewRequest("GET", downloadPhotoURL, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", photoPrismToken))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return "", err
}
return photoPath, nil
}