-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter_feed.py
executable file
·102 lines (86 loc) · 3.44 KB
/
filter_feed.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env python3
from dataclasses import asdict
from typing import Any
import xml.etree.ElementTree as ET
from absl import logging
import flask
import requests
from google.cloud import ndb # type: Any
from opentelemetry import trace
from jqqb_evaluator.evaluator import Evaluator
import model
from item import Item
tracer = trace.get_tracer(__name__)
class NamespaceRecordingTreeBuilder(ET.TreeBuilder):
def __init__(self, *args, **kwargs):
self.ns = {}
super().__init__(*args, **kwargs)
def start_ns(self, prefix, uri):
self.ns[prefix] = uri
def modifyRss(root: ET.Element, settings: model.FilterFeed):
title = root.find(".//channel/title")
if title is None:
logging.warning("Could not find .//channel/title to modify")
else:
title.text += " (filtered)"
with tracer.start_as_current_span('filter_rss'):
chan = root.find("channel")
if chan is None:
raise Exception('Missing channel element')
evaluator = Evaluator(settings.query_builder)
delete_items = filter(
lambda i: evaluator.object_matches_rules(asdict(Item.fromRssItem(i))),
root.iterfind(".//item"))
for item in delete_items:
chan.remove(item)
def modifyAtom(root: ET.Element, settings: model.FilterFeed):
title = root.find("./{http://www.w3.org/2005/Atom}title")
if title is None:
logging.warning("Could not find ./{http://www.w3.org/2005/Atom}title to modify")
else:
title.text += " (filtered)"
with tracer.start_as_current_span('filter_atom'):
evaluator = Evaluator(settings.query_builder)
delete_entries = filter(
lambda i: evaluator.object_matches_rules(asdict(Item.fromAtomEntry(i))),
root.iterfind(".//{http://www.w3.org/2005/Atom}entry"))
for entry in delete_entries:
root.remove(entry)
def detectRss(content_type: str, root: ET.Element) -> bool:
if content_type in (
"application/rss+xml",
):
return True
return root.tag in "rss"
def detectAtom(content_type: str, root: ET.Element) -> bool:
if content_type in (
"application/atom+xml",
):
return True
return root.tag in ("feed", "{http://www.w3.org/2005/Atom}feed")
def feed_by_key(request: flask.Request, key: ndb.Key) -> flask.Response:
res = flask.Response()
settings = key.get()
if settings is None:
flask.abort(404)
upstream = requests.get(settings.url)
with tracer.start_as_current_span('parse'):
tb = NamespaceRecordingTreeBuilder()
root = ET.fromstring(upstream.text, parser=ET.XMLParser(target=tb))
if detectRss(upstream.headers.get('Content-Type', None), root):
modifyRss(root, settings)
elif detectAtom(upstream.headers.get('Content-Type', None), root):
modifyAtom(root, settings)
else:
logging.error('Could not detect content-type, returning XML unmodified')
with tracer.start_as_current_span('serialize'):
# pytype: disable=module-attr
nsmap = ET._namespace_map.copy()
for prefix, uri in tb.ns.items():
ET.register_namespace(prefix, uri)
res.set_data(ET.tostring(root, encoding='unicode') )
ET._namespace_map.clear()
ET._namespace_map.update(nsmap)
# pytype: enable=module-attr
res.content_type = upstream.headers.get('Content-Type', None)
return res