add rich KML support, mitigate KML vulnerabilities
All checks were successful
pedestrian-simulator / build (push) Successful in 1m0s
All checks were successful
pedestrian-simulator / build (push) Successful in 1m0s
This commit is contained in:
370
frontend/app.js
370
frontend/app.js
@@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user