package server import ( "bytes" "log/slog" "net/http" "git.lastassault.de/speatzle/morffix/constants" "github.com/jackc/pgx/v5" ) type StatsDisplay struct { CodecCounts []CodecCount } type CodecCount struct { Codec string Count int } func handleStats(w http.ResponseWriter, r *http.Request) { data := StatsDisplay{} rows, err := db.Query(r.Context(), `SELECT COALESCE(jsonb_path_query_first(ffprobe_data, '$.streams[*] ? (@.codec_type == "video") ? (@.disposition.attached_pic == 0).codec_name')::text, 'Unknown') AS codec, COUNT(*) AS count FROM files WHERE ffprobe_data IS NOT NULL GROUP BY jsonb_path_query_first(ffprobe_data, '$.streams[*] ? (@.codec_type == "video") ? (@.disposition.attached_pic == 0).codec_name');`) if err != nil { slog.ErrorContext(r.Context(), "Query Stats", "err", err) http.Error(w, "Error Query Stats: "+err.Error(), http.StatusInternalServerError) return } codecCounts, err := pgx.CollectRows[CodecCount](rows, pgx.RowToStructByName[CodecCount]) if err != nil { slog.ErrorContext(r.Context(), "Collect Rows", "err", err) http.Error(w, "Error Query Libraries: "+err.Error(), http.StatusInternalServerError) return } data.CodecCounts = codecCounts buf := bytes.Buffer{} err = templates.ExecuteTemplate(&buf, constants.STATS_TEMPLATE_NAME, data) if err != nil { slog.ErrorContext(r.Context(), "Executing Stats 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) } }