-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrss_parser.py
More file actions
61 lines (48 loc) · 2.21 KB
/
Copy pathrss_parser.py
File metadata and controls
61 lines (48 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Copyright 2024-2026 Simon Brunning
import logging
from collections import OrderedDict
from typing import TYPE_CHECKING
from defusedxml.ElementTree import fromstring
from wireup import injectable
from yarl import URL
from rss_agg.logging_utils import log_duration
if TYPE_CHECKING:
from collections.abc import Iterable
from xml.etree import ElementTree as ET
from rss_agg.domain import ExcludeTag
from rss_agg.services.feeds_services.base_feeds_service import FeedsAndExclusions
from rss_agg.services import Fetcher # noqa: TC001
logger = logging.getLogger(__name__)
@injectable
class RSSParser:
def __init__(self, fetcher: Fetcher) -> None:
self.fetcher = fetcher
async def read_rss_feeds(self, feeds_and_exclusions: FeedsAndExclusions) -> Iterable[ET.Element]:
exclusions = set(feeds_and_exclusions.exclusions)
items: dict[str, ET.Element] = OrderedDict()
responses = await self.fetcher.fetch_all(feeds_and_exclusions.feeds)
with log_duration(logger.debug, "deduping", response_count=len(responses)):
for response in responses:
for guid, item in self._parse_feed_items(response, exclusions):
if guid not in items:
items[guid] = item
logger.debug("deduped-items", extra={"count": len(items)})
return list(items.values())
def _parse_feed_items(self, response: str, exclusions: set[ExcludeTag]) -> Iterable[tuple[str, ET.Element]]:
if not response:
return
feed: ET.Element = fromstring(response)
for item in feed.findall(".//item"):
guid = item.findtext("guid")
if guid and not self._is_excluded(item, exclusions):
yield guid, item
@staticmethod
def _is_excluded(item: ET.Element, exclusions: set[ExcludeTag]) -> bool:
categories = {URL(domain) for cat in item.findall("category") if (domain := cat.get("domain"))}
is_excluded = bool(categories & exclusions)
if is_excluded:
logger.debug(
"exclusion",
extra={"exclusions": exclusions, "categories": categories, "cause": categories & exclusions},
)
return is_excluded