morffix/server/library.go
2024-05-05 01:31:45 +02:00

79 lines
1.9 KiB
Go

package server
import (
"bytes"
"log/slog"
"net/http"
"git.lastassault.de/speatzle/morffix/constants"
"github.com/jackc/pgx/v5"
)
type LibraryData struct {
Library Library
Files []File
}
type File struct {
ID int `db:"id"`
Path string `db:"path"`
Size int64 `db:"size"`
Missing bool `db:"missing"`
}
func handleLibrary(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
handleLibraries(w, r)
return
}
data := LibraryData{}
var name string
var path string
var enabled bool
err := db.QueryRow(r.Context(), "SELECT name, path, enable FROM libraries WHERE id = $1", id).Scan(&name, &path, &enabled)
if err != nil {
slog.ErrorContext(r.Context(), "Get Library", "err", err)
http.Error(w, "Error Get Library: "+err.Error(), http.StatusInternalServerError)
return
}
data.Library = Library{
ID: id,
Name: name,
Path: path,
Enable: enabled,
}
if r.Method == "PUT" {
// TODO
}
rows, err := db.Query(r.Context(), "SELECT id, path, size, missing FROM files where library_id = $1", id)
if err != nil {
slog.ErrorContext(r.Context(), "Query Files", "err", err)
http.Error(w, "Error Query Files: "+err.Error(), http.StatusInternalServerError)
return
}
files, err := pgx.CollectRows[File](rows, pgx.RowToStructByName[File])
if err != nil {
slog.ErrorContext(r.Context(), "Collect Rows", "err", err)
http.Error(w, "Error Query Files: "+err.Error(), http.StatusInternalServerError)
return
}
data.Files = files
buf := bytes.Buffer{}
err = templates.ExecuteTemplate(&buf, constants.LIBRARY_TEMPLATE_NAME, data)
if err != nil {
slog.ErrorContext(r.Context(), "Executing Library Template", "err", err)
http.Error(w, "Error Executing Template: "+err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(buf.Bytes())
if err != nil {
slog.ErrorContext(r.Context(), "Writing http Response", "err", err)
}
}