package main import ( "bytes" "encoding/json" "encoding/xml" "fmt" "io" "math" "net/http" "os" "path/filepath" "sort" "strings" "sync" "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) } // Global vote tracking: kmlID -> userID -> vote (+1, -1, or 0) type VoteRegistry struct { Votes map[string]map[string]int `json:"votes"` // kmlID -> (userID -> vote) mu sync.RWMutex } var voteRegistry *VoteRegistry // InitVoteRegistry loads the vote registry from disk func InitVoteRegistry() { voteRegistry = &VoteRegistry{ Votes: make(map[string]map[string]int), } voteRegistry.Load() } func (vr *VoteRegistry) Load() error { vr.mu.Lock() defer vr.mu.Unlock() data, err := os.ReadFile("data/kml_votes.json") if err != nil { if os.IsNotExist(err) { return nil } return err } return json.Unmarshal(data, vr) } func (vr *VoteRegistry) Save() error { vr.mu.RLock() defer vr.mu.RUnlock() return vr.saveUnlocked() } func (vr *VoteRegistry) saveUnlocked() error { if err := os.MkdirAll("data", 0755); err != nil { return err } data, err := json.MarshalIndent(vr, "", " ") if err != nil { return err } return os.WriteFile("data/kml_votes.json", data, 0644) } // GetVote return the vote of a user for a KML file (-1, 0, +1) func (vr *VoteRegistry) GetVote(kmlID, userID string) int { vr.mu.RLock() defer vr.mu.RUnlock() if userVotes, exists := vr.Votes[kmlID]; exists { return userVotes[userID] } return 0 } // SetVote sets a user's vote for a KML file func (vr *VoteRegistry) SetVote(kmlID, userID string, vote int) error { vr.mu.Lock() defer vr.mu.Unlock() if vr.Votes[kmlID] == nil { vr.Votes[kmlID] = make(map[string]int) } if vote == 0 { delete(vr.Votes[kmlID], userID) } else { vr.Votes[kmlID][userID] = vote } return vr.saveUnlocked() } // CalculateNetVotes calculates net votes for a KML file func (vr *VoteRegistry) CalculateNetVotes(kmlID string) int { vr.mu.RLock() defer vr.mu.RUnlock() total := 0 if userVotes, exists := vr.Votes[kmlID]; exists { for _, vote := range userVotes { total += vote } } 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 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 } // Get user info user, _ := userRegistry.GetUser(userID) displayName := userID if user != nil { displayName = user.DisplayName } // Create metadata metadata := KMLMetadata{ Filename: handler.Filename, UserID: userID, DisplayName: displayName, Distance: distance, IsPublic: false, // Private by default UploadedAt: time.Now(), Votes: 0, } metaPath := filepath.Join(kmlDir, handler.Filename+".meta.json") metaData, _ := json.MarshalIndent(metadata, "", " ") if err := os.WriteFile(metaPath, metaData, 0644); err != nil { http.Error(w, "Failed to save metadata", http.StatusInternalServerError) 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 (user's own + public files) func HandleKMLList(w http.ResponseWriter, r *http.Request) { userID, ok := getUserID(r.Context()) if !ok { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } var allFiles []KMLMetadata // Walk through all user directories usersDir := "data/users" entries, err := os.ReadDir(usersDir) if err != nil { // No users yet w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "my_files": []KMLMetadata{}, "public_files": []KMLMetadata{}, }) return } for _, entry := range entries { if !entry.IsDir() { continue } ownerID := entry.Name() kmlDir := filepath.Join(usersDir, ownerID, "kml") kmlFiles, err := os.ReadDir(kmlDir) if err != nil { continue } for _, kmlFile := range kmlFiles { if !strings.HasSuffix(kmlFile.Name(), ".meta.json") { continue } metaPath := filepath.Join(kmlDir, kmlFile.Name()) data, err := os.ReadFile(metaPath) if err != nil { continue } var meta KMLMetadata if err := json.Unmarshal(data, &meta); err != nil { continue } // Calculate current votes kmlID := fmt.Sprintf("%s/%s", ownerID, meta.Filename) meta.Votes = voteRegistry.CalculateNetVotes(kmlID) // Include if: 1) owned by current user, OR 2) public if ownerID == userID || meta.IsPublic { allFiles = append(allFiles, meta) } } } // Separate into own files and public files var myFiles, publicFiles []KMLMetadata for _, file := range allFiles { if file.UserID == userID { myFiles = append(myFiles, file) } if file.IsPublic { publicFiles = append(publicFiles, file) } } // Sort public files by votes (highest first) sort.Slice(publicFiles, func(i, j int) bool { return publicFiles[i].Votes > publicFiles[j].Votes }) // Sort my files by upload date (newest first) sort.Slice(myFiles, func(i, j int) bool { return myFiles[i].UploadedAt.After(myFiles[j].UploadedAt) }) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "my_files": myFiles, "public_files": publicFiles, }) } // 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 } metaPath := fmt.Sprintf("data/users/%s/kml/%s.meta.json", userID, req.Filename) data, err := os.ReadFile(metaPath) if err != nil { http.Error(w, "File not found", http.StatusNotFound) return } var meta KMLMetadata if err := json.Unmarshal(data, &meta); err != nil { http.Error(w, "Failed to parse metadata", http.StatusInternalServerError) return } // Verify ownership if meta.UserID != userID { http.Error(w, "Forbidden", http.StatusForbidden) return } // Toggle privacy meta.IsPublic = !meta.IsPublic // Save updated metadata newData, _ := json.MarshalIndent(meta, "", " ") if err := os.WriteFile(metaPath, newData, 0644); err != nil { http.Error(w, "Failed to update metadata", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "success": true, "is_public": meta.IsPublic, }) } // 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 } kmlID := fmt.Sprintf("%s/%s", req.OwnerID, req.Filename) // Set the vote if err := voteRegistry.SetVote(kmlID, userID, req.Vote); err != nil { http.Error(w, "Failed to save vote", http.StatusInternalServerError) return } // Calculate new net votes netVotes := voteRegistry.CalculateNetVotes(kmlID) 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 by reading metadata metaPath := fmt.Sprintf("data/users/%s/kml/%s.meta.json", userID, req.Filename) data, err := os.ReadFile(metaPath) if err != nil { http.Error(w, "File not found", http.StatusNotFound) return } var meta KMLMetadata if err := json.Unmarshal(data, &meta); err != nil { http.Error(w, "Failed to parse metadata", http.StatusInternalServerError) return } // Verify ownership if meta.UserID != userID { http.Error(w, "Forbidden - you can only delete your own files", http.StatusForbidden) return } // Delete KML file and metadata kmlPath := fmt.Sprintf("data/users/%s/kml/%s", userID, req.Filename) os.Remove(kmlPath) os.Remove(metaPath) 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 { metaPath := fmt.Sprintf("data/users/%s/kml/%s.meta.json", ownerID, filename) data, err := os.ReadFile(metaPath) if err != nil { http.Error(w, "File not found", http.StatusNotFound) return } var meta KMLMetadata if err := json.Unmarshal(data, &meta); err != nil { http.Error(w, "Error reading metadata", http.StatusInternalServerError) return } if !meta.IsPublic { 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) }