feat: expand Niedersachsen Hub with tourism data catalogue
* feat(tourism): add typed Niedersachsen Hub API ingestion, rights checks, catalogue and moderation * feat(tourism): add open data catalogue migration and frontend * feat(tourism): add open data catalogue migration and frontend * feat(tourism): add open data catalogue migration and frontend * feat(tourism): add open data catalogue migration and frontend * feat(tourism): integrate Niedersachsen Hub catalogue into public and admin routing * test(tourism): verify types, open licensing, parsers and URL safety * test: expect Landwelle v1.5.71 * fix(tourism): independent image rights and attribution enforcement * feat(tourism): persist independent rights-holder attribution for text and images * feat(tourism): permit editorial source and media credit review with re-approval * feat(tourism): add moderated text and media rights controls * feat(tourism): show rights holder and license in public detail * style(tourism): rights review form layout * test(tourism): render public/admin pages and reject NC licenses * feat(tourism): checkpoint multi-page sync to eventually traverse entire source catalogue * feat(tourism): persist import cursors per tourist type * docs(release): document Niedersachsen Hub and package GitHub source * docs(release): document Niedersachsen Hub and package GitHub source * perf(tourism): upsert source records in bounded SQL batches * fix(tourism): de-duplicate source items before batch upsert * fix(tourism): reject ShareAlike non-commercial and no-derivatives licenses
This commit is contained in:
1 parent
1684c1879b
commit
1c1a77a06b
11 files changed
+708
-3
No files matched your search
@@ -0,0 +1,39 @@
|
||||
name: Landwelle GitHub source ZIP
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
source-zip:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout exact commit
|
||||
uses: actions/checkout@v4
|
||||
- name: Determine version
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
version=$(sed -nE 's/^[[:space:]]*applicationVersion[[:space:]]*=[[:space:]]*"([^"]+)".*/\1/p' main.go | head -n1)
|
||||
test -n "$version"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
- name: Package tracked source
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p release
|
||||
git archive --format=zip --output="release/landwelle-go-portal-v${{ steps.version.outputs.version }}-COMPLETE-source.zip" HEAD
|
||||
cd release
|
||||
sha256sum *.zip > "landwelle-go-portal-v${{ steps.version.outputs.version }}-COMPLETE-source.sha256"
|
||||
unzip -t *.zip >/dev/null
|
||||
- name: Upload ZIP and checksum
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: landwelle-v${{ steps.version.outputs.version }}-source
|
||||
path: release/*
|
||||
retention-days: 14
|
||||
if-no-files-found: error
|
||||
@@ -629,6 +629,7 @@ 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))
|
||||
@@ -2596,7 +2597,7 @@ func adminNavigationHTML() string {
|
||||
<span class="admin-nav-subheading">Redaktion</span>
|
||||
<a href="/admin/editorial" data-admin-nav-link>Redaktion & Beiträge</a><a href="/admin/mediathek" data-admin-nav-link>Mediathek</a><a href="/admin/media" data-admin-nav-link>Mediengalerie</a><a href="/admin/presse" data-admin-nav-link>Pressebereich</a><a href="/admin/karriere" data-admin-nav-link>Karriere</a><a href="/admin/faq" data-admin-nav-link>FAQ</a><a href="/admin/kontakt" data-admin-nav-link>Kontakt & Anfragen</a><a href="/admin/team" data-admin-nav-link>Team</a>
|
||||
<span class="admin-nav-subheading">Planung & Verzeichnisse</span>
|
||||
<a href="/admin/program" data-admin-nav-link>Programm</a><a href="/admin/events" data-admin-nav-link>Veranstaltungen</a><a href="/admin/excursions" data-admin-nav-link>Ausflugstipps</a><a href="/admin/directory" data-admin-nav-link>Branchenbuch</a><a href="/admin/navigation" data-admin-nav-link>Website-Navigation</a>
|
||||
<a href="/admin/program" data-admin-nav-link>Programm</a><a href="/admin/events" data-admin-nav-link>Veranstaltungen</a><a href="/admin/niedersachsen-hub" data-admin-nav-link>Niedersachsen Hub · Tourismus</a><a href="/admin/excursions" data-admin-nav-link>Ausflugstipps</a><a href="/admin/directory" data-admin-nav-link>Branchenbuch</a><a href="/admin/navigation" data-admin-nav-link>Website-Navigation</a>
|
||||
</div></details>
|
||||
<details data-admin-nav-group="community"><summary><i>♫</i><span><strong>Hörer & Community</strong><small>Charts, Wünsche und Forum</small></span><b>⌄</b></summary><div>
|
||||
<span class="admin-nav-subheading">Höreraktionen</span>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# 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.
|
||||
@@ -36,7 +36,7 @@ const (
|
||||
apiVersion = "v1"
|
||||
apiContractVersion = "1.0.0"
|
||||
applicationName = "Landwelle Radio"
|
||||
applicationVersion = "1.5.70"
|
||||
applicationVersion = "1.5.71"
|
||||
)
|
||||
|
||||
var publicTemplateFiles = []string{
|
||||
@@ -73,6 +73,7 @@ var publicTemplateFiles = []string{
|
||||
"web/contact.html",
|
||||
"web/mediathek.html",
|
||||
"web/landwelle-zuhause.html",
|
||||
"web/tourism.html",
|
||||
}
|
||||
|
||||
func displayVersion() string {
|
||||
@@ -280,6 +281,7 @@ func main() {
|
||||
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)
|
||||
@@ -327,6 +329,7 @@ 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)
|
||||
@@ -524,6 +527,8 @@ 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))
|
||||
@@ -688,6 +693,7 @@ func main() {
|
||||
defer cancel()
|
||||
rss.Stop(ctx)
|
||||
destinationOne.Stop(ctx)
|
||||
tourismHub.Stop(ctx)
|
||||
if err := server.Shutdown(ctx); err != nil {
|
||||
logger.Printf("Graceful Shutdown: %v", err)
|
||||
}
|
||||
|
||||
+1
-1
@@ -181,7 +181,7 @@ func TestWeatherHelpers(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApplicationVersion(t *testing.T) {
|
||||
if applicationVersion != "1.5.70" {
|
||||
if applicationVersion != "1.5.71" {
|
||||
t.Fatalf("unexpected application version %q", applicationVersion)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
SET search_path TO landwelle, public;
|
||||
|
||||
-- Tourism data is deliberately separated from user-submitted events, directory
|
||||
-- entries and editorial excursions. No imported record is public by default.
|
||||
CREATE TABLE IF NOT EXISTS tourism_hub_items (
|
||||
id bigserial PRIMARY KEY,
|
||||
content_type text NOT NULL CHECK (content_type IN ('POI','Tour','Gastro','Hotel','City','Area','Package','Article')),
|
||||
external_id text NOT NULL,
|
||||
title text NOT NULL,
|
||||
category text NOT NULL DEFAULT '',
|
||||
city text NOT NULL DEFAULT '',
|
||||
postal_code text NOT NULL DEFAULT '',
|
||||
description text NOT NULL DEFAULT '',
|
||||
website text NOT NULL DEFAULT '',
|
||||
source_url text NOT NULL DEFAULT '',
|
||||
data_license text NOT NULL DEFAULT '',
|
||||
attribution text NOT NULL DEFAULT '',
|
||||
image_url text NOT NULL DEFAULT '',
|
||||
image_license text NOT NULL DEFAULT '',
|
||||
image_attribution text NOT NULL DEFAULT '',
|
||||
published boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_seen timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE(content_type, external_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS tourism_hub_public_filter ON tourism_hub_items (content_type, published, city);
|
||||
CREATE INDEX IF NOT EXISTS tourism_hub_last_seen ON tourism_hub_items (last_seen DESC);
|
||||
CREATE INDEX IF NOT EXISTS tourism_hub_review ON tourism_hub_items (published, updated_at DESC);
|
||||
|
||||
-- Import progress is maintained separately for each tourist content type.
|
||||
-- A timed-out run can resume at the last successful page.
|
||||
CREATE TABLE IF NOT EXISTS tourism_hub_sync_state (
|
||||
content_type text PRIMARY KEY CHECK (content_type IN ('POI','Tour','Gastro','Hotel','City','Area','Package','Article')),
|
||||
next_offset integer NOT NULL DEFAULT 0 CHECK (next_offset >= 0),
|
||||
last_sync_at timestamptz
|
||||
);
|
||||
|
||||
-- Make the public discovery area findable without touching the event/calendar menu.
|
||||
DO $$
|
||||
DECLARE
|
||||
north_id bigint;
|
||||
next_sort integer;
|
||||
BEGIN
|
||||
SELECT id INTO north_id FROM navigation_items
|
||||
WHERE lower(trim(label))='unser norden' AND parent_id IS NULL
|
||||
ORDER BY id LIMIT 1;
|
||||
IF north_id IS NULL THEN
|
||||
INSERT INTO navigation_items(label,url,sort_order,active,open_new)
|
||||
VALUES ('Unser Norden','',55,true,false) RETURNING id INTO north_id;
|
||||
END IF;
|
||||
SELECT COALESCE(MAX(sort_order),0)+10 INTO next_sort FROM navigation_items WHERE parent_id=north_id;
|
||||
IF NOT EXISTS (SELECT 1 FROM navigation_items WHERE url='/niedersachsen-entdecken') THEN
|
||||
INSERT INTO navigation_items(parent_id,label,url,sort_order,active,open_new)
|
||||
VALUES (north_id,'Niedersachsen entdecken','/niedersachsen-entdecken',next_sort,true,false);
|
||||
END IF;
|
||||
END $$;
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
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;start<len(items);start+=5 {
|
||||
end:=start+5
|
||||
if end>len(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.Page<d.Pages;d.PrevPage=d.Page-1;d.NextPage=d.Page+1
|
||||
}
|
||||
w.Header().Set("Content-Type","text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control","public, max-age=120")
|
||||
if r.Method==http.MethodHead{return}
|
||||
if err:=tmpl.ExecuteTemplate(w,"tourism.html",d);err!=nil{logger.Printf("Tourismus Template: %v",err)}
|
||||
}
|
||||
}
|
||||
func (a *adminHandler) adminTourismHub(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.MethodGet && r.Method!=http.MethodPost {http.Error(w,"Methode nicht erlaubt",405);return}
|
||||
hub:=newTourismHub(a.database,a.settings,a.logger)
|
||||
var flash string
|
||||
if r.Method==http.MethodPost {
|
||||
r.Body=http.MaxBytesReader(w,r.Body,1<<20)
|
||||
if err:=r.ParseForm();err!=nil{http.Error(w,"Ungültiges Formular",400);return}
|
||||
if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf_token")),[]byte(session.CSRFToken))!=1{http.Error(w,"CSRF-Prüfung fehlgeschlagen",403);return}
|
||||
switch r.FormValue("action") {
|
||||
case "sync":
|
||||
ctx,cancel:=context.WithTimeout(r.Context(),4*time.Minute)
|
||||
n,err:=hub.SyncType(ctx,r.FormValue("type"))
|
||||
cancel()
|
||||
if err!=nil {flash="Fehler: "+err.Error()} else {flash=fmt.Sprintf("%d Datensätze importiert und geprüft.",n)}
|
||||
case "review_rights":
|
||||
id,err:=strconv.ParseInt(r.FormValue("id"),10,64)
|
||||
if err==nil && id>0 {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)}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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":"<p>Ein Ort in Niedersachsen.</p>",
|
||||
"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,"<p>"){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")}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{{define "tourism-admin.html"}}
|
||||
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow">
|
||||
<title>Niedersachsen Hub – Landwelle</title><link rel="stylesheet" href="/assets/admin-v37.css"><link rel="stylesheet" href="/assets/tourism-hub-v1.css"></head>
|
||||
<body class="admin-dashboard-page"><div class="admin-layout">
|
||||
<aside class="admin-sidebar"><a class="admin-sidebar-brand" href="/admin"><img src="/assets/landwelle-logo-trim.png" alt="Landwelle"><span>Verwaltung</span></a>{{adminNavigation}}</aside>
|
||||
<div class="admin-workspace"><header class="admin-topbar"><div><span>Landwelle Radio</span><strong>Niedersachsen Hub</strong></div><div class="admin-user"><strong>{{.Username}}</strong></div></header>
|
||||
<main class="admin-content"><div class="admin-page-heading"><div><span class="admin-kicker">Touristische Open Data</span><h1>Niedersachsen Hub verwalten</h1><p>Datentypen getrennt importieren, Lizenzstatus prüfen und Inhalte redaktionell veröffentlichen.</p></div></div>
|
||||
{{if .Error}}<div class="admin-alert is-error">{{.Error}}</div>{{end}}{{if .Success}}<div class="admin-alert is-success">{{.Success}}</div>{{end}}
|
||||
<section class="admin-card tourism-admin-panel"><h2>Import der touristischen Inhalte</h2>
|
||||
<p>Quelle: Niedersachsen Hub / destination.one. Bestehende Veranstaltungsimporte bleiben separat unter <a href="/admin/events?tab=hub">Veranstaltungen</a>.</p>
|
||||
<p>Status: {{if .Enabled}}aktiv{{else}}deaktiviert{{end}} · Lizenzschlüssel: {{if .KeySet}}hinterlegt{{else}}fehlt{{end}}. <a href="/admin/settings#events">Zugang konfigurieren</a>.</p>
|
||||
<div class="tourism-type-actions">{{range .Types}}<form method="post" action="/admin/niedersachsen-hub"><input type="hidden" name="csrf_token" value="{{$.CSRFToken}}"><input type="hidden" name="action" value="sync"><input type="hidden" name="type" value="{{.}}"><button type="submit" class="admin-secondary-button" {{if not $.Enabled}}disabled{{end}}>{{.}} importieren</button></form>{{end}}</div>
|
||||
<p><small>Importierte Datensätze sind niemals automatisch veröffentlicht. Texte und Bilder benötigen getrennte Nutzungsrechte. Bei unklaren Lizenzen ist eine Veröffentlichung gesperrt.</small></p>
|
||||
</section>
|
||||
<section class="admin-card tourism-admin-panel"><h2>Importierte Datensätze – letzte 80</h2>
|
||||
<div class="tourism-admin-list">{{range .Items}}
|
||||
<article class="tourism-admin-item"><div><span class="tourism-chip">{{.ContentType}} · {{.DataLicense}}</span><h3>{{.Title}}</h3><p>{{.City}} · {{.Category}}</p><p>{{if .SourceURL}}<a href="{{.SourceURL}}" target="_blank" rel="noopener noreferrer">Quelle prüfen ↗</a>{{else}}Kein Quelllink vorhanden{{end}}</p><p>Text: {{if .Attribution}}{{.Attribution}}{{else}}Urheberangabe noch prüfen{{end}} · Bild: {{if .ImageLicense}}{{.ImageLicense}}{{else}}nicht separat freigegeben{{end}}</p>{{if .ImageURL}}<p><a href="{{.ImageURL}}" target="_blank" rel="noopener noreferrer">Bildquelle prüfen ↗</a></p>{{end}}</div>
|
||||
<div class="tourism-rights-actions"><form method="post" action="/admin/niedersachsen-hub">
|
||||
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}"><input type="hidden" name="id" value="{{.ID}}">
|
||||
<input type="hidden" name="action" value="review_rights">
|
||||
<label>Texturheber / Quelle<input type="text" name="attribution" value="{{.Attribution}}" maxlength="500" placeholder="Urheber laut Quelldatensatz"></label>
|
||||
<label>Bildlizenz<select name="image_license"><option value="">Bild nicht freigeben</option><option value="CC0" {{if eq .ImageLicense "CC0"}}selected{{end}}>CC0</option><option value="CC BY" {{if eq .ImageLicense "CC BY"}}selected{{end}}>CC BY</option><option value="CC BY-SA" {{if eq .ImageLicense "CC BY-SA"}}selected{{end}}>CC BY-SA</option></select></label>
|
||||
<label>Bildurheber<input type="text" name="image_attribution" value="{{.ImageAttribution}}" maxlength="500" placeholder="Name laut Bildlizenz"></label>
|
||||
<button type="submit" class="admin-secondary-button">Rechte speichern</button></form>
|
||||
<form method="post" action="/admin/niedersachsen-hub"><input type="hidden" name="csrf_token" value="{{$.CSRFToken}}"><input type="hidden" name="id" value="{{.ID}}">
|
||||
{{if .Published}}<button name="action" value="unpublish" class="admin-secondary-button">Veröffentlichung zurücknehmen</button>
|
||||
{{else}}<button name="action" value="publish" class="admin-primary-button" {{if not .DataLicense}}disabled title="Keine eindeutig offene Textlizenz"{{end}}>Nach Prüfung freigeben</button>{{end}}</form></div></article>{{else}}<p>Noch keine touristischen Datensätze importiert.</p>{{end}}
|
||||
</div></section>
|
||||
<a href="/niedersachsen-entdecken" target="_blank" rel="noopener noreferrer">Öffentlichen Tourismusbereich ansehen ↗</a>
|
||||
</main></div></div></body></html>
|
||||
{{end}}
|
||||
@@ -0,0 +1,7 @@
|
||||
.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%}}
|
||||
@@ -0,0 +1,59 @@
|
||||
{{define "tourism.html"}}
|
||||
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
{{seoHead "Niedersachsen entdecken – Landwelle" "Ausflugsziele, Sehenswürdigkeiten, Touren, Gastgeber, Gastronomie und touristische Regionen in Niedersachsen entdecken." "/niedersachsen-entdecken" "website"}}
|
||||
<link rel="icon" href="/assets/landwelle-logo-trim.png">
|
||||
<link rel="stylesheet" href="/assets/styles-v22.css"><link rel="stylesheet" href="/assets/tourism-hub-v1.css"><script src="/assets/app-v18.js" defer></script>
|
||||
</head><body>
|
||||
{{template "public_header" .}}
|
||||
<main class="tourism-main">
|
||||
<section class="tourism-hero">
|
||||
<span class="tourism-kicker">Landwelle · Unterwegs in Niedersachsen</span>
|
||||
<h1>{{if .Item}}{{.Item.Title}}{{else}}Niedersachsen entdecken{{end}}</h1>
|
||||
<p>{{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}}</p>
|
||||
<a href="/niedersachsen-entdecken">Alle touristischen Angebote</a>
|
||||
</section>
|
||||
{{if .Item}}
|
||||
<article class="tourism-detail">
|
||||
<div class="tourism-detail-body">
|
||||
<p class="tourism-chip">{{.Item.ContentType}}{{if .Item.Category}} · {{.Item.Category}}{{end}}</p>
|
||||
{{if .Item.City}}<p><strong>Ort:</strong> {{.Item.PostalCode}} {{.Item.City}}</p>{{end}}
|
||||
{{if .Item.ImageURL}}<figure><img src="{{.Item.ImageURL}}" alt="{{.Item.Title}}" loading="lazy"><figcaption>Bild: {{if .Item.ImageAttribution}}{{.Item.ImageAttribution}} · {{end}}{{.Item.ImageLicense}}</figcaption></figure>{{end}}
|
||||
<div class="tourism-description">{{.Item.Description}}</div>
|
||||
{{if .Item.Website}}<p><a href="{{.Item.Website}}" target="_blank" rel="noopener noreferrer">Offizielle Webseite / Angebot öffnen ↗</a></p>{{end}}
|
||||
</div>
|
||||
<aside class="tourism-source"><h2>Quelle und Nutzungsrechte</h2><p>Datensatz: Niedersachsen Hub / destination.one</p><p>Textlizenz: {{.Item.DataLicense}}</p>{{if .Item.Attribution}}<p>Urheber / Quelle: {{.Item.Attribution}}</p>{{end}}{{if .Item.SourceURL}}<a href="{{.Item.SourceURL}}" target="_blank" rel="noopener noreferrer">Originaldatensatz / Quelle ↗</a>{{end}}<p>Die Angaben stammen aus dem Tourismusdatenangebot. Verfügbarkeit und Preise bitte beim Anbieter prüfen.</p></aside>
|
||||
</article>
|
||||
{{else}}
|
||||
<section class="tourism-content">
|
||||
<form action="/niedersachsen-entdecken" method="get" class="tourism-filter">
|
||||
<label>Suchbegriff<input name="suche" value="{{.Query}}" placeholder="Ausflugsziel, Region, Thema …"></label>
|
||||
<label>Bereich<select name="typ"><option value="">Alle Bereiche</option>{{range .Types}}<option value="{{.}}" {{if eq . $.FilterType}}selected{{end}}>{{.}}</option>{{end}}</select></label>
|
||||
<label>Ort<input name="ort" value="{{.FilterCity}}" placeholder="z. B. Lüneburg"></label>
|
||||
<button type="submit">Angebote finden</button>
|
||||
</form>
|
||||
<p class="tourism-count">{{.Total}} veröffentlichte Angebote gefunden{{if .Query}} für „{{.Query}}“{{end}}</p>
|
||||
{{if .Error}}<p class="tourism-error">{{.Error}}</p>{{end}}
|
||||
<div class="tourism-grid">
|
||||
{{range .Items}}
|
||||
<article class="tourism-card">
|
||||
{{if .ImageURL}}<img src="{{.ImageURL}}" loading="lazy" alt="{{.Title}}">{{else}}<div class="tourism-placeholder" aria-hidden="true">Niedersachsen</div>{{end}}
|
||||
<div class="tourism-card-copy"><span class="tourism-chip">{{.ContentType}}{{if .Category}} · {{.Category}}{{end}}</span>
|
||||
<h2><a href="/niedersachsen-entdecken/{{.ID}}">{{.Title}}</a></h2>
|
||||
<p class="tourism-place">{{.PostalCode}} {{.City}}</p>
|
||||
<p>{{.Description}}</p>
|
||||
<a class="tourism-details" href="/niedersachsen-entdecken/{{.ID}}">Mehr entdecken →</a></div>
|
||||
</article>{{else}}
|
||||
<div class="tourism-empty"><h2>Noch keine freigegebenen Angebote</h2><p>Neue Einträge werden erst nach Prüfung der Daten- und Bildrechte von der Landwelle-Redaktion veröffentlicht.</p></div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{if gt .Pages 1}}<nav class="tourism-pagination" aria-label="Ergebnisseiten">
|
||||
{{if .HasPrev}}<a href="/niedersachsen-entdecken?typ={{urlquery .FilterType}}&ort={{urlquery .FilterCity}}&suche={{urlquery .Query}}&seite={{.PrevPage}}">← Zurück</a>{{end}}
|
||||
<span>Seite {{.Page}} von {{.Pages}}</span>
|
||||
{{if .HasNext}}<a href="/niedersachsen-entdecken?typ={{urlquery .FilterType}}&ort={{urlquery .FilterCity}}&suche={{urlquery .Query}}&seite={{.NextPage}}">Weiter →</a>{{end}}
|
||||
</nav>{{end}}
|
||||
<p class="tourism-disclaimer">Quelle: Niedersachsen Hub / destination.one. Angebote und Termine können sich ändern. Die jeweiligen Lizenz- und Quellenangaben stehen am Datensatz.</p>
|
||||
</section>{{end}}
|
||||
</main>
|
||||
{{template "public_footer" .}}
|
||||
</body></html>
|
||||
{{end}}
|
||||
Reference in new issue
Block a user