oedb-backend/oedb/resources/demo/demo_main.py
2025-09-21 13:35:01 +02:00

417 lines
No EOL
21 KiB
Python

"""
Main demo page resource for the OpenEventDatabase.
"""
import falcon
from oedb.utils.logging import logger
class DemoMainResource:
"""
Resource for the main demo page.
Handles the /demo endpoint.
"""
def on_get(self, req, resp):
"""
Handle GET requests to the /demo endpoint.
Returns an HTML page with a MapLibre map showing current events.
Args:
req: The request object.
resp: The response object.
"""
logger.info("Processing GET request to /demo")
try:
# Set content type to HTML
resp.content_type = 'text/html'
# Create HTML response with MapLibre map
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenEventDatabase Demo</title>
<script src="https://unpkg.com/maplibre-gl@3.0.0/dist/maplibre-gl.js"></script>
<link href="https://unpkg.com/maplibre-gl@3.0.0/dist/maplibre-gl.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
<style>
body { margin: 0; padding: 0; font-family: Arial, sans-serif; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.map-overlay {
position: absolute;
top: 10px;
left: 10px;
background: rgba(255, 255, 255, 0.9);
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 300px;
}
.map-style-control {
position: absolute;
top: 10px;
right: 10px;
background: rgba(255, 255, 255, 0.9);
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
z-index: 1;
}
.map-style-control button {
display: block;
margin-bottom: 5px;
padding: 5px 10px;
background: #fff;
border: 1px solid #ddd;
border-radius: 3px;
cursor: pointer;
width: 100%;
text-align: left;
}
.map-style-control button:hover {
background: #f5f5f5;
}
.map-style-control button.active {
background: #0078ff;
color: white;
border-color: #0056b3;
}
h2 { margin-top: 0; }
ul { padding-left: 20px; }
a { color: #0078ff; text-decoration: none; }
a:hover { text-decoration: underline; }
.event-popup { max-width: 300px; }
</style>
</head>
<body>
<div id="map"></div>
<div class="map-overlay">
<h2>OpenEventDatabase Demo</h2>
<p>This map shows current events from the OpenEventDatabase.</p>
<h3>API Endpoints:</h3>
<ul>
<li><a href="/" target="_blank">/ - API Information</a></li>
<li><a href="/event" target="_blank">/event - Get Events</a></li>
<li><a href="/stats" target="_blank">/stats - Database Statistics</a></li>
</ul>
<h3>Demo Pages:</h3>
<ul>
<li><a href="/demo/search" target="_blank">/demo/search - Advanced Search</a></li>
<li><a href="/demo/by-what" target="_blank">/demo/by-what - Events by Type</a></li>
<li><a href="/demo/map-by-what" target="_blank">/demo/map-by-what - Map by Event Type</a></li>
<li><a href="/demo/traffic" target="_blank">/demo/traffic - Report Traffic Jam</a></li>
<li><a href="/demo/view-events" target="_blank">/demo/view-events - View Saved Events</a></li>
<li><a href="/event?what=music" target="_blank">Search Music Events</a></li>
<li><a href="/event?what=sport" target="_blank">Search Sport Events</a></li>
</ul>
<p><a href="/demo/add" class="add-event-btn" style="display: block; text-align: center; margin-top: 15px; padding: 8px; background-color: #0078ff; color: white; border-radius: 4px; font-weight: bold;">+ Add New Event</a></p>
<p style="text-align: center; margin-top: 10px;">
<a href="https://source.cipherbliss.com/tykayn/oedb-backend" target="_blank" title="View Source Code on Cipherbliss" style="font-size: 24px;">
<i class="fas fa-code-branch"></i>
</a>
</p>
</div>
<div class="map-style-control">
<h4 style="margin-top: 0; margin-bottom: 10px;">Map Style</h4>
<button id="style-default" class="active">Default</button>
<button id="style-osm-vector">OSM Vector</button>
<button id="style-osm-raster">OSM Raster</button>
</div>
<script>
// Map style URLs
const mapStyles = {
default: 'https://demotiles.maplibre.org/style.json',
osmVector: 'https://cdn.jsdelivr.net/gh/openmaptiles/osm-bright-gl-style@master/style-cdn.json',
osmRaster: {
version: 8,
sources: {
'osm-raster': {
type: 'raster',
tiles: [
'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
],
tileSize: 256,
attribution: '© <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
}
},
layers: [
{
id: 'osm-raster-layer',
type: 'raster',
source: 'osm-raster',
minzoom: 0,
maxzoom: 19
}
]
}
};
// Initialize the map with default style
const map = new maplibregl.Map({
container: 'map',
style: mapStyles.default,
center: [2.3522, 48.8566], // Default center (Paris)
zoom: 4
});
// Add navigation controls
map.addControl(new maplibregl.NavigationControl());
// Add attribution control with OpenStreetMap attribution
map.addControl(new maplibregl.AttributionControl({
customAttribution: '© <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
}));
// Style switcher functionality
let currentStyle = 'default';
let eventsData = null;
document.getElementById('style-default').addEventListener('click', () => {
if (currentStyle !== 'default') {
switchMapStyle('default');
}
});
document.getElementById('style-osm-vector').addEventListener('click', () => {
if (currentStyle !== 'osmVector') {
switchMapStyle('osmVector');
}
});
document.getElementById('style-osm-raster').addEventListener('click', () => {
if (currentStyle !== 'osmRaster') {
switchMapStyle('osmRaster');
}
});
function switchMapStyle(styleName) {
// Update active button
document.querySelectorAll('.map-style-control button').forEach(button => {
button.classList.remove('active');
});
document.getElementById(`style-${styleName.replace('osm', 'osm-')}`).classList.add('active');
// Save current center and zoom
const center = map.getCenter();
const zoom = map.getZoom();
// Save events data if already loaded
if (map.getSource('events')) {
try {
eventsData = map.getSource('events')._data;
} catch (e) {
console.error('Error saving events data:', e);
}
}
// Apply new style
map.setStyle(mapStyles[styleName]);
// Restore center and zoom after style is loaded
map.once('style.load', () => {
map.setCenter(center);
map.setZoom(zoom);
// Restore events data if available
if (eventsData) {
addEventsToMap(eventsData);
} else {
fetchEvents();
}
});
currentStyle = styleName;
}
// Fetch events when the map is loaded
map.on('load', function() {
fetchEvents();
});
// Function to fetch events from the API
function fetchEvents() {
// Fetch events from the API - using default behavior to get currently active events
fetch('/event')
.then(response => response.json())
.then(data => {
if (data.features && data.features.length > 0) {
// Add events to the map
addEventsToMap(data);
// Fit map to events bounds
fitMapToBounds(data);
} else {
console.log('No events found');
}
})
.catch(error => {
console.error('Error fetching events:', error);
});
}
// Function to add events to the map
function addEventsToMap(geojson) {
// Add a GeoJSON source for events
map.addSource('events', {
type: 'geojson',
data: geojson
});
// Add a circle layer for events
map.addLayer({
id: 'events-circle',
type: 'circle',
source: 'events',
paint: {
'circle-radius': 8,
'circle-color': '#FF5722',
'circle-stroke-width': 2,
'circle-stroke-color': '#FFFFFF'
}
});
// Add popups for events
geojson.features.forEach(feature => {
const coordinates = feature.geometry.coordinates.slice();
const properties = feature.properties;
// Create popup content
let popupContent = '<div class="event-popup">';
popupContent += `<h3>${properties.label || 'Event'}</h3>`;
// Display all properties
popupContent += '<div style="max-height: 300px; overflow-y: auto;">';
popupContent += '<table style="width: 100%; border-collapse: collapse;">';
// Sort properties alphabetically for better organization
const sortedKeys = Object.keys(properties).sort();
for (const key of sortedKeys) {
// Skip the label as it's already displayed as the title
if (key === 'label') continue;
const value = properties[key];
let displayValue;
// Format the value based on its type
if (value === null || value === undefined) {
displayValue = '<em>null</em>';
} else if (typeof value === 'object') {
displayValue = `<pre style="margin: 0; white-space: pre-wrap;">${JSON.stringify(value, null, 2)}</pre>`;
} else if (typeof value === 'string' && value.startsWith('http')) {
displayValue = `<a href="${value}" target="_blank">${value}</a>`;
} else {
displayValue = String(value);
}
popupContent += `
<tr style="border-bottom: 1px solid #eee;">
<td style="padding: 4px; font-weight: bold; vertical-align: top;">${key}:</td>
<td style="padding: 4px;">${displayValue}</td>
</tr>`;
}
popupContent += '</table>';
popupContent += '</div>';
// Add edit link
popupContent += `<div style="margin-top: 10px; text-align: center;">
<a href="/demo/edit/${properties.id}" class="edit-event-btn" style="display: inline-block; padding: 5px 10px; background-color: #0078ff; color: white; border-radius: 4px; text-decoration: none; font-weight: bold;">Edit Event</a>
</div>`;
popupContent += '</div>';
// Create popup
const popup = new maplibregl.Popup({
closeButton: true,
closeOnClick: true
}).setHTML(popupContent);
// Get event type for icon selection
const eventType = properties.what || 'unknown';
// Define icon based on event type
let iconClass = 'info-circle'; // Default icon
let iconColor = '#0078ff'; // Default color
// Map event types to icons
if (eventType.startsWith('weather')) {
iconClass = 'cloud';
iconColor = '#00d1b2'; // Teal
} else if (eventType.startsWith('traffic')) {
iconClass = 'car';
iconColor = '#ff3860'; // Red
} else if (eventType.startsWith('sport')) {
iconClass = 'futbol';
iconColor = '#3273dc'; // Blue
} else if (eventType.startsWith('culture')) {
iconClass = 'theater-masks';
iconColor = '#ffdd57'; // Yellow
} else if (eventType.startsWith('health')) {
iconClass = 'heartbeat';
iconColor = '#ff3860'; // Red
} else if (eventType.startsWith('education')) {
iconClass = 'graduation-cap';
iconColor = '#3273dc'; // Blue
} else if (eventType.startsWith('politics')) {
iconClass = 'landmark';
iconColor = '#209cee'; // Light blue
} else if (eventType.startsWith('nature')) {
iconClass = 'leaf';
iconColor = '#23d160'; // Green
}
// Create custom HTML element for marker
const el = document.createElement('div');
el.className = 'marker';
el.innerHTML = `<span class="icon" style="background-color: white; border-radius: 50%; padding: 8px; box-shadow: 0 0 5px rgba(0,0,0,0.3);">
<i class="fas fa-${iconClass}" style="color: ${iconColor}; font-size: 16px;"></i>
</span>`;
// Add marker with popup
new maplibregl.Marker(el)
.setLngLat(coordinates)
.setPopup(popup)
.addTo(map);
});
}
// Function to fit map to events bounds
function fitMapToBounds(geojson) {
if (geojson.features.length === 0) return;
// Create a bounds object
const bounds = new maplibregl.LngLatBounds();
// Extend bounds with each feature
geojson.features.forEach(feature => {
bounds.extend(feature.geometry.coordinates);
});
// Fit map to bounds with padding
map.fitBounds(bounds, {
padding: 50,
maxZoom: 12
});
}
</script>
</body>
</html>
"""
# Set the response body and status
resp.text = html
resp.status = falcon.HTTP_200
logger.success("Successfully processed GET request to /demo")
except Exception as e:
logger.error(f"Error processing GET request to /demo: {e}")
resp.status = falcon.HTTP_500
resp.text = f"Error: {str(e)}"
# Create a global instance of DemoMainResource
demo_main = DemoMainResource()