add rich KML support, mitigate KML vulnerabilities
All checks were successful
pedestrian-simulator / build (push) Successful in 1m0s

This commit is contained in:
2026-01-11 22:48:50 -07:00
parent eaea2c4edb
commit f985d3433d
8 changed files with 705 additions and 34 deletions

View File

@@ -30,7 +30,9 @@ let currentMyPage = 1;
let currentPublicPage = 1;
const KML_PAGE_LIMIT = 10;
// Custom Route Logic
let apiKey = null;
let currentUserID = null; // Store current user ID for ownership checks
window.isGeneratingRoute = false;
@@ -98,6 +100,9 @@ async function checkAuth() {
function updateUserProfile(user) {
if (!user) return;
currentUserID = user.fitbit_user_id || user.id; // Store ID
console.log(`[KML] User Profile Updated. currentUserID: ${currentUserID}`);
const nameEl = document.getElementById('userName');
const avatarEl = document.getElementById('userAvatar');
const defaultAvatar = 'https://www.fitbit.com/images/profile/defaultProfile_150_male.png';
@@ -115,6 +120,79 @@ function setupLoginHandler() {
});
}
// ...
// (Skipping to openKMLDetails implementation)
async function openKMLDetails(file) {
currentKmlFile = file;
const overlay = document.getElementById('kml-details-overlay');
// Reset UI
document.getElementById('kmlDetailsTitle').textContent = file.filename;
document.getElementById('kmlDetailsDistance').textContent = `📏 ${file.distance.toFixed(2)} km`;
document.getElementById('kmlDetailsAuthor').textContent = file.display_name ? `👤 ${file.display_name}` : '';
document.getElementById('kmlDetailsVotes').textContent = `👍 ${file.votes}`;
document.getElementById('kmlDescriptionDisplay').textContent = file.description || 'No description provided.';
// Show/Hide Edit Button (only for owner)
console.log(`[KML] Opening details. File Owner: ${file.user_id} (type: ${typeof file.user_id}), Current User: ${currentUserID} (type: ${typeof currentUserID})`);
if (file.user_id === currentUserID) {
document.getElementById('editDescriptionBtn').classList.remove('hidden');
} else {
document.getElementById('editDescriptionBtn').classList.add('hidden');
}
overlay.classList.add('active');
// Fetch and Parse KML
try {
const response = await fetch(`/api/kml/download?owner_id=${file.user_id}&filename=${encodeURIComponent(file.filename)}`);
if (!response.ok) throw new Error('Failed to download KML');
const kmlText = await response.text();
const parsed = parseKMLData(kmlText);
currentKmlPath = parsed.path;
currentKmlMarkers = parsed.markers;
// Render Map
if (!previewMap) {
previewMap = new google.maps.Map(document.getElementById('kmlPreviewMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
fullscreenControl: false,
streetViewControl: false
});
}
// Draw Route
if (previewPolyline) previewPolyline.setMap(null);
previewPolyline = new google.maps.Polyline({
path: currentKmlPath,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 4,
map: previewMap
});
const bounds = new google.maps.LatLngBounds();
currentKmlPath.forEach(pt => bounds.extend(pt));
previewMap.fitBounds(bounds);
} catch (err) {
console.error('Error loading KML details:', err);
alert('Failed to load route details.');
}
}
function setupLoginHandler() {
document.getElementById('fitbitLoginButton').addEventListener('click', () => {
window.location.href = '/auth/fitbit';
});
}
async function setupUserMenu() {
// This function could fetch user info and display it
// For now, the backend handles this via the Fitbit callback
@@ -138,6 +216,7 @@ async function setupUserMenu() {
function setupKMLBrowser() {
// Setup user menu
setupUserMenu();
setupKMLDetailsListeners();
// Tab switching
document.querySelectorAll('.kml-tab').forEach(tab => {
@@ -291,12 +370,12 @@ function renderKMLFiles(listId, files, isOwnFiles) {
const uniqueId = `${listId}-${index}`;
try {
// Use This Route button
const useBtn = document.getElementById(`use-${uniqueId}`);
if (useBtn) {
useBtn.addEventListener('click', (e) => {
console.log(`[KML] 'Use' click for: ${file.filename}`);
handleUseRoute(file);
// Open Details button
const openBtn = document.getElementById(`open-${uniqueId}`);
if (openBtn) {
openBtn.addEventListener('click', () => {
console.log(`[KML] 'Open' click for: ${file.filename}`);
openKMLDetails(file);
});
}
@@ -352,7 +431,7 @@ function createKMLFileHTML(file, isOwnFiles, listId, index) {
</div>
</div>
<div class="kml-file-actions">
<button id="use-${uniqueId}" class="action-btn" title="Use This Route">▶️ Use</button>
<button id="open-${uniqueId}" class="primary-btn small" title="View Details">📂 Open</button>
${!isOwnFiles ? `
<button id="upvote-${uniqueId}" class="vote-btn" title="Upvote">
👍 <span class="vote-count">${file.votes}</span>
@@ -428,10 +507,182 @@ async function handlePrivacyToggle(file) {
}
}
/**
* Shows a custom confirmation overlay
* @returns {Promise<boolean>}
*/
// ========================================
// KML Details Overlay Logic
// ========================================
let previewMap;
let previewPolyline;
let currentKmlFile = null;
let currentKmlPath = [];
let currentKmlMarkers = [];
function setupKMLDetailsListeners() {
document.getElementById('closeKmlDetails').addEventListener('click', closeKMLDetails);
document.getElementById('backToKmlListBtn').addEventListener('click', closeKMLDetails); // Just close overlay to reveal browser behind
document.getElementById('startKmlTripBtn').addEventListener('click', () => {
if (!currentKmlFile || currentKmlPath.length === 0) return;
// Start the trip
startFromCustomRoute(currentKmlPath, currentKmlFile.filename, false, currentKmlMarkers);
// Close overlays
closeKMLDetails();
document.getElementById('kml-browser-overlay').classList.remove('active');
});
// Description Editing
document.getElementById('editDescriptionBtn').addEventListener('click', () => {
document.getElementById('kmlDescriptionDisplay').classList.add('hidden');
document.getElementById('kmlDescriptionEditor').classList.remove('hidden');
document.getElementById('kmlDescriptionInput').value = currentKmlFile.description || '';
document.getElementById('editDescriptionBtn').classList.add('hidden');
});
document.getElementById('cancelDescriptionBtn').addEventListener('click', () => {
document.getElementById('kmlDescriptionDisplay').classList.remove('hidden');
document.getElementById('kmlDescriptionEditor').classList.add('hidden');
document.getElementById('editDescriptionBtn').classList.remove('hidden');
});
document.getElementById('saveDescriptionBtn').addEventListener('click', async () => {
const newDesc = document.getElementById('kmlDescriptionInput').value.trim();
try {
const response = await fetch('/api/kml/edit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: currentKmlFile.filename,
description: newDesc
})
});
if (response.ok) {
currentKmlFile.description = newDesc;
document.getElementById('kmlDescriptionDisplay').textContent = newDesc || 'No description provided.';
document.getElementById('kmlDescriptionDisplay').classList.remove('hidden');
document.getElementById('kmlDescriptionEditor').classList.add('hidden');
document.getElementById('editDescriptionBtn').classList.remove('hidden');
loadKMLFiles(); // Refresh list to update cache/view if needed
} else {
alert('Failed to save description');
}
} catch (err) {
console.error('Save description failed:', err);
alert('Failed to save description');
}
});
}
function closeKMLDetails() {
document.getElementById('kml-details-overlay').classList.remove('active');
}
async function openKMLDetails(file) {
currentKmlFile = file;
const overlay = document.getElementById('kml-details-overlay');
// Reset UI
document.getElementById('kmlDetailsTitle').textContent = file.filename;
document.getElementById('kmlDetailsDistance').textContent = `📏 ${file.distance.toFixed(2)} km`;
document.getElementById('kmlDetailsAuthor').textContent = file.display_name ? `👤 ${file.display_name}` : '';
document.getElementById('kmlDetailsVotes').textContent = `👍 ${file.votes}`;
document.getElementById('kmlDescriptionDisplay').textContent = file.description || 'No description provided.';
// Show/Hide Edit Button (only for owner)
console.log(`[KML] Opening details. File Owner: ${file.user_id} (type: ${typeof file.user_id}), Current User: ${currentUserID} (type: ${typeof currentUserID})`);
// Loose equality check in case of string vs number mismatch
if (file.user_id == currentUserID) {
document.getElementById('editDescriptionBtn').classList.remove('hidden');
} else {
document.getElementById('editDescriptionBtn').classList.add('hidden');
}
overlay.classList.add('active');
// Fetch and Parse KML
try {
const response = await fetch(`/api/kml/download?owner_id=${file.user_id}&filename=${encodeURIComponent(file.filename)}`);
if (!response.ok) throw new Error('Failed to download KML');
const kmlText = await response.text();
const parsed = parseKMLData(kmlText);
currentKmlPath = parsed.path;
currentKmlMarkers = parsed.markers;
// Render Map
if (!previewMap) {
previewMap = new google.maps.Map(document.getElementById('kmlPreviewMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
fullscreenControl: false,
streetViewControl: false
});
}
// Draw Route
if (previewPolyline) previewPolyline.setMap(null);
previewPolyline = new google.maps.Polyline({
path: currentKmlPath,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 4,
map: previewMap
});
const bounds = new google.maps.LatLngBounds();
currentKmlPath.forEach(pt => bounds.extend(pt));
previewMap.fitBounds(bounds);
} catch (err) {
console.error('Error loading KML details:', err);
alert('Failed to load route details.');
}
}
function parseKMLData(kmlContent) {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(kmlContent, "text/xml");
const placemarks = xmlDoc.getElementsByTagName("Placemark");
let fullPath = [];
let markers = [];
for (let i = 0; i < placemarks.length; i++) {
const pm = placemarks[i];
// Check for LineString
const lineString = pm.getElementsByTagName("LineString")[0];
if (lineString) {
const coordsText = lineString.getElementsByTagName("coordinates")[0].textContent.trim();
const points = parseCoordinates(coordsText);
fullPath = fullPath.concat(points);
}
// Check for Point (Markers)
const point = pm.getElementsByTagName("Point")[0];
if (point) {
const coordsText = point.getElementsByTagName("coordinates")[0].textContent.trim();
const points = parseCoordinates(coordsText);
if (points.length > 0) {
const nameNode = pm.getElementsByTagName("name")[0];
const descNode = pm.getElementsByTagName("description")[0];
markers.push({
lat: points[0].lat,
lng: points[0].lng,
name: nameNode ? nameNode.textContent : 'Marker',
description: descNode ? descNode.textContent : ''
});
}
}
}
return { path: fullPath, markers: markers };
}
function showConfirm({ title, message, confirmText = 'Yes', cancelText = 'Cancel', isDanger = false }) {
return new Promise((resolve) => {
const overlay = document.getElementById('confirm-overlay');
@@ -570,7 +821,7 @@ function initializeMap() {
// For now, let's just re-calculate the route on load if we have start/end addresses
if (locationData.isCustom && locationData.customPath) {
// Restore custom route
startFromCustomRoute(locationData.customPath, locationData.routeName, true);
startFromCustomRoute(locationData.customPath, locationData.routeName, true, locationData.customMarkers || []);
} else if (locationData.startAddress && locationData.endAddress) {
document.getElementById('routeInfo').textContent = `${locationData.startAddress}${locationData.endAddress}`;
calculateAndStartRoute(locationData.startAddress, locationData.endAddress, true); // isRestoring = true
@@ -1398,6 +1649,15 @@ function initializeMainMap() {
});
mainMapPolyline.setMap(mainMap);
}
// Restore Markers
const savedLocation = localStorage.getItem(LOCATION_STORAGE);
if (savedLocation) {
const locationData = JSON.parse(savedLocation);
if (locationData.customMarkers && locationData.customMarkers.length > 0) {
renderTripMarkers(locationData.customMarkers);
}
}
}
@@ -1493,7 +1753,8 @@ function densifyPath(path, maxSegmentLength = 20) {
return densified;
}
function startFromCustomRoute(pathData, routeName, isRestoring = false) {
function startFromCustomRoute(pathData, routeName, isRestoring = false, markers = []) {
if (!window.google) return;
// Convert to Google Maps LatLng objects
@@ -1512,6 +1773,7 @@ function startFromCustomRoute(pathData, routeName, isRestoring = false) {
const locationData = {
isCustom: true,
customPath: pathData, // Save raw objects {lat, lng} for serialization
customMarkers: markers, // Save markers
routeName: routeName,
startLat: startPoint.lat(),
startLng: startPoint.lng(),
@@ -1569,6 +1831,88 @@ function startFromCustomRoute(pathData, routeName, isRestoring = false) {
mainMapPolyline.setMap(mainMap);
}
// Render Markers
renderTripMarkers(markers);
// Initial trip meter update
updateTripMeter(0);
}
let tripMarkers = []; // Global array to hold marker instances
function renderTripMarkers(markers) {
// Clear existing markers
tripMarkers.forEach(m => m.setMap(null));
tripMarkers = [];
if (!markers || markers.length === 0) return;
markers.forEach(m => {
const position = new google.maps.LatLng(m.lat, m.lng);
const title = m.name || 'Marker';
// 1. Marker for Maps (Main + Minimap)
// Note: Google Maps markers can only belong to one map at a time.
// We might need duplicate markers if we want them on both maps + panorama?
// Actually, for Panorama we use setMap(panorama).
// Let's create one marker for the Main Map/Minimap (whichever is visible logic? or just Main Map)
// If we want it on Minimap too, we need a second marker.
// Marker for Minimap
if (minimap) {
const mmMarker = new google.maps.Marker({
position: position,
map: minimap,
title: title,
icon: {
url: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
scaledSize: new google.maps.Size(32, 32)
}
});
tripMarkers.push(mmMarker);
}
// Marker for Main Map
if (mainMap) {
const mMapMarker = new google.maps.Marker({
position: position,
map: mainMap,
title: title,
icon: {
url: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
scaledSize: new google.maps.Size(32, 32)
}
});
tripMarkers.push(mMapMarker);
}
// Marker for Street View
// Street View markers need to be added to the panorama
if (panorama) {
const svMarker = new google.maps.Marker({
position: position,
map: panorama, // This puts it in the 3D world
title: title,
icon: {
url: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png', // Yellow for SV visibility
scaledSize: new google.maps.Size(48, 48) // Slightly larger
}
// We could add info windows here if needed
});
// Add info window for description
if (m.description) {
const infoWindow = new google.maps.InfoWindow({
content: `<div><strong>${escapeHtml(title)}</strong><br>${escapeHtml(m.description)}</div>`
});
svMarker.addListener('click', () => {
infoWindow.open(panorama, svMarker);
});
}
tripMarkers.push(svMarker);
}
});
}

View File

@@ -195,6 +195,52 @@
</div>
</div>
<!-- KML Details Overlay -->
<div id="kml-details-overlay" class="overlay">
<div class="kml-details-card">
<div class="kml-details-header">
<h2 id="kmlDetailsTitle">Route Details</h2>
<button id="closeKmlDetails" class="close-btn">×</button>
</div>
<div class="kml-details-content">
<div id="kmlPreviewMap" class="kml-preview-map"></div>
<div class="kml-metadata-section">
<div class="metadata-row">
<span id="kmlDetailsDistance" class="meta-tag">📏 0.00 km</span>
<span id="kmlDetailsAuthor" class="meta-tag">👤 User</span>
<span id="kmlDetailsVotes" class="meta-tag">👍 0</span>
</div>
<div class="description-container">
<div class="description-header">
<h3>Description</h3>
<button id="editDescriptionBtn" class="icon-button small hidden"
title="Edit Description"></button>
</div>
<div id="kmlDescriptionDisplay" class="description-text">
No description provided.
</div>
<div id="kmlDescriptionEditor" class="description-editor hidden">
<textarea id="kmlDescriptionInput"
placeholder="Enter a description for this route..."></textarea>
<div class="editor-actions">
<button id="saveDescriptionBtn" class="primary-btn small">Save</button>
<button id="cancelDescriptionBtn" class="secondary-btn small">Cancel</button>
</div>
</div>
</div>
</div>
</div>
<div class="kml-details-footer">
<button id="backToKmlListBtn" class="secondary-btn">← Back to List</button>
<button id="startKmlTripBtn" class="primary-btn large">▶️ Start Trip</button>
</div>
</div>
</div>
<!-- General Confirmation Overlay -->
<div id="confirm-overlay" class="overlay">
<div class="setup-card">

View File

@@ -793,6 +793,7 @@ body {
border-color: #ef4444;
color: #ef4444;
}
/* Secondary Links (Privacy, etc) */
.privacy-link-container {
margin-top: 1.5rem;
@@ -811,3 +812,168 @@ body {
.secondary-link:hover {
color: var(--primary);
}
/* KML Details Overlay Styles */
.kml-details-card {
background: var(--bg-card);
border-radius: 16px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
max-width: 900px;
width: 95%;
max-height: 90vh;
display: flex;
flex-direction: column;
border: 1px solid var(--border);
}
.kml-details-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.5rem 2rem;
border-bottom: 2px solid var(--border);
}
.kml-details-header h2 {
font-size: 1.5rem;
background: linear-gradient(135deg, var(--primary), var(--secondary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin: 0;
}
.kml-details-content {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: row;
/* Side by side on desktop */
}
.kml-preview-map {
flex: 1;
min-height: 400px;
background: #000;
border-right: 2px solid var(--border);
}
.kml-metadata-section {
flex: 1;
padding: 2rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
overflow-y: auto;
min-width: 300px;
}
.metadata-row {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.meta-tag {
background: rgba(15, 23, 42, 0.6);
padding: 0.5rem 1rem;
border-radius: 8px;
font-size: 0.9rem;
border: 1px solid var(--border);
color: var(--text-primary);
}
.description-container {
flex: 1;
display: flex;
flex-direction: column;
background: rgba(15, 23, 42, 0.4);
border-radius: 12px;
border: 1px solid var(--border);
padding: 1rem;
}
.description-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
border-bottom: 1px solid var(--border);
padding-bottom: 0.5rem;
}
.description-header h3 {
font-size: 1.1rem;
margin: 0;
}
.description-text {
flex: 1;
white-space: pre-wrap;
line-height: 1.6;
color: var(--text-secondary);
font-size: 0.95rem;
overflow-y: auto;
max-height: 300px;
}
.description-editor {
flex: 1;
display: flex;
flex-direction: column;
gap: 1rem;
}
.description-editor textarea {
width: 100%;
height: 200px;
background: var(--bg-dark);
border: 1px solid var(--border);
padding: 1rem;
color: var(--text-primary);
border-radius: 8px;
resize: vertical;
font-family: inherit;
}
.editor-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
}
.kml-details-footer {
padding: 1.5rem 2rem;
border-top: 2px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
background: var(--bg-card);
}
.primary-btn.small {
padding: 0.5rem 1rem;
font-size: 0.9rem;
}
.primary-btn.large {
font-size: 1.2rem;
padding: 1rem 3rem;
width: auto;
}
.hidden {
display: none !important;
}
@media (max-width: 900px) {
.kml-details-content {
flex-direction: column;
}
.kml-preview-map {
min-height: 300px;
border-right: none;
border-bottom: 2px solid var(--border);
}
}