File size: 40,995 Bytes
4b3470c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 | # 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):
@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"""<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"
@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"<h1>AliExpress Dashboard Error</h1><pre>{traceback.format_exc()}</pre>"
@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/<scan_type>')
@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/<asin>')
@requires_auth
def report_mismatch(asin):
return _handle_report(asin, "product_mismatch")
@app.route('/report_price/<asin>')
@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/<ali_id>', 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}<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 ---
@app.route('/check_off/<asin>')
@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/<asin>')
@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/<ali_id>')
@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/<ali_id>')
@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 = "<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>"""
@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 = "<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>"""
@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 = "<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>"""
@app.route('/admin/download/<filename>')
@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/<filename>')
@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}<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>"
@app.route('/debug/view/<filename>')
@requires_auth
def view_debug_image(filename): return send_from_directory(STORAGE_DIR, filename)
@app.route('/static/<filename>')
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"<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/")
@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) |