018e5c715b
- sources/opml.py: парсинг OPML (xml.etree, без зависимостей), CLI import, новые источники enabled:false по умолчанию, дедуп по нормализованному feed_url - change opml-import: реализован и протестирован (dry-run, temp yaml, повторный импорт) - change mastodon-crawler: план — сбор из федеверса через Mastodon API (public timeline + hashtag-ленты), mastodon.py не нужен (httpx)
5.8 KiB
5.8 KiB
design: opml-import
Новый модуль sources/opml.py
# VESTI — импорт подписок из OPML (xml.etree, без новых зависимостей).
# CLI: python -m sources.opml import <file.opml> [--direction DIR] [--lang LANG]
# [--priority P0|P1|P2|P3] [--enable] [--dry-run]
import argparse
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from urllib.parse import urlparse
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from sources.sources import upsert_source_yaml, sync_sources_to_db, load_sources_yaml
DEFAULT_PRIORITY = "P1"
DEFAULT_LANG = "ru"
def _slugify(title: str, url: str) -> str:
"""Генерирует slug из title (или host url): нижний регистр, [a-z0-9_-]."""
base = (title or url or "source").lower().strip()
slug = re.sub(r"[^a-z0-9]+", "-", base).strip("-")[:40].strip("-")
if not slug:
host = urlparse(url).netloc.replace(".", "-")
slug = host[:40].strip("-") or "source"
return slug
def _normalize_feed_url(feed_url: str) -> str:
"""Нормализация для дедупа: strip, схема+host в нижний регистр."""
u = urlparse(feed_url.strip())
return f"{u.scheme.lower()}://{u.netloc.lower()}{u.path}"
def parse_opml(path: Path) -> list[dict]:
"""Возвращает [{'title':..., 'url':..., 'feed_url':...}], только xmlUrl-элементы."""
tree = ET.parse(path)
root = tree.getroot()
out = []
for el in root.iter("outline"):
xml_url = el.get("xmlUrl")
if not xml_url:
continue # папки/категории без ленты
out.append({
"title": el.get("title") or el.get("text") or "",
"url": el.get("htmlUrl") or "",
"feed_url": xml_url,
})
return out
def import_opml(path, direction=None, lang=DEFAULT_LANG, priority=DEFAULT_PRIORITY,
enable=False, dry_run=False):
"""Импорт OPML → sources.yaml (+БД). Возвращает отчёт dict."""
subs = parse_opml(path)
existing = load_sources_yaml()
existing_feeds = {_normalize_feed_url(s.get("feed_url") or ""): s.get("slug")
for s in existing if s.get("feed_url")}
report = {"recognized": len(subs), "skipped": 0, "added": 0, "duplicates": 0}
new_sources = []
for sub in subs:
norm = _normalize_feed_url(sub["feed_url"])
if not sub["feed_url"] or not norm.startswith("http"):
report["skipped"] += 1
continue
if norm in existing_feeds:
report["duplicates"] += 1
continue
slug = _slugify(sub["title"], sub["feed_url"])
# уникальность slug в рамках импорта
i = 1
base = slug
while slug in existing_feeds.values() or slug in {s["slug"] for s in new_sources}:
slug = f"{base}-{i}"; i += 1
new_sources.append({
"slug": slug,
"name": sub["title"] or sub["feed_url"],
"url": sub["url"] or sub["feed_url"],
"channel": None,
"crawler": "rss",
"feed_url": sub["feed_url"],
"direction": direction, # None по умолчанию
"lang": lang,
"priority": priority,
"enabled": enable, # False по умолчанию — безопасный импорт
"own": False,
})
existing_feeds[norm] = slug # защита от дублей внутри одного файла
report["added"] += 1
if dry_run:
return {**report, "dry_run": True, "sources": new_sources}
for s in new_sources:
upsert_source_yaml(s)
sync_sources_to_db()
return {**report, "dry_run": False, "sources": new_sources}
if __name__ == "__main__":
ap = argparse.ArgumentParser(description="Импорт RSS-подписок из OPML в VESTI")
ap.add_argument("cmd", choices=["import"])
ap.add_argument("file", type=Path, help="путь к .opml")
ap.add_argument("--direction", default=None)
ap.add_argument("--lang", default=DEFAULT_LANG)
ap.add_argument("--priority", default=DEFAULT_PRIORITY, choices=["P0", "P1", "P2", "P3"])
ap.add_argument("--enable", action="store_true", help="включить новые источники")
ap.add_argument("--dry-run", action="store_true")
a = ap.parse_args()
r = import_opml(a.file, a.direction, a.lang, a.priority, a.enable, a.dry_run)
print(f"распознано: {r['recognized']}, пропущено: {r['skipped']}, "
f"добавлено: {r['added']}, дубликатов: {r['duplicates']}"
+ (" (dry-run, БД не тронута)" if r["dry_run"] else ""))
Импорт НЕ меняет существующих источников; enabled по умолчанию False; --enable
включает сразу. Отчёт печатается в stdout.
Тесты
python -m sources.opml import sample.opml --dry-run— отчёт, БД не тронута.--direction linux— устанавливает direction;--enable— enabled: true.- Повторный импорт того же файла — «дубликатов: N», новых 0.
- Не-OPML / битый XML — корректная ошибка (ET.ParseError).
Проверка
cd /opt/vesti
.venv/bin/python -m sources.opml import /tmp/sample.opml --dry-run # отчёт
.venv/bin/python -m sources.opml import /tmp/sample.opml --direction linux
grep -A2 'huggingface\|lwn' sources/sources.yaml # новые записи enabled: false
.venv/bin/python -c "from sources.sources import get_enabled_sources; print(len(get_enabled_sources()))"
openspec validate opml-import