79 lines
3.4 KiB
Python
79 lines
3.4 KiB
Python
"""Self-growth: из собранных ссылок находит новые борды и проверяет, живой ли парсер.
|
|
|
|
Логика: берём домены из items -> пробуем типовые машинные точки входа ->
|
|
если распарсили записи, добавляем источник в базу. Мёртвое не добавляем.
|
|
"""
|
|
import re
|
|
from collections import Counter
|
|
from urllib.parse import urlparse
|
|
|
|
from . import adapters, fetch, store
|
|
|
|
PROBES = [
|
|
"/latest.json", "/top.json", "/latest", "/syndication.php", "/forums/-/index.rss",
|
|
"/feed", "/rss", "/rss.xml", "/atom.xml", "/index.php?act=rssout&id=1", "/api/topics/hot.json",
|
|
]
|
|
SKIP_HOSTS = re.compile(
|
|
r"(github\.com|githubusercontent|t\.me|telegram\.|youtube\.|youtu\.be|twitter\.com|x\.com|"
|
|
r"google\.|cloudflare|jsdelivr|imgur|cdn|static\.|fonts\.|googletagmanager|doubleclick)", re.I)
|
|
|
|
|
|
def candidate_hosts(con, limit: int = 40):
|
|
rows = con.execute("SELECT url FROM items ORDER BY id DESC LIMIT 5000").fetchall()
|
|
host = Counter()
|
|
for r in rows:
|
|
h = urlparse(r["url"]).netloc.lower()
|
|
if not h or SKIP_HOSTS.search(h):
|
|
continue
|
|
host[h] += 1
|
|
known = {urlparse(r["url"]).netloc.lower() for r in con.execute("SELECT url FROM sources")}
|
|
base = {urlparse(r["url"]).netloc.lower().lstrip("www.") for r in con.execute("SELECT url FROM sources")}
|
|
out = []
|
|
for h, n in host.most_common(limit * 3):
|
|
if h in known or h.lstrip("www.") in base:
|
|
continue
|
|
out.append((h, n))
|
|
return out[:limit]
|
|
|
|
|
|
def probe_host(host: str, s=None, max_probes: int = 6):
|
|
"""Возвращает (url, adapter, items) первого рабочего эндпоинта или None."""
|
|
s = s or __import__("imba.config", fromlist=["settings"]).settings()
|
|
for path in PROBES[:max_probes]:
|
|
url = f"https://{host}{path}"
|
|
r = fetch.fetch(url, s)
|
|
if not r.ok:
|
|
continue
|
|
items = adapters.parse(url, r.text, r.headers)
|
|
if len(items) >= 3:
|
|
return url, adapters.detect(url, r.text, r.headers), items
|
|
return None
|
|
|
|
|
|
def discover(con, limit: int = 12, workers: int = 8, verbose: bool = True):
|
|
import concurrent.futures
|
|
s = __import__("imba.config", fromlist=["settings"]).settings()
|
|
hosts = candidate_hosts(con, limit)
|
|
added = []
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
|
|
futs = {ex.submit(probe_host, h, s): h for h, _ in hosts}
|
|
for fut in concurrent.futures.as_completed(futs):
|
|
host = futs[fut]
|
|
try:
|
|
res = fut.result()
|
|
except Exception as e:
|
|
if verbose:
|
|
print(f" {host}: error {type(e).__name__}")
|
|
continue
|
|
if not res:
|
|
if verbose:
|
|
print(f" {host}: нет машинной точки входа")
|
|
continue
|
|
url, adapter, items = res
|
|
if store.add_source(con, host, url, adapter, note=f"auto:{len(items)} items"):
|
|
con.execute("UPDATE sources SET ok=1, last_ok=datetime('now'), last_status=200 WHERE name=?", (host,))
|
|
con.commit()
|
|
added.append((host, url, adapter, len(items)))
|
|
if verbose:
|
|
print(f" + {host} [{adapter}] {len(items)} записей: {url}")
|
|
return added |