303 lines
13 KiB
Go
303 lines
13 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type chartOrderItem struct {
|
|
ID int64 `json:"id"`
|
|
Position int `json:"position"`
|
|
}
|
|
|
|
type chartOrderRequest struct {
|
|
ChartKey string `json:"chart_key"`
|
|
ChartYear int `json:"chart_year"`
|
|
Order []chartOrderItem `json:"order"`
|
|
}
|
|
|
|
func (a *adminHandler) chartGenerationStatus(ctx context.Context, chartKey string) (bool, string, string) {
|
|
chartKey = normalizeAdminChartKey(chartKey)
|
|
if chartKey == "annual" || chartKey == "archive" || a.database == nil || !a.database.Enabled() {
|
|
return false, "", ""
|
|
}
|
|
var row struct {
|
|
GeneratedAt string `json:"generated_at"`
|
|
}
|
|
query := fmt.Sprintf(`SELECT COALESCE((SELECT json_build_object(
|
|
'generated_at',to_char(generated_at AT TIME ZONE 'Europe/Berlin','DD.MM.YYYY HH24:MI'))
|
|
FROM chart_generation_runs WHERE chart_key=%s ORDER BY generated_at DESC LIMIT 1),'{}'::json)::text;`, sqlText(chartKey))
|
|
if err := a.database.queryJSON(ctx, query, &row); err != nil {
|
|
return true, "", ""
|
|
}
|
|
return true, row.GeneratedAt, ""
|
|
}
|
|
|
|
func (a *adminHandler) adminChartsReorder(w http.ResponseWriter, r *http.Request) {
|
|
session, ok := a.chartAdminAPISession(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
writeAdminJSONError(w, http.StatusMethodNotAllowed, "Methode nicht erlaubt.")
|
|
return
|
|
}
|
|
if !validAdminCSRF(r, session) {
|
|
writeAdminJSONError(w, http.StatusForbidden, "Ungültige Sicherheitsprüfung. Bitte die Seite neu laden.")
|
|
return
|
|
}
|
|
var in chartOrderRequest
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256<<10)).Decode(&in); err != nil {
|
|
writeAdminJSONError(w, http.StatusBadRequest, "Die neue Reihenfolge konnte nicht gelesen werden.")
|
|
return
|
|
}
|
|
in.ChartKey = normalizeAdminChartKey(in.ChartKey)
|
|
if len(in.Order) == 0 || len(in.Order) > 200 {
|
|
writeAdminJSONError(w, http.StatusBadRequest, "Die Reihenfolge ist leer oder zu groß.")
|
|
return
|
|
}
|
|
if err := validateChartOrder(in.Order); err != nil {
|
|
writeAdminJSONError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
if err := a.persistChartOrder(r.Context(), in); err != nil {
|
|
writeAdminJSONError(w, http.StatusInternalServerError, "Reihenfolge konnte nicht gespeichert werden: "+err.Error())
|
|
return
|
|
}
|
|
a.audit(r.Context(), session, r, "chart.reorder", "chart", 0, "Chartpositionen neu sortiert", true)
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "Die neue Reihenfolge wurde gespeichert.", "order": in.Order})
|
|
}
|
|
|
|
func validateChartOrder(order []chartOrderItem) error {
|
|
ids, positions := map[int64]bool{}, map[int]bool{}
|
|
for _, item := range order {
|
|
if item.ID <= 0 || item.Position < 1 || item.Position > 200 {
|
|
return fmt.Errorf("Eine Chartposition ist ungültig")
|
|
}
|
|
if ids[item.ID] || positions[item.Position] {
|
|
return fmt.Errorf("IDs und Positionen müssen eindeutig sein")
|
|
}
|
|
ids[item.ID], positions[item.Position] = true, true
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *adminHandler) persistChartOrder(ctx context.Context, in chartOrderRequest) error {
|
|
if a.database == nil || !a.database.Enabled() {
|
|
return fmt.Errorf("PostgreSQL ist nicht verfügbar")
|
|
}
|
|
sql, err := chartOrderSQL(in)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = a.database.exec(ctx, sql)
|
|
return err
|
|
}
|
|
|
|
func chartOrderSQL(in chartOrderRequest) (string, error) {
|
|
if len(in.Order) == 0 {
|
|
return "", fmt.Errorf("Die Reihenfolge ist leer")
|
|
}
|
|
var values strings.Builder
|
|
for i, item := range in.Order {
|
|
if i > 0 {
|
|
values.WriteByte(',')
|
|
}
|
|
values.WriteString(fmt.Sprintf("(%d,%d)", item.ID, item.Position))
|
|
}
|
|
if in.ChartKey == "annual" {
|
|
if in.ChartYear < 1900 || in.ChartYear > 2200 {
|
|
return "", fmt.Errorf("Das Chartjahr ist ungültig")
|
|
}
|
|
return fmt.Sprintf(`BEGIN;
|
|
SET CONSTRAINTS chart_year_entries_chart_year_position_key DEFERRED;
|
|
UPDATE chart_year_entries AS entry
|
|
SET previous_week_position=entry.position,
|
|
current_week_position=ordered.position,
|
|
position=ordered.position,
|
|
updated_at=now()
|
|
FROM (VALUES %s) AS ordered(id,position)
|
|
WHERE entry.id=ordered.id AND entry.chart_year=%d;
|
|
COMMIT;`, values.String(), in.ChartYear), nil
|
|
}
|
|
if in.ChartKey != "listener" && in.ChartKey != "dockx" && in.ChartKey != "schlager" {
|
|
return "", fmt.Errorf("Der Chartbereich ist ungültig")
|
|
}
|
|
return fmt.Sprintf(`BEGIN;
|
|
SET CONSTRAINTS chart_entries_chart_key_position_key DEFERRED;
|
|
UPDATE chart_entries AS entry
|
|
SET previous_position=entry.position,
|
|
previous_week_position=entry.position,
|
|
current_week_position=ordered.position,
|
|
position=ordered.position,
|
|
updated_at=now()
|
|
FROM (VALUES %s) AS ordered(id,position)
|
|
WHERE entry.id=ordered.id AND entry.chart_key=%s AND entry.active=true;
|
|
COMMIT;`, values.String(), sqlText(in.ChartKey)), nil
|
|
}
|
|
|
|
func sortChartEntriesByVotingStand(entries []ChartEntry) {
|
|
sort.SliceStable(entries, func(i, j int) bool {
|
|
iEmpty := strings.TrimSpace(entries[i].Artist) == "" || strings.TrimSpace(entries[i].Title) == ""
|
|
jEmpty := strings.TrimSpace(entries[j].Artist) == "" || strings.TrimSpace(entries[j].Title) == ""
|
|
if iEmpty != jEmpty {
|
|
return !iEmpty
|
|
}
|
|
if entries[i].VotePoints != entries[j].VotePoints {
|
|
return entries[i].VotePoints > entries[j].VotePoints
|
|
}
|
|
return entries[i].Position < entries[j].Position
|
|
})
|
|
}
|
|
|
|
func (a *adminHandler) adminChartsGenerate(w http.ResponseWriter, r *http.Request) {
|
|
session, ok := a.chartAdminAPISession(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
writeAdminJSONError(w, http.StatusMethodNotAllowed, "Methode nicht erlaubt.")
|
|
return
|
|
}
|
|
if !validAdminCSRF(r, session) {
|
|
writeAdminJSONError(w, http.StatusForbidden, "Ungültige Sicherheitsprüfung. Bitte die Seite neu laden.")
|
|
return
|
|
}
|
|
var in struct {
|
|
ChartKey string `json:"chart_key"`
|
|
}
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32<<10)).Decode(&in); err != nil {
|
|
writeAdminJSONError(w, http.StatusBadRequest, "Chartbereich fehlt.")
|
|
return
|
|
}
|
|
key := normalizeAdminChartKey(in.ChartKey)
|
|
if key != "listener" && key != "dockx" && key != "schlager" {
|
|
writeAdminJSONError(w, http.StatusBadRequest, "Dieser Chart kann nicht generiert werden.")
|
|
return
|
|
}
|
|
entries, err := newChartStore(a.database).AdminChart(r.Context(), key)
|
|
if err != nil || len(entries) == 0 {
|
|
writeAdminJSONError(w, http.StatusInternalServerError, "Charttitel konnten nicht geladen werden.")
|
|
return
|
|
}
|
|
sortChartEntriesByVotingStand(entries)
|
|
order := make([]chartOrderItem, 0, len(entries))
|
|
for i, entry := range entries {
|
|
order = append(order, chartOrderItem{ID: int64(entry.ID), Position: i + 1})
|
|
}
|
|
if err := a.persistChartOrder(r.Context(), chartOrderRequest{ChartKey: key, Order: order}); err != nil {
|
|
writeAdminJSONError(w, http.StatusInternalServerError, "Charts konnten nicht neu sortiert werden: "+err.Error())
|
|
return
|
|
}
|
|
insert := fmt.Sprintf(`INSERT INTO chart_generation_runs(chart_key,iso_year,iso_week,generated_by_user_id,generated_at) VALUES(%s,EXTRACT(isoyear FROM now() AT TIME ZONE 'Europe/Berlin')::int,EXTRACT(week FROM now() AT TIME ZONE 'Europe/Berlin')::int,%s,now()) ON CONFLICT(chart_key,iso_year,iso_week) DO UPDATE SET generated_by_user_id=EXCLUDED.generated_by_user_id,generated_at=now() RETURNING id;`, sqlText(key), sqlNullableInt64(session.UserID))
|
|
if _, err := a.database.exec(r.Context(), insert); err != nil {
|
|
writeAdminJSONError(w, http.StatusInternalServerError, "Sortierung wurde gespeichert, der Auswertungszeitpunkt aber nicht: "+err.Error())
|
|
return
|
|
}
|
|
a.audit(r.Context(), session, r, "chart.generate", "chart", 0, adminChartTitle(key)+" neu generiert", true)
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": adminChartTitle(key) + " wurden nach dem aktuellen Voting-Stand neu sortiert.", "order": order})
|
|
}
|
|
|
|
func (a *adminHandler) chartAdminAPISession(w http.ResponseWriter, r *http.Request) (adminSession, bool) {
|
|
_, session, ok := a.sessionFromRequest(r)
|
|
if !ok {
|
|
writeAdminJSONError(w, http.StatusUnauthorized, "Die Admin-Sitzung ist abgelaufen. Bitte neu anmelden.")
|
|
return session, false
|
|
}
|
|
if !requireAdminPermission(w, session, "charts.manage") {
|
|
return session, false
|
|
}
|
|
return session, true
|
|
}
|
|
|
|
func (a *adminHandler) adminChartYearInfoGenerate(w http.ResponseWriter, r *http.Request) {
|
|
session, ok := a.chartAdminAPISession(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
writeAdminJSONError(w, http.StatusMethodNotAllowed, "Methode nicht erlaubt.")
|
|
return
|
|
}
|
|
if !validAdminCSRF(r, session) {
|
|
writeAdminJSONError(w, http.StatusForbidden, "Ungültige Sicherheitsprüfung. Bitte die Seite neu laden.")
|
|
return
|
|
}
|
|
var in struct {
|
|
Year int `json:"year"`
|
|
Position int `json:"position"`
|
|
Force bool `json:"force"`
|
|
}
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32<<10)).Decode(&in); err != nil {
|
|
writeAdminJSONError(w, http.StatusBadRequest, "Titel konnte nicht gelesen werden.")
|
|
return
|
|
}
|
|
if in.Year < 1900 || in.Year > 2200 || in.Position < 1 || in.Position > 200 {
|
|
writeAdminJSONError(w, http.StatusBadRequest, "Jahr oder Position ist ungültig.")
|
|
return
|
|
}
|
|
var entry struct {
|
|
Artist string `json:"artist"`
|
|
Title string `json:"title"`
|
|
}
|
|
q := fmt.Sprintf(`SELECT COALESCE((SELECT json_build_object('artist',artist,'title',title) FROM chart_year_entries WHERE chart_year=%d AND position=%d LIMIT 1),'{}'::json)::text;`, in.Year, in.Position)
|
|
if err := a.database.queryJSON(r.Context(), q, &entry); err != nil || strings.TrimSpace(entry.Artist) == "" || strings.TrimSpace(entry.Title) == "" {
|
|
writeAdminJSONError(w, http.StatusNotFound, "Jahrescharttitel wurde nicht gefunden.")
|
|
return
|
|
}
|
|
if !in.Force {
|
|
if info, err := newChartStore(a.database).SongInfo(r.Context(), in.Year, in.Position); err == nil && (info.ArtistInfo != "" || info.SongInfo != "") {
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "skipped": true, "message": "Titelinformationen sind bereits vorhanden.", "data": info})
|
|
return
|
|
}
|
|
}
|
|
info, err := a.ai.generateChartSongInfo(r.Context(), entry.Artist, entry.Title)
|
|
if err != nil {
|
|
writeAdminJSONError(w, http.StatusBadGateway, "KI-Titelinfo fehlgeschlagen: "+err.Error())
|
|
return
|
|
}
|
|
cfg := a.settings.Get().OpenAI
|
|
upsert := fmt.Sprintf(`INSERT INTO chart_song_infos(chart_year,position,artist,title,artist_info,song_info,release_year,genre,dance_styles,generated_by,generated_at,updated_at) VALUES(%d,%d,%s,%s,%s,%s,%s,%s,%s,%s,now(),now()) ON CONFLICT(chart_year,position) DO UPDATE SET artist=excluded.artist,title=excluded.title,artist_info=excluded.artist_info,song_info=excluded.song_info,release_year=excluded.release_year,genre=excluded.genre,dance_styles=excluded.dance_styles,generated_by=excluded.generated_by,generated_at=now(),updated_at=now();`, in.Year, in.Position, sqlText(entry.Artist), sqlText(entry.Title), sqlText(info.ArtistInfo), sqlText(info.SongInfo), sqlNullableInteger(info.ReleaseYear), sqlText(info.Genre), sqlText(info.DanceStyles), sqlText(cfg.Model))
|
|
if _, err := a.database.exec(r.Context(), upsert); err != nil {
|
|
writeAdminJSONError(w, http.StatusInternalServerError, "Titelinfo konnte nicht gespeichert werden: "+err.Error())
|
|
return
|
|
}
|
|
a.audit(r.Context(), session, r, "chart.year.info.generate", "chart_year", 0, fmt.Sprintf("KI-Titelinfo %d/%d erzeugt", in.Year, in.Position), true)
|
|
info.ChartYear, info.Position, info.Artist, info.Title = in.Year, in.Position, entry.Artist, entry.Title
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": fmt.Sprintf("Titelinfo für Position %d wurde erzeugt.", in.Position), "data": info})
|
|
}
|
|
|
|
func sqlNullableInteger(v int) string {
|
|
if v <= 0 {
|
|
return "NULL"
|
|
}
|
|
return strconv.Itoa(v)
|
|
}
|
|
|
|
func (s *aiService) generateChartSongInfo(ctx context.Context, artist, title string) (chartSongInfo, error) {
|
|
var info chartSongInfo
|
|
cfg := s.settings.Get().OpenAI
|
|
if !cfg.Enabled || strings.TrimSpace(cfg.APIKey) == "" {
|
|
return info, fmt.Errorf("OpenAI ist in den Einstellungen nicht aktiviert")
|
|
}
|
|
schema := map[string]any{"type": "json_schema", "name": "landwelle_chart_song_info", "strict": true, "schema": map[string]any{"type": "object", "additionalProperties": false, "properties": map[string]any{
|
|
"artist_info": map[string]any{"type": "string"}, "song_info": map[string]any{"type": "string"}, "release_year": map[string]any{"type": [2]string{"integer", "null"}}, "genre": map[string]any{"type": "string"}, "dance_styles": map[string]any{"type": "string"},
|
|
}, "required": []string{"artist_info", "song_info", "release_year", "genre", "dance_styles"}}}
|
|
prompt := fmt.Sprintf("Erstelle sachliche, sendefähige Titelinformationen für Landwelle Radio. Interpret: %s. Titel: %s. Künstlerinfo und Songinfo jeweils 2 bis 4 kurze deutsche Sätze. Keine erfundenen Details. Genre und geeignete Tanzstile knapp nennen.", artist, title)
|
|
payload := map[string]any{"model": cfg.Model, "instructions": "Du recherchierst und formulierst präzise Musikinformationen für ein deutsches Radioprogramm. Antworte ausschließlich im verlangten JSON-Schema.", "input": prompt, "text": map[string]any{"format": schema}}
|
|
contents, err := s.createOpenAIResponse(ctx, cfg, payload)
|
|
if err != nil {
|
|
return info, err
|
|
}
|
|
raw, err := openAIResponseText(contents)
|
|
if err != nil {
|
|
return info, err
|
|
}
|
|
return decodeChartSongInfo(raw)
|
|
}
|