ed9d5b9370
- proposal/design/tasks: lookup_acct → GET /api/v1/accounts/lookup → /accounts/<id>/statuses;
примеры: @simon@fedi.simonwillison.net, @SebRaschka@mastodon.social,
@stroughtonsmith@mastodon.social, @Edent@mastodon.social (даны пользователем 2026-10-03)
- WALKTHROUGH: хронология 2026-09-20 (HF RSS) и 2026-10-03 (OPML + mastodon)
- STATUS/TODO: OPML закрыта (018e5c7), mastodon-crawler — открыта (план)
127 lines
4.8 KiB
Markdown
127 lines
4.8 KiB
Markdown
# design: mastodon-crawler
|
|
|
|
## Схема
|
|
|
|
```sql
|
|
-- db/schema.sql (миграция ALTER, как rss_state)
|
|
CREATE TABLE mastodon_state (
|
|
instance TEXT PRIMARY KEY, -- host (напр. mastodon.social)
|
|
last_id TEXT, -- последний обработанный status.id
|
|
last_poll_at TEXT, -- ISO-время
|
|
status TEXT DEFAULT 'alive',
|
|
error_count INTEGER DEFAULT 0,
|
|
last_error TEXT
|
|
);
|
|
```
|
|
|
|
## sources.yaml — новый тип источника
|
|
|
|
```yaml
|
|
- slug: fosstodon-selfhosting # crawl_sources: mastodon
|
|
name: Fosstodon #selfhosting
|
|
url: https://fosstodon.org/tags/selfhosting
|
|
crawler: mastodon
|
|
base_url: https://fosstodon.org # инстанс
|
|
hashtag: selfhosting # опц. — хэштег-лента
|
|
feed_url: null # не используется для mastodon
|
|
direction: tech
|
|
lang: en
|
|
priority: P1
|
|
enabled: true
|
|
own: false
|
|
```
|
|
|
|
Для публичной ленты всего инстанса: `hashtag: null` (или отсутствует).
|
|
|
|
Для account-ленты (посты конкретного автора): `lookup_acct`.
|
|
|
|
```yaml
|
|
- slug: simon-willison # аккаунт — аналог автора/канала
|
|
name: Simon Willison (fedi)
|
|
url: https://fedi.simonwillison.net/@simon
|
|
crawler: mastodon
|
|
base_url: https://fedi.simonwillison.net # инстанс аккаунта
|
|
lookup_acct: simon@fedi.simonwillison.net # lookup → /api/v1/accounts/<id>/statuses
|
|
direction: llm
|
|
lang: en
|
|
priority: P1
|
|
enabled: false
|
|
own: false
|
|
```
|
|
|
|
## crawler/mastodon_crawler.py (по образцу rss_crawler)
|
|
|
|
```python
|
|
# VESTI — Mastodon-краулер (Mastodon API, httpx).
|
|
# Читает источники sources.yaml crawler: mastodon, ленты:
|
|
# /timelines/tag/<tag> | /timelines/public | /accounts/lookup + /accounts/<id>/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 x --dry-run
|
|
|
|
MASTODON_TIMEOUT = 20
|
|
MAX_PAGES = 5 # максимум страниц за запуск (пагинация max_id)
|
|
PAGE_LIMIT = 40 # максимум статусов на страницу
|
|
RATE_LIMIT_SEC = 1.5 # пауза между источниками
|
|
|
|
def _clean_html(html: str) -> str:
|
|
"""HTML статуса -> текст: selectolax/bleach (как rss_crawler), убрать теги."""
|
|
# <p>, <a>, <br> -> текст; #хэштеги и @упоминания остаются (классификатор решает)
|
|
|
|
async def fetch_statuses(httpx_client, base_url: str, hashtag: str | None, account_id: str | None, max_id=None):
|
|
"""GET /api/v1/timelines/(tag/<tag>|public) или /accounts/<id>/statuses
|
|
?limit=40[&max_id=...] -> list[dict]."""
|
|
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"
|
|
...
|
|
|
|
def lookup_account(httpx_client, base_url: str, acct: str) -> str | None:
|
|
"""GET /api/v1/accounts/lookup?acct=<acct> -> account['id'] (или None)."""
|
|
|
|
def process_status(status: dict, base_url: str) -> dict | None:
|
|
"""Статус -> запись posts: {url, title, text, published_at, author}."""
|
|
# url = status['url'] or f"{base_url}/@{acct}/{id}"
|
|
# content -> _clean_html; если пусто (только медиа) -> None
|
|
...
|
|
|
|
def crawl_source(slug, source, dry_run=False):
|
|
"""Один источник: пагинация, дедуп, вставка, обновление mastodon_state."""
|
|
# if source.get('lookup_acct'): account_id = lookup_account(...) (кеш не нужен, редко)
|
|
# state = SELECT * FROM mastodon_state WHERE instance=host
|
|
# while page < MAX_PAGES:
|
|
# statuses = fetch_statuses(...)
|
|
# for st in statuses: process_status -> insert (sha256-дедуп по url/posts)
|
|
# if not statuses or all(id <= last_id): break
|
|
# max_id = statuses[-1]['id']
|
|
# update mastodon_state (last_id, last_poll_at, status='alive')
|
|
```
|
|
|
|
## Классификатор (SOURCE_RULES)
|
|
|
|
```python
|
|
# classifier/keywords.py
|
|
SOURCE_RULES = {
|
|
"lwn": ["tech"],
|
|
"fosstodon-selfhosting": ["tech"], # тематика хэштега -> направление
|
|
"mastodon-social-linux": ["linux"],
|
|
}
|
|
```
|
|
|
|
## Проверка
|
|
|
|
```bash
|
|
# dry-run (без записи):
|
|
.venv/bin/python -m crawler.mastodon_crawler --source fosstodon-selfhosting --dry-run
|
|
# прод:
|
|
.venv/bin/python -m crawler.mastodon_crawler --all
|
|
# в БД:
|
|
SELECT slug, crawler, base_url, hashtag, direction FROM sources WHERE crawler='mastodon';
|
|
SELECT * FROM mastodon_state;
|
|
``` |