bitch
This commit is contained in:
2026-01-02 23:13:03 -06:00
commit e20cdf1af1
35 changed files with 5731 additions and 0 deletions

60
.gitignore vendored Normal file
View File

@@ -0,0 +1,60 @@
# Binaries
bin/
*.exe
*.exe~
*.dll
*.so
*.dylib
# Go
*.test
*.out
/vendor/
# Python
.venv/
__pycache__/
*.py[cod]
*$py.class
# Environment
.env.local
.env.*.local
.env
.env.production
.env.development
# Logs and coverage
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
coverage/
# Node / Vite (frontend)
web/node_modules/
web/dist/
web/.vite/
web/.turbo/
web/.parcel-cache/
web/.eslintcache
web/.stylelintcache
web/.cache/
# Docker
postgres_data/
# Data
data/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db

265
API.md Normal file
View File

@@ -0,0 +1,265 @@
# Mandalay API Documentation
Base URL: `http://localhost:8080`
## Endpoints
### Health Check
**GET** `/health`
Returns server health status.
**Response:**
```json
{
"status": "ok"
}
```
---
### Statistics
**GET** `/api/v1/stats`
Get database statistics including geometry counts and folder distribution.
**Response:**
```json
{
"total_placemarks": 545,
"total_styles": 44,
"geometry_types": {
"Point": 420,
"LineString": 50,
"Polygon": 75
},
"top_folders": {
"Audio (911 calls)": 155,
"Videos taken on foot": 132,
"Las Vegas Village - Venue Features": 84,
...
}
}
```
---
### List Placemarks
**GET** `/api/v1/placemarks`
List all placemarks with pagination.
**Query Parameters:**
- `limit` (int, default: 100) - Maximum results
- `offset` (int, default: 0) - Pagination offset
- `folder` (string) - Filter by folder name
**Response:**
```json
{
"placemarks": [
{
"id": 1,
"name": "Placemark Name",
"description": "Description...",
"style_id": "icon-1538-0288D1",
"folder_path": ["Videos taken on foot"],
"geometry_type": "Point",
"geometry": "{\"type\":\"Point\",\"coordinates\":[-115.172,36.094]}",
"media_links": ["https://youtube.com/..."],
"created_at": "2026-01-02T22:48:54Z"
}
],
"limit": 100,
"offset": 0
}
```
---
### Get Placemark
**GET** `/api/v1/placemarks/{id}`
Get a single placemark by ID with extended data.
**Response:**
```json
{
"id": 1,
"name": "Placemark Name",
"description": "Description...",
"geometry_type": "Point",
"geometry": "{\"type\":\"Point\",\"coordinates\":[-115.172,36.094]}",
"media_links": ["https://youtube.com/..."],
"extended_data": [
{
"key": "custom_field",
"value": "value"
}
]
}
```
---
### Timeline Events
**GET** `/api/v1/timeline/events`
Get all placemarks that have timestamps in their names, useful for building interactive timelines.
**Response:**
```json
[
{
"timestamp": null,
"name": "10/1/2017 09:41:56 PM - Event Name",
"description": "...",
"location": {
"lat": 36.094506,
"lon": -115.172281
},
"media_links": ["https://youtube.com/..."],
"placemark_id": 131,
"folder_path": ["Videos taken on foot"]
}
]
```
---
### Timeline Summary
**GET** `/api/v1/timeline`
Get timeline events with count metadata.
**Response:**
```json
{
"events": [...],
"count": 234
}
```
---
### Spatial Bounding Box Query
**GET** `/api/v1/spatial/bbox`
Get placemarks within a geographic bounding box.
**Query Parameters (required):**
- `min_lon` (float) - Minimum longitude
- `min_lat` (float) - Minimum latitude
- `max_lon` (float) - Maximum longitude
- `max_lat` (float) - Maximum latitude
- `limit` (int, default: 1000) - Maximum results
**Example:**
```
/api/v1/spatial/bbox?min_lon=-115.18&min_lat=36.09&max_lon=-115.16&max_lat=36.10&limit=50
```
**Response:**
```json
{
"placemarks": [...],
"bbox": {
"min_lon": -115.18,
"min_lat": 36.09,
"max_lon": -115.16,
"max_lat": 36.10
},
"count": 42
}
```
---
### List Folders
**GET** `/api/v1/folders`
Get all unique folder names from the dataset.
**Response:**
```json
{
"folders": [
"Audio (911 calls)",
"Videos taken on foot",
"LVMPD Body Worn Cameras",
"Places of Interest",
"Victims"
],
"count": 9
}
```
---
## Data Model
### Placemark
```typescript
{
id: number
name: string
description?: string
style_id?: string
folder_path: string[]
geometry_type: "Point" | "LineString" | "Polygon"
geometry: string // GeoJSON
coordinates_raw?: string
media_links?: string[]
created_at: timestamp
extended_data?: Array<{key: string, value: string}>
}
```
### Timeline Event
```typescript
{
timestamp?: Date
name: string
description?: string
location?: {lat: number, lon: number}
media_links?: string[]
placemark_id: number
folder_path: string[]
}
```
---
## Running the API
```bash
# Start database
docker-compose up -d
# Start API server
make api
# or
go run cmd/api/main.go
# or
./bin/api
# Server runs on http://localhost:8080
```
## CORS
API allows requests from:
- `http://localhost:*`
- `http://127.0.0.1:*`
For production, update CORS settings in `cmd/api/main.go`.

Binary file not shown.

92
Makefile Normal file
View File

@@ -0,0 +1,92 @@
.PHONY: help deps fmt lint test build build-api build-import run dev api api-binary docker-up docker-down docker-logs db-shell import-data clean web-install web-dev web-build web-lint web-preview
GO ?= go
DOCKER_COMPOSE ?= docker-compose
WEB_DIR ?= web
API_BIN := bin/api
IMPORT_BIN := bin/import
DB_CONTAINER := mandalay-postgres
.DEFAULT_GOAL := help
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-22s\033[0m %s\n", $$1, $$2}'
# Go tooling
deps: ## Download and tidy Go modules
@$(GO) mod download
@$(GO) mod tidy
fmt: ## Format Go code
@$(GO) fmt ./...
lint: ## Lint Go code (go vet)
@$(GO) vet ./...
test: ## Run Go tests
@$(GO) test -v ./...
build: build-import build-api ## Build all binaries
build-import: ## Build importer binary
@echo "Building import tool..."
@$(GO) build -o $(IMPORT_BIN) ./cmd/import
build-api: ## Build API server binary
@echo "Building API server..."
@$(GO) build -o $(API_BIN) ./cmd/api
run: ## Run the API server (local env)
@$(GO) run ./cmd/api/main.go
dev: ## Run API server with auto-reload (requires air)
@air
# Database / Docker
docker-up: ## Start PostgreSQL/PostGIS container
@$(DOCKER_COMPOSE) up -d
@echo "Waiting for database to be ready..."
@sleep 3
docker-down: ## Stop PostgreSQL container
@$(DOCKER_COMPOSE) down
docker-logs: ## View PostgreSQL container logs
@$(DOCKER_COMPOSE) logs -f postgres
db-shell: ## Open psql shell inside database container
@docker exec -it $(DB_CONTAINER) psql -U mandalay -d vegasmap
import-data: docker-up ## Import KML data into database (truncate existing)
@echo "Importing KML data..."
@$(GO) run ./cmd/import/main.go --truncate
@echo "Import complete!"
# API server helpers
api: docker-up ## Start API server (go run) against containerized DB
@echo "Starting API server on :8080..."
@$(GO) run ./cmd/api/main.go
api-binary: docker-up build-api ## Start API server from compiled binary
@echo "Starting compiled API server on :8080..."
@./$(API_BIN)
# Frontend (Vite/React/Tailwind)
web-install: ## Install web dependencies
@npm install --prefix $(WEB_DIR)
web-dev: ## Run Vite dev server
@npm run dev --prefix $(WEB_DIR)
web-build: ## Build frontend
@npm run build --prefix $(WEB_DIR)
web-lint: ## Lint frontend
@npm run lint --prefix $(WEB_DIR)
web-preview: ## Preview built frontend
@npm run preview --prefix $(WEB_DIR)
clean: ## Clean build artifacts
@rm -rf bin/
@echo "Cleaned build artifacts"

121
README.md Normal file
View File

@@ -0,0 +1,121 @@
# Mandalay - Vegas Shooting Map Data
Go backend for extracting and managing KML geographic data from the Vegas Shooting Map in a PostGIS-enabled PostgreSQL database.
## Architecture
- **Backend**: Go with pgx for PostgreSQL connectivity
- **Database**: PostgreSQL 16 with PostGIS 3.4 (Docker)
- **Data Source**: KMZ/KML file containing 545 placemarks (420 points, 50 lines, 75 polygons)
## Project Structure
```
mandalay/
├── cmd/
│ └── import/ # KML import CLI tool
├── data/
│ └── raw/ # Extracted KML and assets
├── docker-compose.yml # PostgreSQL/PostGIS container
├── .env # Database connection config
└── go.mod
```
## Database Schema
### Tables
**styles** - KML style definitions
- `id` (PK) - Style identifier
- `icon_href`, `icon_scale`, `label_scale` - Icon styling
- `raw_xml` - Original XML
**placemarks** - Geographic features
- `id` (PK, serial)
- `name`, `description` - Feature metadata
- `style_id` (FK → styles)
- `folder_path` (text[]) - Hierarchical location
- `geometry_type` - Point/LineString/Polygon
- `geom` (geometry SRID 4326) - PostGIS geometry
- `coordinates_raw` - Original coordinate text
- `gx_media_links` (text[]) - YouTube/media URLs
- `created_at` - Timestamp
**placemark_data** - Extended key-value attributes
- `placemark_id` (FK → placemarks)
- `key`, `value`
### Indexes
- GIST index on `geom` for spatial queries
- GIN index on `folder_path` for hierarchy queries
## Quick Start
### 1. Start PostgreSQL
```bash
docker-compose up -d
```
Container runs at `localhost:5432` with credentials:
- User: `mandalay`
- Password: `mandalay`
- Database: `vegasmap`
### 2. Import KML Data
```bash
# Dry run (parse only, no database writes)
go run cmd/import/main.go --dry-run
# Import with existing data truncation
go run cmd/import/main.go --truncate
# Limit import for testing
go run cmd/import/main.go --limit 50
```
### 3. Query the Data
```bash
# Connect to database
PGPASSWORD=mandalay psql -h localhost -U mandalay -d vegasmap
# Sample queries
SELECT geometry_type, COUNT(*) FROM placemarks GROUP BY geometry_type;
SELECT name, ST_AsText(geom) FROM placemarks WHERE geometry_type = 'Point' LIMIT 5;
```
## Current Status
✅ 545 placemarks imported
✅ 44 styles loaded
✅ PostGIS spatial indexes created
✅ Docker containerized database
## Next Steps
- Build REST API for querying placemarks
- Add spatial query endpoints (bbox, radius search)
- Implement frontend map visualization
- Add data update/CRUD operations
## Environment
Copy `.env` and adjust if needed:
```
DATABASE_URL=postgresql://mandalay:mandalay@localhost:5432/vegasmap?sslmode=disable
```
## Dependencies
- Go 1.24+
- Docker & Docker Compose
- PostgreSQL client (optional, for psql)
```bash
go get github.com/jackc/pgx/v5
go get github.com/jackc/pgx/v5/pgxpool
go get github.com/joho/godotenv
```

113
cmd/api/main.go Normal file
View File

@@ -0,0 +1,113 @@
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/joho/godotenv"
"github.com/onnwee/mandalay/internal/api"
"github.com/onnwee/mandalay/internal/store"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
log.Fatal("DATABASE_URL environment variable not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, dbURL)
if err != nil {
log.Fatalf("Unable to connect to database: %v", err)
}
defer pool.Close()
// Initialize store
placemarkStore := store.NewPlacemarkStore(pool)
// Initialize handlers
handlers := api.NewHandlers(placemarkStore)
// Set up router
r := chi.NewRouter()
// Middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"http://localhost:*", "http://127.0.0.1:*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
}))
// Routes
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
r.Route("/api/v1", func(r chi.Router) {
r.Get("/placemarks", handlers.ListPlacemarks)
r.Get("/placemarks/{id}", handlers.GetPlacemark)
r.Get("/timeline", handlers.GetTimeline)
r.Get("/timeline/events", handlers.GetTimelineEvents)
r.Get("/spatial/bbox", handlers.GetPlacemarksInBBox)
r.Get("/folders", handlers.ListFolders)
r.Get("/stats", handlers.GetStats)
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
srv := &http.Server{
Addr: ":" + port,
Handler: r,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Graceful shutdown
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
log.Printf("Server starting on port %s", port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server failed to start: %v", err)
}
}()
<-done
log.Println("Server shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
log.Println("Server exited")
}

550
cmd/import/main.go Normal file
View File

@@ -0,0 +1,550 @@
package main
import (
"context"
"encoding/xml"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/joho/godotenv"
)
// KML namespace structures
type KML struct {
XMLName xml.Name `xml:"kml"`
Document Document `xml:"Document"`
}
type Document struct {
Name string `xml:"name"`
Description string `xml:"description"`
Styles []Style `xml:"Style"`
StyleMaps []StyleMap `xml:"StyleMap"`
Folders []Folder `xml:"Folder"`
Placemarks []Placemark `xml:"Placemark"`
}
type Style struct {
ID string `xml:"id,attr"`
IconStyle *IconStyle `xml:"IconStyle"`
LabelStyle *LabelStyle `xml:"LabelStyle"`
LineStyle *LineStyle `xml:"LineStyle"`
PolyStyle *PolyStyle `xml:"PolyStyle"`
}
type StyleMap struct {
ID string `xml:"id,attr"`
}
type IconStyle struct {
Scale float64 `xml:"scale"`
Icon *Icon `xml:"Icon"`
}
type Icon struct {
Href string `xml:"href"`
}
type LabelStyle struct {
Scale float64 `xml:"scale"`
}
type LineStyle struct {
Color string `xml:"color"`
Width float64 `xml:"width"`
}
type PolyStyle struct {
Color string `xml:"color"`
}
type Folder struct {
Name string `xml:"name"`
Placemarks []Placemark `xml:"Placemark"`
Folders []Folder `xml:"Folder"`
}
type Placemark struct {
Name string `xml:"name"`
Description string `xml:"description"`
StyleURL string `xml:"styleUrl"`
Point *Point `xml:"Point"`
LineString *LineString `xml:"LineString"`
Polygon *Polygon `xml:"Polygon"`
ExtendedData *ExtendedData `xml:"ExtendedData"`
}
type Point struct {
Coordinates string `xml:"coordinates"`
}
type LineString struct {
Coordinates string `xml:"coordinates"`
}
type Polygon struct {
OuterBoundary OuterBoundary `xml:"outerBoundaryIs"`
InnerBoundary []InnerBoundary `xml:"innerBoundaryIs"`
}
type OuterBoundary struct {
LinearRing LinearRing `xml:"LinearRing"`
}
type InnerBoundary struct {
LinearRing LinearRing `xml:"LinearRing"`
}
type LinearRing struct {
Coordinates string `xml:"coordinates"`
}
type ExtendedData struct {
Data []Data `xml:"Data"`
}
type Data struct {
Name string `xml:"name,attr"`
Value string `xml:"value"`
}
// Database record structures
type PlacemarkRecord struct {
Name string
Description string
StyleID string
FolderPath []string
GeometryType string
GeomWKT string
CoordinatesRaw string
MediaLinks []string
ExtendedData map[string]string
}
func main() {
kmlPath := flag.String("kml", "data/raw/doc.kml", "Path to KML file")
truncate := flag.Bool("truncate", false, "Truncate existing data before import")
dryRun := flag.Bool("dry-run", false, "Parse KML and print summary without database operations")
limit := flag.Int("limit", 0, "Limit number of placemarks to import (0 = no limit)")
flag.Parse()
// Load environment variables
if err := godotenv.Load(); err != nil {
log.Println("No .env file found, using environment variables")
}
// Parse KML
placemarks, styles, err := parseKML(*kmlPath)
if err != nil {
log.Fatalf("Failed to parse KML: %v", err)
}
if *limit > 0 && len(placemarks) > *limit {
placemarks = placemarks[:*limit]
}
// Print summary
summary := summarize(styles, placemarks)
fmt.Println(summary)
if *dryRun {
return
}
// Connect to database
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
log.Fatal("DATABASE_URL environment variable not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, dbURL)
if err != nil {
log.Fatalf("Unable to connect to database: %v", err)
}
defer pool.Close()
// Run migrations
if err := ensureSchema(ctx, pool); err != nil {
log.Fatalf("Failed to create schema: %v", err)
}
if *truncate {
if err := truncateData(ctx, pool); err != nil {
log.Fatalf("Failed to truncate data: %v", err)
}
}
// Import data
if err := importStyles(ctx, pool, styles); err != nil {
log.Fatalf("Failed to import styles: %v", err)
}
if err := importPlacemarks(ctx, pool, placemarks); err != nil {
log.Fatalf("Failed to import placemarks: %v", err)
}
fmt.Printf("\nImported %d placemarks into PostgreSQL\n", len(placemarks))
}
func parseKML(path string) ([]PlacemarkRecord, []Style, error) {
file, err := os.Open(path)
if err != nil {
return nil, nil, fmt.Errorf("failed to open KML file: %w", err)
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
return nil, nil, fmt.Errorf("failed to read KML file: %w", err)
}
var kml KML
if err := xml.Unmarshal(data, &kml); err != nil {
return nil, nil, fmt.Errorf("failed to parse KML XML: %w", err)
}
var placemarks []PlacemarkRecord
// Process top-level placemarks
for _, pm := range kml.Document.Placemarks {
if rec := processPlacemark(pm, []string{}); rec != nil {
placemarks = append(placemarks, *rec)
}
}
// Process folders recursively
for _, folder := range kml.Document.Folders {
placemarks = append(placemarks, processFolderPlacemarks(folder, []string{})...)
}
return placemarks, kml.Document.Styles, nil
}
func processFolderPlacemarks(folder Folder, parentPath []string) []PlacemarkRecord {
var placemarks []PlacemarkRecord
folderPath := append(parentPath, folder.Name)
for _, pm := range folder.Placemarks {
if rec := processPlacemark(pm, folderPath); rec != nil {
placemarks = append(placemarks, *rec)
}
}
// Process nested folders
for _, subfolder := range folder.Folders {
placemarks = append(placemarks, processFolderPlacemarks(subfolder, folderPath)...)
}
return placemarks
}
func processPlacemark(pm Placemark, folderPath []string) *PlacemarkRecord {
var geomType, geomWKT, coordsRaw string
if pm.Point != nil {
geomType = "Point"
coordsRaw = strings.TrimSpace(pm.Point.Coordinates)
geomWKT = buildPointWKT(coordsRaw)
} else if pm.LineString != nil {
geomType = "LineString"
coordsRaw = strings.TrimSpace(pm.LineString.Coordinates)
geomWKT = buildLineStringWKT(coordsRaw)
} else if pm.Polygon != nil {
geomType = "Polygon"
coordsRaw = strings.TrimSpace(pm.Polygon.OuterBoundary.LinearRing.Coordinates)
geomWKT = buildPolygonWKT(pm.Polygon)
} else {
return nil
}
if geomWKT == "" {
return nil
}
styleID := strings.TrimPrefix(pm.StyleURL, "#")
extData := make(map[string]string)
var mediaLinks []string
if pm.ExtendedData != nil {
for _, data := range pm.ExtendedData.Data {
if data.Name == "gx_media_links" {
mediaLinks = append(mediaLinks, data.Value)
} else {
extData[data.Name] = data.Value
}
}
}
return &PlacemarkRecord{
Name: strings.TrimSpace(pm.Name),
Description: strings.TrimSpace(pm.Description),
StyleID: styleID,
FolderPath: folderPath,
GeometryType: geomType,
GeomWKT: geomWKT,
CoordinatesRaw: coordsRaw,
MediaLinks: mediaLinks,
ExtendedData: extData,
}
}
func parseCoordinates(coordsText string) [][2]float64 {
var coords [][2]float64
parts := strings.Fields(strings.TrimSpace(coordsText))
for _, part := range parts {
vals := strings.Split(part, ",")
if len(vals) < 2 {
continue
}
var lon, lat float64
if _, err := fmt.Sscanf(vals[0], "%f", &lon); err != nil {
continue
}
if _, err := fmt.Sscanf(vals[1], "%f", &lat); err != nil {
continue
}
coords = append(coords, [2]float64{lon, lat})
}
return coords
}
func buildPointWKT(coordsText string) string {
coords := parseCoordinates(coordsText)
if len(coords) == 0 {
return ""
}
return fmt.Sprintf("POINT(%f %f)", coords[0][0], coords[0][1])
}
func buildLineStringWKT(coordsText string) string {
coords := parseCoordinates(coordsText)
if len(coords) < 2 {
return ""
}
var points []string
for _, c := range coords {
points = append(points, fmt.Sprintf("%f %f", c[0], c[1]))
}
return fmt.Sprintf("LINESTRING(%s)", strings.Join(points, ", "))
}
func buildPolygonWKT(polygon *Polygon) string {
outer := parseCoordinates(polygon.OuterBoundary.LinearRing.Coordinates)
if len(outer) < 3 {
return ""
}
// Ensure ring is closed
if outer[0] != outer[len(outer)-1] {
outer = append(outer, outer[0])
}
var outerPoints []string
for _, c := range outer {
outerPoints = append(outerPoints, fmt.Sprintf("%f %f", c[0], c[1]))
}
rings := []string{fmt.Sprintf("(%s)", strings.Join(outerPoints, ", "))}
// Process inner rings (holes)
for _, inner := range polygon.InnerBoundary {
innerCoords := parseCoordinates(inner.LinearRing.Coordinates)
if len(innerCoords) < 3 {
continue
}
if innerCoords[0] != innerCoords[len(innerCoords)-1] {
innerCoords = append(innerCoords, innerCoords[0])
}
var innerPoints []string
for _, c := range innerCoords {
innerPoints = append(innerPoints, fmt.Sprintf("%f %f", c[0], c[1]))
}
rings = append(rings, fmt.Sprintf("(%s)", strings.Join(innerPoints, ", ")))
}
return fmt.Sprintf("POLYGON(%s)", strings.Join(rings, ", "))
}
func summarize(styles []Style, placemarks []PlacemarkRecord) string {
typeCounts := make(map[string]int)
for _, pm := range placemarks {
typeCounts[pm.GeometryType]++
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Styles: %d\n", len(styles)))
sb.WriteString(fmt.Sprintf("Placemarks: %d\n", len(placemarks)))
for geomType, count := range typeCounts {
sb.WriteString(fmt.Sprintf(" %s: %d\n", geomType, count))
}
return sb.String()
}
func ensureSchema(ctx context.Context, pool *pgxpool.Pool) error {
schema := `
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE TABLE IF NOT EXISTS styles (
id TEXT PRIMARY KEY,
icon_href TEXT,
icon_scale DOUBLE PRECISION,
label_scale DOUBLE PRECISION,
raw_xml TEXT
);
CREATE TABLE IF NOT EXISTS placemarks (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
style_id TEXT REFERENCES styles(id),
folder_path TEXT[],
geometry_type TEXT NOT NULL,
geom GEOMETRY(GEOMETRY, 4326) NOT NULL,
coordinates_raw TEXT,
gx_media_links TEXT[],
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS placemark_data (
id SERIAL PRIMARY KEY,
placemark_id INTEGER REFERENCES placemarks(id) ON DELETE CASCADE,
key TEXT,
value TEXT
);
CREATE INDEX IF NOT EXISTS placemarks_geom_gix ON placemarks USING GIST (geom);
CREATE INDEX IF NOT EXISTS placemarks_folder_gin ON placemarks USING GIN (folder_path);
`
_, err := pool.Exec(ctx, schema)
return err
}
func truncateData(ctx context.Context, pool *pgxpool.Pool) error {
_, err := pool.Exec(ctx, "TRUNCATE placemark_data, placemarks RESTART IDENTITY CASCADE")
return err
}
func importStyles(ctx context.Context, pool *pgxpool.Pool, styles []Style) error {
if len(styles) == 0 {
return nil
}
batch := &pgx.Batch{}
for _, style := range styles {
var iconHref *string
var iconScale, labelScale *float64
if style.IconStyle != nil {
iconScale = &style.IconStyle.Scale
if style.IconStyle.Icon != nil {
iconHref = &style.IconStyle.Icon.Href
}
}
if style.LabelStyle != nil {
labelScale = &style.LabelStyle.Scale
}
batch.Queue(
`INSERT INTO styles (id, icon_href, icon_scale, label_scale, raw_xml)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE SET
icon_href = EXCLUDED.icon_href,
icon_scale = EXCLUDED.icon_scale,
label_scale = EXCLUDED.label_scale,
raw_xml = EXCLUDED.raw_xml`,
style.ID, iconHref, iconScale, labelScale, "",
)
}
br := pool.SendBatch(ctx, batch)
defer br.Close()
for range styles {
if _, err := br.Exec(); err != nil {
return fmt.Errorf("failed to insert style: %w", err)
}
}
return nil
}
func importPlacemarks(ctx context.Context, pool *pgxpool.Pool, placemarks []PlacemarkRecord) error {
if len(placemarks) == 0 {
return nil
}
tx, err := pool.Begin(ctx)
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback(ctx)
for _, pm := range placemarks {
var styleID *string
if pm.StyleID != "" {
// Verify style exists before referencing it
var exists bool
err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM styles WHERE id = $1)", pm.StyleID).Scan(&exists)
if err == nil && exists {
styleID = &pm.StyleID
}
}
var mediaLinks []string
if len(pm.MediaLinks) > 0 {
mediaLinks = pm.MediaLinks
}
var placemarkID int
err := tx.QueryRow(
ctx,
`INSERT INTO placemarks
(name, description, style_id, folder_path, geometry_type, geom, coordinates_raw, gx_media_links)
VALUES ($1, $2, $3, $4, $5, ST_GeomFromText($6, 4326), $7, $8)
RETURNING id`,
pm.Name, pm.Description, styleID, pm.FolderPath, pm.GeometryType,
pm.GeomWKT, pm.CoordinatesRaw, mediaLinks,
).Scan(&placemarkID)
if err != nil {
return fmt.Errorf("failed to insert placemark: %w", err)
}
// Insert extended data
for key, value := range pm.ExtendedData {
_, err := tx.Exec(
ctx,
`INSERT INTO placemark_data (placemark_id, key, value) VALUES ($1, $2, $3)`,
placemarkID, key, value,
)
if err != nil {
return fmt.Errorf("failed to insert extended data: %w", err)
}
}
}
return tx.Commit(ctx)
}

20
docker-compose.yml Normal file
View File

@@ -0,0 +1,20 @@
services:
postgres:
image: postgis/postgis:16-3.4
container_name: mandalay-postgres
environment:
POSTGRES_USER: mandalay
POSTGRES_PASSWORD: mandalay
POSTGRES_DB: vegasmap
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U mandalay -d vegasmap"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres_data:

20
go.mod Normal file
View File

@@ -0,0 +1,20 @@
module github.com/onnwee/mandalay
go 1.24.0
toolchain go1.24.11
require (
github.com/go-chi/chi/v5 v5.2.3
github.com/go-chi/cors v1.2.2
github.com/jackc/pgx/v5 v5.8.0
github.com/joho/godotenv v1.5.1
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/text v0.29.0 // indirect
)

32
go.sum Normal file
View File

@@ -0,0 +1,32 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

167
internal/api/handlers.go Normal file
View File

@@ -0,0 +1,167 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/onnwee/mandalay/internal/store"
)
type Handlers struct {
placemarkStore *store.PlacemarkStore
}
func NewHandlers(placemarkStore *store.PlacemarkStore) *Handlers {
return &Handlers{
placemarkStore: placemarkStore,
}
}
func (h *Handlers) ListPlacemarks(w http.ResponseWriter, r *http.Request) {
limit := getIntParam(r, "limit", 100)
offset := getIntParam(r, "offset", 0)
folder := r.URL.Query().Get("folder")
placemarks, err := h.placemarkStore.List(r.Context(), limit, offset, folder)
if err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
respondJSON(w, http.StatusOK, map[string]interface{}{
"placemarks": placemarks,
"limit": limit,
"offset": offset,
})
}
func (h *Handlers) GetPlacemark(w http.ResponseWriter, r *http.Request) {
idStr := chi.URLParam(r, "id")
id, err := strconv.Atoi(idStr)
if err != nil {
respondError(w, http.StatusBadRequest, "invalid id")
return
}
placemark, err := h.placemarkStore.GetByID(r.Context(), id)
if err != nil {
respondError(w, http.StatusNotFound, "placemark not found")
return
}
respondJSON(w, http.StatusOK, placemark)
}
func (h *Handlers) GetTimeline(w http.ResponseWriter, r *http.Request) {
events, err := h.placemarkStore.GetTimeline(r.Context())
if err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
respondJSON(w, http.StatusOK, map[string]interface{}{
"events": events,
"count": len(events),
})
}
func (h *Handlers) GetTimelineEvents(w http.ResponseWriter, r *http.Request) {
events, err := h.placemarkStore.GetTimeline(r.Context())
if err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
respondJSON(w, http.StatusOK, events)
}
func (h *Handlers) GetPlacemarksInBBox(w http.ResponseWriter, r *http.Request) {
minLon := getFloatParam(r, "min_lon", 0)
minLat := getFloatParam(r, "min_lat", 0)
maxLon := getFloatParam(r, "max_lon", 0)
maxLat := getFloatParam(r, "max_lat", 0)
limit := getIntParam(r, "limit", 1000)
if minLon == 0 || minLat == 0 || maxLon == 0 || maxLat == 0 {
respondError(w, http.StatusBadRequest, "missing bbox parameters")
return
}
bbox := store.BoundingBox{
MinLon: minLon,
MinLat: minLat,
MaxLon: maxLon,
MaxLat: maxLat,
}
placemarks, err := h.placemarkStore.GetInBBox(r.Context(), bbox, limit)
if err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
respondJSON(w, http.StatusOK, map[string]interface{}{
"placemarks": placemarks,
"bbox": bbox,
"count": len(placemarks),
})
}
func (h *Handlers) ListFolders(w http.ResponseWriter, r *http.Request) {
folders, err := h.placemarkStore.ListFolders(r.Context())
if err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
respondJSON(w, http.StatusOK, map[string]interface{}{
"folders": folders,
"count": len(folders),
})
}
func (h *Handlers) GetStats(w http.ResponseWriter, r *http.Request) {
stats, err := h.placemarkStore.GetStats(r.Context())
if err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
respondJSON(w, http.StatusOK, stats)
}
func getIntParam(r *http.Request, key string, defaultVal int) int {
val := r.URL.Query().Get(key)
if val == "" {
return defaultVal
}
intVal, err := strconv.Atoi(val)
if err != nil {
return defaultVal
}
return intVal
}
func getFloatParam(r *http.Request, key string, defaultVal float64) float64 {
val := r.URL.Query().Get(key)
if val == "" {
return defaultVal
}
floatVal, err := strconv.ParseFloat(val, 64)
if err != nil {
return defaultVal
}
return floatVal
}
func respondJSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(data)
}
func respondError(w http.ResponseWriter, status int, message string) {
respondJSON(w, status, map[string]string{"error": message})
}

325
internal/store/placemark.go Normal file
View File

@@ -0,0 +1,325 @@
package store
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type Placemark struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
StyleID *string `json:"style_id,omitempty"`
FolderPath []string `json:"folder_path"`
GeometryType string `json:"geometry_type"`
Geometry string `json:"geometry"`
CoordinatesRaw string `json:"coordinates_raw,omitempty"`
MediaLinks []string `json:"media_links,omitempty"`
CreatedAt time.Time `json:"created_at"`
ExtendedData []KVPair `json:"extended_data,omitempty"`
}
type KVPair struct {
Key string `json:"key"`
Value string `json:"value"`
}
type TimelineEvent struct {
Timestamp *time.Time `json:"timestamp,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Location *Point `json:"location,omitempty"`
MediaLinks []string `json:"media_links,omitempty"`
PlacemarkID int `json:"placemark_id"`
FolderPath []string `json:"folder_path"`
}
type Point struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
type BoundingBox struct {
MinLon float64 `json:"min_lon"`
MinLat float64 `json:"min_lat"`
MaxLon float64 `json:"max_lon"`
MaxLat float64 `json:"max_lat"`
}
type PlacemarkStore struct {
db *pgxpool.Pool
}
func NewPlacemarkStore(db *pgxpool.Pool) *PlacemarkStore {
return &PlacemarkStore{db: db}
}
func (s *PlacemarkStore) List(ctx context.Context, limit, offset int, folderFilter string) ([]Placemark, error) {
query := `
SELECT id, name, description, style_id, folder_path, geometry_type,
ST_AsGeoJSON(geom) as geometry, coordinates_raw, gx_media_links, created_at
FROM placemarks
WHERE ($3 = '' OR $3 = ANY(folder_path))
ORDER BY id
LIMIT $1 OFFSET $2
`
rows, err := s.db.Query(ctx, query, limit, offset, folderFilter)
if err != nil {
return nil, fmt.Errorf("failed to query placemarks: %w", err)
}
defer rows.Close()
var placemarks []Placemark
for rows.Next() {
var p Placemark
err := rows.Scan(
&p.ID, &p.Name, &p.Description, &p.StyleID, &p.FolderPath,
&p.GeometryType, &p.Geometry, &p.CoordinatesRaw, &p.MediaLinks, &p.CreatedAt,
)
if err != nil {
return nil, fmt.Errorf("failed to scan placemark: %w", err)
}
placemarks = append(placemarks, p)
}
return placemarks, nil
}
func (s *PlacemarkStore) GetByID(ctx context.Context, id int) (*Placemark, error) {
query := `
SELECT p.id, p.name, p.description, p.style_id, p.folder_path, p.geometry_type,
ST_AsGeoJSON(p.geom) as geometry, p.coordinates_raw, p.gx_media_links, p.created_at
FROM placemarks p
WHERE p.id = $1
`
var p Placemark
err := s.db.QueryRow(ctx, query, id).Scan(
&p.ID, &p.Name, &p.Description, &p.StyleID, &p.FolderPath,
&p.GeometryType, &p.Geometry, &p.CoordinatesRaw, &p.MediaLinks, &p.CreatedAt,
)
if err != nil {
return nil, fmt.Errorf("failed to get placemark: %w", err)
}
// Fetch extended data
extQuery := `SELECT key, value FROM placemark_data WHERE placemark_id = $1`
extRows, err := s.db.Query(ctx, extQuery, id)
if err != nil {
return &p, nil
}
defer extRows.Close()
for extRows.Next() {
var kv KVPair
if err := extRows.Scan(&kv.Key, &kv.Value); err == nil {
p.ExtendedData = append(p.ExtendedData, kv)
}
}
return &p, nil
}
func (s *PlacemarkStore) GetInBBox(ctx context.Context, bbox BoundingBox, limit int) ([]Placemark, error) {
query := `
SELECT id, name, description, style_id, folder_path, geometry_type,
ST_AsGeoJSON(geom) as geometry, coordinates_raw, gx_media_links, created_at
FROM placemarks
WHERE ST_Intersects(
geom,
ST_MakeEnvelope($1, $2, $3, $4, 4326)
)
LIMIT $5
`
rows, err := s.db.Query(ctx, query, bbox.MinLon, bbox.MinLat, bbox.MaxLon, bbox.MaxLat, limit)
if err != nil {
return nil, fmt.Errorf("failed to query bbox: %w", err)
}
defer rows.Close()
var placemarks []Placemark
for rows.Next() {
var p Placemark
err := rows.Scan(
&p.ID, &p.Name, &p.Description, &p.StyleID, &p.FolderPath,
&p.GeometryType, &p.Geometry, &p.CoordinatesRaw, &p.MediaLinks, &p.CreatedAt,
)
if err != nil {
return nil, fmt.Errorf("failed to scan placemark: %w", err)
}
placemarks = append(placemarks, p)
}
return placemarks, nil
}
func (s *PlacemarkStore) GetTimeline(ctx context.Context) ([]TimelineEvent, error) {
query := `
SELECT id, name, description, geometry_type, ST_AsGeoJSON(geom) as geometry,
gx_media_links, folder_path
FROM placemarks
WHERE name ~ '^\d{1,2}/\d{1,2}/\d{4}'
ORDER BY name
`
rows, err := s.db.Query(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to query timeline: %w", err)
}
defer rows.Close()
var events []TimelineEvent
for rows.Next() {
var (
id int
name string
description string
geomType string
geometry string
mediaLinks []string
folderPath []string
)
err := rows.Scan(&id, &name, &description, &geomType, &geometry, &mediaLinks, &folderPath)
if err != nil {
continue
}
event := TimelineEvent{
PlacemarkID: id,
Name: name,
Description: description,
MediaLinks: mediaLinks,
FolderPath: folderPath,
}
// Parse timestamp from name
event.Timestamp = parseTimestampFromName(name)
// Extract point if geometry is a point
if geomType == "Point" {
event.Location = extractPointFromGeoJSON(geometry)
}
events = append(events, event)
}
return events, nil
}
func (s *PlacemarkStore) ListFolders(ctx context.Context) ([]string, error) {
query := `
SELECT DISTINCT unnest(folder_path) as folder
FROM placemarks
WHERE array_length(folder_path, 1) > 0
ORDER BY folder
`
rows, err := s.db.Query(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to query folders: %w", err)
}
defer rows.Close()
var folders []string
for rows.Next() {
var folder string
if err := rows.Scan(&folder); err == nil {
folders = append(folders, folder)
}
}
return folders, nil
}
func (s *PlacemarkStore) GetStats(ctx context.Context) (map[string]interface{}, error) {
stats := make(map[string]interface{})
// Total counts
var totalPlacemarks, totalStyles int
s.db.QueryRow(ctx, "SELECT COUNT(*) FROM placemarks").Scan(&totalPlacemarks)
s.db.QueryRow(ctx, "SELECT COUNT(*) FROM styles").Scan(&totalStyles)
stats["total_placemarks"] = totalPlacemarks
stats["total_styles"] = totalStyles
// Geometry type breakdown
geomQuery := `SELECT geometry_type, COUNT(*) FROM placemarks GROUP BY geometry_type`
rows, err := s.db.Query(ctx, geomQuery)
if err == nil {
defer rows.Close()
geomTypes := make(map[string]int)
for rows.Next() {
var gtype string
var count int
if rows.Scan(&gtype, &count) == nil {
geomTypes[gtype] = count
}
}
stats["geometry_types"] = geomTypes
}
// Folders
folderQuery := `SELECT unnest(folder_path) as folder, COUNT(*) FROM placemarks GROUP BY folder ORDER BY COUNT(*) DESC LIMIT 10`
rows2, err := s.db.Query(ctx, folderQuery)
if err == nil {
defer rows2.Close()
folders := make(map[string]int)
for rows2.Next() {
var folder string
var count int
if rows2.Scan(&folder, &count) == nil {
folders[folder] = count
}
}
stats["top_folders"] = folders
}
return stats, nil
}
func parseTimestampFromName(name string) *time.Time {
layouts := []string{
"1/2/2006 3:04:05 PM",
"01/02/2006 03:04:05 PM",
"1/2/2006 3:04:05 PM",
"01/02/2006 03:04:05 PM",
}
for _, layout := range layouts {
if len(name) < len(layout) {
continue
}
timeStr := name[:len(layout)]
if t, err := time.Parse(layout, timeStr); err == nil {
return &t
}
}
return nil
}
func extractPointFromGeoJSON(geojson string) *Point {
var result struct {
Coordinates []float64 `json:"coordinates"`
}
if err := json.Unmarshal([]byte(geojson), &result); err != nil {
return nil
}
if len(result.Coordinates) < 2 {
return nil
}
return &Point{
Lon: result.Coordinates[0],
Lat: result.Coordinates[1],
}
}

1
web/.env.example Normal file
View File

@@ -0,0 +1 @@
VITE_API_URL=http://localhost:8080

24
web/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
web/README.md Normal file
View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
web/eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
web/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3280
web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

33
web/package.json Normal file
View File

@@ -0,0 +1,33 @@
{
"name": "web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"autoprefixer": "^10.4.23",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.18",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
"vite": "^7.2.4"
}
}

6
web/postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

1
web/public/vite.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

42
web/src/App.css Normal file
View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

8
web/src/App.tsx Normal file
View File

@@ -0,0 +1,8 @@
import { Timeline } from './components/Timeline'
import './App.css'
function App() {
return <Timeline />
}
export default App

1
web/src/assets/react.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,178 @@
import { useState, useEffect } from 'react';
import type { TimelineEvent, PlacemarkDetail } from '../types/api';
import { fetchTimelineEvents } from '../lib/api';
import { TimelineItem } from './TimelineItem';
export function Timeline() {
const [events, setEvents] = useState<TimelineEvent[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedEvent, setSelectedEvent] = useState<TimelineEvent | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [placemarkDetail, setPlacemarkDetail] = useState<PlacemarkDetail | null>(null);
useEffect(() => {
async function loadEvents() {
try {
setLoading(true);
const data = await fetchTimelineEvents();
setEvents(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load timeline events');
} finally {
setLoading(false);
}
}
loadEvents();
}, []);
const handleEventClick = async (event: TimelineEvent) => {
setSelectedEvent(event);
if (!event.placemark_id) return;
try {
setDetailLoading(true);
const response = await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:8080'}/api/v1/placemarks/${event.placemark_id}`);
if (!response.ok) throw new Error('Failed to load placemark details');
const detail = await response.json();
setPlacemarkDetail(detail);
} catch (err) {
console.error('Failed to load placemark details:', err);
} finally {
setDetailLoading(false);
}
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-blue-600 border-r-transparent"></div>
<p className="mt-4 text-gray-600">Loading timeline events...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6 bg-red-50 border border-red-200 rounded-lg">
<svg className="mx-auto h-12 w-12 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<h3 className="mt-2 text-lg font-medium text-red-900">Error Loading Timeline</h3>
<p className="mt-1 text-sm text-red-700">{error}</p>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-7xl mx-auto px-4 py-8">
<header className="mb-8">
<h1 className="text-3xl font-bold text-gray-900">Vegas Shooting Timeline</h1>
<p className="mt-2 text-gray-600">{events.length} events</p>
</header>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Timeline Events */}
<div className="lg:col-span-2 space-y-4">
{events.map((event) => (
<TimelineItem
key={event.placemark_id}
event={event}
onClick={() => handleEventClick(event)}
/>
))}
</div>
{/* Detail Panel */}
<div className="lg:col-span-1">
{selectedEvent ? (
<div className="sticky top-4 bg-white rounded-lg shadow-lg p-6">
<h2 className="text-xl font-bold text-gray-900 mb-4">Event Details</h2>
{detailLoading ? (
<div className="flex justify-center py-8">
<div className="inline-block h-6 w-6 animate-spin rounded-full border-4 border-solid border-blue-600 border-r-transparent"></div>
</div>
) : placemarkDetail ? (
<div className="space-y-4">
<div>
<h3 className="font-medium text-gray-700 mb-1">Name</h3>
<p className="text-gray-900">{placemarkDetail.name}</p>
</div>
{placemarkDetail.timestamp && (
<div>
<h3 className="font-medium text-gray-700 mb-1">Time</h3>
<p className="text-gray-900 font-mono text-sm">
{new Date(placemarkDetail.timestamp).toLocaleString()}
</p>
</div>
)}
{placemarkDetail.description && (
<div>
<h3 className="font-medium text-gray-700 mb-1">Description</h3>
<div className="text-sm text-gray-900 prose prose-sm max-w-none">
{placemarkDetail.description}
</div>
</div>
)}
{placemarkDetail.folder_path.length > 0 && (
<div>
<h3 className="font-medium text-gray-700 mb-1">Category</h3>
<p className="text-sm text-gray-600">
{placemarkDetail.folder_path.join(' > ')}
</p>
</div>
)}
{placemarkDetail.location && (
<div>
<h3 className="font-medium text-gray-700 mb-1">Location</h3>
<p className="text-sm text-gray-600 font-mono">
{placemarkDetail.location.coordinates[1].toFixed(6)}, {placemarkDetail.location.coordinates[0].toFixed(6)}
</p>
</div>
)}
{placemarkDetail.media_links && placemarkDetail.media_links.length > 0 && (
<div>
<h3 className="font-medium text-gray-700 mb-2">Media</h3>
<div className="space-y-2">
{placemarkDetail.media_links.map((link: string, idx: number) => (
<a
key={idx}
href={link}
target="_blank"
rel="noopener noreferrer"
className="block text-sm text-blue-600 hover:text-blue-800 hover:underline"
>
{link.includes('youtube') ? 'YouTube Video' : 'Media'} {idx + 1}
</a>
))}
</div>
</div>
)}
</div>
) : (
<p className="text-gray-500">No additional details available</p>
)}
</div>
) : (
<div className="sticky top-4 bg-white rounded-lg shadow-lg p-6 text-center text-gray-500">
Select an event to view details
</div>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,89 @@
import type { TimelineEvent } from '../types/api';
interface TimelineItemProps {
event: TimelineEvent;
onClick: () => void;
}
export function TimelineItem({ event, onClick }: TimelineItemProps) {
const parsedTime = event.timestamp ? new Date(event.timestamp) : null;
const timeDisplay = parsedTime?.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
return (
<div
onClick={onClick}
className="group relative cursor-pointer border-l-4 border-blue-500 bg-white p-4 shadow-sm transition-all hover:shadow-md hover:border-blue-600"
>
<div className="flex items-start justify-between gap-4">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
{timeDisplay && (
<span className="text-sm font-mono text-gray-500 bg-gray-100 px-2 py-0.5 rounded">
{timeDisplay}
</span>
)}
{event.folder_path.length > 0 && (
<span className="text-xs text-gray-400">
{event.folder_path[0]}
</span>
)}
</div>
<h3 className="font-medium text-gray-900 group-hover:text-blue-600">
{event.name}
</h3>
{event.description && (
<p className="mt-1 text-sm text-gray-600 line-clamp-2">
{event.description.substring(0, 150)}
</p>
)}
</div>
{event.location && (
<div className="flex-shrink-0">
<svg
className="h-5 w-5 text-gray-400"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
</div>
)}
</div>
{event.media_links && event.media_links.length > 0 && (
<div className="mt-2 flex gap-2">
{event.media_links.map((link, idx) => (
<a
key={idx}
href={link}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800"
>
<svg className="h-3 w-3" fill="currentColor" viewBox="0 0 20 20">
<path d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" />
</svg>
Video {idx + 1}
</a>
))}
</div>
)}
</div>
);
}

3
web/src/index.css Normal file
View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

50
web/src/lib/api.ts Normal file
View File

@@ -0,0 +1,50 @@
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080/api/v1';
export async function fetchTimelineEvents() {
const response = await fetch(`${API_BASE_URL}/timeline/events`);
if (!response.ok) {
throw new Error('Failed to fetch timeline events');
}
return response.json();
}
export async function fetchStats() {
const response = await fetch(`${API_BASE_URL}/stats`);
if (!response.ok) {
throw new Error('Failed to fetch stats');
}
return response.json();
}
export async function fetchPlacemarks(params?: {
limit?: number;
offset?: number;
folder?: string;
}) {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', params.limit.toString());
if (params?.offset) searchParams.set('offset', params.offset.toString());
if (params?.folder) searchParams.set('folder', params.folder);
const response = await fetch(`${API_BASE_URL}/placemarks?${searchParams}`);
if (!response.ok) {
throw new Error('Failed to fetch placemarks');
}
return response.json();
}
export async function fetchPlacemark(id: number) {
const response = await fetch(`${API_BASE_URL}/placemarks/${id}`);
if (!response.ok) {
throw new Error('Failed to fetch placemark');
}
return response.json();
}
export async function fetchFolders() {
const response = await fetch(`${API_BASE_URL}/folders`);
if (!response.ok) {
throw new Error('Failed to fetch folders');
}
return response.json();
}

10
web/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

52
web/src/types/api.ts Normal file
View File

@@ -0,0 +1,52 @@
export interface TimelineEvent {
timestamp: string | null;
name: string;
description?: string;
location?: {
lat: number;
lon: number;
};
media_links?: string[];
placemark_id: number;
folder_path: string[];
}
export interface Placemark {
id: number;
name: string;
description?: string;
style_id?: string;
folder_path: string[];
geometry_type: string;
geometry: string;
coordinates_raw?: string;
media_links?: string[];
created_at: string;
}
export interface Stats {
total_placemarks: number;
total_styles: number;
geometry_types: {
[key: string]: number;
};
top_folders: {
[key: string]: number;
};
}
export interface GeoJSONGeometry {
type: string;
coordinates: number[] | number[][] | number[][][];
}
export interface PlacemarkDetail {
id: number;
name: string;
description?: string;
style_id?: string;
folder_path: string[];
timestamp?: string;
location?: GeoJSONGeometry;
media_links?: string[];
}

11
web/tailwind.config.js Normal file
View File

@@ -0,0 +1,11 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

28
web/tsconfig.app.json Normal file
View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
web/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

26
web/tsconfig.node.json Normal file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

7
web/vite.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})