# 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"
| # | 🖼️ | Produkt | Live | Coupon | Endpreis | Ref-Preis | Ersparnis | Status | Artikel |
|---|
Hier könnte deine Hero-Liste stehen.

{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/Produkt: {title}
ID: {ali_id}
Definiere hier die AliExpress-Gutscheine (Spend & Save).
Format: Mindestbestellwert:Rabatt