Files

242 lines
8.8 KiB
Python

# -*- coding: utf-8 -*-
"""SOURCE PROMOTE — авто-улучшение списка источников.
Замыкает цикл: discovery.py (ищет кандидатов) -> ЭТОТ скрипт (валидирует
живость, апгрейдит до RSS/JSON-эндпоинтов, дедуплицирует) ->
sources_extra.json (parse.py подхватывает автоматически).
Кандидаты: SEEDS (кураторский список) + data/discovery_state.json +
feedspot-каталоги (cracking/hacking/dumps/carding).
Запуск: python promote.py [--dry] [--max N] [--seeds-only]
Cron: 0 */6 * * *
"""
import json
import os
import re
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlparse
import requests
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
BASE = Path(__file__).resolve().parent
EXTRA_FILE = BASE / "sources_extra.json"
DISCOVERY_STATE = BASE / "data" / "discovery_state.json"
LOG = BASE / "output" / "promote_log.jsonl"
LOG.parent.mkdir(exist_ok=True)
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36"}
PARKED_RE = re.compile(r"domain (is )?for sale|buy this domain|parkingcrew|sedoparking|Researches: No results|account suspended|522 Connection timed out", re.I)
SEEDS = [
{"url": "https://www.nodeloc.com/latest.json", "topic": "freebie"},
{"url": "https://www.v2ex.com/api/topics/hot.json", "topic": "freebie"},
{"url": "https://hostloc.com/forum.php?mod=rss", "topic": "freebie"},
{"url": "https://findaicredits.com/", "topic": "freebie"},
{"url": "https://linux.do/latest.json", "topic": "freebie"},
{"url": "https://linux.do/c/welfare/26.json", "topic": "freebie"},
{"url": "https://bhf.io/", "topic": "cracking"},
{"url": "https://leak.sx/", "topic": "cracking"},
{"url": "https://xss.is/", "topic": "hacking"},
{"url": "https://forum.hashkiller.io/index.php", "topic": "cracking"},
{"url": "https://crackingarena.com/", "topic": "cracking"},
{"url": "https://www.crackingpro.com/", "topic": "cracking"},
{"url": "https://cybernulled.com/", "topic": "cracking"},
{"url": "https://crackia.com/", "topic": "cracking"},
{"url": "https://craxpro.io/", "topic": "cracking"},
]
FEEDSPOT_PAGES = [
"https://forums.feedspot.com/cracking_forums/",
"https://forums.feedspot.com/dumps_forums/",
"https://forums.feedspot.com/carding_forums/",
]
TOPIC_HINTS = [
("freebie", r"nodeloc|linux\.do|v2ex|hostloc|freebie|welfare|credits|free.?trial|халяв"),
("combo", r"combo|dump|database|breach"),
("configs", r"config|openbullet|silverbullet|storm"),
("carding", r"card|cc|cvv|fullz"),
("proxies", r"proxy|proxies|vpn"),
("traffic", r"traffic|arbitrage|cpa|seo|affiliate"),
("accounts", r"account"),
("hacking", r"hack|exploit|xss|security"),
("cracking", r"crack|nulled"),
]
def infer_topic(url: str, name: str = "") -> str:
text = f"{url} {name}".lower()
for topic, pat in TOPIC_HINTS:
if re.search(pat, text):
return topic
return "cracking"
def domain_of(url: str) -> str:
h = urlparse(url).netloc.lower()
return h[4:] if h.startswith("www.") else h
def firecrawl_ok(url: str) -> bool:
"""keyless firecrawl v2 probe (per-IP rate-limit)."""
try:
r = requests.post("https://api.firecrawl.dev/v2/scrape",
headers={"Content-Type": "application/json", "X-Origin": "mcp-fastmcp"},
json={"url": url, "formats": ["markdown"], "onlyMainContent": True},
timeout=40)
if r.status_code == 200:
md = ((r.json().get("data") or {}).get("markdown") or "")
return len(md) > 1500 and not PARKED_RE.search(md[:3000])
except Exception:
pass
return False
def probe(url: str):
"""returns (alive, final_url, status)."""
try:
r = requests.get(url, headers=UA, timeout=14, allow_redirects=True)
except Exception:
return False, url, 0
body = r.text
if r.status_code == 200 and len(body) > 1500 and not PARKED_RE.search(body[:3000]):
return True, str(r.url), 200
if r.status_code in (403, 503) and ("cloudflare" in body.lower() or "ddos-guard" in body.lower() or r.status_code == 403):
if firecrawl_ok(url):
return True, str(r.url), 201
return False, url, r.status_code
def upgrade_url(url: str) -> str:
"""XenForo -> syndication.php RSS, Discourse -> latest.json (если ещё не)."""
if url.endswith((".json", ".rss")) or "syndication.php" in url or "mod=rss" in url:
return url
base = url.rstrip("/")
try:
r = requests.get(base + "/latest.json", headers=UA, timeout=10)
if r.status_code == 200 and "topic_list" in r.text[:400]:
return base + "/latest.json"
except Exception:
pass
try:
r = requests.get(base + "/syndication.php?limit=50", headers=UA, timeout=10)
if r.status_code == 200 and ("<rss" in r.text[:500] or "<?xml" in r.text[:200]):
return base + "/syndication.php?limit=50"
except Exception:
pass
return url
def load_extra() -> list:
if EXTRA_FILE.exists():
try:
return json.loads(EXTRA_FILE.read_text(encoding="utf-8"))
except Exception:
return []
return []
def existing_urls() -> set:
urls = set()
try:
for s in json.loads((BASE / "sources.json").read_text(encoding="utf-8")):
urls.add(s["url"].lower())
except Exception:
pass
for s in load_extra():
urls.add(s["url"].lower())
return urls
def save_extra(items: list):
tmp = EXTRA_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(items, ensure_ascii=False, indent=1), encoding="utf-8")
os.replace(tmp, EXTRA_FILE)
def log(rec: dict):
with open(LOG, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
def collect_candidates(seeds_only: bool) -> list:
cands = [dict(s) for s in SEEDS]
if seeds_only:
return cands
try:
st = json.loads(DISCOVERY_STATE.read_text(encoding="utf-8"))
for s in st.get("found", []):
u = s.get("url", "")
if u.startswith("http") and "t.me" not in u and "github.com" not in u:
cands.append({"url": u, "topic": infer_topic(u, s.get("name", "")), "name": s.get("name", "")})
except Exception:
pass
for page in FEEDSPOT_PAGES:
try:
r = requests.get(page, headers=UA, timeout=15)
for u in re.findall(r"\*\*Forum\*\*\s*\[([^\]]+)\]\((https?://[^)]+)\)", r.text):
cands.append({"url": u[1], "topic": infer_topic(u[1], u[0]), "name": u[0]})
for u in re.findall(r"\[\w[^\]]*Forum[^\]]*\]\((https?://[^)]+)\)", r.text):
cands.append({"url": u, "topic": "cracking"})
except Exception:
pass
time.sleep(1)
return cands
def main():
dry = "--dry" in sys.argv
seeds_only = "--seeds-only" in sys.argv
max_add = 15
if "--max" in sys.argv:
max_add = int(sys.argv[sys.argv.index("--max") + 1])
extra = load_extra()
have_urls = existing_urls()
have_doms = {domain_of(u) for u in have_urls} | {domain_of(s["url"]) for s in extra}
cands = collect_candidates(seeds_only)
print(f"[promote] candidates: {len(cands)} | extra now: {len(extra)}")
added = 0
for c in cands:
if added >= max_add:
break
url = c["url"].split("?utm")[0].rstrip("#")
dom = domain_of(url)
if url.lower() in have_urls or dom in have_doms:
continue
alive, final, status = probe(url)
if not alive:
log({"at": datetime.now(timezone.utc).isoformat(), "url": url, "verdict": "DEAD", "status": status})
print(f" DEAD {status} {dom}")
continue
up = upgrade_url(final if final != url else url)
have_doms.add(dom)
have_urls.add(up.lower())
sid = re.sub(r"[^a-z0-9]+", "-", dom.replace(".", "-")).strip("-")[:40]
entry = {"id": f"auto-{sid}", "url": up, "topic": c.get("topic") or infer_topic(up, c.get("name", "")),
"auto": True, "added": datetime.now(timezone.utc).isoformat()[:10]}
log({"at": entry["added"], "url": url, "verdict": "PROMOTED", "final": up, "via": status})
print(f" ADD {dom} -> {up}")
if not dry:
extra.append(entry)
added += 1
time.sleep(0.5)
if not dry and added:
save_extra(extra)
print(f"[promote] {'(dry) ' if dry else ''}added: {added} | extra total: {len(extra)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())