mastodon-crawler: реализация — crawler/mastodon_crawler.py, источники mastodon (base_url+hashtag/lookup_acct), интеграция crawl_sources
- crawler/mastodon_crawler.py: публичная/хэштег/аккаунт-ленты (Mastodon API, httpx), пагинация max_id (первый запуск — свежая страница), дедуп по status.id, состояние mastodon_state (last_id, ошибки→dead), runs как mastodon:<slug>, 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 обновлён
This commit is contained in:
+86
-16
@@ -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/<tag> → {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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user