Mercurial > hg > index.fcgi > www > www-1
view myrss/myrss_app.py @ 142:2ed8cf5f36bf
myrss2: fix handling of null feed title or links; miscellaneous URL updates
author | paulo |
---|---|
date | Mon, 18 Dec 2023 20:10:27 +0000 |
parents | e2817e789895 |
children |
line source
1 import os
2 import sys
3 import re
4 import urllib2
5 import threading
6 import Queue
7 import datetime
8 import time
9 import traceback
10 import StringIO
12 import logging
13 #logging.basicConfig(
14 # level=logging.DEBUG,
15 # filename="_LOG",
16 # format="%(asctime)s %(levelname)-8s %(message)s",
17 #)
19 import xml.etree.ElementTree
20 import HTMLParser
22 import html
25 FEEDS_FILE = "FEEDS"
26 CACHE_HTML_FILE = "__cache__.html"
28 CACHE_LIFE = 1200 # [seconds]
29 MAX_ITEMS = 50
30 MAX_LINK_Z = 4
31 MAX_THREADS = 20
32 URLOPEN_TIMEOUT = 10 # [seconds]
35 _PARSE_ROOT_TAG_RE = re.compile(r"(\{(.+)\})?(.+)")
37 def _parse_root_tag(root_tag):
38 re_match = _PARSE_ROOT_TAG_RE.match(root_tag)
40 if re_match is None:
41 return (None, None)
42 else:
43 return re_match.group(2, 3)
46 def _strip_if_not_none(txt):
47 return txt.strip() if txt is not None else ''
50 def _go_rss(elementTree):
51 title = _strip_if_not_none(elementTree.find("channel/title").text)
52 link = elementTree.find("channel/link").text
54 items = []
56 for i in elementTree.findall("channel/item")[:MAX_ITEMS]:
57 it_title = _strip_if_not_none(i.find("title").text)
58 it_link = i.find("link").text
60 items.append((it_title, it_link))
62 return (title, link, items)
65 def _go_atom(elementTree):
66 ns = "http://www.w3.org/2005/Atom"
68 title = _strip_if_not_none(elementTree.find("{%s}title" % ns).text)
69 link = ''
71 links = elementTree.findall("{%s}link" % ns)
72 for i in links:
73 if len(links) == 1 or i.get("rel") == "alternate":
74 link = i.get("href")
75 break
77 items = []
79 for i in elementTree.findall("{%s}entry" % ns)[:MAX_ITEMS]:
80 it_title = _strip_if_not_none(i.find("{%s}title" % ns).text)
81 it_link = ''
83 it_links = i.findall("{%s}link" % ns)
84 for j in it_links:
85 if len(it_links) == 1 or j.get("rel") == "alternate":
86 it_link = j.get("href")
87 break
89 items.append((it_title, it_link))
91 return (title, link, items)
94 def _go_purl_rss(elementTree):
95 ns = "http://purl.org/rss/1.0/"
97 title = _strip_if_not_none(elementTree.find("{%s}channel/{%s}title" % (ns, ns)).text)
98 link = elementTree.find("{%s}channel/{%s}link" % (ns, ns)).text
100 items = []
102 for i in elementTree.findall("{%s}item" % ns)[:MAX_ITEMS]:
103 it_title = _strip_if_not_none(i.find("{%s}title" % ns).text)
104 it_link = i.find("{%s}link" % ns).text
106 items.append((it_title, it_link))
108 return (title, link, items)
111 _STRIP_HTML_RE = re.compile(r"<.*?>")
112 _htmlParser = HTMLParser.HTMLParser()
114 def _strip_html(txt):
115 return _htmlParser.unescape(_STRIP_HTML_RE.sub('', txt))
118 def _to_html(dtnow, docstruct):
119 datetime_str = dtnow.strftime("%Y-%m-%d %H:%M %Z")
120 page_title = "myrss -- %s" % datetime_str
122 root = html.HTML("html")
124 header = root.head
125 header.meta(name="viewport", content="width=device-width, initial-scale=1")
126 header.title(page_title)
127 header.link(rel="stylesheet", type="text/css", href="index.css")
129 body = root.body
130 body.h1(page_title)
132 link_z = 0
134 for feed in docstruct:
135 if feed is None:
136 continue
138 (title, link, items) = feed
140 logging.debug("title: %s", title)
141 body.h2.a(_strip_html(title), href=link, klass="z%d" % (link_z % MAX_LINK_Z))
142 link_z += 1
143 p = body.p
145 for (i, (it_title, it_link)) in enumerate(items):
146 if i > 0:
147 p += " - "
149 if not it_title:
150 it_title = "(missing title)"
151 if it_link is not None:
152 p.a(_strip_html(it_title), href=it_link, klass="z%d" % (link_z % MAX_LINK_Z))
153 else:
154 p += _strip_html(it_title)
156 link_z += 1
158 dtdelta = datetime.datetime.now() - dtnow
159 root.div("%.3f" % (dtdelta.days*86400 + dtdelta.seconds + dtdelta.microseconds/1e6), klass="debug")
161 return unicode(root).encode("utf-8")
164 def _fetch_url(url):
165 try:
166 logging.info("processing %s" % url)
167 feed = urllib2.urlopen(urllib2.Request(url, headers={"User-Agent": "Mozilla/5.0 Browser"}), timeout=URLOPEN_TIMEOUT)
168 except urllib2.HTTPError as e:
169 logging.info("(%s) %s" % (url, e))
170 return None
172 return feed.read()
175 def _filter_feed(feed):
176 ret = feed
178 filter_out = ["\x16"]
179 for i in filter_out:
180 ret = ret.replace(i, "")
182 return ret
185 def _process_feed(feed):
186 ret = None
188 feed_sio = StringIO.StringIO(feed)
189 elementTree = xml.etree.ElementTree.parse(feed_sio)
190 root = elementTree.getroot()
192 parsed_root_tag = _parse_root_tag(root.tag)
194 if parsed_root_tag == (None, "rss"):
195 version = float(root.get("version", 0.0))
196 if version >= 2.0:
197 ret = _go_rss(elementTree)
198 else:
199 raise NotImplementedError("Unsupported rss version")
200 elif parsed_root_tag == ("http://www.w3.org/2005/Atom", "feed"):
201 ret = _go_atom(elementTree)
202 elif parsed_root_tag == ("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF"):
203 ret = _go_purl_rss(elementTree)
204 else:
205 raise NotImplementedError("Unknown root tag")
207 return ret
210 class WorkerThread(threading.Thread):
211 def __init__(self, *args, **kwargs):
212 self._input_queue = kwargs.pop("input_queue")
213 self._output_queue = kwargs.pop("output_queue")
214 threading.Thread.__init__(self, *args, **kwargs)
215 self.daemon = True
217 def run(self):
218 while True:
219 (idx, url) = self._input_queue.get()
220 docfeed = None
221 try:
222 feed = _fetch_url(url)
223 if feed is not None:
224 docfeed = _process_feed(_filter_feed(feed))
225 except Exception as e:
226 logging.info("(%s) exception: (%s) %s" % (url, type(e), e))
227 self._output_queue.put((idx, docfeed))
230 def main(input_queue, output_queue, lock):
231 ret = ''
233 with lock:
234 logging.debug("main() started")
235 epoch_now = time.time()
236 dtnow = datetime.datetime.fromtimestamp(epoch_now)
238 if os.path.exists(CACHE_HTML_FILE) and (epoch_now - os.stat(CACHE_HTML_FILE).st_mtime) < float(CACHE_LIFE):
239 with open(CACHE_HTML_FILE) as cache_html_file:
240 ret = cache_html_file.read()
242 else:
243 with open(FEEDS_FILE) as feeds_file:
244 feedlines = feeds_file.readlines()
246 docstruct = [None]*len(feedlines)
247 num_input = 0
248 for (i, l) in enumerate(feedlines):
249 if l[0] != '#':
250 l = l.strip()
251 input_queue.put((i, l))
252 num_input += 1
254 for _ in range(num_input):
255 (idx, docfeed) = output_queue.get()
256 docstruct[idx] = docfeed
258 ret = _to_html(dtnow, docstruct)
260 with open(CACHE_HTML_FILE, 'w') as cache_html_file:
261 cache_html_file.write(ret)
262 logging.debug("main() ended")
264 return ret
267 class MyRssApp:
268 def __init__(self):
269 logging.debug("MyRssApp.__init__() called")
270 self._iq = Queue.Queue(MAX_THREADS)
271 self._oq = Queue.Queue(MAX_THREADS)
272 self._main_lock = threading.Lock()
274 for i in range(MAX_THREADS):
275 logging.debug("Starting thread: %d" % i)
276 WorkerThread(input_queue=self._iq, output_queue=self._oq).start()
278 def __call__(self, environ, start_response):
279 response_code = "500 Internal Server Error"
280 response_type = "text/plain; charset=UTF-8"
282 try:
283 response_body = main(self._iq, self._oq, self._main_lock)
284 response_code = "200 OK"
285 response_type = "text/html; charset=UTF-8"
286 except:
287 response_body = traceback.format_exc()
289 response_headers = [
290 ("Content-Type", response_type),
291 ("Content-Length", str(len(response_body))),
292 ]
293 start_response(response_code, response_headers)
295 return [response_body]