2026-01-11 17:16:59 -07:00
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"encoding/xml"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"math"
|
|
|
|
|
"net/http"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
2026-01-11 20:24:50 -07:00
|
|
|
"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)
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
// 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
|
|
|
|
|
}
|
2026-01-11 20:24:50 -07:00
|
|
|
_, 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
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -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 {
|
2026-01-11 20:24:50 -07:00
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
// 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,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 21:40:48 -07:00
|
|
|
// Parse parameters for My Files
|
|
|
|
|
myLimit, _ := strconv.Atoi(r.URL.Query().Get("my_limit"))
|
|
|
|
|
if myLimit <= 0 {
|
|
|
|
|
myLimit = 10
|
2026-01-11 20:24:50 -07:00
|
|
|
}
|
2026-01-11 21:40:48 -07:00
|
|
|
myPage, _ := strconv.Atoi(r.URL.Query().Get("my_page"))
|
|
|
|
|
if myPage <= 0 {
|
|
|
|
|
myPage = 1
|
|
|
|
|
}
|
|
|
|
|
mySortBy := r.URL.Query().Get("my_sort_by")
|
|
|
|
|
if mySortBy == "" {
|
|
|
|
|
mySortBy = "date"
|
2026-01-11 20:24:50 -07:00
|
|
|
}
|
|
|
|
|
|
2026-01-11 21:40:48 -07:00
|
|
|
// Parse parameters for Public Files
|
|
|
|
|
publicLimit, _ := strconv.Atoi(r.URL.Query().Get("public_limit"))
|
|
|
|
|
if publicLimit <= 0 {
|
|
|
|
|
publicLimit = 10
|
|
|
|
|
}
|
|
|
|
|
publicPage, _ := strconv.Atoi(r.URL.Query().Get("public_page"))
|
|
|
|
|
if publicPage <= 0 {
|
|
|
|
|
publicPage = 1
|
|
|
|
|
}
|
|
|
|
|
publicSortBy := r.URL.Query().Get("public_sort_by")
|
|
|
|
|
if publicSortBy == "" {
|
|
|
|
|
publicSortBy = "votes"
|
2026-01-11 20:24:50 -07:00
|
|
|
}
|
2026-01-11 17:16:59 -07:00
|
|
|
|
2026-01-11 21:40:48 -07:00
|
|
|
// 1. Get My Files
|
|
|
|
|
myFiles, myTotal, err := fetchKMLList(userID, true, myPage, myLimit, mySortBy)
|
2026-01-11 17:16:59 -07:00
|
|
|
if err != nil {
|
2026-01-11 20:24:50 -07:00
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
2026-01-11 17:16:59 -07:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 21:40:48 -07:00
|
|
|
// 2. Get Public Files
|
|
|
|
|
publicFiles, publicTotal, err := fetchKMLList(userID, false, publicPage, publicLimit, publicSortBy)
|
|
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
|
|
|
"my_files": myFiles,
|
|
|
|
|
"my_total": myTotal,
|
|
|
|
|
"my_page": myPage,
|
|
|
|
|
"public_files": publicFiles,
|
|
|
|
|
"public_total": publicTotal,
|
|
|
|
|
"public_page": publicPage,
|
|
|
|
|
"limit": 10, // Default limit reference for UI
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func fetchKMLList(userID string, mineOnly bool, page, limit int, sortBy string) ([]KMLMetadata, int, error) {
|
|
|
|
|
offset := (page - 1) * limit
|
|
|
|
|
|
|
|
|
|
var whereClause string
|
|
|
|
|
var args []interface{}
|
|
|
|
|
if mineOnly {
|
|
|
|
|
whereClause = "WHERE m.user_id = ?"
|
|
|
|
|
args = append(args, userID)
|
|
|
|
|
} else {
|
|
|
|
|
whereClause = "WHERE m.is_public = 1"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get total count first
|
|
|
|
|
var total int
|
|
|
|
|
err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM kml_metadata m %s", whereClause), args...).Scan(&total)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
sortClause := "votes"
|
2026-01-11 21:40:48 -07:00
|
|
|
order := "DESC"
|
2026-01-11 20:24:50 -07:00
|
|
|
switch sortBy {
|
|
|
|
|
case "date":
|
|
|
|
|
sortClause = "m.uploaded_at"
|
|
|
|
|
case "distance":
|
|
|
|
|
sortClause = "m.distance"
|
2026-01-11 21:40:48 -07:00
|
|
|
case "votes":
|
|
|
|
|
sortClause = "votes"
|
|
|
|
|
case "filename":
|
|
|
|
|
sortClause = "m.filename"
|
|
|
|
|
order = "ASC"
|
2026-01-11 17:16:59 -07:00
|
|
|
}
|
|
|
|
|
|
2026-01-11 21:40:48 -07:00
|
|
|
query := fmt.Sprintf(`
|
2026-01-11 20:24:50 -07:00
|
|
|
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
|
2026-01-11 21:40:48 -07:00
|
|
|
%s
|
2026-01-11 20:24:50 -07:00
|
|
|
ORDER BY %s %s
|
|
|
|
|
LIMIT ? OFFSET ?
|
2026-01-11 21:40:48 -07:00
|
|
|
`, whereClause, sortClause, order)
|
2026-01-11 17:16:59 -07:00
|
|
|
|
2026-01-11 21:40:48 -07:00
|
|
|
args = append(args, limit, offset)
|
|
|
|
|
files, err := queryKMLMetadata(query, args...)
|
|
|
|
|
return files, total, err
|
2026-01-11 17:16:59 -07:00
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
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,
|
2026-01-11 20:24:50 -07:00
|
|
|
"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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
// 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
|
2026-01-11 20:24:50 -07:00
|
|
|
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
|
2026-01-11 20:24:50 -07:00
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
// 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 {
|
2026-01-11 20:24:50 -07:00
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 20:24:50 -07:00
|
|
|
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)
|
|
|
|
|
}
|