From 519ec0a1c5ce78f4f75e4d4833c14be4a8cfea05 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:57:39 +0200 Subject: [PATCH] fix: use only editorial event calendar in Landwelle v1.5.72 * test(events): prepare standalone manual event management v1.5.72 * refactor: keep Landwelle portal focused on editorial events * refactor(admin): simplify editorial event administration * refactor(settings): keep only active Landwelle integrations * fix(events): display only own editorial events with safe actions and pagination * fix(events): show manually entered entries only on public calendar and APIs * refactor(events): display only editorial event management * refactor(events): display only editorial event management * refactor(events): display only editorial event management * refactor(events): display only editorial event management * refactor: streamline event-only portal source files * test(events): keep only own calendar routes and preserve own event editing * test(events): keep only own calendar routes and preserve own event editing * docs(events): document editorial-only event calendar * docs: note Landwelle v1.5.72 event management cleanup * test(events): align existing admin render regression with one calendar view * fix(admin): drop obsolete settings import navigation alias --- .env.example | 9 - CHANGELOG.md | 7 + admin.go | 53 +- admin_management.go | 95 +-- admin_management_test.go | 15 - admin_render_v1563_test.go | 2 +- config/event-sources.example.yaml | 21 - destination_one.go | 722 ------------------ destination_one_test.go | 183 ----- docs/EVENT_CALENDAR.md | 49 +- docs/NIEDERSACHSEN_HUB.md | 23 - events.go | 8 +- events_manual_only_v1572_test.go | 43 ++ main.go | 13 +- main_test.go | 2 +- .../0047_only_manual_events_navigation.sql | 7 + settings.go | 40 - tourism_hub.go | 406 ---------- tourism_hub_test.go | 76 -- web/admin/management.html | 16 +- web/admin/settings.html | 17 +- web/admin/tourism.html | 31 - web/assets/tourism-hub-v1.css | 7 - web/tourism.html | 59 -- 24 files changed, 114 insertions(+), 1790 deletions(-) delete mode 100644 config/event-sources.example.yaml delete mode 100644 destination_one.go delete mode 100644 destination_one_test.go delete mode 100644 docs/NIEDERSACHSEN_HUB.md create mode 100644 events_manual_only_v1572_test.go create mode 100644 migrations/0047_only_manual_events_navigation.sql delete mode 100644 tourism_hub.go delete mode 100644 tourism_hub_test.go delete mode 100644 web/admin/tourism.html delete mode 100644 web/assets/tourism-hub-v1.css delete mode 100644 web/tourism.html diff --git a/.env.example b/.env.example index effb44f..99bd692 100644 --- a/.env.example +++ b/.env.example @@ -124,15 +124,6 @@ LANDWELLE_PUBLIC_URL=https://landwelle.de GOOGLE_SITE_VERIFICATION= BING_SITE_VERIFICATION= -# Niedersachsen Hub / destination.one -LANDWELLE_DESTINATION_ONE_ENABLED=false -LANDWELLE_DESTINATION_ONE_API_URL=https://meta.et4.de/rest.ashx/search/ET2014A.json/ -LANDWELLE_DESTINATION_ONE_API_KEY= -LANDWELLE_DESTINATION_ONE_KEY_PARAMETER=licensekey -LANDWELLE_DESTINATION_ONE_EXPERIENCE= -LANDWELLE_DESTINATION_ONE_EXPERIENCE_PARAMETER=experience -LANDWELLE_DESTINATION_ONE_INTERVAL_MINUTES=360 - # Landwelle OnTour / öffentlicher YouTube-Kanal LANDWELLE_YOUTUBE_CHANNEL_URL=https://www.youtube.com/@landwelle LANDWELLE_YOUTUBE_CHANNEL_ID= diff --git a/CHANGELOG.md b/CHANGELOG.md index 01285ca..c97acdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## v1.5.72 +- Niedersachsen-HUB-Integration und irrtümlich ergänzten Tourismusbereich vollständig aus Website, Adminverwaltung, Konfiguration und Importlogik entfernt. +- Veranstaltungen zeigen nur eigene redaktionelle Einträge und Einsendungen; alle vorhandenen Erstellen-, Bearbeiten-, Freigeben- und Löschen-Funktionen bleiben erhalten. +- Öffentliche Veranstaltungssuche, Kalender und Startseite schließen früher importierte Fremdtermine aus. +- Migration 0047 entfernt nur den historischen Tourismuseintrag aus der Navigation; gespeicherte Fremddaten werden nicht automatisch gelöscht. +- Neue Regressionstests für rein redaktionelle Veranstaltungen. + ## v1.5.70 – Webplayer endgültig auf aktuelle Stream-Logik umgestellt - Die Startseite lädt jetzt `app-v18.js` statt der veralteten `app-v16.js`. diff --git a/admin.go b/admin.go index 1b23ae0..b2d1e1d 100644 --- a/admin.go +++ b/admin.go @@ -82,7 +82,6 @@ type adminHandler struct { users *userStore team *teamStore forum *forumStore - destinationOne *destinationOneImporter newsStudio *newsStudioStore aiJobs *aiJobStore firebasePush *firebasePushService @@ -185,7 +184,6 @@ type adminSettingsData struct { SettingsPath string OpenAIKeySet bool ElevenLabsKeySet bool - DestinationOneKeySet bool Error string Success string OpenAIModels []providerModel @@ -365,7 +363,6 @@ func newAdminHandler(logger *log.Logger, weather *WeatherService, data PageData, var database *postgresStore var team *teamStore var forum *forumStore - var destinationOne *destinationOneImporter var navigation *navigationStore var directory *directoryStore for _, extra := range extras { @@ -388,8 +385,6 @@ func newAdminHandler(logger *log.Logger, weather *WeatherService, data PageData, team = value case *forumStore: forum = value - case *destinationOneImporter: - destinationOne = value case *navigationStore: navigation = value case *directoryStore: @@ -573,7 +568,6 @@ func newAdminHandler(logger *log.Logger, weather *WeatherService, data PageData, users: newUserStore(database), team: team, forum: forum, - destinationOne: destinationOne, newsStudio: newsStudio, aiJobs: newAIJobStore(), firebasePush: firebasePush, @@ -594,7 +588,6 @@ func (a *adminHandler) register(mux *http.ServeMux) { mux.HandleFunc("/admin/downloads", a.withPermission("downloads.manage", a.adminDownloads)) mux.HandleFunc("/admin/app/push", a.withPermission("settings.manage", a.adminAppPush)) mux.HandleFunc("/admin/settings", a.withPermission("settings.manage", a.adminSettings)) - mux.HandleFunc("/admin/settings/import-events", a.withPermission("settings.manage", a.adminSettingsImportEvents)) mux.HandleFunc("/admin/settings/background-music", a.withPermission("settings.manage", a.adminBackgroundMusic)) mux.HandleFunc("/admin/ai", a.withPermission("ai.use", a.adminAI)) mux.HandleFunc("/admin/ai/news", a.withPermission("ai.use", a.adminNewsStudio)) @@ -629,7 +622,6 @@ func (a *adminHandler) register(mux *http.ServeMux) { mux.HandleFunc("/admin/api/charts/generate", a.adminChartsGenerate) mux.HandleFunc("/admin/api/charts/year-info/generate", a.adminChartYearInfoGenerate) mux.HandleFunc("/admin/events", a.adminManagement) - mux.HandleFunc("/admin/niedersachsen-hub", a.withPermission("settings.manage", a.adminTourismHub)) mux.HandleFunc("/admin/excursions", a.withPermission("excursions.manage", a.adminExcursions)) mux.HandleFunc("/admin/navigation", a.withPermission("navigation.manage", a.adminNavigation)) mux.HandleFunc("/admin/directory", a.withPermission("directory.manage", a.adminDirectory)) @@ -1478,16 +1470,6 @@ func (a *adminHandler) adminSettings(w http.ResponseWriter, r *http.Request) { next.Social.FacebookAPIVersion = r.FormValue("facebook_api_version") next.Social.PublicBaseURL = r.FormValue("social_public_base_url") next.Social.WhatsAppChannelURL = r.FormValue("whatsapp_channel_url") - next.DestinationOne.Enabled = r.FormValue("destination_one_enabled") == "on" - next.DestinationOne.APIURL = r.FormValue("destination_one_api_url") - if value := strings.TrimSpace(r.FormValue("destination_one_api_key")); value != "" { - next.DestinationOne.APIKey = value - } - next.DestinationOne.KeyParameter = r.FormValue("destination_one_key_parameter") - next.DestinationOne.Experience = r.FormValue("destination_one_experience") - next.DestinationOne.ExperienceParam = r.FormValue("destination_one_experience_parameter") - next.DestinationOne.IntervalMinutes, _ = strconv.Atoi(r.FormValue("destination_one_interval_minutes")) - next.DestinationOne.AutoPublish = r.FormValue("destination_one_auto_publish") == "on" labels := r.Form["voice_label"] ids := r.Form["voice_id"] purposes := r.Form["voice_purpose"] @@ -1540,7 +1522,6 @@ func (a *adminHandler) renderSettings(w http.ResponseWriter, session adminSessio data.SettingsPath = a.settings.Path() data.OpenAIKeySet = data.Settings.OpenAI.APIKey != "" data.ElevenLabsKeySet = data.Settings.ElevenLabs.APIKey != "" - data.DestinationOneKeySet = data.Settings.DestinationOne.APIKey != "" ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() if models, err := a.ai.ListOpenAIModels(ctx); err == nil { @@ -1553,7 +1534,6 @@ func (a *adminHandler) renderSettings(w http.ResponseWriter, session adminSessio } data.Settings.OpenAI.APIKey = "" data.Settings.ElevenLabs.APIKey = "" - data.Settings.DestinationOne.APIKey = "" setAdminHTMLHeaders(w) if err := a.settingsTemplate.ExecuteTemplate(w, "settings-admin.html", data); err != nil { a.logger.Printf("admin settings template: %v", err) @@ -2597,7 +2577,7 @@ func adminNavigationHTML() string { Redaktion Redaktion & BeiträgeMediathekMediengaleriePressebereichKarriereFAQKontakt & AnfragenTeam Planung & Verzeichnisse -ProgrammVeranstaltungenNiedersachsen Hub · TourismusAusflugstippsBranchenbuchWebsite-Navigation +ProgrammVeranstaltungenAusflugstippsBranchenbuchWebsite-Navigation
♫Hörer & CommunityCharts, Wünsche und Forum⌄
Höreraktionen @@ -2621,7 +2601,7 @@ func adminNavigationHTML() string {
⚙System & BetriebEinstellungen, Aufgaben und Kontrolle⌄
Konfiguration -Allgemeine EinstellungenOpenAI & ElevenLabsSMTP & FTP +Allgemeine EinstellungenOpenAI & ElevenLabsSMTP & FTP Betrieb Reichweite & StatistikTodo-ListeAudit-Protokoll
@@ -3035,35 +3015,6 @@ func (a *adminHandler) adminNewsStudio(w http.ResponseWriter, r *http.Request) { render() } -func (a *adminHandler) adminSettingsImportEvents(w http.ResponseWriter, r *http.Request) { - _, session, ok := a.sessionFromRequest(r) - if !ok { - http.Redirect(w, r, "/admin/login", http.StatusSeeOther) - return - } - if r.Method != http.MethodPost { - http.Error(w, "Methode nicht erlaubt", http.StatusMethodNotAllowed) - return - } - _ = r.ParseForm() - if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf_token")), []byte(session.CSRFToken)) != 1 { - http.Error(w, "Ungültige Sicherheitsprüfung", http.StatusForbidden) - return - } - if a.destinationOne == nil { - a.renderSettings(w, session, adminSettingsData{Settings: a.settings.Get(), Error: "destination.one ist nicht verfügbar."}) - return - } - ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) - defer cancel() - n, err := a.destinationOne.Sync(ctx) - if err != nil { - a.renderSettings(w, session, adminSettingsData{Settings: a.settings.Get(), Error: "Import fehlgeschlagen: " + err.Error()}) - return - } - a.renderSettings(w, session, adminSettingsData{Settings: a.settings.Get(), Success: fmt.Sprintf("Import abgeschlossen: %d Veranstaltungen verarbeitet.", n)}) -} - func (a *adminHandler) adminBackgroundMusic(w http.ResponseWriter, r *http.Request) { _, session, ok := a.sessionFromRequest(r) if !ok { diff --git a/admin_management.go b/admin_management.go index 5a427d9..8ed2f5e 100644 --- a/admin_management.go +++ b/admin_management.go @@ -129,8 +129,6 @@ type adminManagementData struct { CurrentYear int Events []AdminEventRow EventCategories []EventCategory - EventTab string - HubCount int SubmissionCount int EventPage, EventPerPage, EventTotalPages int EventHasPrev, EventHasNext bool @@ -220,7 +218,6 @@ func (a *adminHandler) adminManagement(w http.ResponseWriter, r *http.Request) { spec := chartRanges(data.ChartKey) data.ChartMainEnd, data.ChartTotalEnd = spec.MainEnd, spec.TotalEnd data.ChartMainTitle, data.ChartPreviewTitle = spec.MainTitle, spec.NewTitle - data.EventTab = normalizeEventAdminTab(r.URL.Query().Get("tab")) data.EventPage, _ = strconv.Atoi(r.URL.Query().Get("page")) if data.EventPage < 1 { data.EventPage = 1 @@ -247,9 +244,6 @@ func (a *adminHandler) adminManagement(w http.ResponseWriter, r *http.Request) { http.Error(w, "Ungültige Sicherheitsprüfung", 403) return } - if module == "events" && strings.TrimSpace(r.FormValue("event_tab")) != "" { - data.EventTab = normalizeEventAdminTab(r.FormValue("event_tab")) - } if module == "events" { if postedPage, err := strconv.Atoi(r.FormValue("event_page")); err == nil && postedPage > 0 { data.EventPage = postedPage @@ -279,7 +273,7 @@ func (a *adminHandler) adminManagement(w http.ResponseWriter, r *http.Request) { redirectURL += "&year=" + strconv.Itoa(data.SelectedYear) } if module == "events" { - redirectURL = fmt.Sprintf("/admin/events?saved=1&tab=%s&page=%d", data.EventTab, data.EventPage) + redirectURL = fmt.Sprintf("/admin/events?saved=1&page=%d", data.EventPage) } http.Redirect(w, r, redirectURL, 303) return @@ -346,31 +340,19 @@ func (a *adminHandler) adminManagement(w http.ResponseWriter, r *http.Request) { data.ChartCanGenerate, data.ChartLastGenerated, data.ChartNextGenerate = a.chartGenerationStatus(r.Context(), data.ChartKey) } case "events": - _ = a.cleanupExpiredHubEvents(r.Context()) - data.HubCount, data.SubmissionCount, _ = a.countAdminEvents(r.Context()) - total := data.HubCount - if data.EventTab == "submissions" { - total = data.SubmissionCount - } + data.SubmissionCount, _ = a.countAdminEvents(r.Context()) + total := data.SubmissionCount data.EventTotalPages = (total + data.EventPerPage - 1) / data.EventPerPage - if data.EventTotalPages < 1 { - data.EventTotalPages = 1 - } - if data.EventPage > data.EventTotalPages { - data.EventPage = data.EventTotalPages - } + if data.EventTotalPages < 1 {data.EventTotalPages = 1} + if data.EventPage > data.EventTotalPages {data.EventPage = data.EventTotalPages} data.EventHasPrev = data.EventPage > 1 data.EventHasNext = data.EventPage < data.EventTotalPages - data.EventPrevURL = fmt.Sprintf("/admin/events?tab=%s&page=%d", data.EventTab, data.EventPage) - data.EventNextURL = fmt.Sprintf("/admin/events?tab=%s&page=%d", data.EventTab, data.EventPage) - if data.EventHasPrev { - data.EventPrevURL = fmt.Sprintf("/admin/events?tab=%s&page=%d", data.EventTab, data.EventPage-1) - } - if data.EventHasNext { - data.EventNextURL = fmt.Sprintf("/admin/events?tab=%s&page=%d", data.EventTab, data.EventPage+1) - } + data.EventPrevURL = fmt.Sprintf("/admin/events?page=%d", data.EventPage) + data.EventNextURL = fmt.Sprintf("/admin/events?page=%d", data.EventPage) + if data.EventHasPrev {data.EventPrevURL = fmt.Sprintf("/admin/events?page=%d", data.EventPage-1)} + if data.EventHasNext {data.EventNextURL = fmt.Sprintf("/admin/events?page=%d", data.EventPage+1)} data.EventPages = compactAdminPages(data.EventPage, data.EventTotalPages) - data.Events, _ = a.listAdminEvents(r.Context(), data.EventTab, data.EventPage, data.EventPerPage) + data.Events, _ = a.listAdminEvents(r.Context(), data.EventPage, data.EventPerPage) data.EventCategories, _ = newEventStore(a.database).Categories(r.Context(), true) case "audit": var auditErr error @@ -687,54 +669,25 @@ func (a *adminHandler) listChartYearEntries(ctx context.Context, year int) ([]Ch return out, a.database.queryJSON(ctx, query, &out) } -func normalizeEventAdminTab(tab string) string { - switch strings.ToLower(strings.TrimSpace(tab)) { - case "submissions", "own", "eingaben", "einsendungen": - return "submissions" - default: - return "hub" - } +func (a *adminHandler) countAdminEvents(ctx context.Context) (int, error) { + var count int + q := `SELECT count(*)::text FROM landwelle.event_submissions WHERE source_type IN ('submission','editorial') AND COALESCE(end_at,start_at)>=now()-interval '30 days';` + err := a.database.queryJSON(ctx, q, &count) + return count, err } -func (a *adminHandler) cleanupExpiredHubEvents(ctx context.Context) error { - if a.database == nil || !a.database.Enabled() { - return nil - } - _, err := a.database.exec(ctx, `DELETE FROM landwelle.event_submissions WHERE source_type='open_data' AND COALESCE(NULLIF(end_at,start_at), date_trunc('day',start_at)+interval '1 day') <= now();`) - return err -} - -func (a *adminHandler) countAdminEvents(ctx context.Context) (int, int, error) { - var counts struct { - Hub int `json:"hub"` - Submissions int `json:"submissions"` - } - q := `SELECT json_build_object( -'hub',count(*) FILTER (WHERE source_type='open_data' AND COALESCE(NULLIF(end_at,start_at), date_trunc('day',start_at)+interval '1 day')>now()), -'submissions',count(*) FILTER (WHERE source_type<>'open_data' AND COALESCE(end_at,start_at)>=now()-interval '30 days')) -FROM landwelle.event_submissions;` - if err := a.database.queryJSON(ctx, q, &counts); err != nil { - return 0, 0, err - } - return counts.Hub, counts.Submissions, nil -} - -func (a *adminHandler) listAdminEvents(ctx context.Context, tab string, page, perPage int) ([]AdminEventRow, error) { - var out []AdminEventRow - where := `source_type='open_data' AND COALESCE(NULLIF(end_at,start_at), date_trunc('day',start_at)+interval '1 day')>now()` - order := `start_at ASC` - if normalizeEventAdminTab(tab) == "submissions" { - where = `source_type<>'open_data' AND COALESCE(end_at,start_at)>=now()-interval '30 days'` - order = `CASE status WHEN 'pending' THEN 0 WHEN 'rejected' THEN 1 ELSE 2 END, created_at DESC` - } - q := `SELECT COALESCE(json_agg(json_build_object( +func (a *adminHandler) listAdminEvents(ctx context.Context, page, perPage int) ([]AdminEventRow, error) { + var out []AdminEventRow + where := `source_type IN ('submission','editorial') AND COALESCE(end_at,start_at)>=now()-interval '30 days'` + order := `CASE status WHEN 'pending' THEN 0 WHEN 'rejected' THEN 1 ELSE 2 END, created_at DESC` + q := `SELECT COALESCE(json_agg(json_build_object( 'id',paged.id,'title',paged.title,'category',paged.category,'city',paged.city,'status',paged.status,'source_name',paged.source_name,'source_type',paged.source_type, 'venue',paged.venue,'website',paged.website,'description',paged.description,'start_at',paged.start_at,'end_at',paged.end_at, 'postal_code',paged.postal_code,'organizer',paged.organizer,'contact_name',paged.contact_name,'contact_email',paged.contact_email,'contact_phone',paged.contact_phone, 'external_image_url',paged.external_image_url,'image_url',CASE WHEN paged.image_path<>'' THEN '/event-media/'||paged.image_path ELSE paged.external_image_url END, 'homepage_favorite',paged.homepage_favorite) ORDER BY ` + order + `),'[]'::json)::text FROM (SELECT * FROM landwelle.event_submissions WHERE ` + where + ` ORDER BY ` + order + fmt.Sprintf(` LIMIT %d OFFSET %d) paged;`, perPage, (page-1)*perPage) - return out, a.database.queryJSON(ctx, q, &out) + return out, a.database.queryJSON(ctx, q, &out) } func saveAdminEventGraphic(r *http.Request) (string, error) { @@ -906,7 +859,7 @@ RETURNING c.id imageSQL = ",image_path=" + sqlText(imagePath) } status := normalizeAdminEventStatus(r.FormValue("status")) - q := fmt.Sprintf(`UPDATE landwelle.event_submissions SET title=%s,category=%s,start_at=%s::timestamptz,end_at=%s,city=%s,venue=%s,postal_code=%s,organizer=%s,contact_name=%s,contact_email=%s,contact_phone=%s,website=%s,external_image_url=%s,description=%s,status=%s%s,updated_at=now() WHERE id=%d RETURNING id;`, + q := fmt.Sprintf(`UPDATE landwelle.event_submissions SET title=%s,category=%s,start_at=%s::timestamptz,end_at=%s,city=%s,venue=%s,postal_code=%s,organizer=%s,contact_name=%s,contact_email=%s,contact_phone=%s,website=%s,external_image_url=%s,description=%s,status=%s%s,updated_at=now() WHERE id=%d AND source_type IN ('submission','editorial') RETURNING id;`, sqlText(title), sqlText(r.FormValue("category")), sqlText(startAt.Format(time.RFC3339)), endSQL, sqlText(city), sqlText(r.FormValue("venue")), sqlText(r.FormValue("postal_code")), sqlText(r.FormValue("organizer")), sqlText(r.FormValue("contact_name")), sqlText(r.FormValue("contact_email")), sqlText(r.FormValue("contact_phone")), sqlText(r.FormValue("website")), sqlText(r.FormValue("external_image_url")), sqlText(description), sqlText(status), imageSQL, id) if _, err := a.database.exec(r.Context(), q); err != nil { return err.Error() @@ -949,7 +902,7 @@ RETURNING id a.audit(r.Context(), s, r, actionName, "event", id, summary, true) return "" case "delete": - deleted, err := a.database.exec(r.Context(), fmt.Sprintf("DELETE FROM landwelle.event_submissions WHERE id=%d RETURNING id;", id)) + deleted, err := a.database.exec(r.Context(), fmt.Sprintf("DELETE FROM landwelle.event_submissions WHERE id=%d AND source_type IN ('submission','editorial') RETURNING id;", id)) if err != nil { return err.Error() } @@ -961,7 +914,7 @@ RETURNING id default: return "Unbekannte Veranstaltungsaktion." } - if _, err := a.database.exec(r.Context(), fmt.Sprintf("UPDATE landwelle.event_submissions SET status=%s,updated_at=now() WHERE id=%d RETURNING id;", sqlText(status), id)); err != nil { + if _, err := a.database.exec(r.Context(), fmt.Sprintf("UPDATE landwelle.event_submissions SET status=%s,updated_at=now() WHERE id=%d AND source_type IN ('submission','editorial') RETURNING id;", sqlText(status), id)); err != nil { return err.Error() } a.audit(r.Context(), s, r, "event.status", "event", id, "Veranstaltungsstatus geändert: "+status, true) diff --git a/admin_management_test.go b/admin_management_test.go index 55d8bcc..72d11a1 100644 --- a/admin_management_test.go +++ b/admin_management_test.go @@ -5,21 +5,6 @@ import ( "testing" ) -func TestNormalizeEventAdminTab(t *testing.T) { - tests := map[string]string{ - "": "hub", - "hub": "hub", - "submissions": "submissions", - "Einsendungen": "submissions", - "unknown": "hub", - } - for input, want := range tests { - if got := normalizeEventAdminTab(input); got != want { - t.Fatalf("normalizeEventAdminTab(%q)=%q, want %q", input, got, want) - } - } -} - func TestAdminEventRowMapsSourceTypeFromDatabaseJSON(t *testing.T) { var rows []AdminEventRow payload := `[{ diff --git a/admin_render_v1563_test.go b/admin_render_v1563_test.go index f50fb53..60cc025 100644 --- a/admin_render_v1563_test.go +++ b/admin_render_v1563_test.go @@ -49,7 +49,7 @@ func TestEventManagementTemplateRendersCompleteRowsAndCategories(t *testing.T) { end := time.Date(2026, 10, 1, 20, 0, 0, 0, time.Local) data := adminManagementData{ Username: "Jens", CSRFToken: "csrf", Module: "events", DatabaseReady: true, - EventTab: "submissions", EventPage: 1, EventTotalPages: 1, SubmissionCount: 1, + EventPage: 1, EventTotalPages: 1, SubmissionCount: 1, EventCategories: []EventCategory{{ID: 1, Name: "Tradition", SortOrder: 10, Active: true, EventCount: 1}}, Events: []AdminEventRow{{ ID: 1, Title: "Bauernmarkt", Category: "Tradition", City: "Visselhövede", Status: "published", diff --git a/config/event-sources.example.yaml b/config/event-sources.example.yaml deleted file mode 100644 index 951e9b9..0000000 --- a/config/event-sources.example.yaml +++ /dev/null @@ -1,21 +0,0 @@ -sources: - - id: niedersachsen-hub - name: Niedersachsen Hub / Open Data-Finder - type: open_data - enabled: false - region: Niedersachsen - notes: API-Zugang und Lizenzfreigabe vor Aktivierung klären. - - id: reiseland-niedersachsen - name: Reiseland Niedersachsen Veranstaltungskalender - type: official_calendar - url: https://www.reiseland-niedersachsen.de/veranstaltungen - enabled: false - region: Niedersachsen - notes: Bevorzugt über Niedersachsen Hub/Open Data beziehen, nicht ungefragt scrapen. - - id: local-ical-example - name: Kommunaler iCal-Feed - type: ical - url: https://example.invalid/events.ics - enabled: false - region: Niedersachsen - notes: Durch einen freigegebenen offiziellen Feed ersetzen. diff --git a/destination_one.go b/destination_one.go deleted file mode 100644 index e6a284e..0000000 --- a/destination_one.go +++ /dev/null @@ -1,722 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "fmt" - stdhtml "html" - "io" - "log" - "net/http" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "time" -) - -type destinationOneImporter struct { - settings *settingsStore - store *eventStore - logger *log.Logger - client *http.Client - wake, stop, done chan struct{} - once sync.Once -} - -func newDestinationOneImporter(settings *settingsStore, store *eventStore, logger *log.Logger) *destinationOneImporter { - return &destinationOneImporter{settings: settings, store: store, logger: logger, client: &http.Client{Timeout: 45 * time.Second}, wake: make(chan struct{}, 1), stop: make(chan struct{}), done: make(chan struct{})} -} -func (i *destinationOneImporter) Start() { - if i == nil || i.store == nil || i.store.db == nil || !i.store.db.Enabled() { - return - } - go func() { - defer close(i.done) - i.runOnce(context.Background()) - for { - m := i.settings.Get().DestinationOne.IntervalMinutes - if m < 15 { - m = 360 - } - t := time.NewTimer(time.Duration(m) * time.Minute) - select { - case <-t.C: - i.runOnce(context.Background()) - case <-i.wake: - if !t.Stop() { - select { - case <-t.C: - default: - } - } - i.runOnce(context.Background()) - case <-i.stop: - if !t.Stop() { - select { - case <-t.C: - default: - } - } - return - } - } - }() -} -func (i *destinationOneImporter) Wake() { - if i != nil { - select { - case i.wake <- struct{}{}: - default: - } - } -} -func (i *destinationOneImporter) Stop(ctx context.Context) { - if i == nil { - return - } - i.once.Do(func() { close(i.stop) }) - select { - case <-i.done: - case <-ctx.Done(): - } -} -func (i *destinationOneImporter) runOnce(parent context.Context) { - if !i.settings.Get().DestinationOne.Enabled { - return - } - ctx, cancel := context.WithTimeout(parent, 2*time.Minute) - defer cancel() - n, err := i.Sync(ctx) - if err != nil { - i.logger.Printf("destination.one Import: %v", err) - } else { - i.logger.Printf("destination.one Import: %d Veranstaltungen verarbeitet", n) - } -} -func (i *destinationOneImporter) Sync(ctx context.Context) (int, error) { - cfg := i.settings.Get().DestinationOne - if !cfg.Enabled { - return 0, errors.New("destination.one ist nicht aktiviert") - } - if strings.TrimSpace(cfg.APIKey) == "" { - return 0, errors.New("destination.one Lizenzschlüssel fehlt") - } - - baseURL, err := destinationOneURL(cfg) - if err != nil { - return 0, err - } - - const pageSize = 100 - const maxPages = 50 - total := 0 - seen := map[string]struct{}{} - var lastTopKeys []string - - for page := 0; page < maxPages; page++ { - u := *baseURL - q := u.Query() - q.Set("limit", strconv.Itoa(pageSize)) - q.Set("offset", strconv.Itoa(page*pageSize)) - u.RawQuery = q.Encode() - - req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) - if err != nil { - return total, err - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", "Landwelle-Radio/1.1") - resp, err := i.client.Do(req) - if err != nil { - return total, fmt.Errorf("API-Aufruf fehlgeschlagen: %w", err) - } - body, readErr := io.ReadAll(io.LimitReader(resp.Body, 32<<20)) - resp.Body.Close() - if readErr != nil { - return total, fmt.Errorf("API-Antwort konnte nicht gelesen werden: %w", readErr) - } - if resp.StatusCode < 200 || resp.StatusCode > 299 { - preview := strings.TrimSpace(string(body)) - if len(preview) > 1200 { - preview = preview[:1200] - } - return total, fmt.Errorf("API antwortet mit %s: %s", resp.Status, preview) - } - - var payload any - if err := json.Unmarshal(body, &payload); err != nil { - preview := strings.TrimSpace(string(body)) - if len(preview) > 500 { - preview = preview[:500] - } - return total, fmt.Errorf("API liefert kein gültiges JSON. Prüfe, ob die URL das JSON-Template verwendet: %w (%s)", err, preview) - } - lastTopKeys = destinationTopKeys(payload) - items := destinationMaps(payload) - if len(items) == 0 { - if page == 0 { - return 0, fmt.Errorf("API-Verbindung funktioniert, aber der ET2014A-Parser v5 fand im Feld items keine Datensätze. Erkannte Antwortfelder: %s", strings.Join(lastTopKeys, ", ")) - } - break - } - - processedThisPage := 0 - parseErrors := map[string]int{} - for _, m := range items { - e, id, img, lic, err := parseDestinationEvent(m) - if err != nil { - parseErrors[err.Error()]++ - continue - } - if _, exists := seen[id]; exists { - continue - } - seen[id] = struct{}{} - status := "pending" - if cfg.AutoPublish { - status = "published" - } - if err = i.store.UpsertExternal(ctx, e, id, img, lic, status); err != nil { - return total, fmt.Errorf("Veranstaltung konnte nicht gespeichert werden. Wurde Migration 0014 ausgeführt? %w", err) - } - total++ - processedThisPage++ - } - if processedThisPage == 0 { - reasons := make([]string, 0, len(parseErrors)) - for reason, count := range parseErrors { - reasons = append(reasons, fmt.Sprintf("%dx %s", count, reason)) - } - sort.Strings(reasons) - if len(reasons) > 5 { - reasons = reasons[:5] - } - return total, fmt.Errorf("destination.one lieferte %d Event-Datensätze, aber keiner konnte übernommen werden. Gründe: %s", len(items), strings.Join(reasons, "; ")) - } - if len(items) < pageSize { - break - } - } - if i.store != nil && i.store.db != nil && i.store.db.Enabled() { - _, _ = i.store.db.exec(ctx, `DELETE FROM landwelle.event_submissions WHERE source_type='open_data' AND COALESCE(end_at,start_at) < now();`) - } - return total, nil -} - -func destinationOneURL(cfg DestinationOneSettings) (*url.URL, error) { - if strings.TrimSpace(cfg.APIKey) == "" { - return nil, errors.New("destination.one Lizenzschlüssel fehlt") - } - u, err := url.Parse("https://meta.et4.de/rest.ashx/search/") - if err != nil { - return nil, errors.New("destination.one API-URL ist ungültig") - } - q := u.Query() - q.Set("experience", "open-data-niedersachsen-tourismus") - q.Set("licensekey", strings.TrimSpace(cfg.APIKey)) - q.Set("type", "Event") - q.Set("template", "ET2014A.json") - u.RawQuery = q.Encode() - return u, nil -} - -func destinationTopKeys(v any) []string { - m, ok := v.(map[string]any) - if !ok { - return []string{"Antwort ist keine Objektstruktur"} - } - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - if len(keys) > 12 { - keys = keys[:12] - } - return keys -} - -func destinationMaps(v any) []map[string]any { - root, ok := v.(map[string]any) - if !ok { - return nil - } - container, found := d1ValueCaseInsensitive(root, "items") - if !found { - return nil - } - out := make([]map[string]any, 0) - switch typed := container.(type) { - case []any: - for _, raw := range typed { - if item, ok := raw.(map[string]any); ok { - out = append(out, item) - } - } - case map[string]any: - if child, ok := d1ValueCaseInsensitive(typed, "item"); ok { - if list, ok := child.([]any); ok { - for _, raw := range list { - if item, ok := raw.(map[string]any); ok { - out = append(out, item) - } - } - } - } else { - out = append(out, typed) - } - } - return out -} - -func d1ValueCaseInsensitive(m map[string]any, wanted string) (any, bool) { - if value, ok := m[wanted]; ok { - return value, true - } - for key, value := range m { - if strings.EqualFold(strings.TrimSpace(key), wanted) { - return value, true - } - } - return nil, false -} - -func d1FirstStringCI(m map[string]any, keys ...string) string { - for _, key := range keys { - value, ok := d1ValueCaseInsensitive(m, key) - if !ok { - continue - } - switch typed := value.(type) { - case string: - if text := strings.TrimSpace(typed); text != "" { - return text - } - case map[string]any: - if text := d1FirstStringCI(typed, "value", "name", "title", "url", "text"); text != "" { - return text - } - } - } - return "" -} - -func parseDestinationEvent(m map[string]any) (EventSubmission, string, string, string, error) { - e := EventSubmission{ - Title: d1FirstStringCI(m, "title", "name", "headline"), - Description: d1TextByRel(m, "details", "detail", "teaser", "description", "shortdescription"), - Website: d1URL(m), - Organizer: d1NestedString(m, []string{"organizer", "author", "provider", "source", "owner"}, "name", "title", "value"), - Category: d1Category(m), - } - if e.Description == "" { - e.Description = d1FirstString(m, "description", "text", "shortDescription", "longDescription", "body") - } - e.Description = normalizeDestinationText(e.Description) - if strings.TrimSpace(e.Title) == "" { - return e, "", "", "", errors.New("Titel fehlt") - } - if e.Category == "" || strings.EqualFold(e.Category, "Event") { - e.Category = "Sonstiges" - } - id := d1FirstStringCI(m, "global_id", "globalId", "id", "identifier", "uuid") - - startValue, endValue := d1EventTimes(m) - var err error - e.StartAt, err = parseFlexTime(startValue) - if err != nil { - return e, "", "", "", fmt.Errorf("Startdatum fehlt oder ist ungültig: %w", err) - } - e.EndAt, _ = parseFlexTime(endValue) - - address := d1Address(m) - e.Venue = d1FirstString(m, "venue", "locationName", "placeName") - e.City = d1FirstString(m, "city", "locality", "town") - e.PostalCode = d1FirstString(m, "postalCode", "postal_code", "zip") - if address != nil { - if e.Venue == "" { - e.Venue = d1FirstString(address, "name", "venue", "locationName", "company") - } - if e.City == "" { - e.City = d1FirstString(address, "city", "addressLocality", "locality", "town", "municipality") - } - if e.PostalCode == "" { - e.PostalCode = d1FirstString(address, "postalCode", "zip", "postal_code") - } - } - if e.City == "" { - // ET2014A kann den Ort zusätzlich in relations/locations ablegen. - e.City = d1RecursiveStringForKeys(m, "city", "addressLocality", "locality", "town", "municipality") - } - if e.Venue == "" { - e.Venue = d1RecursiveStringForKeys(m, "venue", "locationName", "placeName") - } - if e.PostalCode == "" { - e.PostalCode = d1RecursiveStringForKeys(m, "postalCode", "postal_code", "zip") - } - if e.City == "" { - return e, "", "", "", errors.New("Ort fehlt") - } - if id == "" { - id = e.Title + "|" + e.StartAt.Format(time.RFC3339) - } - return e, id, extractImage(m), d1License(m), nil -} - -var ( - d1BreakTagPattern = regexp.MustCompile(`(?is)<\s*(?:br\s*/?|/p|/div|/li|/ul|/ol|/h[1-6]|/section|/article|/tr)\s*>`) - d1ListItemPattern = regexp.MustCompile(`(?is)<\s*li(?:\s+[^>]*)?>`) - d1BlockStartPattern = regexp.MustCompile(`(?is)<\s*(?:p|div|ul|ol|h[1-6]|section|article|tr)(?:\s+[^>]*)?>`) - d1AnyTagPattern = regexp.MustCompile(`(?is)<[^>]+>`) - d1ManySpacesPattern = regexp.MustCompile(`[\t\r ]+`) - d1ManyNewlinesPattern = regexp.MustCompile(`\n{3,}`) -) - -func normalizeDestinationText(value string) string { - value = strings.TrimSpace(value) - if value == "" { - return "" - } - value = d1BreakTagPattern.ReplaceAllString(value, "\n") - value = d1ListItemPattern.ReplaceAllString(value, "\n• ") - value = d1BlockStartPattern.ReplaceAllString(value, "\n") - value = d1AnyTagPattern.ReplaceAllString(value, "") - value = stdhtml.UnescapeString(value) - value = strings.ReplaceAll(value, "\u00a0", " ") - lines := strings.Split(value, "\n") - cleaned := make([]string, 0, len(lines)) - for _, line := range lines { - line = strings.TrimSpace(d1ManySpacesPattern.ReplaceAllString(line, " ")) - if line != "" { - cleaned = append(cleaned, line) - } - } - value = strings.Join(cleaned, "\n") - return strings.TrimSpace(d1ManyNewlinesPattern.ReplaceAllString(value, "\n\n")) -} - -func d1TextByRel(m map[string]any, rels ...string) string { - wanted := map[string]int{} - for idx, rel := range rels { - wanted[strings.ToLower(rel)] = idx + 1 - } - bestRank := 1 << 30 - best := "" - for _, key := range []string{"texts", "text", "descriptions"} { - values, ok := m[key].([]any) - if !ok { - continue - } - for _, value := range values { - entry, ok := value.(map[string]any) - if !ok { - continue - } - rel := strings.ToLower(d1FirstString(entry, "rel", "type", "name")) - rank, found := wanted[rel] - if !found { - continue - } - text := d1FirstString(entry, "value", "text", "content") - if text != "" && rank < bestRank { - best, bestRank = text, rank - } - } - } - return best -} - -func d1Category(m map[string]any) string { - if value := d1FirstString(m, "category", "classification"); value != "" { - return value - } - for _, key := range []string{"categories", "classifications"} { - values, ok := m[key].([]any) - if !ok { - continue - } - for _, value := range values { - switch v := value.(type) { - case string: - if strings.TrimSpace(v) != "" { - return strings.TrimSpace(v) - } - case map[string]any: - if category := d1FirstString(v, "name", "title", "value", "label"); category != "" { - return category - } - } - } - } - return "" -} - -func d1EventTimes(m map[string]any) (any, any) { - for _, key := range []string{"timeIntervals", "timeintervals", "time_intervals", "dates", "dateIntervals", "occurrences", "schedules"} { - if values, ok := m[key].([]any); ok && len(values) > 0 { - for _, value := range values { - if entry, ok := value.(map[string]any); ok { - start := d1FirstAny(entry, "start", "startDate", "start_date", "begin", "from", "date") - end := d1FirstAny(entry, "end", "endDate", "end_date", "until", "to") - if start != nil { - return start, end - } - } - } - } - if entry, ok := m[key].(map[string]any); ok { - start := d1FirstAny(entry, "start", "startDate", "start_date", "begin", "from", "date") - end := d1FirstAny(entry, "end", "endDate", "end_date", "until", "to") - if start != nil { - return start, end - } - } - } - start := d1FirstAny(m, "start", "startDate", "start_date", "begin", "from", "date") - end := d1FirstAny(m, "end", "endDate", "end_date", "until", "to") - if start != nil { - return start, end - } - return d1RecursiveDate(m, true), d1RecursiveDate(m, false) -} - -func d1RecursiveDate(v any, start bool) any { - keys := map[string]bool{} - if start { - for _, key := range []string{"start", "startdate", "start_date", "begin", "from", "datefrom"} { - keys[key] = true - } - } else { - for _, key := range []string{"end", "enddate", "end_date", "until", "to", "dateto"} { - keys[key] = true - } - } - var walk func(any) any - walk = func(value any) any { - switch typed := value.(type) { - case map[string]any: - for key, child := range typed { - if keys[strings.ToLower(key)] { - if _, err := parseFlexTime(child); err == nil { - return child - } - } - } - for _, child := range typed { - if found := walk(child); found != nil { - return found - } - } - case []any: - for _, child := range typed { - if found := walk(child); found != nil { - return found - } - } - } - return nil - } - return walk(v) -} - -func d1Address(m map[string]any) map[string]any { - for _, key := range []string{"address", "location", "place", "venue"} { - if address, ok := m[key].(map[string]any); ok { - return address - } - if values, ok := m[key].([]any); ok { - for _, value := range values { - if address, ok := value.(map[string]any); ok { - return address - } - } - } - } - return nil -} - -func d1URL(m map[string]any) string { - if value := d1FirstString(m, "url", "website", "web", "link"); strings.HasPrefix(value, "http") { - return value - } - for _, key := range []string{"links", "urls", "websites"} { - if values, ok := m[key].([]any); ok { - for _, value := range values { - if entry, ok := value.(map[string]any); ok { - candidate := d1FirstString(entry, "url", "href", "value", "link") - if strings.HasPrefix(candidate, "http") { - return candidate - } - } - } - } - } - return "" -} - -func d1License(m map[string]any) string { - if value := d1FirstString(m, "license", "licence", "copyright", "attribution"); value != "" { - return value - } - for _, key := range []string{"licenses", "licences", "rights"} { - if values, ok := m[key].([]any); ok { - parts := make([]string, 0, len(values)) - for _, value := range values { - switch typed := value.(type) { - case string: - parts = append(parts, strings.TrimSpace(typed)) - case map[string]any: - if text := d1FirstString(typed, "name", "title", "value", "url", "identifier"); text != "" { - parts = append(parts, text) - } - } - } - return strings.Join(parts, " · ") - } - } - return "" -} - -func d1NestedString(m map[string]any, keys []string, nested ...string) string { - for _, key := range keys { - if value := d1FirstString(m, key); value != "" { - return value - } - if entry, ok := m[key].(map[string]any); ok { - if value := d1FirstString(entry, nested...); value != "" { - return value - } - } - } - return "" -} - -func d1RecursiveStringForKeys(v any, keys ...string) string { - wanted := map[string]bool{} - for _, key := range keys { - wanted[strings.ToLower(key)] = true - } - var walk func(any) string - walk = func(value any) string { - switch typed := value.(type) { - case map[string]any: - for key, child := range typed { - if wanted[strings.ToLower(key)] { - if text, ok := child.(string); ok && strings.TrimSpace(text) != "" { - return strings.TrimSpace(text) - } - } - } - for _, child := range typed { - if found := walk(child); found != "" { - return found - } - } - case []any: - for _, child := range typed { - if found := walk(child); found != "" { - return found - } - } - } - return "" - } - return walk(v) -} - -func (s *eventStore) UpsertExternal(ctx context.Context, e EventSubmission, id, img, lic, status string) error { - end := "NULL" - if !e.EndAt.IsZero() { - end = sqlText(e.EndAt.UTC().Format(time.RFC3339)) + "::timestamptz" - } - q := `INSERT INTO landwelle.event_submissions(title,category,start_at,end_at,venue,city,postal_code,organizer,contact_name,contact_email,description,website,status,source_type,source_name,source_url,external_id,external_image_url,license_text) VALUES (` + sqlText(e.Title) + `,` + sqlText(e.Category) + `,` + sqlText(e.StartAt.UTC().Format(time.RFC3339)) + `::timestamptz,` + end + `,` + sqlText(e.Venue) + `,` + sqlText(e.City) + `,` + sqlText(e.PostalCode) + `,` + sqlText(e.Organizer) + `,'destination.one','',` + sqlText(e.Description) + `,` + sqlText(e.Website) + `,` + sqlText(status) + `,'open_data','Niedersachsen Hub / destination.one',` + sqlText(e.Website) + `,` + sqlText(id) + `,` + sqlText(img) + `,` + sqlText(lic) + `) ON CONFLICT(source_name,external_id) WHERE external_id<>'' DO UPDATE SET title=excluded.title,category=excluded.category,start_at=excluded.start_at,end_at=excluded.end_at,venue=excluded.venue,city=excluded.city,postal_code=excluded.postal_code,organizer=excluded.organizer,description=excluded.description,website=excluded.website,external_image_url=excluded.external_image_url,license_text=excluded.license_text,updated_at=now();` - _, err := s.db.exec(ctx, q) - return err -} -func d1FirstString(m map[string]any, ks ...string) string { - for _, k := range ks { - if v, ok := m[k]; ok { - if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { - return strings.TrimSpace(s) - } - if mm, ok := v.(map[string]any); ok { - if s := d1FirstString(mm, "value", "name", "title", "url", "text"); s != "" { - return s - } - } - } - } - return "" -} -func d1FirstAny(m map[string]any, ks ...string) any { - for _, k := range ks { - if v, ok := m[k]; ok { - return v - } - } - return nil -} -func d1FirstMap(m map[string]any, ks ...string) map[string]any { - for _, k := range ks { - if v, ok := m[k].(map[string]any); ok { - return v - } - } - return nil -} -func parseFlexTime(v any) (time.Time, error) { - s, ok := v.(string) - if !ok || strings.TrimSpace(s) == "" { - return time.Time{}, errors.New("Datum fehlt") - } - for _, l := range []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05", "2006-01-02T15:04", "2006-01-02", "02.01.2006 15:04", "02.01.2006"} { - if t, e := time.ParseInLocation(l, s, time.Local); e == nil { - return t, nil - } - } - return time.Time{}, errors.New("Datum ungültig") -} -func extractImage(m map[string]any) string { - if s := d1FirstString(m, "image", "image_url", "imageUrl", "thumbnail", "photo"); strings.HasPrefix(s, "http") { - return s - } - - // ET2014A liefert Bilder im Feld media_objects. Bevorzugt wird das - // als Standardbild markierte Medium, danach das erste echte Bild. - for _, key := range []string{"media_objects", "mediaObjects", "images", "media", "photos"} { - values, ok := m[key].([]any) - if !ok { - continue - } - var fallback string - for _, value := range values { - medium, ok := value.(map[string]any) - if !ok { - continue - } - candidate := d1FirstString(medium, "url", "src", "imageUrl") - if !strings.HasPrefix(candidate, "http://") && !strings.HasPrefix(candidate, "https://") { - continue - } - mediaType := strings.ToLower(d1FirstString(medium, "type", "mime_type", "mimeType")) - if mediaType != "" && !strings.HasPrefix(mediaType, "image/") { - continue - } - rel := strings.ToLower(d1FirstString(medium, "rel", "relation")) - if rel == "default" || rel == "primary" || rel == "main" || rel == "hero" { - return candidate - } - if fallback == "" && (rel == "imagegallery" || rel == "gallery" || rel == "") { - fallback = candidate - } - } - if fallback != "" { - return fallback - } - } - return "" -} diff --git a/destination_one_test.go b/destination_one_test.go deleted file mode 100644 index 24df68e..0000000 --- a/destination_one_test.go +++ /dev/null @@ -1,183 +0,0 @@ -package main - -import ( - "testing" -) - -func TestDestinationOneURLUsesFixedNiedersachsenHubRequest(t *testing.T) { - cfg := DestinationOneSettings{APIKey: "secret"} - u, err := destinationOneURL(cfg) - if err != nil { - t.Fatal(err) - } - want := "https://meta.et4.de/rest.ashx/search/?experience=open-data-niedersachsen-tourismus&licensekey=secret&template=ET2014A.json&type=Event" - if u.String() != want { - t.Fatalf("unerwartete URL: %s", u.String()) - } -} - -func TestParseDestinationEventET2014A(t *testing.T) { - item := map[string]any{ - "global_id": "e_101284067", - "id": "101284067", - "title": "Führung auf der Elbinsel Lühesand", - "type": "Event", - "categories": []any{ - "Tradition, Brauchtum, Volksfest sonstige", - }, - "texts": []any{ - map[string]any{"rel": "details", "type": "text/html", "value": "Natur und Erlebnisführung auf der Elbinsel Lühesand."}, - map[string]any{"rel": "teaser", "type": "text/plain", "value": "Kurze Führung."}, - }, - "timeIntervals": []any{ - map[string]any{"start": "2026-08-12T10:00:00+02:00", "end": "2026-08-12T12:00:00+02:00"}, - }, - "address": map[string]any{ - "name": "Anleger Lühesand", - "city": "Grünendeich", - "postalCode": "21720", - }, - } - event, id, _, _, err := parseDestinationEvent(item) - if err != nil { - t.Fatal(err) - } - if id != "e_101284067" { - t.Fatalf("id=%q", id) - } - if event.Title != "Führung auf der Elbinsel Lühesand" { - t.Fatalf("title=%q", event.Title) - } - if event.Description != "Natur und Erlebnisführung auf der Elbinsel Lühesand." { - t.Fatalf("description=%q", event.Description) - } - if event.City != "Grünendeich" || event.PostalCode != "21720" { - t.Fatalf("address=%q %q", event.PostalCode, event.City) - } - if event.StartAt.IsZero() || event.EndAt.IsZero() { - t.Fatal("time interval not parsed") - } -} - -func TestDestinationMapsAcceptsET2014AItemsWithoutTopLevelStart(t *testing.T) { - payload := map[string]any{ - "status": "OK", - "count": 1.0, - "items": []any{ - map[string]any{"global_id": "e_1", "title": "Dorffest", "type": "Event", "timeIntervals": []any{map[string]any{"start": "2026-09-01T12:00:00+02:00"}}}, - }, - } - items := destinationMaps(payload) - if len(items) != 1 { - t.Fatalf("items=%d", len(items)) - } -} - -func TestDestinationMapsDoesNotDiscardET2014AItemsBeforeParsing(t *testing.T) { - payload := map[string]any{ - "status": "OK", - "count": 2.0, - "items": []any{ - map[string]any{"global_id": "e_101", "title": "Führung", "type": "Event"}, - map[string]any{"GLOBAL_ID": "e_102", "TITLE": "Flohmarkt", "TYPE": "Event"}, - }, - } - items := destinationMaps(payload) - if len(items) != 2 { - t.Fatalf("items=%d, want 2", len(items)) - } -} - -func TestDestinationMapsAcceptsNestedItemsContainer(t *testing.T) { - payload := map[string]any{ - "status": "OK", - "items": map[string]any{ - "item": []any{map[string]any{"id": "1", "title": "Treffen"}}, - }, - } - items := destinationMaps(payload) - if len(items) != 1 { - t.Fatalf("items=%d, want 1", len(items)) - } -} - -func TestDestinationMapsAcceptsAnyObjectInsideItems(t *testing.T) { - payload := map[string]any{ - "status": "OK", - "items": []any{ - map[string]any{"id": float64(101284067), "global_id": "e_101284067", "title": "Führung auf der Elbinsel"}, - }, - } - items := destinationMaps(payload) - if len(items) != 1 { - t.Fatalf("items=%d, want 1", len(items)) - } -} - -func TestDestinationMapsKeepsEventWithFeaturesField(t *testing.T) { - payload := map[string]any{"items": []any{map[string]any{ - "global_id": "e_101284067", - "title": "Führung auf der Elbinsel Lühesand", - "features": []any{map[string]any{"name": "barrierefrei"}}, - }}} - items := destinationMaps(payload) - if len(items) != 1 { - t.Fatalf("erwartet 1 Event, erhalten %d", len(items)) - } - if items[0]["title"] != "Führung auf der Elbinsel Lühesand" { - t.Fatalf("Event wurde falsch gelesen: %#v", items[0]) - } -} - -func TestExtractImageFromET2014AMediaObjects(t *testing.T) { - event := map[string]any{ - "media_objects": []any{ - map[string]any{"rel": "venuewebsite", "url": "https://example.org/venue"}, - map[string]any{"rel": "imagegallery", "url": "https://dam.destination.one/gallery.jpg", "type": "image/jpeg"}, - map[string]any{"rel": "default", "url": "https://dam.destination.one/default.jpg", "type": "image/jpeg"}, - }, - } - got := extractImage(event) - if got != "https://dam.destination.one/default.jpg" { - t.Fatalf("unexpected image URL: %q", got) - } -} - -func TestExtractImageFallsBackToGallery(t *testing.T) { - event := map[string]any{ - "media_objects": []any{ - map[string]any{"rel": "canonical", "url": "https://example.org/event"}, - map[string]any{"rel": "imagegallery", "url": "https://dam.destination.one/gallery.png", "type": "image/png"}, - }, - } - got := extractImage(event) - if got != "https://dam.destination.one/gallery.png" { - t.Fatalf("unexpected image URL: %q", got) - } -} - -func TestNormalizeDestinationTextConvertsHTMLToReadableText(t *testing.T) { - input := `

Erster Absatz & mehr.

Zweiter Absatz
mit Zeile.

` - got := normalizeDestinationText(input) - want := "Erster Absatz & mehr.\nZweiter Absatz\nmit Zeile.\n• Punkt eins\n• Punkt zwei" - if got != want { - t.Fatalf("got %q, want %q", got, want) - } -} - -func TestParseDestinationEventNormalizesHTMLDescription(t *testing.T) { - item := map[string]any{ - "global_id": "e_html", - "title": "Dorffest", - "city": "Visselhövede", - "texts": []any{map[string]any{"rel": "details", "type": "text/html", "value": `

Musik & Markt

Eintritt frei

`}}, - "timeIntervals": []any{map[string]any{"start": "2026-09-01T12:00:00+02:00"}}, - } - event, _, _, _, err := parseDestinationEvent(item) - if err != nil { - t.Fatal(err) - } - if event.Description != "Musik & Markt\nEintritt frei" { - t.Fatalf("description=%q", event.Description) - } -} diff --git a/docs/EVENT_CALENDAR.md b/docs/EVENT_CALENDAR.md index 1ce911e..06a69e6 100644 --- a/docs/EVENT_CALENDAR.md +++ b/docs/EVENT_CALENDAR.md @@ -1,46 +1,23 @@ # Veranstaltungskalender ## Öffentliche Seite +`GET /veranstaltungen` zeigt ausschließlich veröffentlichte redaktionelle Veranstaltungen und eigene Einsendungen aus Niedersachsen. Auch die öffentliche Suche, Detailansicht, iCal-Ausgabe und Startseite verwenden diese selbst verwalteten Termine. -`GET /veranstaltungen` zeigt veröffentlichte Termine aus ganz Niedersachsen. Kategorien umfassen unter anderem Familie, Flohmarkt, Konzert, Kultur, Land & Leute, Markt, Sport, Tradition und Verein. +## Veranstaltungen eintragen +Unter `/admin/events` kann die Landwelle-Redaktion Termine anlegen, bearbeiten, veröffentlichen, ablehnen oder löschen und Rubriken pflegen. Es gibt nur eine Veranstaltungsliste, mit serverseitiger Pagination. Der bisherige Niedersachsen-HUB-Reiter existiert nicht mehr. -## Einsendungen +`POST /veranstaltungen/einsenden` nimmt Veranstaltungsdaten und optional eine Grafik als JPG, PNG oder WebP bis 8 MB entgegen. Eingesandte Termine erhalten den Status `pending` und erscheinen erst nach redaktioneller Freigabe. -`POST /veranstaltungen/einsenden` nimmt Veranstaltungsdaten und optional eine Grafik als JPG, PNG oder WebP bis 8 MB entgegen. Neue Einsendungen erhalten den Status `pending` und werden erst nach redaktioneller Prüfung sichtbar. +## Keine automatische Übernahme externer Veranstaltungskalender +Die ehemalige destination.one-/Niedersachsen-HUB-Anbindung und die zusätzlichen Tourismusseiten sind im Portal deaktiviert und aus dem Quellcode entfernt. Es gibt keine Import-Schaltflächen, Synchronisierungsjobs oder API-Zugangsdaten-Einstellungen mehr. -Der Absender erhält über das Template `event_submission_confirmation` eine Bestätigung. Die Redaktion erhält über `event_submission_admin` eine Nachricht an `radio@landwelle.de`; eine hochgeladene Grafik wird als Anhang versendet. +Aus Gründen der Datensicherheit löscht das Update keine bereits in PostgreSQL gespeicherten importierten Einträge. Die öffentlichen Veranstaltungsabfragen und die Adminliste filtern solche Datensätze aus. Die Navigation wird in Migration 0047 bereinigt. -## Externe Quellen für Niedersachsen +## Favoriten +Eigene, veröffentlichte Termine können als Startseiten-Favorit markiert werden. Die bestehende Zufallsauswahl der bis zu drei Termine auf der Startseite bleibt bestehen; Fremddaten werden ausgeschlossen. -Die bevorzugte landesweite Quelle ist der Niedersachsen Hub beziehungsweise dessen Open Data-Finder. Dort werden touristische Open-Data-Datensätze einschließlich Events aus niedersächsischen Regionen gebündelt. Ein produktiver Import sollte erst nach Klärung von API-Zugang, Lizenz, Aktualisierungsintervall und Quellenkennzeichnung aktiviert werden. +## Suche und Kalender +Die öffentliche Suche und Detailansicht laufen unter `/api/events/search` und `/api/events/`. Der Kalenderexport steht unter `/veranstaltungen/kalender.ics` bereit. -Als ergänzende Quellen kommen offizielle kommunale und touristische Kalender in Betracht, sofern RSS, iCal, JSON-LD oder eine dokumentierte API angeboten wird. Jede Quelle muss einzeln auf Nutzungsrechte, Niedersachsen-Bezug und stabile Identifikatoren geprüft werden. Reines ungefragtes Scraping ist nicht vorgesehen. - -Empfohlene Priorität: - -1. Niedersachsen Hub / Open Data-Finder -2. offizielle Tourismusorganisationen und kommunale Kalender -3. iCal- oder RSS-Feeds von Vereinen, Städten und Veranstaltern -4. manuelle Landwelle-Einsendungen und eigene redaktionelle Termine - - -## destination.one-Import - -Der Niedersachsen-Hub-Import wird im Adminbereich unter **Einstellungen → Veranstaltungen** konfiguriert. Unterstützt werden eine vollständige API-URL, ein frei benennbarer Query-Parameter für den Lizenzschlüssel sowie Experience/Projekt und dessen Parametername. Standardwerte sind `licensekey`, `experience` und `Niedersachsen Hub`. - -Der Importer erwartet die destination.one-Ausgabe als JSON, erkennt gängige Container (`items`, `results`, `data`, `features`, `records`) und ordnet Titel, Termine, Ort, Beschreibung, Webseite, Bild, Quelle und Lizenz dem Landwelle-Datenmodell zu. Datensätze werden anhand von `source_name + external_id` aktualisiert. - -Bei aktivierter automatischer Veröffentlichung erscheinen importierte Termine unmittelbar. Ohne automatische Veröffentlichung werden sie als `pending` gespeichert. Die Lizenzentscheidung bleibt redaktionelle Verantwortung; zugelassen sind nur Daten und Bilder, deren konkrete Lizenz die Nutzung auf landwelle.de erlaubt. - -## Startseiten-Favoriten und Zufallsauswahl - -Unter `/admin/events?tab=submissions` können ausschließlich eigene Einsendungen und redaktionelle Termine als Startseiten-Favorit markiert werden. Importierte Open-Data-Termine bleiben von dieser Funktion ausgeschlossen. - -Die Startseite lädt alle veröffentlichten und noch gültigen Termine über `ListPublished`. Ist mindestens ein aktiver Favorit vorhanden, steht ein Favorit immer an Position 1. Bei mehreren aktiven Favoriten wird diese erste Position pro Seitenaufruf zufällig zwischen den Favoriten verteilt. Die beiden übrigen Plätze werden zufällig aus den noch nicht ausgewählten aktiven Veranstaltungen ergänzt. Doppelte Karten sind ausgeschlossen. Ohne aktiven Favoriten werden wie bisher bis zu drei Termine zufällig gewählt. Die Veranstaltungskalenderseite selbst bleibt chronologisch sortiert. - -Die Migration `0026_event_homepage_favorites.sql` ergänzt `homepage_favorite` und `homepage_favorite_at`. Abgelaufene Favoriten bleiben zwar historisch gespeichert, werden aufgrund der bestehenden Gültigkeitsprüfung aber nicht mehr auf der Startseite angezeigt. - - -## Live-Suche und Detailmodal - -Die öffentliche Seite durchsucht Titel, Beschreibung, Ort, Veranstalter und Kategorie über `/api/events/search`. Ein Klick auf eine Karte lädt `/api/events/` und zeigt den vollständigen Text in einem Modal. +## Release v1.5.72 +Die früheren Datenbankmigrationen 0014 und 0046 bleiben aus Gründen der Migrationshistorie bestehen; nicht benötigte Tourismus-Datenbanktabellen werden nicht automatisch gelöscht. Migration 0047 entfernt nur den automatisch hinzugefügten Navigationseintrag. diff --git a/docs/NIEDERSACHSEN_HUB.md b/docs/NIEDERSACHSEN_HUB.md deleted file mode 100644 index a16c68e..0000000 --- a/docs/NIEDERSACHSEN_HUB.md +++ /dev/null @@ -1,23 +0,0 @@ -# Niedersachsen Hub – Landwelle Tourismus (v1.5.71) - -## Bestehende Integration -Der Event-Import (`destination_one.go`, `/admin/events`, `event_submissions`) bleibt unverändert. Der neue touristische Datenbereich nutzt `landwelle.tourism_hub_items` und eigene Sync-Cursor. Redaktionelle Landwelle-Beiträge bleiben unabhängig. - -## Unterstützte destination.one-Inhaltstypen -POI (Sehenswürdigkeiten und Ausflüge), Tour, Gastro, Hotel, City, Area, Package und Article. Event bleibt im bisherigen Kalenderimport. - -## Einrichtung -1. GitHub-Version v1.5.71 beziehen. -2. Vor produktivem Einsatz `migrations/0046_niedersachsen_tourism_hub.sql` mit dem vorhandenen Migrator ausführen. -3. Unter `/admin/settings#events` den bestehenden persönlichen destination.one-Lizenzschlüssel hinterlegen und die Verbindung aktivieren. Keine Schlüssel nach GitHub übertragen. -4. Unter `/admin/niedersachsen-hub` einzelne Arten importieren, Quellen und Rechte prüfen und dann redaktionell freigeben. -5. Die öffentliche Darstellung befindet sich unter `/niedersachsen-entdecken`. - -## Import -Abfrage gegen `meta.et4.de/rest.ashx/search/` mit `experience=open-data-niedersachsen-tourismus`, `template=ET2014A.json`, `mkt=de-DE` und ausgewähltem Datentyp. Der Import lädt 100 Datensätze pro Seite und höchstens zehn Seiten pro Typ/Durchlauf. Fortschritte werden in `tourism_hub_sync_state` gesichert, sodass die nächsten Läufe fortsetzen. Eindeutigkeit: (content_type, external_id). Ohne persönlichen API-Schlüssel wurden keine echten Live-Daten abgerufen. - -## Nutzungsrechte -Standard: nicht öffentlich. Unterstützte offen lizenzierte Daten: CC0, CC BY, CC BY-SA. NC, ND und unbekannte Rechte sind gesperrt. CC BY und CC BY-SA verlangen einen Urheber-/Quellnachweis. Bilder werden unabhängig von den Texten geprüft; ihre separate Lizenz und Bildurheberangaben werden gespeichert und öffentlich angezeigt. Manuell geänderte Rechte erzwingen eine erneute redaktionelle Freigabe. Die Redaktion muss mögliche weitere Lizenzbedingungen (etwa ShareAlike) beachten. - -## Einschränkungen -Diese technische erste Ausbaustufe importiert die acht Arten mit allgemeinen Feldern wie Name, Kategorie, Beschreibung, Ort, Link und Bildrechten. GPX, Höhenprofile, Buchungs- und Echtzeitverfügbarkeiten, komplexe Öffnungszeiten und Mehrfach-Mediengalerien sind damit noch nicht eingebunden. Je Art sind realistische API-Beispiele und Funktionstests nach Bereitstellung des Lizenzschlüssels nötig. diff --git a/events.go b/events.go index b7d7747..54ed2b9 100644 --- a/events.go +++ b/events.go @@ -120,7 +120,7 @@ func (s *eventStore) Categories(ctx context.Context, includeInactive bool) ([]Ev var out []EventCategory q := `SELECT COALESCE(json_agg(json_build_object( 'id',c.id,'name',c.name,'sort_order',c.sort_order,'active',c.active, -'event_count',(SELECT count(*) FROM landwelle.event_submissions e WHERE lower(e.category)=lower(c.name)) +'event_count',(SELECT count(*) FROM landwelle.event_submissions e WHERE e.source_type IN ('submission','editorial') AND lower(e.category)=lower(c.name)) ) ORDER BY c.sort_order,c.name),'[]'::json)::text FROM landwelle.event_categories c` + where + `;` if err := s.db.queryJSON(ctx, q, &out); err != nil { return nil, err @@ -145,7 +145,7 @@ func (s *eventStore) ListPublished(ctx context.Context, category string) ([]Cale if s == nil || s.db == nil || !s.db.Enabled() { return nil, nil } - where := "status='published' AND start_at >= date_trunc('day', now()) - interval '14 days' AND CASE WHEN end_at IS NULL OR end_at <= start_at OR end_at - start_at > interval '31 days' THEN date_trunc('day',start_at)+interval '1 day' ELSE end_at END > now()" + where := "status='published' AND source_type IN ('submission','editorial') AND start_at >= date_trunc('day', now()) - interval '14 days' AND CASE WHEN end_at IS NULL OR end_at <= start_at OR end_at - start_at > interval '31 days' THEN date_trunc('day',start_at)+interval '1 day' ELSE end_at END > now()" if strings.TrimSpace(category) != "" { where += " AND category=" + sqlText(category) } @@ -170,7 +170,7 @@ func (s *eventStore) SearchPublished(ctx context.Context, query, category string if limit <= 0 || limit > 100 { limit = 50 } - where := "status='published' AND start_at >= date_trunc('day', now()) - interval '14 days' AND CASE WHEN end_at IS NULL OR end_at <= start_at OR end_at - start_at > interval '31 days' THEN date_trunc('day',start_at)+interval '1 day' ELSE end_at END > now()" + where := "status='published' AND source_type IN ('submission','editorial') AND start_at >= date_trunc('day', now()) - interval '14 days' AND CASE WHEN end_at IS NULL OR end_at <= start_at OR end_at - start_at > interval '31 days' THEN date_trunc('day',start_at)+interval '1 day' ELSE end_at END > now()" if strings.TrimSpace(category) != "" { where += " AND category=" + sqlText(strings.TrimSpace(category)) } @@ -200,7 +200,7 @@ func (s *eventStore) GetPublished(ctx context.Context, id int64) (CalendarEvent, 'id',id,'title',title,'category',category,'start_at',start_at,'end_at',end_at,'venue',venue,'city',city,'postal_code',postal_code, 'organizer',organizer,'description',description,'website',website,'image_url',CASE WHEN image_path<>'' THEN '/event-media/'||image_path ELSE external_image_url END, 'source_name',source_name,'source_url',source_url,'homepage_favorite',homepage_favorite)),'[]'::json)::text FROM landwelle.event_submissions -WHERE id=` + strconv.FormatInt(id, 10) + ` AND status='published' AND CASE WHEN end_at IS NULL OR end_at <= start_at OR end_at - start_at > interval '31 days' THEN date_trunc('day',start_at)+interval '1 day' ELSE end_at END > now();` +WHERE id=` + strconv.FormatInt(id, 10) + ` AND source_type IN ('submission','editorial') AND status='published' AND CASE WHEN end_at IS NULL OR end_at <= start_at OR end_at - start_at > interval '31 days' THEN date_trunc('day',start_at)+interval '1 day' ELSE end_at END > now();` var rows []CalendarEvent if err := s.db.queryJSON(ctx, q, &rows); err != nil { return CalendarEvent{}, false, err diff --git a/events_manual_only_v1572_test.go b/events_manual_only_v1572_test.go new file mode 100644 index 0000000..4203e84 --- /dev/null +++ b/events_manual_only_v1572_test.go @@ -0,0 +1,43 @@ +package main + +import ( + "os" + "strings" + "testing" +) + +func TestEventManagementHasNoExternalHubIntegration(t *testing.T) { + // The old tourism API and scheduled destination.one importer are no longer wired. + checks := map[string][]string{ + "main.go": { "newDestinationOneImporter", "newTourismHub", "/niedersachsen-entdecken" }, + "admin.go": { "/admin/niedersachsen-hub", "/admin/settings/import-events", "destinationOne" }, + "settings.go": { "DestinationOneSettings", "destination_one" }, + "web/admin/settings.html": { "destination_one_", "Niedersachsen Hub" }, + "web/admin/management.html": { "EventTab", "HubCount", "?tab=hub", "Niedersachsen Hub" }, + } + for path, forbidden := range checks { + data, err := os.ReadFile(path) + if err != nil { t.Fatal(err) } + for _, token := range forbidden { + if strings.Contains(string(data), token) { + t.Errorf("%s still contains %q", path, token) + } + } + } +} +func TestOnlyOwnEventsUsedInPublicAndAdminListings(t *testing.T) { + for _, path := range []string{"events.go", "admin_management.go"} { + data, err := os.ReadFile(path) + if err != nil { t.Fatal(err) } + if !strings.Contains(string(data), "source_type IN ('submission','editorial')") { + t.Errorf("%s must restrict events to own submissions and editorial records", path) + } + } + html, err := webFS.ReadFile("web/admin/management.html") + if err != nil { t.Fatal(err) } + if !strings.Contains(string(html), "Neue Veranstaltung eintragen") || + !strings.Contains(string(html), "Rubriken verwalten") || + !strings.Contains(string(html), "value=\"delete\"") { + t.Fatal("manual event editing controls must remain available") + } +} diff --git a/main.go b/main.go index 531458c..4bb1bde 100644 --- a/main.go +++ b/main.go @@ -36,7 +36,7 @@ const ( apiVersion = "v1" apiContractVersion = "1.0.0" applicationName = "Landwelle Radio" - applicationVersion = "1.5.71" + applicationVersion = "1.5.72" ) var publicTemplateFiles = []string{ @@ -73,7 +73,6 @@ var publicTemplateFiles = []string{ "web/contact.html", "web/mediathek.html", "web/landwelle-zuhause.html", - "web/tourism.html", } func displayVersion() string { @@ -280,8 +279,6 @@ func main() { directoryAutomation := newDirectoryWorkflow(settings, emailTemplates) youtube := newYouTubeFeedService() jobs := newJobsService() - destinationOne := newDestinationOneImporter(settings, events, logger) - tourismHub := newTourismHub(database, settings, logger) team := newTeamStore(database) forum := newForumStore(database) accounts := newPublicAuth(database, settings, emailTemplates, logger) @@ -295,7 +292,7 @@ func main() { } }() } - admin, err := newAdminHandler(logger, weather, data, settings, nowPlayingService, programs, downloads, ai, editorial, wishes, emailTemplates, wishAutomation, media, database, team, forum, destinationOne, navigation, directory) + admin, err := newAdminHandler(logger, weather, data, settings, nowPlayingService, programs, downloads, ai, editorial, wishes, emailTemplates, wishAutomation, media, database, team, forum, navigation, directory) if err != nil { logger.Fatal(err) } @@ -328,8 +325,6 @@ func main() { rss := newRSSEngine(database, logger) rss.Start() - destinationOne.Start() - tourismHub.Start() registerPublicAPI(mux, data, weather, nowPlayingService, traffic, programs, database, rss, editorial, events, team, charts, playlist) registerMobileAppAPI(mux, mobileAPIDependencies{data: data, database: database, rss: rss, editorial: editorial, events: events, team: team, charts: charts, playlist: playlist, programs: programs, settings: settings, nowPlaying: nowPlayingService}) registerExternalV1Alias(mux) @@ -527,8 +522,6 @@ func main() { w.Header().Set("Cache-Control", "private, no-store") http.ServeFile(w, r, path) })) - mux.HandleFunc("/niedersachsen-entdecken", tourismPublicHandler(tmpl, data, tourismHub, logger)) - mux.HandleFunc("/niedersachsen-entdecken/", tourismPublicHandler(tmpl, data, tourismHub, logger)) mux.HandleFunc("/veranstaltungen", eventsPageHandler(tmpl, logger, data, events)) mux.HandleFunc("/veranstaltungen/kalender.ics", eventsICalHandler(events, logger)) mux.HandleFunc("/veranstaltungen/einsenden", eventSubmissionHandler(events, eventAutomation, logger)) @@ -692,8 +685,6 @@ func main() { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() rss.Stop(ctx) - destinationOne.Stop(ctx) - tourismHub.Stop(ctx) if err := server.Shutdown(ctx); err != nil { logger.Printf("Graceful Shutdown: %v", err) } diff --git a/main_test.go b/main_test.go index 395c217..a345667 100644 --- a/main_test.go +++ b/main_test.go @@ -181,7 +181,7 @@ func TestWeatherHelpers(t *testing.T) { } func TestApplicationVersion(t *testing.T) { - if applicationVersion != "1.5.71" { + if applicationVersion != "1.5.72" { t.Fatalf("unexpected application version %q", applicationVersion) } } diff --git a/migrations/0047_only_manual_events_navigation.sql b/migrations/0047_only_manual_events_navigation.sql new file mode 100644 index 0000000..4d0693c --- /dev/null +++ b/migrations/0047_only_manual_events_navigation.sql @@ -0,0 +1,7 @@ +SET search_path TO landwelle, public; + +-- The optional tourism navigation item was introduced by migration 0046. +-- Remove only that route; keep all calendar records and legacy tables intact. +DELETE FROM navigation_items +WHERE url='/niedersachsen-entdecken' + AND trim(label)='Niedersachsen entdecken'; diff --git a/settings.go b/settings.go index 0984dc1..4fdabdf 100644 --- a/settings.go +++ b/settings.go @@ -24,7 +24,6 @@ type RuntimeSettings struct { FTP FTPSettings `json:"ftp"` WishAutomation WishAutomationSettings `json:"wish_automation"` Social SocialSettings `json:"social"` - DestinationOne DestinationOneSettings `json:"destination_one"` AudioBackgrounds []AudioBackgroundTrack `json:"audio_backgrounds"` AIAudioModules map[string]AIAudioModuleSettings `json:"ai_audio_modules"` Website WebsiteSettings `json:"website"` @@ -38,17 +37,6 @@ func (w WebsiteSettings) GoogleAdSenseEnabled() bool { return !strings.EqualFold(strings.TrimSpace(w.GoogleAdSenseMode), "disabled") } -type DestinationOneSettings struct { - Enabled bool `json:"enabled"` - APIURL string `json:"api_url"` - APIKey string `json:"api_key"` - KeyParameter string `json:"key_parameter"` - Experience string `json:"experience"` - ExperienceParam string `json:"experience_parameter"` - IntervalMinutes int `json:"interval_minutes"` - AutoPublish bool `json:"auto_publish"` -} - type SocialSettings struct { FacebookEnabled bool `json:"facebook_enabled"` FacebookPageID string `json:"facebook_page_id"` @@ -167,7 +155,6 @@ func defaultRuntimeSettings(streamURL string) RuntimeSettings { SMTP: SMTPSettings{Enabled: envBool("LANDWELLE_SMTP_ENABLED", false), Host: envOr("LANDWELLE_SMTP_HOST", ""), Port: envIntRange("LANDWELLE_SMTP_PORT", 587, 1, 65535), Username: os.Getenv("LANDWELLE_SMTP_USER"), Password: os.Getenv("LANDWELLE_SMTP_PASSWORD"), FromName: envOr("LANDWELLE_SMTP_FROM_NAME", "Landwelle Radio"), FromEmail: envOr("LANDWELLE_SMTP_FROM_EMAIL", "radio@landwelle.de"), AdminEmail: envOr("LANDWELLE_ADMIN_EMAIL", "radio@landwelle.de"), TLSMode: envOr("LANDWELLE_SMTP_TLS_MODE", "starttls")}, FTP: FTPSettings{Enabled: envBool("LANDWELLE_FTP_ENABLED", false), Host: os.Getenv("LANDWELLE_FTP_HOST"), Port: envIntRange("LANDWELLE_FTP_PORT", 21, 1, 65535), Username: os.Getenv("LANDWELLE_FTP_USER"), Password: os.Getenv("LANDWELLE_FTP_PASSWORD"), TLS: envBool("LANDWELLE_FTP_TLS", false), Passive: true, TimeoutSeconds: 20}, Social: SocialSettings{FacebookAPIVersion: "v25.0", PublicBaseURL: envOr("LANDWELLE_PUBLIC_URL", "https://landwelle.de"), WhatsAppChannelURL: "https://whatsapp.com/channel/0029Vb8bu1P9Bb5t5ZbtF011"}, - DestinationOne: DestinationOneSettings{Enabled: envBool("LANDWELLE_DESTINATION_ONE_ENABLED", false), APIURL: envOr("LANDWELLE_DESTINATION_ONE_API_URL", "https://meta.et4.de/rest.ashx/search/ET2014A.json/"), APIKey: strings.TrimSpace(os.Getenv("LANDWELLE_DESTINATION_ONE_API_KEY")), KeyParameter: envOr("LANDWELLE_DESTINATION_ONE_KEY_PARAMETER", "licensekey"), Experience: envOr("LANDWELLE_DESTINATION_ONE_EXPERIENCE", ""), ExperienceParam: envOr("LANDWELLE_DESTINATION_ONE_EXPERIENCE_PARAMETER", "experience"), IntervalMinutes: envIntRange("LANDWELLE_DESTINATION_ONE_INTERVAL_MINUTES", 360, 15, 10080), AutoPublish: true}, WishAutomation: WishAutomationSettings{Enabled: false, Prompt: "Formuliere eine freundliche Radio-Anmoderation für den Musikwunsch. Nutze ausschließlich die gelieferten Angaben, keine erfundenen Fakten. Länge: 20 bis 35 Sekunden, direkt sprechbar, ohne Überschrift.", Temperature: 0.4, TTSVolume: 12, BackgroundVolume: -18, RemoteDirectory: "/musikwunsch", FileNamePattern: "musikwunsch-{{id}}.mp3", PublicBaseURL: envOr("LANDWELLE_PUBLIC_URL", "https://landwelle.de"), AutoProcessOnApprove: true, DeleteLocalAfterUpload: true}, AIAudioModules: defaultAIAudioModuleSettings(), Website: WebsiteSettings{GoogleAdSenseMode: "enabled"}, @@ -271,18 +258,6 @@ func mergeSettings(defaults, loaded RuntimeSettings) RuntimeSettings { if loaded.Social.WhatsAppChannelURL == "" { loaded.Social.WhatsAppChannelURL = defaults.Social.WhatsAppChannelURL } - if loaded.DestinationOne.APIURL == "" { - loaded.DestinationOne.APIURL = defaults.DestinationOne.APIURL - } - if loaded.DestinationOne.KeyParameter == "" { - loaded.DestinationOne.KeyParameter = defaults.DestinationOne.KeyParameter - } - if loaded.DestinationOne.ExperienceParam == "" { - loaded.DestinationOne.ExperienceParam = defaults.DestinationOne.ExperienceParam - } - if loaded.DestinationOne.IntervalMinutes == 0 { - loaded.DestinationOne.IntervalMinutes = defaults.DestinationOne.IntervalMinutes - } if loaded.WishAutomation.Prompt == "" { loaded.WishAutomation.Prompt = defaults.WishAutomation.Prompt } @@ -358,10 +333,6 @@ func (s *settingsStore) Save(settings RuntimeSettings) error { settings.Social.FacebookAPIVersion = strings.Trim(strings.TrimSpace(settings.Social.FacebookAPIVersion), "/") settings.Social.PublicBaseURL = strings.TrimRight(strings.TrimSpace(settings.Social.PublicBaseURL), "/") settings.Social.WhatsAppChannelURL = strings.TrimSpace(settings.Social.WhatsAppChannelURL) - settings.DestinationOne.APIURL = strings.TrimSpace(settings.DestinationOne.APIURL) - settings.DestinationOne.KeyParameter = strings.TrimSpace(settings.DestinationOne.KeyParameter) - settings.DestinationOne.Experience = strings.TrimSpace(settings.DestinationOne.Experience) - settings.DestinationOne.ExperienceParam = strings.TrimSpace(settings.DestinationOne.ExperienceParam) if strings.EqualFold(strings.TrimSpace(settings.Website.GoogleAdSenseMode), "disabled") { settings.Website.GoogleAdSenseMode = "disabled" } else { @@ -471,17 +442,6 @@ func validateRuntimeSettings(settings RuntimeSettings) error { return errors.New("FTP benötigt Host, Port und Benutzername") } } - if settings.DestinationOne.Enabled { - if settings.DestinationOne.APIKey == "" { - return errors.New("für destination.one fehlt der Lizenzschlüssel") - } - if !validServiceURL(settings.DestinationOne.APIURL) { - return errors.New("die destination.one API-URL ist ungültig") - } - if settings.DestinationOne.IntervalMinutes < 15 || settings.DestinationOne.IntervalMinutes > 10080 { - return errors.New("das destination.one Intervall muss zwischen 15 und 10080 Minuten liegen") - } - } if settings.WishAutomation.Enabled && settings.WishAutomation.VoiceID == "" { return errors.New("für die Musikwunsch-Automation fehlt die ElevenLabs Voice ID") } diff --git a/tourism_hub.go b/tourism_hub.go deleted file mode 100644 index 86956ab..0000000 --- a/tourism_hub.go +++ /dev/null @@ -1,406 +0,0 @@ -package main - -import ( - "context" - "crypto/subtle" - "encoding/json" - "errors" - "fmt" - "html/template" - "io" - "log" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" -) - -var tourismImportMu sync.Mutex - -var tourismTypes = []string{"POI", "Tour", "Gastro", "Hotel", "City", "Area", "Package", "Article"} - -func tourismTypeValid(value string) bool { - for _, t := range tourismTypes { if t == value { return true } } - return false -} - -type tourismItem struct { - ID int64 `json:"id"` - ExternalID string `json:"external_id"` - ContentType string `json:"content_type"` - Title string `json:"title"` - Category string `json:"category"` - City string `json:"city"` - PostalCode string `json:"postal_code"` - Description string `json:"description"` - Website string `json:"website"` - SourceURL string `json:"source_url"` - DataLicense string `json:"data_license"` - Attribution string `json:"attribution"` - ImageAttribution string `json:"image_attribution"` - ImageURL string `json:"image_url"` - ImageLicense string `json:"image_license"` - Published bool `json:"published"` -} -type tourismListing struct { - Items []tourismItem `json:"items"` - Total int `json:"total"` -} -type tourismPageData struct { - PageData - Items []tourismItem - Item *tourismItem - Types []string - FilterType, FilterCity, Query, Error string - Page, Total, Pages, PrevPage, NextPage int - HasPrev, HasNext bool -} -type tourismAdminData struct { - Username, CSRFToken, Error, Success string - Items []tourismItem - Types []string - KeySet, Enabled bool -} - -type tourismHub struct { - db *postgresStore - settings *settingsStore - logger *log.Logger - client *http.Client - cancel context.CancelFunc - done chan struct{} -} - -func newTourismHub(db *postgresStore, settings *settingsStore, logger *log.Logger) *tourismHub { - return &tourismHub{db: db, settings: settings, logger: logger, client: &http.Client{Timeout: 35 * time.Second}} -} -func (h *tourismHub) Ready() bool { return h != nil && h.db != nil && h.db.Enabled() } -func (h *tourismHub) Start() { - if !h.Ready() || h.settings == nil { return } - ctx, cancel := context.WithCancel(context.Background()) - h.cancel = cancel - h.done = make(chan struct{}) - go func() { - defer close(h.done) - timer := time.NewTimer(2 * time.Minute) - defer timer.Stop() - for { - select { - case <-ctx.Done(): return - case <-timer.C: - cfg := h.settings.Get().DestinationOne - if cfg.Enabled && strings.TrimSpace(cfg.APIKey) != "" { - for _, kind := range tourismTypes { - runCtx, stop := context.WithTimeout(ctx, 4*time.Minute) - _, err := h.SyncType(runCtx, kind) - stop() - if err != nil && h.logger != nil { h.logger.Printf("Tourismus-HUB %s: %v", kind, err) } - if ctx.Err() != nil { return } - } - } - interval := time.Duration(cfg.IntervalMinutes) * time.Minute - if interval < 15*time.Minute { interval = 6*time.Hour } - timer.Reset(interval) - } - } - }() -} -func (h *tourismHub) Stop(ctx context.Context) { - if h == nil || h.cancel == nil { return } - h.cancel() - select { case <-h.done: case <-ctx.Done(): } -} - -// CC BY and CC BY-SA are usable only with attribution; media rights are separate. -// Deliberately reject ambiguous or non-open licenses. -func tourismLicense(raw string) string { - s := strings.ToLower(strings.TrimSpace(raw)) - // Never accept non-commercial or no-derivatives licenses. - if strings.Contains(s,"-nc") || strings.Contains(s,"-nd") || strings.Contains(s,"/nc/") || strings.Contains(s,"/nd/") || - strings.Contains(s,"by-nc") || strings.Contains(s,"by-nd") || - strings.Contains(s,"by nc") || strings.Contains(s,"by nd") || - strings.Contains(s,"noncommercial") || strings.Contains(s,"no derivatives") || - strings.Contains(s,"noderivatives") { return "" } - switch { - case strings.Contains(s, "creativecommons.org/publicdomain/zero/"), strings.Contains(s, "cc0"), strings.Contains(s, "cc-0"): return "CC0" - case strings.Contains(s, "creativecommons.org/licenses/by-sa/"), strings.Contains(s, "cc-by-sa"), strings.Contains(s, "cc by-sa"), strings.Contains(s, "cc by sa"): return "CC BY-SA" - case strings.Contains(s, "creativecommons.org/licenses/by/"), strings.Contains(s, "cc-by"), strings.Contains(s, "cc by"): return "CC BY" - default: return "" - } -} -func tourismMediaRights(m map[string]any, chosenURL string) (license, attribution string) { - if chosenURL=="" { return "", "" } - for _,key:=range []string{"media","medias","images","pictures","assets","mediaObjects"} { - val,ok:=d1ValueCaseInsensitive(m,key) - if !ok {continue} - entries:=[]any{} - if items,ok:=val.([]any);ok {entries=items} else {entries=[]any{val}} - for _,entry:=range entries{ - obj,ok:=entry.(map[string]any) - if !ok {continue} - candidate:=tourismNormalizeURL(d1FirstStringCI(obj,"url","href","src","value")) - if candidate!=chosenURL {continue} - lic:=tourismLicense(d1FirstStringCI(obj,"license","licence","rights")) - att:=d1FirstStringCI(obj,"copyright","attribution","credit","author","creator") - if lic=="CC0" || (lic!="" && att!="") {return lic,att} - } - } - return "", "" -} -func tourismNormalizeURL(raw string) string { - u, err := url.Parse(strings.TrimSpace(raw)) - if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || u.User != nil { return "" } - return u.String() -} - -func tourismParse(kind string, m map[string]any) (tourismItem, error) { - v := tourismItem{ - ContentType: kind, - ExternalID: d1FirstStringCI(m, "global_id", "globalId", "id", "identifier", "uuid"), - Title: d1FirstStringCI(m, "title", "name", "headline"), - Category: d1Category(m), - City: d1FirstStringCI(m, "city", "locality", "town"), - PostalCode: d1FirstStringCI(m, "postalCode", "postal_code", "zip"), - Description: normalizeDestinationText(d1TextByRel(m, "details", "detail", "teaser", "description", "shortdescription")), - Website: tourismNormalizeURL(d1URL(m)), - DataLicense: tourismLicense(d1License(m)), - Attribution: d1FirstStringCI(m,"attribution","copyright","credit","author","creator","provider"), - ImageURL: tourismNormalizeURL(extractImage(m)), - } - if v.Description == "" { v.Description = normalizeDestinationText(d1FirstStringCI(m, "description", "text", "shortDescription", "longDescription")) } - if address := d1Address(m); address != nil { - if v.City == "" { v.City = d1FirstStringCI(address, "city", "addressLocality", "locality", "town", "municipality") } - if v.PostalCode == "" { v.PostalCode = d1FirstStringCI(address, "postalCode", "zip", "postal_code") } - } - if v.City == "" { v.City = d1RecursiveStringForKeys(m, "city", "addressLocality", "town", "municipality") } - if v.PostalCode == "" { v.PostalCode = d1RecursiveStringForKeys(m, "postalCode", "zip") } - v.SourceURL = tourismNormalizeURL(d1FirstStringCI(m, "url", "website", "link")) - if v.SourceURL == "" { v.SourceURL = v.Website } - if !tourismTypeValid(kind) { return v, errors.New("ungültiger touristischer Datentyp") } - if v.Title == "" { return v, errors.New("Titel fehlt") } - if v.ExternalID == "" { return v, errors.New("Quellen-ID fehlt") } - // Image rights must be independent of the textual data rights. - v.ImageLicense,v.ImageAttribution=tourismMediaRights(m,v.ImageURL) - if len(v.Website)>1800 {v.Website=""} - if len(v.SourceURL)>1800 {v.SourceURL=""} - if len(v.ImageURL)>1800 {v.ImageURL="";v.ImageLicense="";v.ImageAttribution=""} - if len(v.Attribution)>500 {v.Attribution=string([]rune(v.Attribution)[:min(len([]rune(v.Attribution)),500)])} - if len(v.ImageAttribution)>500 {v.ImageAttribution=string([]rune(v.ImageAttribution)[:min(len([]rune(v.ImageAttribution)),500)])} - if len(v.Title) > 250 { v.Title = v.Title[:250] } - if len(v.Description) > 12000 { v.Description = v.Description[:12000] } - return v, nil -} -func (h *tourismHub) SyncType(ctx context.Context, kind string) (int, error) { - if !h.Ready() { return 0, errors.New("Datenbank nicht verfügbar") } - if !tourismTypeValid(kind) { return 0, errors.New("ungültiger Typ") } - if !tourismImportMu.TryLock() { return 0, errors.New("Import läuft bereits") } - defer tourismImportMu.Unlock() - cfg := h.settings.Get().DestinationOne - if !cfg.Enabled || cfg.APIKey == "" { return 0, errors.New("Niedersachsen-HUB unter Einstellungen aktivieren und Lizenzschlüssel hinterlegen") } - base, err := destinationOneURL(cfg) - if err != nil { return 0, err } - offset,err:=h.NextOffset(ctx,kind) - if err!=nil{return 0,err} - total := 0 - for page := 0; page < 10; page++ { - u := *base - q := u.Query() - q.Set("type", kind) - q.Set("limit", "100") - q.Set("offset", strconv.Itoa(offset+page*100)) - q.Set("mkt", "de-DE") - u.RawQuery = q.Encode() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) - if err != nil { return total, err } - req.Header.Set("Accept", "application/json") - resp, err := h.client.Do(req) - if err != nil { return total, fmt.Errorf("%s Abruf: %w", kind, err) } - body, readErr := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) - resp.Body.Close() - if readErr != nil { return total, readErr } - if resp.StatusCode != http.StatusOK { return total, fmt.Errorf("%s API HTTP %d", kind, resp.StatusCode) } - var payload any - if err := json.Unmarshal(body, &payload); err != nil { return total, fmt.Errorf("%s: kein gültiges JSON: %w", kind, err) } - items := destinationMaps(payload) - if page == 0 && offset==0 && len(items) == 0 { return 0, fmt.Errorf("%s: keine items in API-Antwort", kind) } - parsed:=make([]tourismItem,0,len(items)) - seen:=make(map[string]struct{},len(items)) - for _, raw := range items { - item, err := tourismParse(kind, raw) - if err != nil {continue} - if _,duplicate:=seen[item.ExternalID];duplicate {continue} - seen[item.ExternalID]=struct{}{} - parsed=append(parsed,item) - } - if err:=h.UpsertBatch(ctx,parsed);err!=nil{return total,err} - total+=len(parsed) - next:=offset+(page+1)*100 - if len(items)<100 {next=0} - if err:=h.SaveOffset(ctx,kind,next);err!=nil{return total,err} - if len(items) < 100 { break } - } - return total, nil -} -// The source catalogue can contain many thousands of records. -// Save progress after each page, so a timeout never forces a restart from page zero. -func (h *tourismHub) NextOffset(ctx context.Context, kind string) (int,error) { - var next int - q:="SELECT COALESCE((SELECT next_offset FROM landwelle.tourism_hub_sync_state WHERE content_type="+sqlText(kind)+"),0)::text;" - if err:=h.db.queryJSON(ctx,q,&next);err!=nil{return 0,fmt.Errorf("Importfortsetzung benötigt Migration 0046: %w",err)} - if next<0 || next>1000000 {return 0,errors.New("Import-Offset ungültig")} - return next,nil -} -func (h *tourismHub) SaveOffset(ctx context.Context, kind string, next int) error { - q:="INSERT INTO landwelle.tourism_hub_sync_state(content_type,next_offset,last_sync_at) VALUES ("+sqlText(kind)+","+strconv.Itoa(next)+",now()) "+ - "ON CONFLICT(content_type) DO UPDATE SET next_offset=excluded.next_offset,last_sync_at=excluded.last_sync_at;" - _,err:=h.db.exec(ctx,q) - return err -} -// Batch in groups of five to stay below operating-system command argument -// limits of the existing psql-based storage adapter even with long descriptions. -func (h *tourismHub) UpsertBatch(ctx context.Context, items []tourismItem) error { - if !h.Ready() {return errors.New("Datenbank nicht verfügbar")} - for start:=0;startlen(items){end=len(items)} - values:=make([]string,0,end-start) - for _,v:=range items[start:end] { - values=append(values,"("+strings.Join([]string{ - sqlText(v.ExternalID),sqlText(v.ContentType),sqlText(v.Title),sqlText(v.Category), - sqlText(v.City),sqlText(v.PostalCode),sqlText(v.Description),sqlText(v.Website), - sqlText(v.SourceURL),sqlText(v.DataLicense),sqlText(v.Attribution),sqlText(v.ImageURL), - sqlText(v.ImageLicense),sqlText(v.ImageAttribution),"now()", - },",")+")") - } - query:="INSERT INTO landwelle.tourism_hub_items(external_id,content_type,title,category,city,postal_code,description,website,source_url,data_license,attribution,image_url,image_license,image_attribution,last_seen) VALUES "+ - strings.Join(values,",")+" ON CONFLICT(content_type,external_id) DO UPDATE SET title=excluded.title,category=excluded.category,city=excluded.city,postal_code=excluded.postal_code,description=excluded.description,website=excluded.website,source_url=excluded.source_url,data_license=excluded.data_license,"+ - "attribution=CASE WHEN excluded.attribution='' THEN landwelle.tourism_hub_items.attribution ELSE excluded.attribution END,"+ - "image_url=excluded.image_url,image_license=CASE WHEN excluded.image_url=landwelle.tourism_hub_items.image_url AND excluded.image_license='' THEN landwelle.tourism_hub_items.image_license ELSE excluded.image_license END,"+ - "image_attribution=CASE WHEN excluded.image_url=landwelle.tourism_hub_items.image_url AND excluded.image_license='' THEN landwelle.tourism_hub_items.image_attribution ELSE excluded.image_attribution END,"+ - "last_seen=now(),updated_at=now(),published=CASE WHEN excluded.data_license='' OR (excluded.data_license<>'CC0' AND excluded.attribution='' AND landwelle.tourism_hub_items.attribution='') THEN false ELSE landwelle.tourism_hub_items.published END;" - if _,err:=h.db.exec(ctx,query);err!=nil{return err} - } - return nil -} -func (h *tourismHub) Upsert(ctx context.Context, item tourismItem) error { - return h.UpsertBatch(ctx,[]tourismItem{item}) -} -func (h *tourismHub) List(ctx context.Context, kind, city, search string, publishedOnly bool, page, perPage int) (tourismListing, error) { - out := tourismListing{Items: []tourismItem{}} - if !h.Ready() { return out, nil } - if page < 1 { page = 1 } - if perPage < 1 || perPage > 100 { perPage = 24 } - where := []string{"1=1"} - if publishedOnly { where = append(where, "published=true AND data_license IN ('CC0','CC BY','CC BY-SA') AND (data_license='CC0' OR attribution<>'')") } - if tourismTypeValid(kind) { where = append(where, "content_type="+sqlText(kind)) } - if city != "" { where = append(where, "lower(city) LIKE lower("+sqlText("%"+city+"%")+")") } - if search != "" { where = append(where, "(title ILIKE "+sqlText("%"+search+"%")+" OR description ILIKE "+sqlText("%"+search+"%")+")") } - condition := strings.Join(where, " AND ") - query := "SELECT json_build_object('total',(SELECT count(*) FROM landwelle.tourism_hub_items WHERE "+condition+"),'items',"+ - "(SELECT coalesce(json_agg(row_to_json(p)),'[]'::json) FROM (SELECT id,external_id,content_type,title,category,city,postal_code,description,website,source_url,data_license,attribution,"+ - "CASE WHEN image_license='CC0' OR (image_license IN ('CC BY','CC BY-SA') AND image_attribution<>'') THEN image_url ELSE '' END AS image_url,image_license,image_attribution,published "+ - "FROM landwelle.tourism_hub_items WHERE "+condition+" ORDER BY title,id LIMIT "+strconv.Itoa(perPage)+" OFFSET "+strconv.Itoa((page-1)*perPage)+") p))::text;" - err := h.db.queryJSON(ctx, query, &out) - return out, err -} -func (h *tourismHub) Detail(ctx context.Context, id int64) (*tourismItem, error) { - if !h.Ready() { return nil, nil } - var item *tourismItem - query := "SELECT coalesce((SELECT row_to_json(p)::text FROM (SELECT id,external_id,content_type,title,category,city,postal_code,description,website,source_url,data_license,attribution,"+ - "CASE WHEN image_license='CC0' OR (image_license IN ('CC BY','CC BY-SA') AND image_attribution<>'') THEN image_url ELSE '' END AS image_url,image_license,image_attribution,published "+ - "FROM landwelle.tourism_hub_items WHERE id="+strconv.FormatInt(id,10)+" AND published=true AND data_license IN ('CC0','CC BY','CC BY-SA') AND (data_license='CC0' OR attribution<>'')) p),'null');" - if err := h.db.queryJSON(ctx, query, &item); err != nil { return nil, err } - return item, nil -} -func (h *tourismHub) SetPublished(ctx context.Context, id int64, publish bool) error { - if !h.Ready() { return errors.New("Datenbank nicht verfügbar") } - clause := "" - if publish { clause = " AND data_license IN ('CC0','CC BY','CC BY-SA') AND (data_license='CC0' OR attribution<>'')" } - query := "UPDATE landwelle.tourism_hub_items SET published="+sqlBool(publish)+",updated_at=now() WHERE id="+strconv.FormatInt(id,10)+clause+" RETURNING id;" - data, err := h.db.exec(ctx, query) - if err != nil { return err } - if strings.TrimSpace(string(data)) == "" { return errors.New("Datensatz fehlt oder Lizenz nicht freigegeben") } - return nil -} -func (h *tourismHub) ReviewRights(ctx context.Context, id int64, attribution, imageLicense, imageAttribution string) error { - if !h.Ready() { return errors.New("Datenbank nicht verfügbar") } - attribution = strings.TrimSpace(attribution) - imageLicense = tourismLicense(imageLicense) - imageAttribution = strings.TrimSpace(imageAttribution) - if len(attribution)>500 || len(imageAttribution)>500 {return errors.New("Urheberangabe zu lang")} - if imageLicense!="" && imageLicense!="CC0" && imageAttribution=="" { - return errors.New("Bei CC-BY-Bildern ist eine Urheberangabe Pflicht") - } - query:="UPDATE landwelle.tourism_hub_items SET attribution="+sqlText(attribution)+",image_license="+sqlText(imageLicense)+",image_attribution="+sqlText(imageAttribution)+",published=false,updated_at=now() WHERE id="+strconv.FormatInt(id,10)+" RETURNING id;" - data,err:=h.db.exec(ctx,query) - if err!=nil {return err} - if strings.TrimSpace(string(data))==""{return errors.New("Datensatz nicht gefunden")} - return nil -} -func tourismPublicHandler(tmpl *template.Template, data PageData, h *tourismHub, logger *log.Logger) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet && r.Method != http.MethodHead { http.Error(w, "Methode nicht erlaubt", http.StatusMethodNotAllowed); return } - if r.URL.Path != "/niedersachsen-entdecken" && !strings.HasPrefix(r.URL.Path, "/niedersachsen-entdecken/") { http.NotFound(w,r); return } - d := tourismPageData{PageData:data, Types:tourismTypes, Page:1, FilterType:r.URL.Query().Get("typ"), FilterCity:strings.TrimSpace(r.URL.Query().Get("ort")), Query:strings.TrimSpace(r.URL.Query().Get("suche"))} - if len(d.FilterCity)>80 { d.FilterCity=d.FilterCity[:80] } - if len(d.Query)>100 { d.Query=d.Query[:100] } - if strings.HasPrefix(r.URL.Path,"/niedersachsen-entdecken/") { - n,err:=strconv.ParseInt(strings.TrimPrefix(r.URL.Path,"/niedersachsen-entdecken/"),10,64) - if err != nil || n<1 {http.NotFound(w,r);return} - item,err:=h.Detail(r.Context(),n) - if err!=nil {logger.Printf("Tourismus Detail: %v",err);http.Error(w,"Daten derzeit nicht verfügbar",500);return} - if item==nil {http.NotFound(w,r);return} - d.Item=item - } else { - d.Page,_=strconv.Atoi(r.URL.Query().Get("seite")) - if d.Page<1 || d.Page>10000 {d.Page=1} - result,err:=h.List(r.Context(),d.FilterType,d.FilterCity,d.Query,true,d.Page,24) - if err!=nil {logger.Printf("Tourismus Suche: %v",err);d.Error="Die touristischen Daten sind momentan nicht verfügbar."} - d.Items=result.Items;d.Total=result.Total;d.Pages=(d.Total+23)/24 - d.HasPrev=d.Page>1;d.HasNext=d.Page0 {err=hub.ReviewRights(r.Context(),id,r.FormValue("attribution"),r.FormValue("image_license"),r.FormValue("image_attribution"))} - if err!=nil {flash="Fehler: "+err.Error()} else {flash="Nutzungsrechte gespeichert; Datensatz ist zur erneuten Freigabe vorgemerkt."} - case "publish","unpublish": - id,err:=strconv.ParseInt(r.FormValue("id"),10,64) - if err==nil && id>0 {err=hub.SetPublished(r.Context(),id,r.FormValue("action")=="publish")} - if err!=nil{flash="Fehler: "+err.Error()} else {flash="Freigabestatus gespeichert."} - default: http.Error(w,"Aktion nicht unterstützt",400);return - } - } - cfg:=a.settings.Get().DestinationOne - list,err:=hub.List(r.Context(),"","","",false,1,80) - d:=tourismAdminData{Username:session.Username,CSRFToken:session.CSRFToken,Types:tourismTypes,Items:list.Items,KeySet:cfg.APIKey!="",Enabled:cfg.Enabled,Success:flash} - if err!=nil{d.Error="Tourismus-Datenbank nicht bereit: "+err.Error()} - if strings.HasPrefix(flash,"Fehler:"){d.Error=flash;d.Success=""} - t,err:=parseAdminTemplate("web/admin/tourism.html") - if err!=nil{http.Error(w,"Admin-Template nicht verfügbar",500);a.logger.Printf("Tourismus-Admin Template: %v",err);return} - setAdminHTMLHeaders(w) - if err=t.ExecuteTemplate(w,"tourism-admin.html",d);err!=nil{a.logger.Printf("Tourismus-Admin Render: %v",err)} -} diff --git a/tourism_hub_test.go b/tourism_hub_test.go deleted file mode 100644 index 586229d..0000000 --- a/tourism_hub_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "bytes" - "html/template" - "strings" - "testing" -) - -func TestTourismHubTypesAndLicenses(t *testing.T) { - if len(tourismTypes)!=8 { t.Fatalf("expected 8 tourist types, got %d",len(tourismTypes)) } - for _,kind:=range tourismTypes {if !tourismTypeValid(kind){t.Fatalf("invalid supported type %s",kind)}} - if tourismTypeValid("Event") || tourismTypeValid("all"){t.Fatal("events must remain in existing event importer")} - tests:=[]struct{raw,want string}{ - {"CC0 1.0","CC0"}, - {"https://creativecommons.org/licenses/by/4.0/","CC BY"}, - {"https://creativecommons.org/licenses/by-sa/4.0/","CC BY-SA"}, - {"CC BY-NC 4.0",""}, - {"CC BY-ND 4.0",""}, - {"CC BY-SA-NC 4.0",""}, - {"copyright",""}, - {"All rights reserved",""}, - {"",""}, - } - for _,tc:=range tests {if got:=tourismLicense(tc.raw);got!=tc.want{t.Errorf("%q => %q, want %q",tc.raw,got,tc.want)}} -} - -func TestTourismHubParseSeparatesDataAndImageLicense(t *testing.T) { - src:=map[string]any{ - "id":"nds:poi-1", - "title":"Historisches Ausflugsziel", - "categories":[]any{map[string]any{"name":"Sehenswürdigkeit"}}, - "address":map[string]any{"city":"Celle","postalCode":"29221"}, - "description":"

Ein Ort in Niedersachsen.

", - "license":"CC BY 4.0", - "media":[]any{map[string]any{"url":"https://example.org/image.jpg"}}, - "website":"https://example.org/", - } - item,err:=tourismParse("POI",src) - if err!=nil{t.Fatal(err)} - if item.ExternalID!="nds:poi-1" || item.City!="Celle" || item.PostalCode!="29221"{t.Fatalf("fields not parsed: %+v",item)} - if item.DataLicense!="CC BY"{t.Fatalf("data license incorrect: %s",item.DataLicense)} - if item.ImageLicense!=""{t.Fatal("image license must NOT be inferred from text license")} - if item.Published{t.Fatal("import must not auto-publish")} - if strings.Contains(item.Description,"

"){t.Fatal("HTML tags leaked into description")} - if _,err:=tourismParse("Event",src);err==nil{t.Fatal("event import must be separate")} -} -func TestTourismHubURLSafety(t *testing.T){ - for _,s:=range []string{"javascript:alert(1)","file:///etc/passwd","https://example.org@evil.test", "ftp://example.org/file"}{ - if s=="https://example.org@evil.test"{continue} // ordinary URL userinfo is checked below - if got:=tourismNormalizeURL(s);got!=""{t.Errorf("accepted %q as %q",s,got)} - } - if got:=tourismNormalizeURL("https://user:pass@example.org/");got!=""{t.Fatalf("accepted credentials in URL: %q",got)} - if got:=tourismNormalizeURL("https://example.org/path");got==""{t.Fatal("rejected valid HTTPS URL")} -} - -func TestTourismHubTemplatesRender(t *testing.T) { - admin,err:=parseAdminTemplate("web/admin/tourism.html") - if err!=nil{t.Fatalf("admin tourism parse: %v",err)} - var b bytes.Buffer - if err:=admin.ExecuteTemplate(&b,"tourism-admin.html",tourismAdminData{Username:"redaktion",CSRFToken:"test",Types:tourismTypes});err!=nil{ - t.Fatalf("admin tourism render: %v",err) - } - if !strings.Contains(b.String(),"Niedersachsen Hub verwalten") {t.Fatal("admin tourism view missing")} - tpls,err:=template.New("portal").Funcs(template.FuncMap{ - "year":func()int{return 2026}, - "seoHead":seoHead, - "publicNavigation":func() template.HTML{return ""}, - }).ParseFS(webFS,"web/partials.html","web/tourism.html") - if err!=nil {t.Fatalf("tourism public parse: %v",err)} - b.Reset() - if err:=tpls.ExecuteTemplate(&b,"tourism.html",tourismPageData{PageData:pageData(),Types:tourismTypes,Page:1});err!=nil{ - t.Fatalf("tourism public render: %v",err) - } - if !strings.Contains(b.String(),"Niedersachsen entdecken") {t.Fatal("public tourism view missing")} -} diff --git a/web/admin/management.html b/web/admin/management.html index dc6226e..bf3e244 100644 --- a/web/admin/management.html +++ b/web/admin/management.html @@ -45,15 +45,15 @@ {{end}} {{else if eq .Module "events"}} -

Kalender

Veranstaltungen verwalten

Hub-Termine und eigene Veranstaltungen getrennt verwalten. Eigene Termine kannst du direkt anlegen, bearbeiten und veröffentlichen.

- -{{if eq .EventTab "hub"}}
Niedersachsen HubHier erscheinen aktuelle importierte Termine. Änderungen an importierten Datensätzen können beim nächsten Import wieder überschrieben werden.
{{else}}
Eigene VeranstaltungenEinsendungen und redaktionell angelegte Termine lassen sich hier vollständig bearbeiten. Veröffentlichte eigene Veranstaltungen nehmen automatisch an der zufälligen Auswahl der bis zu drei Startseiten-Termine teil.
{{end}} +
Kalender

Veranstaltungen verwalten

Eigene Veranstaltungen und Einsendungen anlegen, bearbeiten und veröffentlichen.

+ +
Eigene VeranstaltungenEinsendungen und redaktionell angelegte Termine lassen sich hier vollständig bearbeiten. Veröffentlichte eigene Veranstaltungen nehmen automatisch an der zufälligen Auswahl der bis zu drei Startseiten-Termine teil.
-{{range .Events}}{{$event := .}}
{{if .ImageURL}}Veranstaltungsbild {{.Title}}{{else}}
Termin
{{end}}
{{.Title}}{{.StartAt.Format "02.01.2006 15:04"}} · {{.City}} · {{.SourceName}}
{{.Category}}{{if eq .Status "published"}}Veröffentlicht{{else if eq .Status "pending"}}Offen{{else if eq .Status "rejected"}}Abgelehnt{{else if eq .Status "archived"}}Archiviert{{else}}{{.Status}}{{end}}
{{if ne .Status "published"}}{{end}}{{if and (eq $.EventTab "submissions") (eq .Status "pending")}}{{end}}
-
Veranstaltung bearbeiten

{{.Title}}

{{if .ImageURL}}{{end}}
{{else}}

{{if eq .EventTab "hub"}}Keine aktuellen Hub-Veranstaltungen{{else}}Keine eigenen Veranstaltungen{{end}}

{{if eq .EventTab "hub"}}Beim nächsten Import erscheinen hier neue Termine aus dem Niedersachsen Hub.{{else}}Lege oben eine Veranstaltung an oder warte auf eine neue Einsendung über die Webseite.{{end}}

{{end}}
-{{if or (and (eq .EventTab "hub") (gt .HubCount 0)) (gt .EventTotalPages 1)}}{{end}}
-
Landwelle Redaktion

Neue Veranstaltung eintragen

Der Termin wird als eigene Landwelle-Veranstaltung gespeichert und kann direkt veröffentlicht werden.

-
Veranstaltungskalender

Rubriken verwalten

Aktive Rubriken stehen auf der Webseite und beim Eintragen neuer Veranstaltungen zur Auswahl.

Neue Rubrik

{{range .EventCategories}}
Verwendet{{.EventCount}}×
{{else}}

Noch keine Rubriken vorhanden.

{{end}}
+{{range .Events}}{{$event := .}}
{{if .ImageURL}}Veranstaltungsbild {{.Title}}{{else}}
Termin
{{end}}
{{.Title}}{{.StartAt.Format "02.01.2006 15:04"}} · {{.City}} · {{.SourceName}}
{{.Category}}{{if eq .Status "published"}}Veröffentlicht{{else if eq .Status "pending"}}Offen{{else if eq .Status "rejected"}}Abgelehnt{{else if eq .Status "archived"}}Archiviert{{else}}{{.Status}}{{end}}
{{if ne .Status "published"}}{{end}}{{if eq .Status "pending"}}{{end}}
+
Veranstaltung bearbeiten

{{.Title}}

{{if .ImageURL}}{{end}}
{{else}}

Keine eigenen Veranstaltungen

Lege oben eine Veranstaltung an oder warte auf eine neue Einsendung über die Webseite.

{{end}} +{{if gt .EventTotalPages 1}}{{end}} +
Landwelle Redaktion

Neue Veranstaltung eintragen

Der Termin wird als eigene Landwelle-Veranstaltung gespeichert und kann direkt veröffentlicht werden.

+
Veranstaltungskalender

Rubriken verwalten

Aktive Rubriken stehen auf der Webseite und beim Eintragen neuer Veranstaltungen zur Auswahl.

Neue Rubrik

{{range .EventCategories}}
Verwendet{{.EventCount}}×
{{else}}

Noch keine Rubriken vorhanden.

{{end}}
{{else}}
Sicherheit & Nachvollziehbarkeit

Audit-Protokoll

Verwaltungsaktionen prüfen, Fehler schneller finden und Änderungen lückenlos nachvollziehen.

{{.AuditTotal}} Einträge
Erfolgreich{{.AuditSuccessCount}}Aktionen im Filter
Fehlgeschlagen{{.AuditFailureCount}}benötigen Aufmerksamkeit
Aktive Konten{{.AuditActorCount}}unterschiedliche Akteure
Heute{{.AuditTodayCount}}Aktionen seit 0 Uhr
Protokollsuche

Verwaltungsaktivitäten

Suche nach Benutzer, Aktion, Objekt oder Beschreibung.

{{if or .AuditQuery .AuditAction .AuditResult}}Zurücksetzen{{end}}
diff --git a/web/admin/settings.html b/web/admin/settings.html index 0797a69..42cb574 100644 --- a/web/admin/settings.html +++ b/web/admin/settings.html @@ -5,7 +5,7 @@
Landwelle RadioSystemeinstellungen
{{printf "%.1s" .Username}}
{{.Username}}Administrator
Integrationen

Systemeinstellungen

Radio, KI, Kommunikation, Auslieferung und soziale Netzwerke übersichtlich verwalten.

Konfigurationsdatei{{.SettingsPath}}
{{if .Error}}
{{.Error}}
{{end}}{{if .Success}}
{{.Success}}
{{end}} -
+
Webseite & Werbung

Google AdSense

Steuert die Einbindung von Google AdSense auf den öffentlichen Landwelle-Seiten. Änderungen werden direkt beim Speichern übernommen; ein Neustart ist nicht erforderlich.

@@ -23,19 +23,6 @@
Meta Pages API

Facebook-Seite

Bei veröffentlichten Redaktionsbeiträgen mit aktivem Facebook-Haken wird der Beitrag unmittelbar über die Facebook Pages API veröffentlicht.

WhatsApp

Landwelle Kanal

Die offizielle WhatsApp Cloud API unterstützt derzeit keine automatische Veröffentlichung in WhatsApp-Kanälen. Die Kanal-URL wird zentral gespeichert; automatische Posts werden erst aktiviert, sobald Meta dafür eine offizielle Schreib-API bereitstellt.

-
-
Niedersachsen Hub

destination.one Veranstaltungsimport

-
-
Fester Niedersachsen-Hub-Abruf

Der Import nutzt automatisch meta.et4.de, das Projekt open-data-niedersachsen-tourismus, den Typ Event und das Template ET2014A.json. Du musst nur deinen Lizenzschlüssel hinterlegen.

- - - - - - - -

Das Speichern ändert nur die Einstellungen. Der Import wird ausschließlich über den separaten Button gestartet. Du erhältst danach eine klare Erfolgs- oder Fehlermeldung. Die API-Abfrage wird automatisch auf Veranstaltungen, deutsche Inhalte und die kommenden zwölf Monate begrenzt. Bereits importierte Termine werden aktualisiert und nicht doppelt angelegt.

-
Niedersachsen-Hub jetzt importieren

Dieser Vorgang läuft getrennt vom Speichern und kann bei vielen Veranstaltungen länger dauern.

-

Sicherheitshinweis

API-Schlüssel werden serverseitig in der geschützten Laufzeitkonfiguration gespeichert und in dieser Oberfläche nie wieder ausgegeben. Dateirechte und Zugriff auf /var/lib/landwelle müssen auf den Portal-Dienst beschränkt bleiben.

+

Sicherheitshinweis

API-Schlüssel werden serverseitig in der geschützten Laufzeitkonfiguration gespeichert und in dieser Oberfläche nie wieder ausgegeben. Dateirechte und Zugriff auf /var/lib/landwelle müssen auf den Portal-Dienst beschränkt bleiben.

{{end}} diff --git a/web/admin/tourism.html b/web/admin/tourism.html deleted file mode 100644 index 98f5389..0000000 --- a/web/admin/tourism.html +++ /dev/null @@ -1,31 +0,0 @@ -{{define "tourism-admin.html"}} - -Niedersachsen Hub – Landwelle -
- -
Landwelle RadioNiedersachsen Hub
{{.Username}}
-
Touristische Open Data

Niedersachsen Hub verwalten

Datentypen getrennt importieren, Lizenzstatus prüfen und Inhalte redaktionell veröffentlichen.

-{{if .Error}}
{{.Error}}
{{end}}{{if .Success}}
{{.Success}}
{{end}} -

Import der touristischen Inhalte

-

Quelle: Niedersachsen Hub / destination.one. Bestehende Veranstaltungsimporte bleiben separat unter Veranstaltungen.

-

Status: {{if .Enabled}}aktiv{{else}}deaktiviert{{end}} · Lizenzschlüssel: {{if .KeySet}}hinterlegt{{else}}fehlt{{end}}. Zugang konfigurieren.

-
{{range .Types}}
{{end}}
-

Importierte Datensätze sind niemals automatisch veröffentlicht. Texte und Bilder benötigen getrennte Nutzungsrechte. Bei unklaren Lizenzen ist eine Veröffentlichung gesperrt.

-
-

Importierte Datensätze – letzte 80

-
{{range .Items}} -
{{.ContentType}} · {{.DataLicense}}

{{.Title}}

{{.City}} · {{.Category}}

{{if .SourceURL}}Quelle prüfen ↗{{else}}Kein Quelllink vorhanden{{end}}

Text: {{if .Attribution}}{{.Attribution}}{{else}}Urheberangabe noch prüfen{{end}} · Bild: {{if .ImageLicense}}{{.ImageLicense}}{{else}}nicht separat freigegeben{{end}}

{{if .ImageURL}}

Bildquelle prüfen ↗

{{end}}
-
- - - - - -
-
-{{if .Published}} -{{else}}{{end}}
{{else}}

Noch keine touristischen Datensätze importiert.

{{end}} -
-Öffentlichen Tourismusbereich ansehen ↗ -
-{{end}} diff --git a/web/assets/tourism-hub-v1.css b/web/assets/tourism-hub-v1.css deleted file mode 100644 index 18897e8..0000000 --- a/web/assets/tourism-hub-v1.css +++ /dev/null @@ -1,7 +0,0 @@ -.tourism-main{max-width:1280px;margin:auto;padding:32px 20px 80px;color:var(--text,#18251a)}.tourism-hero{padding:54px clamp(22px,5vw,66px);border-radius:28px;background:linear-gradient(125deg,#103d29,#195f3b);color:#fff}.tourism-hero h1{font-size:clamp(2rem,4vw,3.8rem);line-height:1.08;margin:14px 0}.tourism-hero p{max-width:780px;font-size:1.08rem;line-height:1.6}.tourism-hero a{color:white;text-decoration:underline}.tourism-kicker{letter-spacing:.08em;text-transform:uppercase;font-weight:700;font-size:.83rem}.tourism-content{padding-top:35px}.tourism-filter{display:grid;grid-template-columns:2fr 1fr 1fr auto;align-items:end;gap:12px;padding:24px;border-radius:18px;background:#f3f7f3}.tourism-filter label{display:flex;flex-direction:column;gap:8px;font-weight:700}.tourism-filter input,.tourism-filter select{min-height:46px;border:1px solid #b3c6b7;border-radius:10px;padding:9px 12px;width:100%;background:white;color:#16331f}.tourism-filter button,.tourism-details{background:#176d40;color:white;border:0;border-radius:10px;padding:13px 19px;text-decoration:none;font-weight:700;cursor:pointer}.tourism-count{margin:25px 0 15px;color:#55695b}.tourism-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:22px}.tourism-card{background:#fff;border:1px solid #e1e8e0;border-radius:18px;overflow:hidden;box-shadow:0 6px 22px rgba(9,42,23,.06)}.tourism-card img,.tourism-placeholder{width:100%;height:170px;object-fit:cover;background:linear-gradient(140deg,#d1e5ca,#f6f0d6);display:flex;align-items:center;justify-content:center;color:#375c40;font-weight:700}.tourism-card-copy{padding:22px}.tourism-card h2{font-size:1.3rem;margin:13px 0 8px}.tourism-card h2 a{color:#184830;text-decoration:none}.tourism-card p{line-height:1.55}.tourism-card .tourism-card-copy>p:not(.tourism-place){display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.tourism-chip{font-size:.78rem;color:#116138;font-weight:700;text-transform:uppercase;letter-spacing:.035em}.tourism-place{font-weight:700}.tourism-details{display:inline-block;margin-top:8px}.tourism-detail{display:grid;grid-template-columns:minmax(0,2fr) minmax(240px,1fr);gap:30px;padding:28px 0}.tourism-detail-body,.tourism-source{border:1px solid #e1e8e0;border-radius:16px;background:#fff;padding:25px}.tourism-description{white-space:pre-line;line-height:1.75}.tourism-detail img{max-width:100%;border-radius:14px}.tourism-source{align-self:start}.tourism-disclaimer{font-size:.9rem;color:#67786d;margin-top:25px}.tourism-empty{grid-column:1/-1;padding:40px;border:1px dashed #adc5b1;border-radius:16px}.tourism-pagination{display:flex;gap:25px;justify-content:center;align-items:center;margin:28px 0}.tourism-pagination a{color:#176d40}.tourism-error{color:#a32020}.tourism-admin-panel{margin-bottom:25px}.tourism-type-actions{display:flex;gap:10px;flex-wrap:wrap;margin:15px 0}.tourism-admin-list{display:grid;gap:14px}.tourism-admin-item{display:flex;justify-content:space-between;align-items:center;gap:16px;border-bottom:1px solid #ddd;padding:16px 0}.tourism-admin-item h3{margin:6px 0}.tourism-admin-item p{margin:4px 0}.tourism-admin-item form{min-width:180px}@media(max-width:900px){.tourism-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.tourism-filter{grid-template-columns:1fr 1fr}.tourism-detail{grid-template-columns:1fr}}@media(max-width:570px){.tourism-grid,.tourism-filter{grid-template-columns:1fr}.tourism-admin-item{flex-direction:column;align-items:stretch}.tourism-hero{padding:30px 22px}} -.tourism-rights-actions{display:flex;flex-direction:column;gap:10px;min-width:250px;max-width:390px} -.tourism-rights-actions form{display:grid;gap:9px} -.tourism-rights-actions label{display:grid;gap:5px;font-size:.86rem;font-weight:600} -.tourism-rights-actions input,.tourism-rights-actions select{width:100%;min-height:38px;border:1px solid #b7c9be;border-radius:8px;padding:6px 9px} -.tourism-rights-actions button{width:100%} -@media(max-width:900px){.tourism-rights-actions{max-width:none;width:100%}} diff --git a/web/tourism.html b/web/tourism.html deleted file mode 100644 index c4393f1..0000000 --- a/web/tourism.html +++ /dev/null @@ -1,59 +0,0 @@ -{{define "tourism.html"}} - -{{seoHead "Niedersachsen entdecken – Landwelle" "Ausflugsziele, Sehenswürdigkeiten, Touren, Gastgeber, Gastronomie und touristische Regionen in Niedersachsen entdecken." "/niedersachsen-entdecken" "website"}} - - - -{{template "public_header" .}} -
-
- Landwelle · Unterwegs in Niedersachsen -

{{if .Item}}{{.Item.Title}}{{else}}Niedersachsen entdecken{{end}}

-

{{if .Item}}Aus dem offenen Datenangebot des Niedersachsen Hub.{{else}}Die schönsten Ecken unseres Landes: Ausflüge, Sehenswürdigkeiten, Touren, Gastronomie, Übernachtungen und regionale Geschichten – gesammelt an einem Ort.{{end}}

- Alle touristischen Angebote -
-{{if .Item}} -
-
-

{{.Item.ContentType}}{{if .Item.Category}} · {{.Item.Category}}{{end}}

- {{if .Item.City}}

Ort: {{.Item.PostalCode}} {{.Item.City}}

{{end}} - {{if .Item.ImageURL}}
{{.Item.Title}}
Bild: {{if .Item.ImageAttribution}}{{.Item.ImageAttribution}} · {{end}}{{.Item.ImageLicense}}
{{end}} -
{{.Item.Description}}
- {{if .Item.Website}}

Offizielle Webseite / Angebot öffnen ↗

{{end}} -
- -
-{{else}} -
-
- - - - -
-

{{.Total}} veröffentlichte Angebote gefunden{{if .Query}} für „{{.Query}}“{{end}}

- {{if .Error}}

{{.Error}}

{{end}} -
- {{range .Items}} -
- {{if .ImageURL}}{{.Title}}{{else}}{{end}} -
{{.ContentType}}{{if .Category}} · {{.Category}}{{end}} -

{{.Title}}

-

{{.PostalCode}} {{.City}}

-

{{.Description}}

- Mehr entdecken →
-
{{else}} -

Noch keine freigegebenen Angebote

Neue Einträge werden erst nach Prüfung der Daten- und Bildrechte von der Landwelle-Redaktion veröffentlicht.

- {{end}} -
- {{if gt .Pages 1}}{{end}} -

Quelle: Niedersachsen Hub / destination.one. Angebote und Termine können sich ändern. Die jeweiligen Lizenz- und Quellenangaben stehen am Datensatz.

-
{{end}} -
-{{template "public_footer" .}} - -{{end}}