diff --git a/README.md b/README.md index 6106eab..063db91 100644 --- a/README.md +++ b/README.md @@ -28,10 +28,17 @@ docker-compose logs -f ``` That's it! The system will automatically: +- **Frontend**: Web interface and admin dashboard (http://localhost:3000) - **Backend API**: Runs continuously for tracking and analytics (http://localhost:5001) - **6:00 AM Berlin time**: Crawl news articles and generate summaries - **7:00 AM Berlin time**: Send newsletter to all subscribers +### Access Points + +- **Newsletter Page**: http://localhost:3000 +- **Admin Dashboard**: http://localhost:3000/admin.html +- **Backend API**: http://localhost:5001 + πŸ“– **New to the project?** See [QUICKSTART.md](QUICKSTART.md) for a detailed 5-minute setup guide. πŸš€ **GPU Acceleration:** Enable 5-10x faster AI processing with [GPU Setup Guide](docs/GPU_SETUP.md) diff --git a/backend/routes/subscription_routes.py b/backend/routes/subscription_routes.py index 344bd85..c68714d 100644 --- a/backend/routes/subscription_routes.py +++ b/backend/routes/subscription_routes.py @@ -61,3 +61,52 @@ def unsubscribe(): return jsonify({'error': 'Email not found in subscribers'}), 404 except Exception as e: return jsonify({'error': str(e)}), 500 + + +@subscription_bp.route('/api/subscribers', methods=['GET']) +def list_subscribers(): + """List all subscribers with optional status filter""" + try: + # Get status filter from query params (default: all) + status = request.args.get('status', None) + + # Build query + query = {} + if status: + query['status'] = status + + # Fetch subscribers + subscribers = list(subscribers_collection.find( + query, + {'_id': 0, 'email': 1, 'subscribed_at': 1, 'status': 1} + ).sort('subscribed_at', -1)) + + # Convert datetime to ISO format + for sub in subscribers: + if 'subscribed_at' in sub: + sub['subscribed_at'] = sub['subscribed_at'].isoformat() + + return jsonify({ + 'subscribers': subscribers, + 'total': len(subscribers) + }), 200 + + except Exception as e: + return jsonify({'error': str(e)}), 500 + + +@subscription_bp.route('/api/subscribers/', methods=['DELETE']) +def remove_subscriber(email): + """Permanently remove a subscriber from the database""" + try: + email = email.strip().lower() + + result = subscribers_collection.delete_one({'email': email}) + + if result.deleted_count > 0: + return jsonify({'message': f'Subscriber {email} permanently removed'}), 200 + else: + return jsonify({'error': 'Email not found in subscribers'}), 404 + + except Exception as e: + return jsonify({'error': str(e)}), 500 diff --git a/docker-compose.yml b/docker-compose.yml index f5b095f..f75b0c5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -154,6 +154,26 @@ services: timeout: 10s retries: 3 + # Frontend Web Interface + frontend: + build: ./frontend + container_name: munich-news-frontend + restart: unless-stopped + ports: + - "3000:3000" + environment: + - API_URL=http://backend:5001 + - PORT=3000 + depends_on: + - backend + networks: + - munich-news-network + healthcheck: + test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3000"] + interval: 30s + timeout: 10s + retries: 3 + volumes: mongodb_data: driver: local diff --git a/docs/ADMIN_DASHBOARD.md b/docs/ADMIN_DASHBOARD.md new file mode 100644 index 0000000..271c507 --- /dev/null +++ b/docs/ADMIN_DASHBOARD.md @@ -0,0 +1,289 @@ +# Admin Dashboard + +## Overview + +The Admin Dashboard provides a web interface to monitor and manage the Munich News system, including AI status, GPU usage, performance metrics, and clustering statistics. + +## Features + +### πŸ“Š System Statistics +- Total articles count +- Crawled articles +- AI summarized articles +- Clustered articles +- Neutral summaries generated +- Active subscribers + +### πŸ€– AI Status (Ollama) +- Connection status +- Current model +- Base URL +- Enabled/disabled state +- Live response test + +### ⚑ GPU Status +- GPU availability detection +- GPU usage status (CPU vs GPU mode) +- Models loaded count +- GPU details (layers, model info) +- Performance recommendations + +### πŸš€ Performance Test +- Real-time performance testing +- Response time measurement +- Performance rating (Excellent/Good/Fair/Slow) +- Recommendations for optimization + +### πŸ“¦ Available Models +- List of downloaded models +- Current model indicator +- Model management info + +### βš™οΈ Configuration +- Ollama configuration details +- Environment file status +- API key status +- Base URL and model settings + +### πŸ”— AI Clustering & Aggregation +- Clustering statistics +- Multi-source story detection +- Neutral summary generation metrics +- Clustering rate percentage + +## Access + +### Using Docker Compose (Recommended) + +The frontend is automatically started with docker-compose: + +```bash +# Start all services including frontend +docker-compose up -d + +# Check frontend status +docker-compose ps frontend + +# View frontend logs +docker-compose logs -f frontend +``` + +The frontend will be available at: **http://localhost:3000** + +### Access Admin Dashboard + +Open your browser and navigate to: +``` +http://localhost:3000/admin.html +``` + +### Manual Start (Development) + +If you want to run the frontend outside Docker: + +```bash +# Navigate to frontend directory +cd frontend + +# Install dependencies (first time only) +npm install + +# Start the server +npm start + +# Or with nodemon for auto-reload +npm run dev +``` + +## Screenshots + +### Dashboard Overview +The dashboard displays: +- Real-time system statistics +- AI/Ollama status with live connection test +- GPU detection and usage +- Performance metrics +- Model management +- Configuration details + +### Performance Test +Click "Run Test" to: +- Test AI response time +- Get performance rating +- Receive optimization recommendations + +### GPU Status +Shows: +- βœ… GPU Active - Using GPU acceleration (fast) +- ⚠️ CPU Mode - Using CPU only (slower) +- Recommendations for enabling GPU + +## API Endpoints Used + +The dashboard connects to these backend APIs: + +- `GET /api/stats` - System statistics +- `GET /api/ollama/ping` - Ollama connection test +- `GET /api/ollama/gpu-status` - GPU detection +- `GET /api/ollama/test` - Performance test +- `GET /api/ollama/models` - List models +- `GET /api/ollama/config` - Configuration + +## Refresh Data + +Click the **πŸ”„ Refresh All** button to reload all dashboard data. + +## Navigation + +- **← Back to Home** - Return to main newsletter page +- **Admin Dashboard** link in footer of main page + +## Troubleshooting + +### Frontend Won't Start + +```bash +# Check if port 3000 is in use +lsof -i :3000 + +# Install dependencies +cd frontend +npm install + +# Start server +npm start +``` + +### Can't Connect to Backend + +1. **Check backend is running:** + ```bash + docker-compose ps backend + ``` + +2. **Check backend URL in frontend/server.js:** + ```javascript + const API_URL = process.env.API_URL || 'http://localhost:5001'; + ``` + +3. **Test backend directly:** + ```bash + curl http://localhost:5001/api/stats + ``` + +### Dashboard Shows Errors + +1. **Check browser console** (F12) for errors +2. **Verify backend APIs are accessible** +3. **Check CORS settings** if running on different domains + +## Development + +### File Structure + +``` +frontend/ +β”œβ”€β”€ public/ +β”‚ β”œβ”€β”€ index.html # Main newsletter page +β”‚ β”œβ”€β”€ admin.html # Admin dashboard ⭐ +β”‚ β”œβ”€β”€ admin.js # Dashboard JavaScript ⭐ +β”‚ β”œβ”€β”€ app.js # Main page JavaScript +β”‚ └── styles.css # Shared styles +β”œβ”€β”€ server.js # Express server +└── package.json # Dependencies +``` + +### Adding New Features + +1. **Add API endpoint** in `backend/routes/` +2. **Add function** in `frontend/public/admin.js` +3. **Add UI section** in `frontend/public/admin.html` +4. **Call function** in `refreshAll()` or on button click + +### Styling + +The dashboard uses inline styles for simplicity. Key classes: +- `.card` - Dashboard cards +- `.stat-row` - Statistic rows +- `.status-indicator` - Status dots (green/red/yellow) +- `.performance-badge` - Performance ratings +- `.btn` - Buttons + +## Production Deployment + +### Option 1: Serve with Backend + +Add frontend to docker-compose: + +```yaml +frontend: + build: ./frontend + ports: + - "3000:3000" + environment: + - API_URL=http://backend:5001 + depends_on: + - backend +``` + +### Option 2: Static Hosting + +Build and serve static files: + +```bash +# Serve with nginx, Apache, or CDN +cp -r frontend/public/* /var/www/html/ +``` + +Update API URLs to point to production backend. + +### Option 3: Reverse Proxy + +Use nginx to serve both: + +```nginx +location / { + proxy_pass http://frontend:3000; +} + +location /api/ { + proxy_pass http://backend:5001; +} +``` + +## Security + +### Production Recommendations + +1. **Add authentication** - Protect admin dashboard +2. **Use HTTPS** - Encrypt traffic +3. **Rate limiting** - Prevent abuse +4. **CORS configuration** - Restrict origins +5. **API keys** - Secure backend access + +### Basic Auth Example + +```javascript +// In server.js +const basicAuth = require('express-basic-auth'); + +app.use('/admin.html', basicAuth({ + users: { 'admin': 'your-secure-password' }, + challenge: true +})); +``` + +## Related Documentation + +- [API.md](API.md) - Backend API reference +- [CHECK_GPU_STATUS.md](CHECK_GPU_STATUS.md) - GPU status checking +- [CHANGING_AI_MODEL.md](CHANGING_AI_MODEL.md) - Model management +- [AI_NEWS_AGGREGATION.md](AI_NEWS_AGGREGATION.md) - AI features + +## Support + +For issues or questions: +1. Check browser console for errors +2. Check backend logs: `docker-compose logs backend` +3. Verify API endpoints with curl +4. Check [TROUBLESHOOTING.md](../TROUBLESHOOTING.md) diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..1493199 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,7 @@ +node_modules +npm-debug.log +.git +.gitignore +README.md +.env +.DS_Store diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..4e4eddd --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,23 @@ +# Frontend Dockerfile +FROM node:18-alpine + +WORKDIR /app + +# Copy package files +COPY package*.json ./ + +# Install dependencies +RUN npm ci --only=production + +# Copy application files +COPY . . + +# Expose port +EXPOSE 3000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ + CMD node -e "require('http').get('http://localhost:3000', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" + +# Start server +CMD ["node", "server.js"] diff --git a/frontend/public/admin.js b/frontend/public/admin.js new file mode 100644 index 0000000..2dd88ce --- /dev/null +++ b/frontend/public/admin.js @@ -0,0 +1,315 @@ +// Admin Dashboard JavaScript +// Use relative URL to go through frontend proxy +const API_BASE = window.location.origin; + +// Load all data on page load +document.addEventListener('DOMContentLoaded', () => { + loadSystemStats(); + loadOllamaStatus(); + loadGPUStatus(); + loadPerformanceTest(); + loadModels(); + loadConfig(); + loadClusteringStats(); +}); + +// Refresh all data +function refreshAll() { + loadSystemStats(); + loadOllamaStatus(); + loadGPUStatus(); + loadPerformanceTest(); + loadModels(); + loadConfig(); + loadClusteringStats(); +} + +// Load system statistics +async function loadSystemStats() { + try { + const response = await fetch(`${API_BASE}/api/stats`); + const data = await response.json(); + + const html = ` +
+ Total Articles + ${data.articles || 0} +
+
+ Crawled Articles + ${data.crawled_articles || 0} +
+
+ AI Summarized + ${data.summarized_articles || 0} +
+
+ Clustered Articles + ${data.clustered_articles || 0} +
+
+ Neutral Summaries + ${data.neutral_summaries || 0} +
+
+ Active Subscribers + ${data.subscribers || 0} +
+ `; + + document.getElementById('systemStats').innerHTML = html; + } catch (error) { + document.getElementById('systemStats').innerHTML = `
Error loading stats: ${error.message}
`; + } +} + +// Load Ollama status +async function loadOllamaStatus() { + try { + const response = await fetch(`${API_BASE}/api/ollama/ping`); + const data = await response.json(); + + const isActive = data.status === 'success'; + const statusClass = isActive ? 'status-active' : 'status-inactive'; + + const html = ` +
+ Status + + + ${isActive ? 'Active' : 'Inactive'} + +
+
+ Base URL + ${data.ollama_config?.base_url || 'N/A'} +
+
+ Current Model + ${data.ollama_config?.model || 'N/A'} +
+
+ Enabled + ${data.ollama_config?.enabled ? 'Yes' : 'No'} +
+ ${isActive ? ` +
+ Response + ${data.response?.substring(0, 50)}... +
+ ` : ''} + `; + + document.getElementById('ollamaStatus').innerHTML = html; + } catch (error) { + document.getElementById('ollamaStatus').innerHTML = `
Error: ${error.message}
`; + } +} + +// Load GPU status +async function loadGPUStatus() { + try { + const response = await fetch(`${API_BASE}/api/ollama/gpu-status`); + const data = await response.json(); + + const gpuActive = data.gpu_in_use; + const statusClass = gpuActive ? 'status-active' : 'status-warning'; + + const html = ` +
+ GPU Available + + + ${data.gpu_available ? 'Yes' : 'No'} + +
+
+ GPU In Use + + + ${gpuActive ? 'Yes' : 'No (CPU Mode)'} + +
+
+ Models Loaded + ${data.models_loaded || 0} +
+ ${data.gpu_details ? ` +
+ GPU Model + ${data.gpu_details.model} +
+
+ GPU Layers + ${data.gpu_details.gpu_layers} +
+ ` : ''} + ${!gpuActive ? ` +
+ πŸ’‘ Enable GPU for 5-10x faster processing +
+ ` : ''} + `; + + document.getElementById('gpuStatus').innerHTML = html; + } catch (error) { + document.getElementById('gpuStatus').innerHTML = `
Error: ${error.message}
`; + } +} + +// Load performance test +async function loadPerformanceTest() { + document.getElementById('performanceTest').innerHTML = '
Click "Run Test" to check performance
'; +} + +// Run performance test +async function runPerformanceTest() { + document.getElementById('performanceTest').innerHTML = '
Running test...
'; + + try { + const response = await fetch(`${API_BASE}/api/ollama/test`); + const data = await response.json(); + + let badgeClass = 'badge-fair'; + if (data.duration_seconds < 5) badgeClass = 'badge-excellent'; + else if (data.duration_seconds < 15) badgeClass = 'badge-good'; + else if (data.duration_seconds > 30) badgeClass = 'badge-slow'; + + const html = ` +
+ Duration + ${data.duration_seconds}s +
+
+ Performance + + ${data.performance} + +
+
+ Model + ${data.model} +
+
+ ${data.recommendation} +
+ `; + + document.getElementById('performanceTest').innerHTML = html; + } catch (error) { + document.getElementById('performanceTest').innerHTML = `
Error: ${error.message}
`; + } +} + +// Load available models +async function loadModels() { + try { + const response = await fetch(`${API_BASE}/api/ollama/models`); + const data = await response.json(); + + if (data.models && data.models.length > 0) { + const modelsList = data.models.map(model => { + const isCurrent = model === data.current_model; + return `
  • ${model} ${isCurrent ? '(current)' : ''}
  • `; + }).join(''); + + const html = ` + +
    + Current: ${data.current_model} +
    + `; + + document.getElementById('modelsList').innerHTML = html; + } else { + document.getElementById('modelsList').innerHTML = '
    No models found
    '; + } + } catch (error) { + document.getElementById('modelsList').innerHTML = `
    Error: ${error.message}
    `; + } +} + +// Load configuration +async function loadConfig() { + try { + const response = await fetch(`${API_BASE}/api/ollama/config`); + const data = await response.json(); + + const html = ` +
    + Base URL + ${data.ollama_config?.base_url || 'N/A'} +
    +
    + Model + ${data.ollama_config?.model || 'N/A'} +
    +
    + Enabled + ${data.ollama_config?.enabled ? 'Yes' : 'No'} +
    +
    + Has API Key + ${data.ollama_config?.has_api_key ? 'Yes' : 'No'} +
    +
    + Config file: ${data.env_file_path || 'N/A'}
    + Exists: ${data.env_file_exists ? 'Yes' : 'No'} +
    + `; + + document.getElementById('configInfo').innerHTML = html; + } catch (error) { + document.getElementById('configInfo').innerHTML = `
    Error: ${error.message}
    `; + } +} + +// Load clustering statistics +async function loadClusteringStats() { + try { + const response = await fetch(`${API_BASE}/api/stats`); + const data = await response.json(); + + const clusteringRate = data.clustered_articles > 0 + ? ((data.neutral_summaries / data.clustered_articles) * 100).toFixed(1) + : 0; + + const html = ` +
    +
    +
    + Total Articles + ${data.articles || 0} +
    +
    + Clustered Articles + ${data.clustered_articles || 0} +
    +
    + Neutral Summaries + ${data.neutral_summaries || 0} +
    +
    +
    +
    + Clustering Rate + ${clusteringRate}% +
    +
    + Multi-Source Stories + ${data.neutral_summaries || 0} +
    +
    + AI Clustering: Automatically detects duplicate stories from different sources and generates neutral summaries. +
    +
    +
    + `; + + document.getElementById('clusteringStats').innerHTML = html; + } catch (error) { + document.getElementById('clusteringStats').innerHTML = `
    Error: ${error.message}
    `; + } +} diff --git a/frontend/public/app.js b/frontend/public/app.js index a56c127..ee57df2 100644 --- a/frontend/public/app.js +++ b/frontend/public/app.js @@ -1,46 +1,268 @@ +// Pagination state +let allArticles = []; +let filteredArticles = []; +let displayedCount = 0; +const ARTICLES_PER_PAGE = 5; +let isLoading = false; +let searchQuery = ''; + // Load news on page load document.addEventListener('DOMContentLoaded', () => { loadNews(); loadStats(); + setupInfiniteScroll(); }); async function loadNews() { const newsGrid = document.getElementById('newsGrid'); - newsGrid.innerHTML = '
    Loading news...
    '; + newsGrid.innerHTML = '
    Loading news...
    '; try { const response = await fetch('/api/news'); const data = await response.json(); if (data.articles && data.articles.length > 0) { - displayNews(data.articles); + allArticles = data.articles; + filteredArticles = data.articles; + displayedCount = 0; + newsGrid.innerHTML = ''; + updateSearchStats(); + loadMoreArticles(); } else { - newsGrid.innerHTML = '
    No news available at the moment. Check back later!
    '; + newsGrid.innerHTML = '
    No news available at the moment. Check back later!
    '; } } catch (error) { console.error('Error loading news:', error); - newsGrid.innerHTML = '
    Failed to load news. Please try again later.
    '; + newsGrid.innerHTML = '
    Failed to load news. Please try again later.
    '; } } -function displayNews(articles) { +function loadMoreArticles() { + if (isLoading || displayedCount >= filteredArticles.length) return; + + isLoading = true; + const newsGrid = document.getElementById('newsGrid'); + + // Remove loading indicator if exists + const loadingIndicator = document.getElementById('loadingIndicator'); + if (loadingIndicator) loadingIndicator.remove(); + + // Get next batch of articles + const nextBatch = filteredArticles.slice(displayedCount, displayedCount + ARTICLES_PER_PAGE); + + nextBatch.forEach((article, index) => { + const card = createNewsCard(article, displayedCount + index); + newsGrid.appendChild(card); + }); + + displayedCount += nextBatch.length; + + // Add loading indicator if more articles available + if (displayedCount < filteredArticles.length) { + const loader = document.createElement('div'); + loader.id = 'loadingIndicator'; + loader.className = 'text-center py-8 text-gray-400'; + loader.innerHTML = '

    Loading more...

    '; + newsGrid.appendChild(loader); + } else if (filteredArticles.length > 0) { + // Add end message + const endMessage = document.createElement('div'); + endMessage.className = 'text-center py-8 text-gray-400 text-sm'; + endMessage.textContent = `βœ“ All ${filteredArticles.length} articles loaded`; + newsGrid.appendChild(endMessage); + } + + isLoading = false; +} + +function setupInfiniteScroll() { + window.addEventListener('scroll', () => { + if (isLoading || displayedCount >= filteredArticles.length) return; + + const scrollPosition = window.innerHeight + window.scrollY; + const threshold = document.documentElement.scrollHeight - 500; + + if (scrollPosition >= threshold) { + loadMoreArticles(); + } + }); +} + +// Search functionality +function handleSearch() { + const searchInput = document.getElementById('searchInput'); + const clearBtn = document.getElementById('clearSearch'); + searchQuery = searchInput.value.trim().toLowerCase(); + + // Show/hide clear button + if (searchQuery) { + clearBtn.classList.remove('hidden'); + } else { + clearBtn.classList.add('hidden'); + } + + // Filter articles + if (searchQuery === '') { + filteredArticles = allArticles; + } else { + filteredArticles = allArticles.filter(article => { + const title = article.title.toLowerCase(); + const summary = (article.summary || '').toLowerCase().replace(/<[^>]*>/g, ''); + const source = formatSourceName(article.source).toLowerCase(); + + return title.includes(searchQuery) || + summary.includes(searchQuery) || + source.includes(searchQuery); + }); + } + + // Reset display + displayedCount = 0; const newsGrid = document.getElementById('newsGrid'); newsGrid.innerHTML = ''; - articles.forEach(article => { - const card = document.createElement('div'); - card.className = 'news-card'; - card.onclick = () => window.open(article.link, '_blank'); - - card.innerHTML = ` -
    ${article.source || 'Munich News'}
    -

    ${article.title}

    -

    ${article.summary || 'No summary available.'}

    - Read more β†’ + // Update stats + updateSearchStats(); + + // Load filtered articles + if (filteredArticles.length > 0) { + loadMoreArticles(); + } else { + newsGrid.innerHTML = ` +
    +
    πŸ”
    +

    No articles found

    +

    Try a different search term

    +
    `; - - newsGrid.appendChild(card); - }); + } +} + +function clearSearch() { + const searchInput = document.getElementById('searchInput'); + searchInput.value = ''; + handleSearch(); + searchInput.focus(); +} + +function updateSearchStats() { + const searchStats = document.getElementById('searchStats'); + if (searchQuery) { + searchStats.textContent = `Found ${filteredArticles.length} of ${allArticles.length} articles`; + } else { + searchStats.textContent = `Showing ${allArticles.length} articles`; + } +} + +function createNewsCard(article, index) { + const card = document.createElement('div'); + card.className = 'group bg-white rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 cursor-pointer border border-gray-100 hover:border-primary/30'; + card.onclick = () => window.open(article.link, '_blank'); + + // Extract image from summary if it's an img tag (from SΓΌddeutsche) + let imageUrl = null; + let cleanSummary = article.summary || 'No summary available.'; + + if (cleanSummary.includes(']*>/g, '').replace(/<\/?p>/g, '').trim(); + } + + // Get source icon/emoji + const sourceIcon = getSourceIcon(article.source); + + // Format source name + const sourceName = formatSourceName(article.source); + + // Get word count badge + const wordCount = article.word_count || article.summary_word_count; + const readTime = wordCount ? Math.ceil(wordCount / 200) : null; + + card.innerHTML = ` +
    + +
    + ${imageUrl ? `${article.title}` : sourceIcon} +
    + + +
    + +
    + + ${sourceName} + ${readTime ? `πŸ“– ${readTime} min read` : ''} +
    + + +

    ${article.title}

    + + +

    ${cleanSummary}

    + + + +
    +
    + `; + + // Add staggered animation + card.style.opacity = '0'; + card.style.animation = `fadeIn 0.5s ease-out ${(index % ARTICLES_PER_PAGE) * 0.1}s forwards`; + + return card; +} + +// Add animation keyframes +if (!document.getElementById('animations')) { + const style = document.createElement('style'); + style.id = 'animations'; + style.textContent = ` + @keyframes fadeIn { + from { opacity: 0; transform: translateY(20px); } + to { opacity: 1; transform: translateY(0); } + } + .line-clamp-2 { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + } + .line-clamp-3 { + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; + } + `; + document.head.appendChild(style); +} + +function getSourceIcon(source) { + const icons = { + 'abendzeitung-muenchen': 'πŸ“°', + 'sueddeutsche': 'πŸ“„', + 'muenchen': 'πŸ›οΈ', + 'default': 'πŸ“°' + }; + return icons[source] || icons.default; +} + +function formatSourceName(source) { + const names = { + 'abendzeitung-muenchen': 'Abendzeitung MΓΌnchen', + 'sueddeutsche': 'SΓΌddeutsche Zeitung', + 'muenchen': 'MΓΌnchen.de' + }; + return names[source] || source.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase()); } async function loadStats() { @@ -65,12 +287,13 @@ async function subscribe() { if (!email || !email.includes('@')) { formMessage.textContent = 'Please enter a valid email address'; - formMessage.className = 'form-message error'; + formMessage.className = 'text-red-200 font-medium'; return; } subscribeBtn.disabled = true; subscribeBtn.textContent = 'Subscribing...'; + subscribeBtn.classList.add('opacity-75', 'cursor-not-allowed'); formMessage.textContent = ''; try { @@ -86,19 +309,20 @@ async function subscribe() { if (response.ok) { formMessage.textContent = data.message || 'Successfully subscribed! Check your email for confirmation.'; - formMessage.className = 'form-message success'; + formMessage.className = 'text-green-200 font-medium'; emailInput.value = ''; loadStats(); // Refresh stats } else { formMessage.textContent = data.error || 'Failed to subscribe. Please try again.'; - formMessage.className = 'form-message error'; + formMessage.className = 'text-red-200 font-medium'; } } catch (error) { formMessage.textContent = 'Network error. Please try again later.'; - formMessage.className = 'form-message error'; + formMessage.className = 'text-red-200 font-medium'; } finally { subscribeBtn.disabled = false; subscribeBtn.textContent = 'Subscribe Free'; + subscribeBtn.classList.remove('opacity-75', 'cursor-not-allowed'); } } @@ -110,13 +334,14 @@ document.getElementById('emailInput').addEventListener('keypress', (e) => { }); function showUnsubscribe() { - document.getElementById('unsubscribeModal').style.display = 'block'; + document.getElementById('unsubscribeModal').classList.remove('hidden'); } function closeUnsubscribe() { - document.getElementById('unsubscribeModal').style.display = 'none'; + document.getElementById('unsubscribeModal').classList.add('hidden'); document.getElementById('unsubscribeEmail').value = ''; document.getElementById('unsubscribeMessage').textContent = ''; + document.getElementById('unsubscribeMessage').className = ''; } async function unsubscribe() { @@ -127,7 +352,7 @@ async function unsubscribe() { if (!email || !email.includes('@')) { unsubscribeMessage.textContent = 'Please enter a valid email address'; - unsubscribeMessage.className = 'form-message error'; + unsubscribeMessage.className = 'text-red-600 font-medium'; return; } @@ -144,7 +369,7 @@ async function unsubscribe() { if (response.ok) { unsubscribeMessage.textContent = data.message || 'Successfully unsubscribed.'; - unsubscribeMessage.className = 'form-message success'; + unsubscribeMessage.className = 'text-green-600 font-medium'; emailInput.value = ''; setTimeout(() => { closeUnsubscribe(); @@ -152,11 +377,11 @@ async function unsubscribe() { }, 2000); } else { unsubscribeMessage.textContent = data.error || 'Failed to unsubscribe. Please try again.'; - unsubscribeMessage.className = 'form-message error'; + unsubscribeMessage.className = 'text-red-600 font-medium'; } } catch (error) { unsubscribeMessage.textContent = 'Network error. Please try again later.'; - unsubscribeMessage.className = 'form-message error'; + unsubscribeMessage.className = 'text-red-600 font-medium'; } } diff --git a/frontend/public/index.html b/frontend/public/index.html index de91c4a..aa1a61d 100644 --- a/frontend/public/index.html +++ b/frontend/public/index.html @@ -4,58 +4,123 @@ Munich News Daily - Your Daily Dose of Munich News - + + + - -
    -
    -
    -

    πŸ“° Munich News Daily

    -

    Get the latest Munich news delivered to your inbox every morning

    -

    Stay informed about what's happening in Munich with our curated daily newsletter. No fluff, just the news that matters.

    + +
    + +
    +
    +

    πŸ“° Munich News Daily

    +

    Get the latest Munich news delivered to your inbox every morning

    +

    Stay informed about what's happening in Munich with our curated daily newsletter. No fluff, just the news that matters.

    -
    + +
    - -

    + +

    -
    -
    - - - Subscribers + +
    +
    +
    -
    +
    Subscribers
    -
    -

    Latest Munich News

    -
    -
    Loading news...
    + +
    +

    Latest Munich News

    + + +
    +
    + + +
    +
    +
    + +
    +
    Loading news...
    -
    -

    © 2024 Munich News Daily. Made with ❀️ for Munich.

    -

    Unsubscribe

    + +
    -