refactoring
This commit is contained in:
151
web/js/api.js
Normal file
151
web/js/api.js
Normal file
@ -0,0 +1,151 @@
|
||||
// API communication functions
|
||||
|
||||
async function scrapeNextListing() {
|
||||
if (!AppState.currentSessionId || !AppState.isScrapingActive) {
|
||||
console.log('Scraping stopped: session or active flag cleared');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/api/scrape/${AppState.currentSessionId}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.cancelled) {
|
||||
console.log('Scraping cancelled by backend');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (data.listing) {
|
||||
AppState.allListings.push(data.listing);
|
||||
addMarker(data.listing);
|
||||
|
||||
// Update display
|
||||
const sortBy = document.getElementById('sortSelect').value;
|
||||
const sortedListings = sortListings(AppState.allListings, sortBy);
|
||||
renderResults(sortedListings);
|
||||
|
||||
// Fit map to markers
|
||||
if (AppState.markers.length > 0) {
|
||||
const group = L.featureGroup(AppState.markers);
|
||||
AppState.map.fitBounds(group.getBounds().pad(0.1));
|
||||
}
|
||||
}
|
||||
|
||||
updateProgress(data.progress.current, data.progress.total);
|
||||
|
||||
if (data.complete) {
|
||||
console.log('Scraping complete, finalizing...');
|
||||
AppState.isScrapingActive = false;
|
||||
document.getElementById('searchBtn').disabled = false;
|
||||
document.getElementById('cancelBtn').style.display = 'none';
|
||||
updateProgress(0, 0);
|
||||
showStatus(`Fertig! ${AppState.allListings.length} Inserate geladen`, 'success');
|
||||
console.log('Final listings count:', AppState.allListings.length);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Scrape error:', error);
|
||||
AppState.isScrapingActive = false;
|
||||
document.getElementById('searchBtn').disabled = false;
|
||||
document.getElementById('cancelBtn').style.display = 'none';
|
||||
showStatus('Fehler beim Laden der Inserate', 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function startScrapingLoop() {
|
||||
while (AppState.isScrapingActive && AppState.currentSessionId) {
|
||||
const shouldContinue = await scrapeNextListing();
|
||||
if (!shouldContinue) {
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
async function searchListings() {
|
||||
const searchTerm = document.getElementById('searchTerm').value.trim();
|
||||
const minPrice = parseInt(document.getElementById('minPrice').value) || 0;
|
||||
const maxPriceInput = document.getElementById('maxPrice').value;
|
||||
const maxPrice = maxPriceInput ? parseInt(maxPriceInput) : 1000000000;
|
||||
const numListings = parseInt(document.getElementById('numListings').value) || 25;
|
||||
|
||||
if (!searchTerm) {
|
||||
showStatus('Bitte Suchbegriff eingeben', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('searchBtn').disabled = true;
|
||||
clearMarkers();
|
||||
AppState.allListings = [];
|
||||
AppState.selectedListingId = null;
|
||||
document.getElementById('resultsList').innerHTML = '';
|
||||
|
||||
showStatus('Suche nach Inseraten...', 'loading');
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/api/search`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
search_term: searchTerm,
|
||||
min_price: minPrice,
|
||||
max_price: maxPrice,
|
||||
num_listings: numListings
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('API request failed');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
AppState.currentSessionId = data.session_id;
|
||||
|
||||
if (data.total === 0) {
|
||||
showStatus('Keine Inserate gefunden', 'error');
|
||||
document.getElementById('searchBtn').disabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
showStatus(`${data.total} Inserate gefunden. Lade Details...`, 'success');
|
||||
|
||||
// Show cancel button
|
||||
document.getElementById('cancelBtn').style.display = 'inline-block';
|
||||
|
||||
// Start scraping
|
||||
AppState.isScrapingActive = true;
|
||||
AppState.scrapeStartTime = Date.now();
|
||||
updateProgress(0, data.total);
|
||||
startScrapingLoop();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Search error:', error);
|
||||
showStatus('Fehler: Verbindung zum Server fehlgeschlagen', 'error');
|
||||
document.getElementById('searchBtn').disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelScraping() {
|
||||
if (!AppState.currentSessionId) return;
|
||||
|
||||
try {
|
||||
await fetch(`${API_BASE_URL}/api/scrape/${AppState.currentSessionId}/cancel`, {
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
AppState.isScrapingActive = false;
|
||||
document.getElementById('searchBtn').disabled = false;
|
||||
document.getElementById('cancelBtn').style.display = 'none';
|
||||
updateProgress(0, 0);
|
||||
showStatus(`Abgebrochen. ${AppState.allListings.length} Inserate geladen`, 'error');
|
||||
|
||||
} catch (error) {
|
||||
console.error('Cancel error:', error);
|
||||
}
|
||||
}
|
||||
24
web/js/app.js
Normal file
24
web/js/app.js
Normal file
@ -0,0 +1,24 @@
|
||||
// Main application initialization and event handlers
|
||||
|
||||
// Event listeners
|
||||
document.getElementById('searchBtn').addEventListener('click', searchListings);
|
||||
document.getElementById('cancelBtn').addEventListener('click', cancelScraping);
|
||||
|
||||
document.getElementById('searchTerm').addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') searchListings();
|
||||
});
|
||||
|
||||
document.getElementById('sortSelect').addEventListener('change', (e) => {
|
||||
if (AppState.allListings.length > 0) {
|
||||
const sortedListings = sortListings(AppState.allListings, e.target.value);
|
||||
renderResults(sortedListings);
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize on page load
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
initMap();
|
||||
initPrivacyModal();
|
||||
console.log('Kleinanzeigen Karten-Suche initialized');
|
||||
console.log('API Base URL:', API_BASE_URL);
|
||||
});
|
||||
15
web/js/config.js
Normal file
15
web/js/config.js
Normal file
@ -0,0 +1,15 @@
|
||||
// Auto-detect API base URL from current domain
|
||||
const API_BASE_URL = window.location.protocol + '//' + window.location.host;
|
||||
|
||||
//const API_BASE_URL = 'http://localhost:5000'; //used for development
|
||||
|
||||
// Application state
|
||||
const AppState = {
|
||||
map: null,
|
||||
markers: [],
|
||||
allListings: [],
|
||||
selectedListingId: null,
|
||||
currentSessionId: null,
|
||||
scrapeStartTime: null,
|
||||
isScrapingActive: false
|
||||
};
|
||||
70
web/js/map.js
Normal file
70
web/js/map.js
Normal file
@ -0,0 +1,70 @@
|
||||
// Map initialization and marker management
|
||||
|
||||
function initMap() {
|
||||
AppState.map = L.map('map').setView([51.1657, 10.4515], 6);
|
||||
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
maxZoom: 19,
|
||||
}).addTo(AppState.map);
|
||||
|
||||
// Try to get user's location
|
||||
if (navigator.geolocation) {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
const lat = position.coords.latitude;
|
||||
const lon = position.coords.longitude;
|
||||
|
||||
// Add user location marker
|
||||
const userIcon = L.divIcon({
|
||||
html: '<div style="width: 16px; height: 16px; background: #0ea5e9; border: 3px solid white; border-radius: 50%; box-shadow: 0 0 10px rgba(14, 165, 233, 0.6);"></div>',
|
||||
className: '',
|
||||
iconSize: [16, 16],
|
||||
iconAnchor: [8, 8]
|
||||
});
|
||||
|
||||
L.marker([lat, lon], { icon: userIcon })
|
||||
.addTo(AppState.map)
|
||||
.bindPopup('<div style="background: #1a1a1a; color: #e0e0e0; padding: 8px;"><strong>Dein Standort</strong></div>');
|
||||
|
||||
console.log('User location:', lat, lon);
|
||||
},
|
||||
(error) => {
|
||||
console.log('Geolocation error:', error.message);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function clearMarkers() {
|
||||
AppState.markers.forEach(marker => AppState.map.removeLayer(marker));
|
||||
AppState.markers = [];
|
||||
}
|
||||
|
||||
function addMarker(listing) {
|
||||
if (!listing.lat || !listing.lon) return;
|
||||
|
||||
const marker = L.marker([listing.lat, listing.lon]).addTo(AppState.map);
|
||||
|
||||
const imageHtml = listing.image
|
||||
? `<img src="${listing.image}" style="width: 100%; max-height: 150px; object-fit: cover; margin: 8px 0;" alt="${listing.title}">`
|
||||
: '';
|
||||
|
||||
const popupContent = `
|
||||
<div style="min-width: 200px; 8px;">
|
||||
<strong style="font-size: 14px;">${listing.title}</strong><br>
|
||||
${imageHtml}
|
||||
<span style="color: #0066cc; font-weight: bold; font-size: 16px;">${listing.price} €</span><br>
|
||||
<span style="color: #666; font-size: 12px;">${listing.address}</span><br>
|
||||
<a href="${listing.url}" target="_blank" style="color: #0066cc; text-decoration: none; font-weight: 600;">Link öffnen →</a>
|
||||
</div>
|
||||
`;
|
||||
marker.bindPopup(popupContent);
|
||||
|
||||
marker.on('click', () => {
|
||||
AppState.selectedListingId = listing.id;
|
||||
highlightSelectedListing();
|
||||
});
|
||||
|
||||
AppState.markers.push(marker);
|
||||
}
|
||||
168
web/js/ui.js
Normal file
168
web/js/ui.js
Normal file
@ -0,0 +1,168 @@
|
||||
// UI management functions
|
||||
|
||||
function showStatus(message, type = 'loading') {
|
||||
const statusBar = document.getElementById('statusBar');
|
||||
statusBar.className = `status-bar visible ${type}`;
|
||||
|
||||
if (type === 'loading') {
|
||||
statusBar.innerHTML = `<span class="loading-spinner"></span>${message}`;
|
||||
} else {
|
||||
statusBar.textContent = message;
|
||||
}
|
||||
|
||||
if (type !== 'loading') {
|
||||
setTimeout(() => {
|
||||
statusBar.classList.remove('visible');
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
function updateProgress(current, total) {
|
||||
const progressInfo = document.getElementById('progressInfo');
|
||||
const progressFill = progressInfo.querySelector('.progress-fill');
|
||||
const progressText = progressInfo.querySelector('.progress-text');
|
||||
const etaText = progressInfo.querySelector('.eta-text');
|
||||
|
||||
if (total === 0) {
|
||||
progressInfo.classList.remove('active');
|
||||
return;
|
||||
}
|
||||
|
||||
progressInfo.classList.add('active');
|
||||
const percentage = (current / total) * 100;
|
||||
progressFill.style.width = percentage + '%';
|
||||
progressText.textContent = `Inserate werden geladen: ${current}/${total}`;
|
||||
|
||||
// Calculate ETA
|
||||
if (AppState.scrapeStartTime && current > 0) {
|
||||
const elapsed = (Date.now() - AppState.scrapeStartTime) / 1000;
|
||||
const avgTimePerListing = elapsed / current;
|
||||
const remaining = total - current;
|
||||
const etaSeconds = Math.round(avgTimePerListing * remaining);
|
||||
|
||||
const minutes = Math.floor(etaSeconds / 60);
|
||||
const seconds = etaSeconds % 60;
|
||||
|
||||
if (minutes > 0) {
|
||||
etaText.textContent = `Noch ca. ${minutes}m ${seconds}s`;
|
||||
} else {
|
||||
etaText.textContent = `Noch ca. ${seconds}s`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function highlightSelectedListing() {
|
||||
document.querySelectorAll('.result-item').forEach(item => {
|
||||
const itemId = parseInt(item.dataset.id);
|
||||
if (itemId === AppState.selectedListingId) {
|
||||
item.classList.add('selected');
|
||||
item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
} else {
|
||||
item.classList.remove('selected');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function formatDate(dateString) {
|
||||
if (!dateString) return 'Unbekanntes Datum';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('de-DE');
|
||||
}
|
||||
|
||||
function renderResults(listings) {
|
||||
const resultsList = document.getElementById('resultsList');
|
||||
const resultsCount = document.querySelector('.results-count');
|
||||
|
||||
if (listings.length === 0) {
|
||||
resultsList.innerHTML = '<div class="no-results">Keine Inserate gefunden</div>';
|
||||
resultsCount.textContent = 'Keine Ergebnisse';
|
||||
return;
|
||||
}
|
||||
|
||||
resultsCount.textContent = `${listings.length} Inserat${listings.length !== 1 ? 'e' : ''}`;
|
||||
|
||||
resultsList.innerHTML = listings.map(listing => `
|
||||
<div class="result-item" data-id="${listing.id}">
|
||||
${listing.image ? `<img src="${listing.image}" class="result-image" alt="${listing.title}">` : '<div class="result-image"></div>'}
|
||||
<div class="result-content">
|
||||
<div class="result-title">${listing.title}</div>
|
||||
<div class="result-price">${listing.price} €</div>
|
||||
<div class="result-meta">
|
||||
<div class="result-location">
|
||||
<span>📍</span>
|
||||
<span>${listing.address || listing.zip_code}</span>
|
||||
</div>
|
||||
<div class="result-date">${formatDate(listing.date_added)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
// Add click handlers
|
||||
document.querySelectorAll('.result-item').forEach(item => {
|
||||
item.addEventListener('click', () => {
|
||||
const id = parseInt(item.dataset.id);
|
||||
const listing = listings.find(l => l.id === id);
|
||||
if (listing) {
|
||||
AppState.selectedListingId = id;
|
||||
highlightSelectedListing();
|
||||
|
||||
if (listing.lat && listing.lon) {
|
||||
AppState.map.setView([listing.lat, listing.lon], 13);
|
||||
const marker = AppState.markers.find(m =>
|
||||
m.getLatLng().lat === listing.lat &&
|
||||
m.getLatLng().lng === listing.lon
|
||||
);
|
||||
if (marker) {
|
||||
marker.openPopup();
|
||||
}
|
||||
}
|
||||
|
||||
window.open(listing.url, '_blank');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function sortListings(listings, sortBy) {
|
||||
const sorted = [...listings];
|
||||
|
||||
switch (sortBy) {
|
||||
case 'price-asc':
|
||||
sorted.sort((a, b) => a.price - b.price);
|
||||
break;
|
||||
case 'price-desc':
|
||||
sorted.sort((a, b) => b.price - a.price);
|
||||
break;
|
||||
case 'date-asc':
|
||||
sorted.sort((a, b) => new Date(a.date_added || 0) - new Date(b.date_added || 0));
|
||||
break;
|
||||
case 'date-desc':
|
||||
sorted.sort((a, b) => new Date(b.date_added || 0) - new Date(a.date_added || 0));
|
||||
break;
|
||||
}
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
// Privacy modal
|
||||
function initPrivacyModal() {
|
||||
const modal = document.getElementById('privacyModal');
|
||||
const link = document.getElementById('privacyLink');
|
||||
const close = document.querySelector('.modal-close');
|
||||
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
modal.classList.add('show');
|
||||
});
|
||||
|
||||
close.addEventListener('click', () => {
|
||||
modal.classList.remove('show');
|
||||
});
|
||||
|
||||
window.addEventListener('click', (e) => {
|
||||
if (e.target === modal) {
|
||||
modal.classList.remove('show');
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user