Files
landwelle/chart_features.go
T

189 lines
7.5 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
)
type chartRangeSpec struct {
MainEnd int
TotalEnd int
MainTitle string
NewTitle string
}
func chartRanges(chartKey string) chartRangeSpec {
switch normalizeAdminChartKey(chartKey) {
case "dockx":
return chartRangeSpec{MainEnd: 30, TotalEnd: 40, MainTitle: "Platz 4 bis 30", NewTitle: "Neuvorstellungen 31 bis 40"}
case "schlager":
return chartRangeSpec{MainEnd: 25, TotalEnd: 35, MainTitle: "Platz 4 bis 25", NewTitle: "Neuvorstellungen 26 bis 35"}
case "annual":
return chartRangeSpec{MainEnd: 100, TotalEnd: 100, MainTitle: "Platz 4 bis 100", NewTitle: ""}
default:
return chartRangeSpec{MainEnd: 32, TotalEnd: 45, MainTitle: "Platz 4 bis 32", NewTitle: "Neuvorstellungen 33 bis 45"}
}
}
func extendChartRangeToEntries(chartKey string, spec chartRangeSpec, entries []ChartEntry) chartRangeSpec {
if normalizeAdminChartKey(chartKey) == "annual" {
return spec
}
maxPosition := spec.TotalEnd
for _, entry := range entries {
if entry.Position > maxPosition {
maxPosition = entry.Position
}
}
if maxPosition <= spec.TotalEnd {
return spec
}
spec.TotalEnd = maxPosition
if spec.NewTitle != "" {
spec.NewTitle = fmt.Sprintf("Neuvorstellungen %d bis %d", spec.MainEnd+1, spec.TotalEnd)
}
return spec
}
func splitChartEntries(entries []ChartEntry, spec chartRangeSpec) (top, main, preview []ChartEntry) {
for _, entry := range entries {
switch {
case entry.Position >= 1 && entry.Position <= 3:
top = append(top, entry)
case entry.Position >= 4 && entry.Position <= spec.MainEnd:
main = append(main, entry)
case entry.Position > spec.MainEnd && entry.Position <= spec.TotalEnd:
preview = append(preview, entry)
}
}
return
}
func (s *chartStore) AnnualYears(ctx context.Context) ([]ChartYear, error) {
if s == nil || s.db == nil || !s.db.Enabled() {
return nil, nil
}
var years []ChartYear
query := `SELECT COALESCE(json_agg(json_build_object(
'chart_year',y.chart_year,'label',y.label,'is_active',y.is_active,'entry_count',COALESCE(c.entry_count,0)) ORDER BY y.chart_year DESC),'[]'::json)::text
FROM chart_years y LEFT JOIN (SELECT chart_year,count(*)::int AS entry_count FROM chart_year_entries GROUP BY chart_year) c ON c.chart_year=y.chart_year;`
if err := s.db.queryJSON(ctx, query, &years); err != nil {
return nil, err
}
return years, nil
}
func (s *chartStore) AnnualChart(ctx context.Context, year int) ([]ChartEntry, error) {
if s == nil || s.db == nil || !s.db.Enabled() {
return nil, nil
}
yearSQL := strconv.Itoa(year)
if year < 1900 || year > 2200 {
yearSQL = `COALESCE((SELECT max(chart_year) FROM chart_years WHERE is_active=true),(SELECT max(chart_year) FROM chart_year_entries))`
}
query := fmt.Sprintf(`SELECT COALESCE(json_agg(x ORDER BY x.position),'[]'::json) FROM (
SELECT e.id,COALESCE(e.legacy_id,0) AS legacy_id,'annual' AS chart_key,e.position,
COALESCE(e.previous_week_position,0) AS previous_position,e.position AS entry_position,e.artist,e.title,
COALESCE(e.cover_url,'') AS cover_url,COALESCE(e.preview_url,'') AS preview_url,COALESCE(e.store_url,'') AS store_url,
0 AS weeks,0 AS manual_points,COALESCE(e.fixed_points,0) AS fixed_vote_points,
COALESCE(e.entry_year,0) AS entry_year,COALESCE(e.entry_month,0) AS entry_month,
COALESCE(e.current_week_position,e.position) AS current_week_position,COALESCE(e.previous_week_position,0) AS previous_week_position,
true AS active,to_char(e.updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS updated_at,
0::float8 AS vote_average,0::int AS vote_count,COALESCE(e.fixed_points,0)::int AS vote_points,
EXISTS(SELECT 1 FROM chart_song_infos si WHERE si.chart_year=e.chart_year AND si.position=e.position AND (COALESCE(si.artist_info,'')<>'' OR COALESCE(si.song_info,'')<>'')) AS has_info,
CASE WHEN COALESCE(e.previous_week_position,0)=0 THEN 'new' WHEN e.previous_week_position>e.position THEN 'up' WHEN e.previous_week_position<e.position THEN 'down' ELSE 'same' END AS trend
FROM chart_year_entries e WHERE e.chart_year=%s AND btrim(e.artist)<>'' AND btrim(e.title)<>'' ORDER BY e.position ASC LIMIT 200) x;`, yearSQL)
var out []ChartEntry
if err := s.db.queryJSON(ctx, query, &out); err != nil {
return nil, err
}
return out, nil
}
type chartSongInfo struct {
ChartYear int `json:"chart_year"`
Position int `json:"position"`
Artist string `json:"artist"`
Title string `json:"title"`
ArtistInfo string `json:"artist_info"`
SongInfo string `json:"song_info"`
ReleaseYear int `json:"release_year"`
Genre string `json:"genre"`
DanceStyles string `json:"dance_styles"`
GeneratedBy string `json:"generated_by"`
GeneratedAt string `json:"generated_at"`
AIGenerated bool `json:"ai_generated"`
AIDisclosure string `json:"ai_disclosure"`
}
func (s *chartStore) SongInfo(ctx context.Context, year, position int) (chartSongInfo, error) {
var info chartSongInfo
if s == nil || s.db == nil || !s.db.Enabled() {
return info, fmt.Errorf("PostgreSQL ist nicht verfügbar")
}
query := fmt.Sprintf(`SELECT COALESCE((SELECT json_build_object(
'chart_year',chart_year,'position',position,'artist',artist,'title',title,'artist_info',COALESCE(artist_info,''),
'song_info',COALESCE(song_info,''),'release_year',COALESCE(release_year,0),'genre',COALESCE(genre,''),
'dance_styles',COALESCE(dance_styles,''),'generated_by',COALESCE(generated_by,''),
'generated_at',COALESCE(to_char(generated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"'),''),
'ai_generated',true,'ai_disclosure','Diese Titelinformationen wurden mit künstlicher Intelligenz erstellt und können trotz Plausibilitätsprüfung Fehler enthalten.'
) FROM chart_song_infos WHERE chart_year=%d AND position=%d LIMIT 1),'{}'::json)::text;`, year, position)
if err := s.db.queryJSON(ctx, query, &info); err != nil {
return info, err
}
if info.Position == 0 {
return info, fmt.Errorf("Für diesen Titel liegen noch keine KI-Informationen vor")
}
return info, nil
}
func chartSongInfoAPI(store *chartStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Nur GET erlaubt.")
return
}
year, _ := strconv.Atoi(r.URL.Query().Get("year"))
position, _ := strconv.Atoi(r.URL.Query().Get("position"))
if year < 1900 || year > 2200 || position < 1 || position > 200 {
writeAPIError(w, http.StatusBadRequest, "invalid_parameters", "Jahr oder Position ist ungültig.")
return
}
info, err := store.SongInfo(r.Context(), year, position)
if err != nil {
writeAPIError(w, http.StatusNotFound, "not_found", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "data": info})
}
}
func compactChartInfoText(value string) string {
return strings.TrimSpace(strings.ReplaceAll(value, "\x00", ""))
}
func decodeChartSongInfo(raw string) (chartSongInfo, error) {
var info chartSongInfo
raw = strings.TrimSpace(raw)
if start := strings.Index(raw, "{"); start >= 0 {
if end := strings.LastIndex(raw, "}"); end > start {
raw = raw[start : end+1]
}
}
if err := json.Unmarshal([]byte(raw), &info); err != nil {
return info, err
}
info.ArtistInfo = compactChartInfoText(info.ArtistInfo)
info.SongInfo = compactChartInfoText(info.SongInfo)
info.Genre = compactChartInfoText(info.Genre)
info.DanceStyles = compactChartInfoText(info.DanceStyles)
if info.ArtistInfo == "" && info.SongInfo == "" {
return info, fmt.Errorf("OpenAI lieferte keine verwertbaren Titelinformationen")
}
return info, nil
}