From 4b641774b8084702c662d556693c0251dfa33e05 Mon Sep 17 00:00:00 2001 From: kpa39l Date: Sat, 3 Oct 2026 13:35:07 +0000 Subject: [PATCH] =?UTF-8?q?mastodon-crawler:=20=D1=80=D0=B5=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=E2=80=94=20crawler/mast?= =?UTF-8?q?odon=5Fcrawler.py,=20=D0=B8=D1=81=D1=82=D0=BE=D1=87=D0=BD=D0=B8?= =?UTF-8?q?=D0=BA=D0=B8=20mastodon=20(base=5Furl+hashtag/lookup=5Facct),?= =?UTF-8?q?=20=D0=B8=D0=BD=D1=82=D0=B5=D0=B3=D1=80=D0=B0=D1=86=D0=B8=D1=8F?= =?UTF-8?q?=20crawl=5Fsources?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - crawler/mastodon_crawler.py: публичная/хэштег/аккаунт-ленты (Mastodon API, httpx), пагинация max_id (первый запуск — свежая страница), дедуп по status.id, состояние mastodon_state (last_id, ошибки→dead), runs как mastodon:, CLI --all/--source/--dry-run - sources.py: валидация crawler=mastodon + base_url, sync/CRUD/normalize новых полей, parse_address_mastodon (инстанс/тег/аккаунт), delete_source чистит mastodon_state - sources.yaml: 6 примеров mastodon-источников (enabled: false) - classifier/keywords.py: SOURCE_RULES для mastodon-источников - crawl_sources.py: --crawler mastodon - db/schema.sql+db.py: колонки base_url/hashtag/lookup_acct в sources, таблица mastodon_state (db/ в .gitignore — применяется локально) - tasks.md: все [x]; STATUS.md обновлён --- STATUS.md | 2 +- classifier/keywords.py | 7 + crawler/crawl_sources.py | 4 +- crawler/mastodon_crawler.py | 333 +++++++++++++++++++++ openspec/changes/mastodon-crawler/tasks.md | 24 +- sources/sources.py | 102 ++++++- sources/sources.yaml | 107 ++++++- 7 files changed, 535 insertions(+), 44 deletions(-) create mode 100644 crawler/mastodon_crawler.py diff --git a/STATUS.md b/STATUS.md index 8799bb4..32563e2 100644 --- a/STATUS.md +++ b/STATUS.md @@ -47,7 +47,7 @@ ## Текущее состояние - **OPML-ИМПОРТ РЕАЛИЗОВАН И ЗАКОММИЧЕН** (2026-10-03, change opml-import, коммит 018e5c7): `sources/opml.py` парсит OPML через `xml.etree.ElementTree` (без новых зависимостей), вытаскивает только элементы с `xmlUrl` (папки игнорируются), новым источникам присваивается `crawler: rss`, slug из title, **`enabled: false` по умолчанию** (безопасный импорт, `--enable` включает). Дедуп по нормализованному `feed_url` (повторный импорт дублей не создаёт). CLI: `python -m sources.opml import [--direction] [--lang] [--priority] [--enable] [--dry-run]`. Отчёт: распознано/пропущено/добавлено/дубликатов. Тест на /tmp/vesti-test-opml.opml: dry-run → «добавлено: 1, дубликатов: 3» (lwn/HF уже в реестре); реальный импорт в temp yaml → запись opennet c enabled: false, direction: linux; повторный импорт → 0 добавлено, 4 дубликата. Change валиден. Закоммичен (018e5c7, вместе с mastodon-crawler). -- **MASTODON-CRAWLER — ПЛАН** (2026-10-03, change mastodon-crawler создан, валиден, закоммичен 018e5c7): сбор постов из федеверса через **Mastodon API** (решение зафиксировано): `GET /api/v1/timelines/public` (публичная лента инстанса), `GET /api/v1/timelines/tag/` (тематические ленты, аналог каналов TG) и **`GET /api/v1/accounts/lookup` + `GET /api/v1/accounts//statuses`** (ленты конкретных аккаунтов — аналог авторов/каналов). Новый тип источника `crawler: mastodon` (base_url + hashtag / lookup_acct). Пагинация max_id, дедуп по status.id, состояние в mastodon_state, посты в общий конвейер. **Примеры аккаунтов по LLM/ИИ (от пользователя 2026-10-03, «с кого собирать новости»):** @simon@fedi.simonwillison.net (Simon Willison), @SebRaschka@mastodon.social (Sebastian Raschka), @stroughtonsmith@mastodon.social (Steve Troughton-Smith), @Edent@mastodon.social (Terence Eden). **mastodon.py НЕ нужен** — для чтения публичных лент достаточно httpx (уже в requirements.txt); библиотека тянет requests и осмысленна только для постинга. Аналог TGStat — FediDB (fedidb.com), но по инстансам (пользователи/софт), не по аккаунтам: в fediverse нет глобального каталога аккаунтов. Реализация не начата (tasks все `[ ]`). +- **MASTODON-CRAWLER РЕАЛИЗОВАН** (2026-10-03, change mastodon-crawler, tasks все `[x]`): сбор постов из федеверса через **Mastodon API**: `GET /api/v1/timelines/public`, `GET /api/v1/timelines/tag/` (тематические ленты) и `GET /api/v1/accounts/lookup` + `GET /api/v1/accounts//statuses` (ленты аккаунтов). Новый тип источника `crawler: mastodon` (base_url + hashtag / lookup_acct). Пагинация max_id (первый запуск — только свежая страница), дедуп по status.id, состояние в mastodon_state (last_id/last_poll_at/error→dead). Посты в общий конвейер. Модуль `crawler/mastodon_crawler.py` (CLI: `--all / --source / --dry-run`), интеграция в `crawl_sources --crawler mastodon`. Примеры аккаунтов: @simon@fedi.simonwillison.net, @SebRaschka@mastodon.social, @stroughtonsmith@mastodon.social, @Edent@mastodon.social (с 2026-10-03, «с кого собирать новости»). Проверено на реальных инстансах: mastodon.social #linux (200 постов), Simon Willison аккаунт-лента (200→инкремент 0), lookup fallback на голый username для локальных аккаунтов (fedi.simonwillison.net). mastodon.py НЕ нужен (httpx достаточно). - **RSS-ИСТОЧНИКИ HUGGING FACE ДОБАВЛЕНЫ** (2026-09-20, change add-huggingface-rss): `huggingface-blog` (https://huggingface.co/blog/feed.xml — официальный блог: релизы моделей, гайды fine-tuning) и `huggingface-papers` (Daily Papers). Важно: официальный `https://huggingface.co/papers.rss` отвечает 404 (HF закрыл ленту Papers), поэтому Daily Papers подключён через рабочих сторонний `https://papers.takara.ai/api/feed` (200, суточные резюме arXiv). Оба — crawler: rss, direction: llm, lang: en, enabled: true, priority P1. Синк в БД, сухие прогоны краулера: посты читаются (Granite 4.2, Gradio-гайд, arXiv-статьи). vesti-web перезапущен (HTTP 200). Зависимость от papers.takara.ai — внешняя, при его падении обновится только блог. - **ПРИНЯТЫ В КОНТЕКСТ НЕЗАКОММИЧЕННЫЕ НАРАБОТКИ** (2026-09-20, проверена реализация): - **extract-post-sources** — backend готов и в HEAD: `sources/extract.py` (extract_sources_from_text: Telegram-каналы + сайты, дедуп, лимит 5), `_post_sources` в app.py, `POST /sources/add-from-post`. **Остаток**: блок «Источники из поста» в candidates.html/selected.html НЕ добавлен (задача 4 в tasks.md открыта). Change валиден. diff --git a/classifier/keywords.py b/classifier/keywords.py index 0c827dc..ad5ccb4 100644 --- a/classifier/keywords.py +++ b/classifier/keywords.py @@ -98,6 +98,13 @@ DEFAULT_DIRECTION = "linux" # прототип: все посты про linux # LWN — технологическое СМИ: весь контент → tech. SOURCE_RULES: dict[str, list[str]] = { "lwn": ["tech"], + # mastodon: принудительное направление по тематике ленты/аккаунта + "mastodon-social-linux": ["linux"], + "fosstodon-selfhosting": ["tech"], + "simon-willison": ["llm"], + "sebastian-raschka": ["llm"], + "stroughtonsmith": ["llm"], + "terence-eden": ["llm"], } diff --git a/crawler/crawl_sources.py b/crawler/crawl_sources.py index ac3c3d6..e303a69 100644 --- a/crawler/crawl_sources.py +++ b/crawler/crawl_sources.py @@ -24,7 +24,7 @@ def run_crawler(mod: str, extra: list[str] | None = None) -> int: def main(): ap = argparse.ArgumentParser(description="VESTI фаза 1: сбор кандидатов с источников в очередь") ap.add_argument("--all", action="store_true", help="сбор со всех включённых краулеров") - ap.add_argument("--crawler", choices=["telegram", "rss"], help="только один тип краулера") + ap.add_argument("--crawler", choices=["telegram", "rss", "mastodon"], help="только один тип краулера") args = ap.parse_args() if not args.all and not args.crawler: @@ -36,6 +36,8 @@ def main(): rc |= run_crawler("crawler.telegram_crawler", ["--all"]) if args.all or args.crawler == "rss": rc |= run_crawler("crawler.rss_crawler", ["--all"]) + if args.all or args.crawler == "mastodon": + rc |= run_crawler("crawler.mastodon_crawler", ["--all"]) sys.exit(rc) diff --git a/crawler/mastodon_crawler.py b/crawler/mastodon_crawler.py new file mode 100644 index 0000000..7ea28d8 --- /dev/null +++ b/crawler/mastodon_crawler.py @@ -0,0 +1,333 @@ +# 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() \ No newline at end of file diff --git a/openspec/changes/mastodon-crawler/tasks.md b/openspec/changes/mastodon-crawler/tasks.md index 1d66f66..ddad9e7 100644 --- a/openspec/changes/mastodon-crawler/tasks.md +++ b/openspec/changes/mastodon-crawler/tasks.md @@ -1,19 +1,19 @@ # tasks ## Схема и конфиг -- [ ] db/schema.sql: + CREATE TABLE mastodon_state; db/db.py — миграция -- [ ] sources.yaml: поддержка crawler: mastodon (base_url, hashtag) в синке/валидации -- [ ] classifier/keywords.py: SOURCE_RULES для тегов (по необходимости) +- [x] db/schema.sql: + CREATE TABLE mastodon_state; db/db.py — миграция +- [x] sources.yaml: поддержка crawler: mastodon (base_url, hashtag) в синке/валидации +- [x] classifier/keywords.py: SOURCE_RULES для тегов (по необходимости) ## Модуль краулера -- [ ] crawler/mastodon_crawler.py: _clean_html (HTML→текст), fetch_statuses (timelines/tag|public), process_status, crawl_source -- [ ] Пагинация max_id + дедуп по (instance, status.id) / sha256 url -- [ ] mastodon_state: чтение last_id, обновление после прогона, ошибки→status dead -- [ ] CLI: --all / --source / --dry-run; запуски в runs (mastodon:) -- [ ] Account-ленты: lookup_acct в источнике → GET /api/v1/accounts/lookup → /accounts//statuses (примеры 4 авторов по LLM/ИИ из proposal) +- [x] crawler/mastodon_crawler.py: _clean_html (HTML→текст), fetch_statuses (timelines/tag|public), process_status, crawl_source +- [x] Пагинация max_id + дедуп по (instance, status.id) / sha256 url +- [x] mastodon_state: чтение last_id, обновление после прогона, ошибки→status dead +- [x] CLI: --all / --source / --dry-run; запуски в runs (mastodon:) +- [x] Account-ленты: lookup_acct в источнике → GET /api/v1/accounts/lookup → /accounts//statuses (примеры 4 авторов по LLM/ИИ из proposal) ## Проверка -- [ ] Сухой прогон на реальном инстансе (mastodon.social/tag/linux) — посты читаются -- [ ] Импорт постов в общий конвейер (классификация/кандидаты) -- [ ] openspec validate mastodon-crawler — чисто -- [ ] Обновить STATUS.md / TODO.md +- [x] Сухой прогон на реальном инстансе (mastodon.social/tag/linux) — посты читаются +- [x] Импорт постов в общий конвейер (классификация/кандидаты) +- [x] openspec validate mastodon-crawler — чисто +- [x] Обновить STATUS.md / TODO.md \ No newline at end of file diff --git a/sources/sources.py b/sources/sources.py index c52a57a..5add35b 100644 --- a/sources/sources.py +++ b/sources/sources.py @@ -32,20 +32,23 @@ def sync_sources_to_db(data=None): if not slug: continue cur = conn.execute( - """INSERT INTO sources (slug, name, url, channel, crawler, feed_url, direction, lang, priority, enabled, status, own) - VALUES (?,?,?,?,?,?,?,?,?,?, 'new', ?) - ON CONFLICT(slug) DO UPDATE SET - name=excluded.name, url=excluded.url, channel=excluded.channel, - crawler=excluded.crawler, feed_url=excluded.feed_url, - direction=excluded.direction, - lang=excluded.lang, priority=excluded.priority, enabled=excluded.enabled, - own=excluded.own""", - (slug, s.get("name"), s.get("url"), s.get("channel"), - s.get("crawler", "telegram"), s.get("feed_url"), - s.get("direction"), s.get("lang", "ru"), - s.get("priority", "P1"), int(s.get("enabled", True)), - int(s.get("own", False) or 0)), - ) + """INSERT INTO sources (slug, name, url, channel, crawler, feed_url, base_url, hashtag, lookup_acct, direction, lang, priority, enabled, status, own) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?, 'new', ?) + ON CONFLICT(slug) DO UPDATE SET + name=excluded.name, url=excluded.url, channel=excluded.channel, + crawler=excluded.crawler, feed_url=excluded.feed_url, + base_url=excluded.base_url, hashtag=excluded.hashtag, + lookup_acct=excluded.lookup_acct, + direction=excluded.direction, + lang=excluded.lang, priority=excluded.priority, enabled=excluded.enabled, + own=excluded.own""", + (slug, s.get("name"), s.get("url"), s.get("channel"), + s.get("crawler", "telegram"), s.get("feed_url"), + s.get("base_url"), s.get("hashtag"), s.get("lookup_acct"), + s.get("direction"), s.get("lang", "ru"), + s.get("priority", "P1"), int(s.get("enabled", True)), + int(s.get("own", False) or 0)), + ) mapping[slug] = cur.lastrowid return mapping @@ -181,6 +184,9 @@ def db_source_to_yaml(source: dict) -> dict: "channel": source.get("channel"), "crawler": source.get("crawler", "telegram"), "feed_url": source.get("feed_url"), + "base_url": source.get("base_url"), + "hashtag": source.get("hashtag"), + "lookup_acct": source.get("lookup_acct"), "direction": source.get("direction"), "lang": source.get("lang", "ru"), "priority": source.get("priority", "P1"), @@ -229,6 +235,8 @@ def parse_address(address: str, crawler: str) -> dict: return {} handle = m.group(1) return {"slug": handle, "channel": handle, "url": f"https://t.me/{handle}"} + if crawler == "mastodon": + return parse_address_mastodon(addr) # rss if not _RSS_URL_RE.match(addr): return {} @@ -237,19 +245,69 @@ def parse_address(address: str, crawler: str) -> dict: return {"feed_url": addr, "url": addr, "slug": host} +_MASTODON_TAG_RE = re.compile(r"^https?://([^/]+)/tags/([a-zA-Z0-9_]+)/?$") +_MASTODON_ACCT_RE = re.compile(r"^@?([a-zA-Z0-9_]+)@([a-zA-Z0-9_.-]+)$") + + +def parse_address_mastodon(addr: str) -> dict: + """Разбирает address для crawler=mastodon. + + https://host/tags/ → {base_url, hashtag, url, slug: host-tag} + https://host/@user [@instance] → account-лента (lookup_acct = user@host) + https://host → публичная лента, slug = host + @user@host | user@host → account-лента (lookup_acct) + Возвращает {} если не разобрано. + """ + addr = (addr or "").strip() + if not addr: + return {} + base = addr.rstrip("/") + m = _MASTODON_TAG_RE.match(addr) + if m: + host, tag = m.group(1), m.group(2).lower() + return { + "base_url": f"https://{host}", + "hashtag": tag, + "url": addr, + "slug": f"{host.split('.')[0]}-{tag}", + } + if addr.startswith(("http://", "https://")): + from urllib.parse import urlparse + host = urlparse(base).netloc + if not host: + return {} + # https://host/@user — account-лента + m2 = re.match(r"^https?://([^/]+)/@([a-zA-Z0-9_]+)/?$", addr) + if m2: + acct = f"{m2.group(2)}@{m2.group(1)}" + return {"base_url": f"https://{m2.group(1)}", "lookup_acct": acct, + "url": addr, "slug": f"{m2.group(1).split('.')[0]}-{m2.group(2)}"} + return {"base_url": f"https://{host}", "url": addr, + "slug": host.split(".")[0] or "mastodon"} + m3 = _MASTODON_ACCT_RE.match(addr) + if m3: + user, instance = m3.group(1), m3.group(2) + acct = f"{user}@{instance}" + return {"base_url": f"https://{instance}", "lookup_acct": acct, + "url": f"https://{instance}/@{user}", "slug": f"{instance.split('.')[0]}-{user}"} + return {} + + def _validate_source(data: dict) -> str | None: """Валидация полей источника. Возвращает текст ошибки или None.""" slug = str(data.get("slug") or "").strip() if not slug or not _SLUG_RE.match(slug): return "slug: только [a-z0-9_-]" - if data.get("crawler", "telegram") not in ("telegram", "rss"): - return 'crawler: только "telegram" или "rss"' + if data.get("crawler", "telegram") not in ("telegram", "rss", "mastodon"): + return 'crawler: только "telegram", "rss" или "mastodon"' if str(data.get("priority", "P1")) not in ("P0", "P1", "P2", "P3"): return "priority: только P0..P3" if data.get("crawler") == "rss" and not str(data.get("feed_url") or "").strip(): return "rss-источнику нужен feed_url" if data.get("crawler") == "telegram" and not str(data.get("channel") or "").strip(): return "telegram-источнику нужен channel" + if data.get("crawler") == "mastodon" and not str(data.get("base_url") or "").startswith(("http://", "https://")): + return "mastodon-источнику нужен base_url (https://инстанс)" return None @@ -269,6 +327,9 @@ def add_or_update_source(data: dict) -> tuple[bool, str]: "channel": (data.get("channel") or "").strip() or None, "crawler": data.get("crawler", "telegram"), "feed_url": (data.get("feed_url") or "").strip() or None, + "base_url": (data.get("base_url") or "").strip() or None, + "hashtag": (data.get("hashtag") or "").strip() or None, + "lookup_acct": (data.get("lookup_acct") or "").strip() or None, "direction": (data.get("direction") or "").strip() or None, "lang": (data.get("lang") or "ru").strip() or "ru", "priority": str(data.get("priority", "P1")).upper(), @@ -289,6 +350,15 @@ def delete_source(slug: str) -> bool: conn.execute("UPDATE posts SET source_id=NULL WHERE source_id=(SELECT id FROM sources WHERE slug=?)", (slug,)) conn.execute("UPDATE runs SET source_id=NULL WHERE source_id=(SELECT id FROM sources WHERE slug=?)", (slug,)) conn.execute("DELETE FROM rss_state WHERE slug=?", (slug,)) + # mastodon_state ключуется по инстансу (base_url) — удаляем только если + # ни один оставшийся источник больше не использует этот инстанс + conn.execute( + """DELETE FROM mastodon_state WHERE instance IN ( + SELECT base_url FROM sources WHERE slug=? + AND NOT EXISTS (SELECT 1 FROM sources s2 WHERE s2.base_url=sources.base_url AND s2.slug<>?) + )""", + (slug, slug), + ) conn.execute("DELETE FROM sources WHERE slug=?", (slug,)) return True diff --git a/sources/sources.yaml b/sources/sources.yaml index 53315cf..028f885 100644 --- a/sources/sources.yaml +++ b/sources/sources.yaml @@ -81,6 +81,31 @@ priority: P1 enabled: true notes: git/devops — смежный с linux +- slug: huggingface-blog + name: Hugging Face Blog + url: https://huggingface.co/blog + channel: null + crawler: rss + feed_url: https://huggingface.co/blog/feed.xml + direction: llm + lang: en + priority: P1 + enabled: true + own: false + notes: официальный блог HF — релизы моделей, гайды fine-tuning, новости платформы +- slug: huggingface-papers + name: Hugging Face Daily Papers + url: https://huggingface.co/papers + channel: null + crawler: rss + feed_url: https://papers.takara.ai/api/feed + direction: llm + lang: en + priority: P1 + enabled: true + own: false + notes: ежедневная кураторская лента научных статей (arXiv-препринты, комментарии + сообщества) — официальный /papers.rss 404, используется сторонний papers.takara.ai - slug: krxnotes name: KRX Notes url: https://t.me/krxnotes @@ -128,6 +153,32 @@ priority: P1 enabled: true own: false +- slug: fosstodon-selfhosting + name: Fosstodon + url: https://fosstodon.org/tags/selfhosting + channel: null + crawler: mastodon + base_url: https://fosstodon.org + hashtag: selfhosting + feed_url: null + direction: tech + lang: en + priority: P1 + enabled: false + own: false +- slug: mastodon-social-linux + name: mastodon.social + url: https://mastodon.social/tags/linux + channel: null + crawler: mastodon + base_url: https://mastodon.social + hashtag: linux + feed_url: null + direction: linux + lang: en + priority: P1 + enabled: false + own: false - slug: omarchy name: omarchy url: https://omarchy.org/ @@ -139,30 +190,58 @@ priority: P1 enabled: false own: false -- slug: huggingface-blog - name: Hugging Face Blog - url: https://huggingface.co/blog +- slug: sebastian-raschka + name: Sebastian Raschka (fedi) + url: https://mastodon.social/@SebRaschka channel: null - crawler: rss - feed_url: https://huggingface.co/blog/feed.xml + crawler: mastodon + base_url: https://mastodon.social + lookup_acct: SebRaschka@mastodon.social + feed_url: null direction: llm lang: en priority: P1 - enabled: true + enabled: false own: false - notes: официальный блог HF — релизы моделей, гайды fine-tuning, новости платформы -- slug: huggingface-papers - name: Hugging Face Daily Papers - url: https://huggingface.co/papers +- slug: simon-willison + name: Simon Willison (fedi) + url: https://fedi.simonwillison.net/@simon channel: null - crawler: rss - feed_url: https://papers.takara.ai/api/feed + crawler: mastodon + base_url: https://fedi.simonwillison.net + lookup_acct: simon@fedi.simonwillison.net + feed_url: null direction: llm lang: en priority: P1 - enabled: true + enabled: false + own: false +- slug: stroughtonsmith + name: Steve Troughton-Smith (fedi) + url: https://mastodon.social/@stroughtonsmith + channel: null + crawler: mastodon + base_url: https://mastodon.social + lookup_acct: stroughtonsmith@mastodon.social + feed_url: null + direction: llm + lang: en + priority: P1 + enabled: false + own: false +- slug: terence-eden + name: Terence Eden (fedi) + url: https://mastodon.social/@Edent + channel: null + crawler: mastodon + base_url: https://mastodon.social + lookup_acct: Edent@mastodon.social + feed_url: null + direction: llm + lang: en + priority: P1 + enabled: false own: false - notes: ежедневная кураторская лента научных статей (arXiv-препринты, комментарии сообщества) — официальный /papers.rss 404, используется сторонний papers.takara.ai # Пример (включить, раскомментировав и поправив direction/приоритет): # - slug: opennet