oedb-backend/oedb/resources/demo/demo_main.py
2025-09-23 11:26:44 +02:00

726 lines
No EOL
38 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'
# Load environment variables from .env file for OAuth2 configuration
from oedb.utils.db import load_env_from_file
load_env_from_file()
# Get OAuth2 configuration parameters
import os
client_id = os.getenv("CLIENT_ID", "")
client_secret = os.getenv("CLIENT_SECRET", "")
client_redirect = os.getenv("CLIENT_REDIRECT", "")
# 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">
<link rel="stylesheet" href="/static/demo_styles.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
<script src="/static/demo_auth.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>
<!-- Hidden OAuth2 configuration for the JavaScript module -->
<input type="hidden" id="osmClientId" value="{client_id}">
<input type="hidden" id="osmClientSecret" value="{client_secret}">
<input type="hidden" id="osmRedirectUri" value="{client_redirect}">
<div class="map-overlay">
<h2>OpenEventDatabase Demo</h2>
<p>This map shows current events from the OpenEventDatabase.</p>
<!-- User Information Panel -->
<div id="user-info-panel" class="user-info-panel" style="display: none; background-color: #f5f5f5; border-radius: 4px; padding: 10px; margin: 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3 style="margin-top: 0; margin-bottom: 10px; color: #333;">User Information</h3>
<p>Username: <strong id="username-display">Anonymous</strong></p>
<p>Points: <span id="points-display" style="font-weight: bold; color: #0078ff;">0</span></p>
</div>
<!-- Authentication section -->
<!--
# <div id="auth-section" class="auth-section">
# <h3>OpenStreetMap Authentication</h3>
#
# <a href="https://www.openstreetmap.org/oauth2/authorize?client_id={client_id}&redirect_uri={client_redirect}&response_type=code&scope=read_prefs" class="osm-login-btn">
# <span class="osm-logo"></span>
# Login with OpenStreetMap
# </a>
# <script>
# // Replace server-side auth section with JavaScript-rendered version if available
# document.addEventListener('DOMContentLoaded', function() {
# if (window.osmAuth) {
# const clientId = document.getElementById('osmClientId').value;
# const redirectUri = document.getElementById('osmRedirectUri').value;
# const authSection = document.getElementById('auth-section');
#
# // Only replace if osmAuth is loaded and has renderAuthSection method
# if (osmAuth.renderAuthSection) {
# authSection.innerHTML = osmAuth.renderAuthSection(clientId, redirectUri);
# }
# }
# });
# </script>
# </div> -->
<h3>API Endpoints:</h3>
<ul>
<li><a href="/" >/ - API Information</a></li>
<li><a href="/event" >/event - Get Events</a></li>
<li><a href="/stats" >/stats - Database Statistics</a></li>
</ul>
<h3>Demo Pages:</h3>
<ul>
<li><a href="/demo/search" >/demo/search - Advanced Search</a></li>
<li><a href="/demo/by-what" >/demo/by-what - Events by Type</a></li>
<li><a href="/demo/map-by-what" >/demo/map-by-what - Map by Event Type</a></li>
<li><a href="/demo/traffic" >/demo/traffic - Report Traffic Jam</a></li>
<li><a href="/demo/view-events" >/demo/view-events - View Saved Events</a></li>
<li><a href="/event?what=music" >Search Music Events</a></li>
<li><a href="/event?what=sport" >Search Sport Events</a></li>
</ul>
<p><a href="/demo/traffic" 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;">+ Traffic event</a></p>
<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;">+ Any Event</a></p>
<p style="text-align: center; margin-top: 10px;">
<a href="https://source.cipherbliss.com/tykayn/oedb-backend" title="View Source Code on Cipherbliss" style="font-size: 24px;">
<i class="fas fa-code-branch"></i> sources
</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://tiles.openfreemap.org/styles/liberty',
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" >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" >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 the external API endpoint
fetch('https://api.openeventdatabase.org/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}" >${value}</a>`;
} else if (typeof value === 'string' && (key === 'start' || key === 'stop' || key.includes('date') || key.includes('time'))) {
// For date fields, show both the original date and the relative time
const relativeTime = getRelativeTimeString(value);
displayValue = `${value} <span style="color: #666; font-style: italic;">(il y a ${relativeTime})</span>`;
} 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>';
// Check if this event needs reality check (traffic events created more than 1 hour ago)
const needsRealityCheck = checkIfNeedsRealityCheck(feature);
// Add reality check buttons if needed
if (needsRealityCheck) {
popupContent += `
<div class="reality-check">
<p>Is this traffic event still present?</p>
<div class="reality-check-buttons">
<button class="confirm-btn" onclick="confirmEvent('${properties.id}', true)">Yes, still there</button>
<button class="deny-btn" onclick="confirmEvent('${properties.id}', false)">No, it's gone</button>
</div>
</div>
`;
} else if (properties['reality_check']) {
// Show reality check information if it exists
popupContent += `
<div class="reality-check-info">
<p>Reality check: ${properties['reality_check']}</p>
</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 calculate relative time (e.g., "2 hours 30 minutes ago")
function getRelativeTimeString(dateString) {
if (!dateString) return '';
// Parse the date string
const date = new Date(dateString);
if (isNaN(date.getTime())) return dateString; // Return original if invalid
// Calculate time difference in milliseconds
const now = new Date();
const diffMs = now - date;
// Convert to hours and minutes
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
// Format the relative time string
let relativeTime = '';
if (diffHours > 0) {
relativeTime += `${diffHours} heure${diffHours > 1 ? 's' : ''}`;
}
if (diffMinutes > 0 || diffHours === 0) {
if (diffHours > 0) relativeTime += ' ';
relativeTime += `${diffMinutes} minute${diffMinutes > 1 ? 's' : ''}`;
}
return relativeTime || "à l instant";
}
// Function to check if an event needs a reality check (created more than 1 hour ago)
function checkIfNeedsRealityCheck(event) {
// Skip if event already has a reality check
if (event.properties['reality_check']) {
return false;
}
// Only for traffic events
if (!event.properties.what || !event.properties.what.startsWith('traffic')) {
return false;
}
// Must have a creation date
const createDate = event.properties.createdate;
if (!createDate) {
return false;
}
const createTime = new Date(createDate).getTime();
if (isNaN(createTime)) {
return false;
}
const currentTime = new Date().getTime();
const oneHourInMs = 60 * 60 * 1000;
return (currentTime - createTime) > oneHourInMs;
}
// 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
});
}
// Function to update user information display
function updateUserInfoDisplay() {
const username = localStorage.getItem('oedb_username');
const points = localStorage.getItem('oedb_points');
const userInfoPanel = document.getElementById('user-info-panel');
// Only show the panel if the user has a username or points
if (username || points) {
userInfoPanel.style.display = 'block';
// Update username display
if (username) {
document.getElementById('username-display').textContent = username;
}
// Update points display
if (points) {
document.getElementById('points-display').textContent = points;
}
}
// Add CSS for reality check buttons if not already added
if (!document.getElementById('reality-check-styles')) {
const style = document.createElement('style');
style.id = 'reality-check-styles';
style.textContent = `
.reality-check {
margin-top: 10px;
padding: 10px;
background-color: #fff3e0;
border-radius: 4px;
}
.reality-check-buttons {
display: flex;
justify-content: space-between;
margin-top: 8px;
}
.confirm-btn, .deny-btn {
padding: 5px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
.confirm-btn {
background-color: #4caf50;
color: white;
}
.deny-btn {
background-color: #f44336;
color: white;
}
.reality-check-info {
margin-top: 10px;
padding: 8px;
background-color: #e8f5e9;
border-radius: 4px;
font-size: 0.9em;
}
`;
document.head.appendChild(style);
}
}
// Function to handle event confirmation or denial
function confirmEvent(eventId, isConfirmed) {
// Get username from localStorage or prompt for it
let username = localStorage.getItem('oedb_username');
if (!username) {
username = promptForUsername();
if (!username) {
// User cancelled the prompt
return;
}
}
// Current date and time
const now = new Date();
const dateTimeString = now.toISOString();
// Create reality check string
const realityCheckStatus = isConfirmed ? 'confirmed' : 'not confirmed';
const realityCheckValue = `${dateTimeString} | ${username} | ${realityCheckStatus}`;
// Fetch the event to update
fetch(`https://api.openeventdatabase.org/event/${eventId}`)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error(`Failed to fetch event ${eventId}`);
}
})
.then(event => {
// Add reality_check property
event.properties['reality_check'] = realityCheckValue;
// Update the event
return fetch(`https://api.openeventdatabase.org/event/${eventId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
});
})
.then(response => {
if (response.ok) {
// Save contribution to localStorage
saveContribution(eventId, isConfirmed);
// Award points
awardPoints(3);
// Show success message
alert(`Thank you for your contribution! You've earned 3 points.`);
// Update user info display
updateUserInfoDisplay();
// Refresh events to update the display
fetchEvents();
} else {
throw new Error('Failed to update event');
}
})
.catch(error => {
console.error('Error updating event:', error);
alert(`Error: ${error.message}`);
});
}
// Function to prompt for username
function promptForUsername() {
const username = prompt('Please enter your username:');
if (username) {
localStorage.setItem('oedb_username', username);
return username;
}
return null;
}
// Function to save contribution to localStorage
function saveContribution(eventId, isConfirmed) {
// Get existing contributions
let contributions = JSON.parse(localStorage.getItem('oedb_contributions') || '[]');
// Add new contribution
contributions.push({
eventId: eventId,
timestamp: new Date().toISOString(),
isConfirmed: isConfirmed
});
// Save back to localStorage
localStorage.setItem('oedb_contributions', JSON.stringify(contributions));
}
// Function to award points
function awardPoints(points) {
// Get current points
let currentPoints = parseInt(localStorage.getItem('oedb_points') || '0');
// Add new points
currentPoints += points;
// Save back to localStorage
localStorage.setItem('oedb_points', currentPoints.toString());
}
// Update user info when the page loads
document.addEventListener('DOMContentLoaded', function() {
updateUserInfoDisplay();
});
</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()