# VESTI — Mastodon-краулер (Mastodon API, httpx). # Читает источники sources.yaml с crawler: mastodon, ленты: # /timelines/tag/ | /timelines/public | /accounts/lookup + /accounts//statuses # Дедуп по (instance, status.id), состояние в mastodon_state, посты в posts. # # Запуск: # python -m crawler.mastodon_crawler --all # python -m crawler.mastodon_crawler --source fosstodon-selfhosting # python -m crawler.mastodon_crawler --source simon-willison --dry-run # печать без записи import argparse import datetime import logging import re import sys import time from pathlib import Path from urllib.parse import urlencode sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from config import RSS_DEFAULT_TIMEOUT, RSS_USER_AGENT, ensure_dirs from db.db import db from sources.sources import ( get_enabled_sources, get_source, load_sources_yaml, sync_sources_to_db, start_run, finish_run, ) logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") log = logging.getLogger("vesti.mastodon") MASTODON_TIMEOUT = RSS_DEFAULT_TIMEOUT MAX_PAGES = 5 # максимум страниц за запуск (пагинация max_id) PAGE_LIMIT = 40 # максимум статусов на страницу RATE_LIMIT_SEC = 1.5 # пауза между источниками (вежливый опрос) ERROR_DEAD_THRESHOLD = 5 # N ошибок подряд → status='dead' def _clean_html(html: str) -> str: """HTML статуса -> текст: selectolax (как rss_crawler), сохраняя абзацы/списки. #хэштеги и @упоминания остаются в тексте (классификатор решает); ссылки вырезаются из текста (у поста есть отдельный URL). """ from crawler.rss_crawler import html_to_text return html_to_text(html or "").strip() def _instance(base_url: str) -> str: """host инстанса из base_url (mastodon.social) — ключ mastodon_state.""" from urllib.parse import urlparse return urlparse(base_url).netloc.lower() def fetch_statuses(httpx_client, base_url: str, hashtag: str | None = None, account_id: str | None = None, max_id=None): """GET /api/v1/timelines/(tag/|public) или /accounts//statuses. ?limit=40[&max_id=...] -> list[dict] (статусы Mastodon). """ if account_id: path = f"/api/v1/accounts/{account_id}/statuses" elif hashtag: path = f"/api/v1/timelines/tag/{hashtag}" else: path = "/api/v1/timelines/public" params = {"limit": PAGE_LIMIT} if max_id: params["max_id"] = max_id url = base_url.rstrip("/") + path + "?" + urlencode(params) r = httpx_client.get(url) r.raise_for_status() data = r.json() return data if isinstance(data, list) else [] def lookup_account(httpx_client, base_url: str, acct: str) -> str | None: """GET /api/v1/accounts/lookup?acct= -> account['id'] (или None). Локальный аккаунт своего инстанса не всегда отвечает на полный user@instance (fedi.simonwillison.net 404, mastodon.social ок) — для acct=@ пробуем сначала голый username. """ candidates = [acct] if "@" in acct: user, instance = acct.split("@", 1) if user and instance.lower() == _instance(base_url): candidates.insert(0, user) for cand in candidates: url = base_url.rstrip("/") + "/api/v1/accounts/lookup?" + urlencode({"acct": cand}) r = httpx_client.get(url) if r.status_code == 404: continue r.raise_for_status() acc = r.json() if isinstance(acc, dict) and acc.get("id"): return acc["id"] return None def _status_url(status: dict, base_url: str) -> str: """Канонический URL статуса (status.url, иначе построить из base_url).""" u = status.get("url") if u: return u acct = status.get("account") or {} username = acct.get("acct", "unknown") or "unknown" if "@" in username: username = username.split("@")[0] sid = status.get("id") return f"{base_url.rstrip('/')}/@{username}/{sid}" def process_status(status: dict, base_url: str) -> dict | None: """Статус -> запись posts: {url, text, published_at, author}. Посты без текста (только медиа) -> None. """ if not isinstance(status, dict) or not status.get("id"): return None if status.get("reblog"): return None # репост (буст) чужого статуса — не создаём отдельный пост content = status.get("content") or "" text = _clean_html(content) if not text: return None # только медиа/пустой — не создаём acc = status.get("account") or {} author = acc.get("acct") or acc.get("username") or None if author and "@" not in author: author = f"{author}@{_instance(base_url)}" published_at = None if status.get("created_at"): try: published_at = datetime.datetime.fromisoformat( status["created_at"].replace("Z", "+00:00") ).isoformat() except Exception: published_at = None # Упоминания (@user@host) и хэштеги (#tag) в тексте смущают классификатор — # убираем их (спека: нормализация контента), ссылки остаются в url поста text = re.sub(r"@([a-zA-Z0-9_]+)@[a-zA-Z0-9_.-]+", r"@\1", text) # @user@host → @user text = re.sub(r"#([a-zA-Z0-9_]+)", r"\1", text) # #tag → tag return { "url": _status_url(status, base_url), "text": text, "published_at": published_at, "author": author, } def store_mastodon_posts(conn, source_id: int, instance: str, posts: list[dict]) -> int: """Вставка постов с дедупом по (instance, status.url). У Mastodon url статуса уникален в пределах инстанса; дополнительный дедуп по sha256(text) (как rss) ловит репосты одного текста. Возвращает new_count. """ import hashlib new = 0 # уже существующие URL этого инстанса (за прошлые запуски) seen = {r[0] for r in conn.execute( "SELECT url FROM posts WHERE source_id=? AND url LIKE ?", (source_id, f"https://{instance}/%"), ).fetchall()} for p in posts: purl = p["url"] if purl in seen: continue sha = hashlib.sha256((p["text"] or "").encode("utf-8", "ignore")).hexdigest() dup = conn.execute( "SELECT id FROM posts WHERE sha256=? OR url=?", (sha, purl), ).fetchone() if dup: seen.add(purl) continue conn.execute( """INSERT INTO posts (sha256, source_id, url, text, content_type, published_at, status, is_own, is_own_canonical) VALUES (?,?,?,?, 'text', ?, 'new', 0, 0)""", (sha, source_id, purl, p["text"], p["published_at"]), ) seen.add(purl) new += 1 return new def run_source(source, dry_run=False): """Краулинг одного Mastodon-источника: лента, пагинация, дедуп, состояние.""" slug = source["slug"] base_url = (source.get("base_url") or "").rstrip("/") if not base_url: log.error("SKIP %s: нет base_url (crawler=mastodon, а инстанс не задан)", slug) return instance = _instance(base_url) hashtag = (source.get("hashtag") or "").strip() or None lookup_acct = (source.get("lookup_acct") or "").strip() or None run_id = start_run(source["id"], f"mastodon:{slug}", "cron") t0 = time.monotonic() try: import httpx headers = {"User-Agent": RSS_USER_AGENT, "Accept": "application/json"} client = httpx.Client(headers=headers, timeout=MASTODON_TIMEOUT, follow_redirects=True) # account-лента: lookup → accounts//statuses account_id = None if lookup_acct: account_id = lookup_account(client, base_url, lookup_acct) if not account_id: raise RuntimeError(f"lookup_acct {lookup_acct} не найден на {instance}") with db() as conn: st = conn.execute( "SELECT * FROM mastodon_state WHERE instance=?", (instance,) ).fetchone() state = dict(st) if st else {} last_id = state.get("last_id") posts = [] first_page_id = None # самый свежий status.id из первой страницы → last_id max_id = None first_run = not last_id # первый запуск: только свежая страница (spec) for page in range(1 if first_run else MAX_PAGES): statuses = fetch_statuses(client, base_url, hashtag, account_id, max_id) if not statuses: break if first_page_id is None: first_page_id = str(statuses[0]["id"]) fresh = 0 for st_ in statuses: sid = str(st_.get("id")) if last_id and str(sid) <= str(last_id): # дошли до уже обработанных — новых больше нет fresh = 0 break p = process_status(st_, base_url) if p: posts.append(p) fresh += 1 if fresh == 0: break max_id = statuses[-1]["id"] # строго по убыванию id (новые→старые) — стоп по last_id корректен if last_id and str(max_id) <= str(last_id): break if dry_run: print(f"=== {slug} ({source['name']}) — dry_run, {len(posts)} постов ===") for p in posts[:15]: print(f" - {p['published_at'] or '????'} | {p['text'][:80]!r} | {p['url']}") if len(posts) > 15: print(f" ... и ещё {len(posts) - 15}") return with db() as conn: new = store_mastodon_posts(conn, source["id"], instance, posts) conn.execute( """INSERT INTO mastodon_state (instance, last_id, last_poll_at, status, error_count, last_error, updated_at) VALUES (?,?,datetime('now'),'alive',0,NULL,datetime('now')) ON CONFLICT(instance) DO UPDATE SET last_id=excluded.last_id, last_poll_at=excluded.last_poll_at, status='alive', error_count=0, last_error=NULL, updated_at=datetime('now')""", (instance, first_page_id), ) conn.execute( "UPDATE sources SET last_fetch=datetime('now'), status='alive', last_error=NULL WHERE id=?", (source["id"],), ) duration = int((time.monotonic() - t0) * 1000) finish_run(run_id, "ok", len(posts), new, None, duration) log.info("OK %s: fetched=%d new=%d (%.1fs)", slug, len(posts), new, duration / 1000) except Exception as e: duration = int((time.monotonic() - t0) * 1000) if not dry_run: with db() as conn: st = conn.execute( "SELECT error_count FROM mastodon_state WHERE instance=?", (instance,) ).fetchone() err_count = (st[0] if st else 0) + 1 status = "dead" if err_count >= ERROR_DEAD_THRESHOLD else "alive" conn.execute( """INSERT INTO mastodon_state (instance, last_error, error_count, status, updated_at) VALUES (?,?,?,?, datetime('now')) ON CONFLICT(instance) DO UPDATE SET last_error=excluded.last_error, error_count=excluded.error_count, status=excluded.status, updated_at=datetime('now')""", (instance, str(e)[:500], err_count, status), ) conn.execute( "UPDATE sources SET last_error=?, status=? WHERE id=?", (str(e)[:500], status, source["id"]), ) finish_run(run_id, "error", 0, 0, str(e)[:500], duration) log.error("ERROR %s: %s", slug, e) def main(): ap = argparse.ArgumentParser(description="VESTI Mastodon crawler") ap.add_argument("--source", help="slug источника (например fosstodon-selfhosting)") ap.add_argument("--direction", help="направление (например llm)") ap.add_argument("--all", action="store_true", help="все включённые mastodon-источники") ap.add_argument("--dry-run", action="store_true", help="печать постов без записи в БД") args = ap.parse_args() ensure_dirs() data = load_sources_yaml() sync_sources_to_db(data) if args.source: src = get_source(args.source) if not src: log.error("source %s not found", args.source) sys.exit(1) sources = [src] elif args.direction: sources = get_enabled_sources(crawler="mastodon", direction=args.direction) else: sources = get_enabled_sources(crawler="mastodon") if not sources: log.info("no mastodon sources to crawl") return for src in sources: run_source(src, dry_run=args.dry_run) time.sleep(RATE_LIMIT_SEC) if __name__ == "__main__": main()