Files
pedestrian-simulator/server/kml.go

479 lines
13 KiB
Go
Raw Normal View History

2026-01-11 17:16:59 -07:00
package main
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
2026-01-11 17:16:59 -07:00
"strings"
"time"
)
// KML structure for parsing
type KML struct {
XMLName xml.Name `xml:"kml"`
Document KMLDocument `xml:"Document"`
}
type KMLDocument struct {
Placemarks []KMLPlacemark `xml:"Placemark"`
}
type KMLPlacemark struct {
LineString KMLLineString `xml:"LineString"`
}
type KMLLineString struct {
Coordinates string `xml:"coordinates"`
}
// KML Metadata
type KMLMetadata struct {
Filename string `json:"filename"`
UserID string `json:"user_id"`
DisplayName string `json:"display_name"` // User's display name
Distance float64 `json:"distance"` // in kilometers
IsPublic bool `json:"is_public"`
UploadedAt time.Time `json:"uploaded_at"`
Votes int `json:"votes"` // Net votes (calculated from voting system)
}
// SetVote sets a user's vote for a KML file in the database
func SetVote(kmlID int, userID string, vote int) error {
if vote == 0 {
_, err := db.Exec("DELETE FROM kml_votes WHERE kml_id = ? AND user_id = ?", kmlID, userID)
2026-01-11 17:16:59 -07:00
return err
}
_, err := db.Exec(`
INSERT INTO kml_votes (kml_id, user_id, vote_value)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE vote_value = ?
`, kmlID, userID, vote, vote)
return err
2026-01-11 17:16:59 -07:00
}
// CalculateNetVotes calculates net votes for a KML file from the database
func CalculateNetVotes(kmlID int) int {
var total int
err := db.QueryRow("SELECT COALESCE(SUM(vote_value), 0) FROM kml_votes WHERE kml_id = ?", kmlID).Scan(&total)
2026-01-11 17:16:59 -07:00
if err != nil {
return 0
2026-01-11 17:16:59 -07:00
}
return total
}
// Haversine formula to calculate distance between two lat/lng points
func haversineDistance(lat1, lon1, lat2, lon2 float64) float64 {
const earthRadiusKm = 6371.0
dLat := (lat2 - lat1) * math.Pi / 180.0
dLon := (lon2 - lon1) * math.Pi / 180.0
a := math.Sin(dLat/2)*math.Sin(dLat/2) +
math.Cos(lat1*math.Pi/180.0)*math.Cos(lat2*math.Pi/180.0)*
math.Sin(dLon/2)*math.Sin(dLon/2)
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
return earthRadiusKm * c
}
// ParseKMLDistance parses a KML file and calculates the total distance
func ParseKMLDistance(kmlData []byte) (float64, error) {
decoder := xml.NewDecoder(bytes.NewReader(kmlData))
totalDistance := 0.0
for {
token, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
switch se := token.(type) {
case xml.StartElement:
// We only care about coordinates within a LineString context.
// However, since Points have only one coordinate and result in 0 anyway,
// searching for any <coordinates> tag is both easier and robust enough.
if se.Name.Local == "coordinates" {
var coords string
if err := decoder.DecodeElement(&coords, &se); err != nil {
continue
}
// Sum up distance from this LineString
items := strings.Fields(coords)
var prevLat, prevLon float64
first := true
for _, item := range items {
parts := strings.Split(strings.TrimSpace(item), ",")
if len(parts) < 2 {
continue
}
var lon, lat float64
_, err1 := fmt.Sscanf(parts[0], "%f", &lon)
_, err2 := fmt.Sscanf(parts[1], "%f", &lat)
if err1 != nil || err2 != nil {
continue
}
if !first {
totalDistance += haversineDistance(prevLat, prevLon, lat, lon)
}
prevLat = lat
prevLon = lon
first = false
}
}
}
}
return totalDistance, nil
}
// HandleKMLUpload handles KML file uploads
func HandleKMLUpload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
userID, ok := getUserID(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Parse multipart form
if err := r.ParseMultipartForm(10 << 20); err != nil { // 10 MB limit
http.Error(w, "Failed to parse form", http.StatusBadRequest)
return
}
file, handler, err := r.FormFile("kml")
if err != nil {
http.Error(w, "No file uploaded", http.StatusBadRequest)
return
}
defer file.Close()
// Read file data
data, err := io.ReadAll(file)
if err != nil {
http.Error(w, "Failed to read file", http.StatusInternalServerError)
return
}
// Calculate distance
distance, err := ParseKMLDistance(data)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to parse KML: %v", err), http.StatusBadRequest)
return
}
// Save KML file
kmlDir := fmt.Sprintf("data/users/%s/kml", userID)
if err := os.MkdirAll(kmlDir, 0755); err != nil {
http.Error(w, "Failed to create directory", http.StatusInternalServerError)
return
}
kmlPath := filepath.Join(kmlDir, handler.Filename)
if err := os.WriteFile(kmlPath, data, 0644); err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
}
// Save metadata to database
_, err = db.Exec(`
INSERT INTO kml_metadata (filename, user_id, distance, is_public, uploaded_at)
VALUES (?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE distance = ?, uploaded_at = NOW()
`, handler.Filename, userID, distance, false, distance)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to save metadata: %v", err), http.StatusInternalServerError)
2026-01-11 17:16:59 -07:00
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"filename": handler.Filename,
"distance": distance,
})
}
// HandleKMLList lists KML files with pagination and sorting
2026-01-11 17:16:59 -07:00
func HandleKMLList(w http.ResponseWriter, r *http.Request) {
userID, ok := getUserID(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Parse pagination parameters
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
if limit <= 0 {
limit = 10
}
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
if page <= 0 {
page = 1
}
offset := (page - 1) * limit
sortBy := r.URL.Query().Get("sort_by")
order := r.URL.Query().Get("order")
if order != "ASC" {
order = "DESC"
}
2026-01-11 17:16:59 -07:00
// 1. Get my files
myFiles, err := queryKMLMetadata(`
SELECT m.filename, m.user_id, u.display_name, m.distance, m.is_public, m.uploaded_at,
(SELECT COALESCE(SUM(v.vote_value), 0) FROM kml_votes v WHERE v.kml_id = m.id) as votes
FROM kml_metadata m
JOIN users u ON m.user_id = u.fitbit_user_id
WHERE m.user_id = ?
ORDER BY m.uploaded_at DESC
`, userID)
2026-01-11 17:16:59 -07:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
2026-01-11 17:16:59 -07:00
return
}
// 2. Get public files (with pagination and sorting)
sortClause := "votes"
switch sortBy {
case "date":
sortClause = "m.uploaded_at"
case "distance":
sortClause = "m.distance"
2026-01-11 17:16:59 -07:00
}
publicFiles, err := queryKMLMetadata(fmt.Sprintf(`
SELECT m.filename, m.user_id, u.display_name, m.distance, m.is_public, m.uploaded_at,
(SELECT COALESCE(SUM(v.vote_value), 0) FROM kml_votes v WHERE v.kml_id = m.id) as votes
FROM kml_metadata m
JOIN users u ON m.user_id = u.fitbit_user_id
WHERE m.is_public = 1
ORDER BY %s %s
LIMIT ? OFFSET ?
`, sortClause, order), limit, offset)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
2026-01-11 17:16:59 -07:00
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"my_files": myFiles,
"public_files": publicFiles,
"page": page,
"limit": limit,
2026-01-11 17:16:59 -07:00
})
}
func queryKMLMetadata(query string, args ...interface{}) ([]KMLMetadata, error) {
rows, err := db.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var files []KMLMetadata
for rows.Next() {
var m KMLMetadata
err := rows.Scan(&m.Filename, &m.UserID, &m.DisplayName, &m.Distance, &m.IsPublic, &m.UploadedAt, &m.Votes)
if err != nil {
return nil, err
}
files = append(files, m)
}
return files, nil
}
2026-01-11 17:16:59 -07:00
// HandleKMLPrivacyToggle toggles the privacy setting of a KML file
func HandleKMLPrivacyToggle(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
userID, ok := getUserID(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var req struct {
Filename string `json:"filename"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
// Toggle privacy in database
if _, err := db.Exec("UPDATE kml_metadata SET is_public = NOT is_public WHERE filename = ? AND user_id = ?", req.Filename, userID); err != nil {
http.Error(w, "Failed to update metadata", http.StatusInternalServerError)
2026-01-11 17:16:59 -07:00
return
}
var isPublic bool
if err := db.QueryRow("SELECT is_public FROM kml_metadata WHERE filename = ? AND user_id = ?", req.Filename, userID).Scan(&isPublic); err != nil {
http.Error(w, "Failed to fetch updated metadata", http.StatusInternalServerError)
2026-01-11 17:16:59 -07:00
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"is_public": isPublic,
2026-01-11 17:16:59 -07:00
})
}
// HandleKMLVote handles voting on KML files (toggle upvote/downvote/none)
func HandleKMLVote(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
userID, ok := getUserID(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var req struct {
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
Vote int `json:"vote"` // +1, -1, or 0 to remove vote
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
// Validate vote value
if req.Vote != -1 && req.Vote != 0 && req.Vote != 1 {
http.Error(w, "Invalid vote value (must be -1, 0, or 1)", http.StatusBadRequest)
return
}
// Get KML ID
var kmlID int
err := db.QueryRow("SELECT id FROM kml_metadata WHERE user_id = ? AND filename = ?", req.OwnerID, req.Filename).Scan(&kmlID)
if err != nil {
http.Error(w, "KML not found", http.StatusNotFound)
return
}
2026-01-11 17:16:59 -07:00
// Set the vote
if err := SetVote(kmlID, userID, req.Vote); err != nil {
2026-01-11 17:16:59 -07:00
http.Error(w, "Failed to save vote", http.StatusInternalServerError)
return
}
// Calculate new net votes
netVotes := CalculateNetVotes(kmlID)
2026-01-11 17:16:59 -07:00
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"net_votes": netVotes,
})
}
// HandleKMLDelete deletes a KML file with ownership verification
func HandleKMLDelete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete && r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
userID, ok := getUserID(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var req struct {
Filename string `json:"filename"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
// Verify ownership and delete metadata from database
if _, err := db.Exec("DELETE FROM kml_metadata WHERE filename = ? AND user_id = ?", req.Filename, userID); err != nil {
http.Error(w, "Failed to delete metadata or file not found", http.StatusInternalServerError)
2026-01-11 17:16:59 -07:00
return
}
// Delete KML file
2026-01-11 17:16:59 -07:00
kmlPath := fmt.Sprintf("data/users/%s/kml/%s", userID, req.Filename)
os.Remove(kmlPath)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
})
}
// HandleKMLDownload serves a KML file for downloading/viewing
func HandleKMLDownload(w http.ResponseWriter, r *http.Request) {
userID, ok := getUserID(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
ownerID := r.URL.Query().Get("owner_id")
filename := r.URL.Query().Get("filename")
if ownerID == "" || filename == "" {
http.Error(w, "Missing owner_id or filename", http.StatusBadRequest)
return
}
// Verify permission: ownerID == userID OR file is public
if ownerID != userID {
var isPublic bool
err := db.QueryRow("SELECT is_public FROM kml_metadata WHERE user_id = ? AND filename = ?", ownerID, filename).Scan(&isPublic)
2026-01-11 17:16:59 -07:00
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
if !isPublic {
2026-01-11 17:16:59 -07:00
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
}
kmlPath := fmt.Sprintf("data/users/%s/kml/%s", ownerID, filename)
data, err := os.ReadFile(kmlPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/vnd.google-earth.kml+xml")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
w.Write(data)
}