Download web_server.py from cg-preis/radar: direct link, hf CLI and curl.
- Browser
- Download file 41 kB
-
https://huggingface.co/spaces/cg-preis/radar/resolve/main/web_server.py
- Command line
-
hf download hf://spaces/cg-preis/radar/web_server.py
-
curl -L -o web_server.py https://huggingface.co/spaces/cg-preis/radar/resolve/main/web_server.py
41 kB
| # Datei: web_server.py | |
| # VERSION: Phönix 9.94 (Uncrashable Boot & Port 7860 Fix) | |
| from flask import Flask, redirect, send_from_directory, request, Response, send_file | |
| from functools import wraps | |
| from datetime import datetime, timedelta | |
| import subprocess | |
| import webbrowser | |
| import os | |
| import sys | |
| import json | |
| import base64 | |
| import sqlite3 | |
| import io | |
| import shutil | |
| import re | |
| from threading import Timer, Thread | |
| import logging | |
| import traceback | |
| app = Flask(__name__) | |
| # --- LOGGING --- | |
| log = logging.getLogger('werkzeug') | |
| log.setLevel(logging.ERROR) | |
| scan_process = None | |
| # --- CONFIG --- | |
| AUTH_USER = os.environ.get("APP_USER", "cg") | |
| AUTH_PASS = os.environ.get("APP_PASSWORD", "radar") | |
| IS_DOCKER = os.path.exists("/data") or os.environ.get("IS_DOCKER") | |
| if IS_DOCKER: | |
| STORAGE_DIR = "/data" | |
| CODE_DIR = "/app" | |
| try: | |
| if not os.path.exists(STORAGE_DIR): os.makedirs(STORAGE_DIR) | |
| os.chdir(STORAGE_DIR) | |
| except: pass | |
| if CODE_DIR not in sys.path: sys.path.append(CODE_DIR) | |
| else: | |
| STORAGE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| CODE_DIR = STORAGE_DIR | |
| DB_PATH = os.path.join(STORAGE_DIR, "radar.db") | |
| # --- DATEINAMEN --- | |
| FULL_SCAN_RESULT_KEY = "last_full_scan" | |
| QUICK_SCAN_RESULT_KEY = "last_quick_scan" | |
| CHECKED_DEALS_KEY = "checked_deals" | |
| # Ali Files | |
| ALI_HERO_RESULTS_FILE = "ali_hero_results.json" | |
| ALI_HERO_QUEUE_FILE = "ali_hero_queue.json" | |
| ALI_COUPON_RULES_FILE = "ali_coupon_rules.txt" | |
| ALI_FULL_SCAN_FILE = "ali_full_scan.json" | |
| ALI_QUICK_SCAN_FILE = "ali_quick_scan.json" | |
| ALI_CHECKED_FILE = "ali_checked.json" | |
| # Mydealz | |
| MYDEALZ_FILE = "mydealz_deals.json" | |
| MYDEALZ_CHECKED_FILE = "mydealz_checked.json" | |
| # Reporting | |
| MISMATCH_FILE = "mismatches.json" | |
| # --- IMPORTS --- | |
| render_dashboard_html = None | |
| try: | |
| from dashboard_engine import ( | |
| render_dashboard_html, render_mydealz_html, db_init | |
| ) | |
| except ImportError as e: | |
| print(f"!! Warnung: dashboard_engine Import Fehler: {e}") | |
| # --- GLOBAL CSS --- | |
| ADMIN_STYLE = """ | |
| <style> | |
| body { font-family: -apple-system, sans-serif; background: #f4f7f6; padding: 20px; display: flex; justify-content: center; } | |
| .card { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); width: 100%; max-width: 900px; } | |
| h1 { margin-top: 0; color: #2c3e50; } | |
| textarea { width: 100%; height: 300px; padding: 15px; border: 1px solid #333; border-radius: 5px; font-family: monospace; font-size: 13px; background: #1e1e1e; color: #00ff00; box-sizing: border-box; resize: vertical; } | |
| input[type=text] { width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; } | |
| button { background: #27ae60; color: white; border: none; padding: 12px 25px; font-size: 16px; border-radius: 5px; cursor: pointer; margin-top: 15px; font-weight: bold; } | |
| button:hover { background: #219150; } | |
| .btn-back { background: #95a5a6; text-decoration: none; display: inline-block; padding: 12px 25px; color: white; border-radius: 5px; margin-left: 10px; } | |
| .error { color: #721c24; background: #f8d7da; padding: 15px; border-radius: 5px; margin-bottom: 20px; border: 1px solid #f5c6cb; } | |
| .success { color: #155724; background: #d4edda; padding: 15px; border-radius: 5px; margin-bottom: 20px; border: 1px solid #c3e6cb; } | |
| </style> | |
| """ | |
| # --- DB HELPERS --- | |
| def get_db_connection(): | |
| if not os.path.exists(DB_PATH): return None | |
| return sqlite3.connect(DB_PATH, timeout=20) | |
| def load_data_direct(key): | |
| conn = get_db_connection() | |
| if not conn: return None, "DB Datei nicht gefunden." | |
| try: | |
| c = conn.cursor() | |
| c.execute("SELECT json_data FROM key_value_store WHERE key=?", (key,)) | |
| row = c.fetchone() | |
| conn.close() | |
| if row and row[0]: return json.loads(row[0]), None | |
| else: return None, f"Key '{key}' nicht gefunden." | |
| except Exception as e: return None, str(e) | |
| def get_json_raw_from_db(key): | |
| conn = get_db_connection() | |
| if not conn: return "{}" | |
| try: | |
| c = conn.cursor(); c.execute("SELECT json_data FROM key_value_store WHERE key=?", (key,)); row = c.fetchone(); conn.close() | |
| return row[0] if row else "{}" | |
| except: return "{}" | |
| # --- LIVE STATUS FIX --- | |
| def apply_db_status(deals): | |
| if not deals: return [] | |
| conn = get_db_connection() | |
| checked_map = {} | |
| if conn: | |
| try: | |
| c = conn.cursor() | |
| c.execute("SELECT json_data FROM key_value_store WHERE key=?", (CHECKED_DEALS_KEY,)) | |
| row = c.fetchone() | |
| if row and row[0]: checked_map = json.loads(row[0]) | |
| except: pass | |
| finally: conn.close() | |
| for deal in deals: | |
| asin = deal.get('asin') | |
| if asin in checked_map: | |
| deal['is_checked_off'] = True | |
| deal['sort_priority'] = 999 | |
| deal['analysis_text'] = f"Abgehakt am {datetime.fromisoformat(checked_map[asin]['checked_at']).strftime('%d.%m.')}" | |
| deals.sort(key=lambda x: (x.get('is_checked_off', False), x.get('sort_priority', 99))) | |
| return deals | |
| # --- FILE LOADERS --- | |
| def load_json_file(filename, default=[]): | |
| fp = os.path.join(STORAGE_DIR, filename) | |
| if not os.path.exists(fp): return default | |
| try: | |
| data = json.load(open(fp, 'r', encoding='utf-8')) | |
| return data if data is not None else default | |
| except: return default | |
| # --- ALI DATA MANAGEMENT --- | |
| def load_ali_hero_results(): return load_json_file(ALI_HERO_RESULTS_FILE, []) | |
| def load_ali_checked(): return set(load_json_file(ALI_CHECKED_FILE, [])) | |
| def save_ali_checked(checked_list): | |
| with open(os.path.join(STORAGE_DIR, ALI_CHECKED_FILE), 'w') as f: json.dump(list(checked_list), f) | |
| # --- COUPON ENGINE --- | |
| def calculate_best_coupon(price, rules_text): | |
| if not price or price <= 0: return 0.0, "" | |
| rules = [] | |
| for line in rules_text.splitlines(): | |
| line = line.strip() | |
| if not line or line.startswith('#'): continue | |
| parts = line.split(':') | |
| if len(parts) == 2: | |
| try: | |
| min_p = float(parts[0].replace(',','.')) | |
| disc = float(parts[1].replace(',','.')) | |
| rules.append((min_p, disc)) | |
| except: pass | |
| rules.sort(key=lambda x: x[0], reverse=True) | |
| for min_p, disc in rules: | |
| if price >= min_p: | |
| return disc, f"-{disc:.0f}€ (ab {min_p:.0f}€)" | |
| return 0.0, "" | |
| # --- ROTATION HELPERS --- | |
| def get_ali_rotation_pointer(): | |
| try: | |
| conn = get_db_connection() | |
| c = conn.cursor() | |
| c.execute("SELECT json_data FROM key_value_store WHERE key='ali_scan_pointer'") | |
| row = c.fetchone() | |
| conn.close() | |
| return int(row[0]) if row else 0 | |
| except: return 0 | |
| def save_ali_rotation_pointer(new_index): | |
| try: | |
| conn = get_db_connection() | |
| c = conn.cursor() | |
| c.execute("INSERT OR REPLACE INTO key_value_store (key, json_data) VALUES (?, ?)", ('ali_scan_pointer', str(new_index))) | |
| conn.commit() | |
| conn.close() | |
| except: pass | |
| # --- INTELLIGENTE LISTERSTELLUNG (SMART SELECT) --- | |
| def regenerate_ali_json_from_db(scan_type="quick"): | |
| print(f"-> Generiere Ali-Scan-Liste ({scan_type})...") | |
| conn = get_db_connection() | |
| if not conn: return [] | |
| try: | |
| conn.row_factory = sqlite3.Row | |
| c = conn.cursor() | |
| base_query = "SELECT * FROM products WHERE asin GLOB '1005*' AND length(asin) = 16 ORDER BY publication_date DESC" | |
| c.execute(base_query) | |
| all_rows = [dict(r) for r in c.fetchall()] | |
| last_known_status = {} | |
| try: | |
| prev_main = load_json_file(ALI_FULL_SCAN_FILE, []) | |
| prev_quick = load_json_file(ALI_QUICK_SCAN_FILE, []) | |
| for item in (prev_main + prev_quick): | |
| if item.get('id'): last_known_status[str(item['id'])] = item.get('status', 'Check') | |
| except: pass | |
| target_items = [] | |
| if scan_type == "quick": | |
| BATCH_SIZE = 60 | |
| newest_items = all_rows[:20] | |
| target_items.extend(newest_items) | |
| seen_ids = {str(item['asin']) for item in target_items} | |
| pool_candidates = [] | |
| for item in all_rows: | |
| aid = str(item['asin']) | |
| if aid in seen_ids: continue | |
| status = last_known_status.get(aid, 'Check') | |
| if status in ['404', 'GeoBlock', 'OOS']: continue | |
| pool_candidates.append(item) | |
| if pool_candidates: | |
| current_pointer = get_ali_rotation_pointer() | |
| if current_pointer >= len(pool_candidates): current_pointer = 0 | |
| needed = BATCH_SIZE - len(target_items) | |
| rotation_chunk = pool_candidates[current_pointer : current_pointer + needed] | |
| target_items.extend(rotation_chunk) | |
| new_pointer = current_pointer + len(rotation_chunk) | |
| if new_pointer >= len(pool_candidates): new_pointer = 0 | |
| save_ali_rotation_pointer(new_pointer) | |
| else: | |
| target_items = all_rows | |
| conn.close() | |
| final_list = [] | |
| for r in target_items: | |
| final_list.append({ | |
| "id": r['asin'], | |
| "live_title": r['verified_name'], | |
| "source_article_url": r['source_article_url'], | |
| "ref_price": r.get('manual_price', 0), | |
| "live_price": 0, | |
| "status": "Check", | |
| "url": f"https://www.aliexpress.com/item/{r['asin']}.html", | |
| "timestamp": r['publication_date'] | |
| }) | |
| target_file = ALI_QUICK_SCAN_FILE if scan_type == "quick" else ALI_FULL_SCAN_FILE | |
| with open(os.path.join(STORAGE_DIR, target_file), 'w', encoding='utf-8') as f: | |
| json.dump(final_list, f, indent=2) | |
| return final_list | |
| except Exception as e: | |
| print(f"!! List Gen Error: {e}") | |
| return [] | |
| def load_ali_scan_results(scan_type="quick"): | |
| target_file = ALI_QUICK_SCAN_FILE if scan_type == "quick" else ALI_FULL_SCAN_FILE | |
| data = load_json_file(target_file, []) | |
| if not data: data = regenerate_ali_json_from_db(scan_type) | |
| return data | |
| # --- RENDERER (ALI) --- | |
| def render_ali_html_page(hero_deals, scan_deals, scan_type="Quick"): | |
| current_rules_text = "" | |
| rules_path = os.path.join(STORAGE_DIR, ALI_COUPON_RULES_FILE) | |
| if os.path.exists(rules_path): | |
| try: current_rules_text = open(rules_path, 'r', encoding='utf-8').read() | |
| except: pass | |
| checked_items = load_ali_checked() | |
| reported_map = {} | |
| mismatch_path = os.path.join(STORAGE_DIR, MISMATCH_FILE) | |
| if os.path.exists(mismatch_path): | |
| try: | |
| raw_data = json.load(open(mismatch_path)) | |
| for item in raw_data: | |
| asin = item.get('asin') | |
| e_type = item.get('error_type', 'product_mismatch') | |
| if asin not in reported_map: reported_map[asin] = [] | |
| reported_map[asin].append(e_type) | |
| except: pass | |
| scan_deals = scan_deals if isinstance(scan_deals, list) else [] | |
| scan_deals.sort(key=lambda x: x.get('id') in checked_items) | |
| def build_ali_rows(items): | |
| rows = "" | |
| for i, d in enumerate(items, 1): | |
| if not isinstance(d, dict): continue | |
| ali_id = str(d.get('id', 'Unknown')) | |
| is_checked = ali_id in checked_items | |
| live_price = float(d.get('live_price', 0)) | |
| ref_price = float(d.get('ref_price', 0)) | |
| coupon_val, coupon_txt = calculate_best_coupon(live_price, current_rules_text) | |
| final_price = live_price - coupon_val if live_price > 0 else 0 | |
| savings_pct = 0 | |
| savings_txt = "-" | |
| savings_color = "#7f8c8d" | |
| if ref_price > 0 and final_price > 0: | |
| savings_pct = ((ref_price - final_price) / ref_price) * 100 | |
| savings_txt = f"{savings_pct:.0f}%" | |
| if savings_pct >= 20: savings_color = "#27ae60" | |
| elif savings_pct < -5: savings_color = "#c0392b" | |
| else: savings_color = "#e67e22" | |
| check_link = f"<a href='/ali/reactivate/{ali_id}' class='check-off-link'>[Reaktivieren]</a>" if is_checked else f"<a href='/ali/check_off/{ali_id}' class='check-off-link'>[Abhaken]</a>" | |
| col1 = f"{i}<br>{check_link}" | |
| title = d.get('live_title') or "Lade..."; | |
| if len(title) > 60: title = title[:60] + "..." | |
| link = f"<a href='{d.get('url')}' target='_blank' style='font-weight:600;color:#2c3e50;text-decoration:none;font-size:1.05em;'>{title}</a><br><small style='color:#999'>ID: {ali_id}</small>" | |
| col2 = "🖼️" | |
| col_live = f"<b>{live_price:.2f}€</b>" if live_price > 0 else "<span class='unavailable'>0.00€</span>" | |
| col_coupon = f"<span style='color:#e74c3c;font-size:0.9em'>{coupon_txt}</span>" if coupon_val > 0 else "-" | |
| col_final = f"<b style='font-size:1.1em;color:#2c3e50'>{final_price:.2f}€</b>" if final_price > 0 else "-" | |
| col_ref = f"{ref_price:.2f}€" if ref_price > 0 else "<span style='color:#ccc'>?</span>" | |
| col_savings = f"<span style='color:{savings_color};font-weight:bold'>{savings_txt}</span>" | |
| status = d.get('status', 'Unknown'); s_col = "#7f8c8d" | |
| if status in ["Active", "Reanimated"]: s_col="#27ae60" | |
| elif status in ["404", "OOS", "GeoBlock"]: s_col="#e74c3c" | |
| col_status = f"<span style='color:{s_col};font-weight:bold'>{status}</span>" | |
| art_url = d.get('source_article_url') | |
| edit_btn = f"<a href='/ali/edit_assignment/{ali_id}' style='color:#3498db;font-size:0.8em;text-decoration:none;margin-left:5px;' title='Link bearbeiten'>✏️</a>" | |
| if art_url: col_art = f"<a href='{art_url}' target='_blank' class='micro-btn btn-idealo' style='background:#3498db;border-color:#2980b9'>Artikel</a>" | |
| else: col_art = "<span style='color:#ccc'>Kein Link</span>" | |
| col_art += edit_btn | |
| reports = reported_map.get(ali_id, []) | |
| if 'product_mismatch' in reports: btn_prod = "<span style='color:#27ae60;font-size:0.7em;'>✅ Prod. gemeldet</span>" | |
| else: btn_prod = f"<a href='/report_mismatch/{ali_id}' style='color:#e74c3c;font-size:0.75em;text-decoration:none;' title='Falsches Produkt'>⚠️ Falsch?</a>" | |
| report_area = f"<div style='margin-top:8px;border-top:1px solid #eee;padding-top:4px;display:flex;flex-direction:column;gap:3px;'>{btn_prod}</div>" | |
| col_art += report_area | |
| row_cls = "checked-off-row" if is_checked else "" | |
| rows += f"""<tr class="{row_cls}"><td data-sort-value="{i}">{col1}</td><td>{col2}</td><td>{link}</td><td data-sort-value="{live_price}">{col_live}</td><td>{col_coupon}</td><td data-sort-value="{final_price}">{col_final}</td><td data-sort-value="{ref_price}">{col_ref}</td><td data-sort-value="{savings_pct}">{col_savings}</td><td>{col_status}</td><td>{col_art}</td></tr>""" | |
| return rows | |
| dashboard_content = f""" | |
| <div class="actions-bar" style="background:#fff;padding:15px;border-radius:8px;box-shadow:0 2px 5px rgba(0,0,0,0.05);margin-bottom:20px;display:flex;align-items:center;gap:15px;"> | |
| <span style="font-size:1.1em;font-weight:bold;">Liste: {scan_type}</span> | |
| <a href="/start/ali_quick" class="button button-main">📝 Quick-Liste bauen</a> | |
| <a href="/start/ali_main" class="button button-secondary">📚 Main-Liste bauen</a> | |
| <div style="margin-left:auto;font-size:0.9em;color:#666;"> | |
| <b>Workflow:</b> 1. Liste hier bauen → 2. Satellit auf PC starten | |
| </div> | |
| <div style="margin-left:10px;font-size:0.9em;color:#666;">Items: <b>{len(scan_deals)}</b> | <a href="/add_asin" style="color:#3498db">Add</a></div> | |
| </div> | |
| <div style="text-align:right;margin-bottom:10px;font-size:0.9em;"> | |
| 💾 <b>Backup:</b> <a href="/admin/download/ali_full_scan.json">Scan-Daten</a> | <a href="/admin/download/radar.db">Datenbank</a> | <a href="/admin/rules" style="color:#e67e22;font-weight:bold;">🎫 Coupon-Regeln</a> | |
| </div> | |
| <table id="deal-table"><thead><tr><th onclick="sortTable(0,false)">#</th><th>🖼️</th><th onclick="sortTable(2,false)">Produkt</th><th onclick="sortTable(3,true)">Live</th><th>Coupon</th><th onclick="sortTable(5,true)">Endpreis</th><th onclick="sortTable(6,true)">Ref-Preis</th><th onclick="sortTable(7,true)">Ersparnis</th><th onclick="sortTable(8,false)">Status</th><th>Artikel</th></tr></thead><tbody>{build_ali_rows(scan_deals)}</tbody></table> | |
| """ | |
| hero_content = f"""<div style="padding:20px;"><h3>Hero Scan (Platzhalter)</h3><p>Hier könnte deine Hero-Liste stehen.</p></div>""" | |
| html = f"""<div style="margin-bottom:20px;border-bottom:1px solid #ddd;"><button class="tab-btn active" onclick="openTab('dash')">📊 Dashboard</button><button class="tab-btn" onclick="openTab('hero')">🦸 Hero</button><a href="/admin/update_ali_cookies" class="button button-meta" style="float:right;margin-top:5px;">🍪 Cookies</a></div><div id="dash" class="tab-content active">{dashboard_content}</div><div id="hero" class="tab-content">{hero_content}</div>""" | |
| return render_html_layout(html, "AliExpress", "#ff4747", "ali") | |
| def render_html_layout(page_content, scan_type, theme_color, active_module): | |
| title = "CG Preis-Radar" | |
| tabs = f""" | |
| <a href="/" class="nav-tab {'active' if active_module == 'amazon' else ''}">Amazon</a> | |
| <a href="/ali" class="nav-tab {'active' if active_module == 'ali' else ''}">AliExpress</a> | |
| <a href="/mydealz" class="nav-tab {'active' if active_module == 'mydealz' else ''}">Mydealz</a> | |
| """ | |
| return f"""<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8"><title>{title}</title><style> | |
| body{{font-family:-apple-system,sans-serif;background:#f4f7f6;margin:0;padding:20px;color:#333}} | |
| .container{{max-width:98%;margin:auto;background:#fff;box-shadow:0 0 20px rgba(0,0,0,0.1);border-radius:10px;overflow:hidden}} | |
| header{{background:{theme_color};color:#fff;padding:15px 25px;display:flex;justify-content:space-between;align-items:center}} | |
| .header-left {{ display: flex; flex-direction: column; gap: 10px; }} | |
| .header-top-row {{ display: flex; align-items: baseline; gap: 15px; }} | |
| .header-title h1 {{ margin: 0; font-size: 1.8em; }} | |
| .nav-tab{{color:#fff;text-decoration:none;padding:8px 15px;border-radius:5px;background:rgba(255,255,255,0.1);transition:0.2s}} | |
| .nav-tab:hover{{background:rgba(255,255,255,0.25)}}.nav-tab.active{{background:rgba(0,0,0,0.3);font-weight:bold}} | |
| .content-wrapper{{padding:20px}} | |
| .actions-bar{{display:flex;gap:10px;margin-bottom:20px;align-items:center}} | |
| .button{{padding:10px 15px;color:#fff;text-decoration:none;border-radius:5px;border:none;cursor:pointer;font-size:0.9em;}} | |
| .button-main{{background:#27ae60}}.button-secondary{{background:#3498db}}.button-meta{{background:#95a5a6}} | |
| table{{width:100%;border-collapse:collapse;margin-top:10px;table-layout: fixed;}} | |
| th,td{{padding:10px;border-bottom:1px solid #ddd;text-align:left;vertical-align:middle;word-wrap:break-word;overflow:hidden;}} | |
| th{{background:#e8eff5;cursor:pointer;user-select:none;font-size:0.9em;color:#555;}} | |
| th:hover{{background:#dfe6ed}} | |
| tr:hover{{background:#f9f9f9}} | |
| th:nth-child(1) {{ width: 5%; }} | |
| th:nth-child(2) {{ width: 5%; }} | |
| th:nth-child(3) {{ width: 25%; }} | |
| th:nth-child(4) {{ width: 8%; }} | |
| th:nth-child(5) {{ width: 10%; }} | |
| th:nth-child(6) {{ width: 8%; }} | |
| th:nth-child(7) {{ width: 8%; }} | |
| th:nth-child(8) {{ width: 8%; }} | |
| th:nth-child(9) {{ width: 8%; }} | |
| th:nth-child(10){{ width: 12%; }} | |
| .unavailable {{ color: #e74c3c; font-weight: bold; font-style: italic; }} .micro-btn {{ display: inline-block; padding: 2px 6px; font-size: 0.75em; font-weight: bold; border-radius: 3px; text-decoration: none; margin-right: 4px; font-family: monospace; }} | |
| .tab-btn {{ background:none; border:none; border-bottom:3px solid transparent; font-size:1.1em; padding:10px 20px; cursor:pointer; color:#7f8c8d; font-weight:bold; }} .tab-btn.active {{ border-bottom:3px solid #e74c3c; color:#2c3e50; }} .tab-content {{ display:none; animation: fadeIn 0.3s; }} .tab-content.active {{ display:block; }} | |
| @keyframes fadeIn {{ from {{ opacity:0; }} to {{ opacity:1; }} }} | |
| .checked-off-row {{ opacity: 0.5; background: #f9f9f9; font-style: italic; }} .check-off-link {{ font-size:0.8em; color:#999; text-decoration:none; }} | |
| </style></head><body><div class="container"><header> | |
| <div class="header-left"><div class="header-top-row"><div class="header-title"><h1>{title}</h1></div></div><nav>{tabs}</nav></div> | |
| <div class="header-logo"><img src="/static/cg_logo.png" alt="Logo" style="max-height:50px;"></div></header> | |
| <div class="content-wrapper"><h2>{scan_type}</h2>{page_content}</div></div> | |
| <script> | |
| function sortTable(n,isNum){{var t=document.getElementById("deal-table"),r,sw,i,x,y,s,dir="asc",cnt=0;sw=true;while(sw){{sw=false;r=t.rows;for(i=1;i<(r.length-1);i++){{s=false;x=r[i].getElementsByTagName("TD")[n];y=r[i+1].getElementsByTagName("TD")[n];var xV=x.getAttribute('data-sort-value')||x.textContent.toLowerCase();var yV=y.getAttribute('data-sort-value')||y.textContent.toLowerCase();if(isNum){{xV=parseFloat(xV);yV=parseFloat(yV);}}if(dir=="asc"){{if(xV>yV){{s=true;break;}}}}else{{if(xV<yV){{s=true;break;}}}}}}if(s){{r[i].parentNode.insertBefore(r[i+1],r[i]);sw=true;cnt++;}}else{{if(cnt==0&&dir=="asc"){{dir="desc";sw=true;}}}}}}}} | |
| function openTab(id) {{ document.querySelectorAll('.tab-content').forEach(e => e.classList.remove('active')); document.querySelectorAll('.tab-btn').forEach(e => e.classList.remove('active')); document.getElementById(id).classList.add('active'); event.target.classList.add('active'); localStorage.setItem('ali_tab_main', id); }} | |
| if(localStorage.getItem('ali_tab_main')) {{ const t = localStorage.getItem('ali_tab_main'); const b = document.querySelector(`button[onclick="openTab('${{t}}')"]`); if(b) b.click(); }} | |
| </script> | |
| </body></html>""" | |
| # --- TERMINAL --- | |
| def get_terminal_html(redirect_target='/'): | |
| return f"""<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8"><title>Scan läuft...</title><style>body{{font-family:-apple-system,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;background:#f4f7f6;margin:0}}.container{{text-align:center;background:white;padding:30px;border-radius:10px;box-shadow:0 4px 15px rgba(0,0,0,0.1);width:90%;max-width:900px;height:85vh;display:flex;flex-direction:column}}.loader{{border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;width:30px;height:30px;animation:spin 1s linear infinite;margin:10px auto}}@keyframes spin{{0%{{transform:rotate(0deg)}}100%{{transform:rotate(360deg)}}}}.btn-stop{{background:#e74c3c;color:white;padding:10px 20px;text-decoration:none;border-radius:5px;font-weight:bold;margin-bottom:15px}}#terminal-window{{flex-grow:1;background-color:#1e1e1e;color:#00ff00;font-family:monospace;font-size:0.85rem;padding:15px;border-radius:5px;text-align:left;overflow-y:auto;white-space:pre-wrap}}</style></head><body><div class="container"><div class="loader"></div><h1>Scan läuft...</h1><div id="terminal-window">Verbinde...</div><div style="margin-top:20px;"><a href="/stop" class="btn-stop">⛔ ABBRECHEN</a></div></div><script>const terminal=document.getElementById('terminal-window');function fetchLogs(){{fetch('/logs/scan.log?t='+Date.now()).then(r=>{{if(!r.ok)throw new Error();return r.text()}}).then(t=>{{if(terminal.innerText.length!==t.length){{terminal.innerText=t;terminal.scrollTop=terminal.scrollHeight}}}}).catch(e=>{{}})}}function checkStatus(){{fetch('/?t='+Date.now()).then(r=>r.text()).then(html=>{{if(!html.includes('id="terminal-window"')){{window.location.href="{redirect_target}"}}}}) }}setInterval(fetchLogs,1000);setInterval(checkStatus,3000);fetchLogs();</script></body></html>""" | |
| # --- AUTH --- | |
| def check_auth(u, p): return u == AUTH_USER and p == AUTH_PASS | |
| def authenticate(): return Response('Zugriff verweigert.', 401, {'WWW-Authenticate': 'Basic realm="Login"'}) | |
| def requires_auth(f): | |
| def decorated(*args, **kwargs): | |
| auth = request.authorization | |
| if not auth or not check_auth(auth.username, auth.password): return authenticate() | |
| return f(*args, **kwargs) | |
| return decorated | |
| def is_scan_running(): global scan_process; return scan_process and scan_process.poll() is None | |
| def run_scan_thread(cmd, shell=False): global scan_process; scan_process = subprocess.Popen(cmd, cwd=STORAGE_DIR, shell=shell, env={**os.environ, 'PYTHONUTF8':'1'}); scan_process.wait() | |
| # --- ROUTES --- | |
| def home(): | |
| if is_scan_running(): return get_terminal_html('/') | |
| try: | |
| deals, error = load_data_direct(QUICK_SCAN_RESULT_KEY) | |
| if deals: | |
| deals = apply_db_status(deals) | |
| if render_dashboard_html: return render_dashboard_html(deals, "Quick-Scan Report", is_full_report=False) | |
| deals_full, error_full = load_data_direct(FULL_SCAN_RESULT_KEY) | |
| if deals_full: | |
| deals_full = apply_db_status(deals_full) | |
| if render_dashboard_html: return render_dashboard_html(deals_full, "Full-Scan (Fallback)", is_full_report=False) | |
| except Exception as e: return f"Fehler im Dashboard: {e}" | |
| return redirect('/full_report') | |
| def full_report(): | |
| if is_scan_running(): return redirect('/') | |
| deals, error = load_data_direct(FULL_SCAN_RESULT_KEY) | |
| if not deals: return f"""<div style='text-align:center;padding:50px;'><h1 style='color:#e74c3c'>Keine Daten.</h1><a href='/start/main' class='button button-main'>Main Scan starten</a></div>""" | |
| deals = apply_db_status(deals) | |
| if render_dashboard_html: return render_dashboard_html(deals, "Haupt-Scan (Archiv)", is_full_report=True) | |
| return "Render Error" | |
| def mydealz_feed(): | |
| if is_scan_running(): return get_terminal_html('/mydealz') | |
| deals = load_json_file(MYDEALZ_FILE); checked_urls = load_json_file(MYDEALZ_CHECKED_FILE, []) | |
| if render_mydealz_html: return render_mydealz_html(deals, checked_urls) | |
| return "Mydealz Render Error" | |
| def ali_dashboard(): | |
| try: | |
| results = load_ali_scan_results("quick") | |
| scan_type = "Quick Scan (Aktiv)" | |
| if not results: | |
| results = load_ali_scan_results("main") | |
| scan_type = "Main Scan (Archiv)" | |
| return render_ali_html_page(load_ali_hero_results(), results, scan_type) | |
| except Exception: return f"<h1>AliExpress Dashboard Error</h1><pre>{traceback.format_exc()}</pre>" | |
| def ali_redirect(): return redirect('/aliexpress') | |
| # --- SATELLITE API (Smart Merge) --- | |
| def api_ali_upload(): | |
| if request.headers.get('X-Auth-Token') != AUTH_PASS: | |
| return "Unauthorized", 401 | |
| try: | |
| incoming_data = request.json | |
| if not isinstance(incoming_data, list): return "Expected list", 400 | |
| target_file = ALI_QUICK_SCAN_FILE | |
| existing_data = load_json_file(target_file, []) | |
| data_map = {str(item.get('id')): item for item in existing_data} | |
| updated_count = 0 | |
| reanimated_count = 0 | |
| for new_item in incoming_data: | |
| new_id = str(new_item.get('id')) | |
| old_id = str(new_item.get('original_id')) if new_item.get('original_id') else None | |
| if old_id and old_id in data_map: | |
| ref_price = data_map[old_id].get('ref_price', 0) | |
| new_item['ref_price'] = ref_price | |
| del data_map[old_id] | |
| data_map[new_id] = new_item | |
| reanimated_count += 1 | |
| else: | |
| if new_id in data_map: | |
| merged = data_map[new_id].copy() | |
| merged.update(new_item) | |
| data_map[new_id] = merged | |
| else: | |
| data_map[new_id] = new_item | |
| updated_count += 1 | |
| final_list = list(data_map.values()) | |
| with open(os.path.join(STORAGE_DIR, target_file), 'w', encoding='utf-8') as f: | |
| json.dump(final_list, f, indent=2) | |
| return f"OK. Updated {updated_count} items (Reanimated: {reanimated_count})", 200 | |
| except Exception as e: | |
| return str(e), 500 | |
| # --- ACTIONS --- | |
| def start_scan(scan_type): | |
| if is_scan_running(): return redirect('/') | |
| if "ali_" in scan_type: | |
| mode = "quick" if "quick" in scan_type else "main" | |
| regenerate_ali_json_from_db(mode) | |
| return redirect('/aliexpress') | |
| script = "mydealz_engine.py" if scan_type == "mydealz_scan" else "dashboard_engine.py" | |
| cmd = ["python", os.path.join(CODE_DIR, script)] | |
| if scan_type == "quick": cmd.append("--quick") | |
| elif scan_type == "main": cmd = f"python {os.path.join(CODE_DIR, 'deal_radar_masterplan.py')} && python {os.path.join(CODE_DIR, 'dashboard_engine.py')} --main" | |
| Thread(target=run_scan_thread, args=(cmd, scan_type == "main")).start() | |
| return redirect('/mydealz' if scan_type == 'mydealz_scan' else '/') | |
| def stop_scan(): | |
| global scan_process | |
| if is_scan_running(): | |
| try: scan_process.terminate() | |
| except: pass | |
| return redirect(request.referrer or '/') | |
| # --- REPORTING ROUTES --- | |
| def report_mismatch(asin): | |
| return _handle_report(asin, "product_mismatch") | |
| def report_price(asin): | |
| return _handle_report(asin, "price_error") | |
| def _handle_report(asin, error_type): | |
| fp = os.path.join(STORAGE_DIR, MISMATCH_FILE) | |
| data = [] | |
| if os.path.exists(fp): | |
| try: data = json.load(open(fp, 'r', encoding='utf-8')) | |
| except: pass | |
| if not any(str(x.get('asin')) == str(asin) and x.get('error_type') == error_type for x in data): | |
| data.append({ | |
| "timestamp": datetime.now().isoformat(), | |
| "error_type": error_type, | |
| "asin": str(asin) | |
| }) | |
| with open(fp, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2) | |
| return redirect(request.referrer or '/') | |
| # --- EDIT ROUTE --- | |
| def ali_edit_assignment(ali_id): | |
| msg = "" | |
| conn = get_db_connection() | |
| c = conn.cursor() | |
| c.execute("SELECT * FROM products WHERE asin=?", (ali_id,)) | |
| row = c.fetchone() | |
| if request.method == 'POST': | |
| new_url = request.form.get('source_url') | |
| if new_url: | |
| c.execute("UPDATE products SET source_article_url=? WHERE asin=?", (new_url, ali_id)) | |
| conn.commit() | |
| f = load_ali_scan_results("quick") | |
| for item in f: | |
| if str(item['id']) == str(ali_id): | |
| item['source_article_url'] = new_url | |
| with open(os.path.join(STORAGE_DIR, ALI_QUICK_SCAN_FILE), 'w') as fh: json.dump(f, fh, indent=2) | |
| return redirect('/aliexpress') | |
| current_url = row['source_article_url'] if row else "" | |
| title = row['verified_name'] if row else "Unbekannt" | |
| conn.close() | |
| return f"""{ADMIN_STYLE}<div class="card"><h1>🔗 Zuordnung bearbeiten</h1> | |
| <p><b>Produkt:</b> {title}</p> | |
| <p><b>ID:</b> {ali_id}</p> | |
| <form method='post'> | |
| <label>CG Artikel URL:</label> | |
| <input type='text' name='source_url' value='{current_url}'> | |
| <button>SPEICHERN</button> | |
| <a href="/aliexpress" class="btn-back">Abbrechen</a> | |
| </form></div>""" | |
| # --- CHECK OFF / REACTIVATE --- | |
| def check_off(asin): | |
| conn = get_db_connection() | |
| if conn: | |
| try: | |
| c = conn.cursor() | |
| c.execute("SELECT json_data FROM key_value_store WHERE key=?", (CHECKED_DEALS_KEY,)) | |
| row = c.fetchone() | |
| data = json.loads(row[0]) if row and row[0] else {} | |
| data[asin] = {"checked_at": datetime.now().isoformat(), "price_at_check": 0} | |
| c.execute("INSERT OR REPLACE INTO key_value_store (key, json_data) VALUES (?, ?)", (CHECKED_DEALS_KEY, json.dumps(data))) | |
| conn.commit() | |
| except: pass | |
| finally: conn.close() | |
| return redirect('/') | |
| def reactivate(asin): | |
| conn = get_db_connection() | |
| if conn: | |
| try: | |
| c = conn.cursor() | |
| c.execute("SELECT json_data FROM key_value_store WHERE key=?", (CHECKED_DEALS_KEY,)) | |
| row = c.fetchone() | |
| data = json.loads(row[0]) if row and row[0] else {} | |
| if asin in data: | |
| del data[asin] | |
| c.execute("INSERT OR REPLACE INTO key_value_store (key, json_data) VALUES (?, ?)", (CHECKED_DEALS_KEY, json.dumps(data))) | |
| conn.commit() | |
| except: pass | |
| finally: conn.close() | |
| return redirect('/') | |
| # --- ALI ACTIONS --- | |
| def ali_check_off(ali_id): | |
| c = load_ali_checked(); c.add(ali_id); save_ali_checked(c) | |
| return redirect('/aliexpress') | |
| def ali_reactivate(ali_id): | |
| c = load_ali_checked() | |
| if ali_id in c: c.remove(ali_id) | |
| save_ali_checked(c) | |
| return redirect('/aliexpress') | |
| # --- ADMIN ROUTES --- | |
| def update_cookies(): | |
| msg = "" | |
| if request.method == 'POST': | |
| try: | |
| data = None | |
| if request.is_json: data = request.get_json() | |
| elif 'cookie_text' in request.form: data = json.loads(request.form['cookie_text']) | |
| if data: json.dump(data, open(os.path.join(STORAGE_DIR, "cookies.json"), 'w'), indent=2); msg = "<div class='success'>✅ Amazon Cookies gespeichert!</div>" | |
| except Exception as e: msg = f"<div class='error'>❌ Fehler: {str(e)}</div>" | |
| return f"""{ADMIN_STYLE}<div class="card"><h1>🍪 Amazon Cookies</h1>{msg}<form method='post'><textarea name='cookie_text'></textarea><button>SPEICHERN</button><a href="/" class="btn-back">Zurück</a></form></div>""" | |
| def update_ali_cookies(): | |
| msg = "" | |
| if request.method == 'POST': | |
| try: | |
| data = None | |
| if request.is_json: data = request.get_json() | |
| elif 'cookie_text' in request.form: data = json.loads(request.form['cookie_text']) | |
| if data: json.dump(data, open(os.path.join(STORAGE_DIR, "ali_cookies.json"), 'w'), indent=2); msg = "<div class='success'>✅ Ali Cookies gespeichert!</div>" | |
| except Exception as e: msg = f"<div class='error'>❌ Fehler: {str(e)}</div>" | |
| return f"""{ADMIN_STYLE}<div class="card"><h1>🍪 AliExpress Cookies</h1>{msg}<form method='post'><textarea name='cookie_text'></textarea><button>SPEICHERN</button><a href="/aliexpress" class="btn-back">Zurück</a></form></div>""" | |
| def admin_rules(): | |
| msg = "" | |
| fp = os.path.join(STORAGE_DIR, ALI_COUPON_RULES_FILE) | |
| if request.method == 'POST': | |
| txt = request.form.get('rules_text', '') | |
| with open(fp, 'w', encoding='utf-8') as f: f.write(txt) | |
| msg = "<div class='success'>✅ Regeln gespeichert!</div>" | |
| current = "" | |
| if os.path.exists(fp): current = open(fp, 'r', encoding='utf-8').read() | |
| else: current = "# Format: MIN_PREIS:RABATT\n29:3\n59:6\n89:10" | |
| return f"""{ADMIN_STYLE}<div class="card"><h1>🎫 Coupon Regeln</h1>{msg} | |
| <p>Definiere hier die AliExpress-Gutscheine (Spend & Save).<br>Format: <code>Mindestbestellwert:Rabatt</code></p> | |
| <form method='post'><textarea name='rules_text'>{current}</textarea><button>SPEICHERN</button><a href="/aliexpress" class="btn-back">Zurück</a></form></div>""" | |
| def download_file(filename): | |
| DB_FILES = {"checked_deals.json": CHECKED_DEALS_KEY,"unavailable_asin_tracker.json":"unavailable_asin_tracker","last_quick_scan.json":QUICK_SCAN_RESULT_KEY,"last_full_scan.json":FULL_SCAN_RESULT_KEY} | |
| if filename in DB_FILES: | |
| j = get_json_raw_from_db(DB_FILES[filename]); m = io.BytesIO(); m.write(j.encode('utf-8')); m.seek(0) | |
| return send_file(m, mimetype='application/json', as_attachment=True, download_name=filename) | |
| if not any(filename.endswith(x) for x in ['.json', '.db', '.log', '.txt']): return "Forbidden", 403 | |
| fp = os.path.join(STORAGE_DIR, filename) | |
| if os.path.exists(fp): return send_file(fp, as_attachment=True) | |
| return "Nicht gefunden", 404 | |
| def logs(filename): return send_file(os.path.join(STORAGE_DIR, filename), as_attachment=True) | |
| def list_debug_images(): | |
| try: f = sorted([x for x in os.listdir(STORAGE_DIR) if x.endswith('.png')], reverse=True) | |
| except: f = [] | |
| h = f"{ADMIN_STYLE}<div class='card'><h1>📸 Screenshots</h1>" | |
| for i in f: h += f'<div><h3>{i}</h3><img src="/debug/view/{i}" style="max-width:100%;border:1px solid #ccc"></div>' | |
| return h + "</div>" | |
| def view_debug_image(filename): return send_from_directory(STORAGE_DIR, filename) | |
| def serve_static(filename): return send_from_directory(CODE_DIR, filename) | |
| def add_asin(): | |
| msg = "" | |
| if request.method == 'POST': | |
| raw = request.form.get('asin_list', '') | |
| asins = re.findall(r'\b(B0[A-Z0-9]{8})\b', raw); ali_ids = re.findall(r'\b(1005\d{10,14})\b', raw) | |
| all_ids = set(asins + ali_ids) | |
| if all_ids: | |
| conn = get_db_connection(); c = conn.cursor() | |
| for a in all_ids: c.execute("INSERT OR IGNORE INTO products (asin,verified_name,source_score,publication_date) VALUES (?,?,500,?)", (a, "Manuell Hinzugefügt", datetime.now().strftime('%Y-%m-%d'))) | |
| conn.commit(); conn.close(); msg = f"<div class='success'>✅ {len(all_ids)} Artikel hinzugefügt.</div>" | |
| else: msg = "<div class='error'>❌ Keine gültigen IDs gefunden.</div>" | |
| return f"""{ADMIN_STYLE}<div class="card"><h1>📦 Artikel hinzufügen</h1>{msg}<form method='post'><textarea name='asin_list' placeholder='Amazon / Ali IDs...'></textarea><button>HINZUFÜGEN</button><a href="/" class="btn-back">Zurück</a></form></div>""" | |
| def initial_checks(): | |
| if IS_DOCKER: | |
| try: | |
| if not os.path.exists(DB_PATH) and os.path.exists(os.path.join(CODE_DIR, "radar.db")): | |
| shutil.copy2(os.path.join(CODE_DIR, "radar.db"), DB_PATH) | |
| db_init() | |
| except: pass | |
| if not os.path.exists(os.path.join(STORAGE_DIR, ALI_FULL_SCAN_FILE)): | |
| regenerate_ali_json_from_db("main") | |
| def open_browser(): | |
| if not IS_DOCKER: webbrowser.open_new("http://127.0.0.1:5000/") | |
| def ping(): return "Pong", 200 | |
| if __name__ == '__main__': | |
| print("--- CG Preis-Radar Server (Phönix 9.94 - STABLE BOOT) ---") | |
| # 1. Port für Hugging Face erzwingen (MUSS 7860 sein) | |
| port_num = 7860 | |
| # 2. Defensiver Start der Hintergrund-Logik | |
| try: | |
| initial_checks() | |
| except Exception as e: | |
| print(f"!!! Initial Check Fail (Non-Fatal): {e}") | |
| Timer(1, open_browser).start() | |
| print(f"-> Starting Flask on 0.0.0.0:{port_num}") | |
| app.run(host="0.0.0.0", port=port_num, debug=False) |