# 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 = """ """ # --- 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"[Reaktivieren]" if is_checked else f"[Abhaken]" col1 = f"{i}
{check_link}" title = d.get('live_title') or "Lade..."; if len(title) > 60: title = title[:60] + "..." link = f"{title}
ID: {ali_id}" col2 = "🖼️" col_live = f"{live_price:.2f}€" if live_price > 0 else "0.00€" col_coupon = f"{coupon_txt}" if coupon_val > 0 else "-" col_final = f"{final_price:.2f}€" if final_price > 0 else "-" col_ref = f"{ref_price:.2f}€" if ref_price > 0 else "?" col_savings = f"{savings_txt}" 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"{status}" art_url = d.get('source_article_url') edit_btn = f"✏️" if art_url: col_art = f"Artikel" else: col_art = "Kein Link" col_art += edit_btn reports = reported_map.get(ali_id, []) if 'product_mismatch' in reports: btn_prod = "✅ Prod. gemeldet" else: btn_prod = f"⚠️ Falsch?" report_area = f"
{btn_prod}
" col_art += report_area row_cls = "checked-off-row" if is_checked else "" rows += f"""{col1}{col2}{link}{col_live}{col_coupon}{col_final}{col_ref}{col_savings}{col_status}{col_art}""" return rows dashboard_content = f"""
Liste: {scan_type} 📝 Quick-Liste bauen 📚 Main-Liste bauen
Workflow: 1. Liste hier bauen → 2. Satellit auf PC starten
Items: {len(scan_deals)} | Add
💾 Backup: Scan-Daten | Datenbank | 🎫 Coupon-Regeln
{build_ali_rows(scan_deals)}
#🖼️ProduktLiveCouponEndpreisRef-PreisErsparnisStatusArtikel
""" hero_content = f"""

Hero Scan (Platzhalter)

Hier könnte deine Hero-Liste stehen.

""" html = f"""
🍪 Cookies
{dashboard_content}
{hero_content}
""" 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""" Amazon AliExpress Mydealz """ return f"""{title}

{title}

{scan_type}

{page_content}
""" # --- TERMINAL --- def get_terminal_html(redirect_target='/'): return f"""Scan läuft...

Scan läuft...

Verbinde...
⛔ ABBRECHEN
""" # --- 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): @wraps(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 --- @app.route('/') @requires_auth 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') @app.route('/full_report') @requires_auth def full_report(): if is_scan_running(): return redirect('/') deals, error = load_data_direct(FULL_SCAN_RESULT_KEY) if not deals: return f"""

Keine Daten.

Main Scan starten
""" deals = apply_db_status(deals) if render_dashboard_html: return render_dashboard_html(deals, "Haupt-Scan (Archiv)", is_full_report=True) return "Render Error" @app.route('/mydealz') @requires_auth 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" @app.route('/aliexpress') @requires_auth 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"

AliExpress Dashboard Error

{traceback.format_exc()}
" @app.route('/ali') def ali_redirect(): return redirect('/aliexpress') # --- SATELLITE API (Smart Merge) --- @app.route('/api/ali_upload', methods=['POST']) 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 --- @app.route('/start/') @requires_auth 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 '/') @app.route('/stop') @requires_auth def stop_scan(): global scan_process if is_scan_running(): try: scan_process.terminate() except: pass return redirect(request.referrer or '/') # --- REPORTING ROUTES --- @app.route('/report_mismatch/') @requires_auth def report_mismatch(asin): return _handle_report(asin, "product_mismatch") @app.route('/report_price/') @requires_auth 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 --- @app.route('/ali/edit_assignment/', methods=['GET', 'POST']) @requires_auth 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}

🔗 Zuordnung bearbeiten

Produkt: {title}

ID: {ali_id}

Abbrechen
""" # --- CHECK OFF / REACTIVATE --- @app.route('/check_off/') @requires_auth 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('/') @app.route('/reactivate/') @requires_auth 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 --- @app.route('/ali/check_off/') @requires_auth def ali_check_off(ali_id): c = load_ali_checked(); c.add(ali_id); save_ali_checked(c) return redirect('/aliexpress') @app.route('/ali/reactivate/') @requires_auth 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 --- @app.route('/admin/update_cookies', methods=['GET', 'POST']) @requires_auth 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 = "
✅ Amazon Cookies gespeichert!
" except Exception as e: msg = f"
❌ Fehler: {str(e)}
" return f"""{ADMIN_STYLE}

🍪 Amazon Cookies

{msg}
Zurück
""" @app.route('/admin/update_ali_cookies', methods=['GET', 'POST']) @requires_auth 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 = "
✅ Ali Cookies gespeichert!
" except Exception as e: msg = f"
❌ Fehler: {str(e)}
" return f"""{ADMIN_STYLE}

🍪 AliExpress Cookies

{msg}
Zurück
""" @app.route('/admin/rules', methods=['GET', 'POST']) @requires_auth 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 = "
✅ Regeln gespeichert!
" 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}

🎫 Coupon Regeln

{msg}

Definiere hier die AliExpress-Gutscheine (Spend & Save).
Format: Mindestbestellwert:Rabatt

Zurück
""" @app.route('/admin/download/') @requires_auth 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 @app.route('/logs/') @requires_auth def logs(filename): return send_file(os.path.join(STORAGE_DIR, filename), as_attachment=True) @app.route('/debug/images') @requires_auth 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}

📸 Screenshots

" for i in f: h += f'

{i}

' return h + "
" @app.route('/debug/view/') @requires_auth def view_debug_image(filename): return send_from_directory(STORAGE_DIR, filename) @app.route('/static/') def serve_static(filename): return send_from_directory(CODE_DIR, filename) @app.route('/add_asin', methods=['GET', 'POST']) @requires_auth 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"
✅ {len(all_ids)} Artikel hinzugefügt.
" else: msg = "
❌ Keine gültigen IDs gefunden.
" return f"""{ADMIN_STYLE}

📦 Artikel hinzufügen

{msg}
Zurück
""" 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/") @app.route('/ping') 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)