view myrss/myrss_app.py @ 76:51f0da3da721

myrss: fix Atom link parsing
author paulo
date Thu, 12 May 2016 01:04:10 -0700
parents d6acf8b093b7
children 583400dc28a0
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
11 import logging
12 logging.basicConfig(
13 #level=logging.DEBUG,
14 #filename="_LOG",
15 #format="%(asctime)s %(levelname)-8s %(message)s",
16 )
18 import xml.etree.ElementTree
19 import HTMLParser
21 import html
24 FEEDS_FILE = "FEEDS"
25 CACHE_HTML_FILE = "__cache__.html"
27 CACHE_LIFE = 1200 # [seconds]
28 MAX_ITEMS = 50
29 MAX_LINK_Z = 4
30 MAX_THREADS = 20
31 URLOPEN_TIMEOUT = 60 # [seconds]
34 _PARSE_ROOT_TAG_RE = re.compile(r"(\{(.+)\})?(.+)")
36 def _parse_root_tag(root_tag):
37 re_match = _PARSE_ROOT_TAG_RE.match(root_tag)
39 if re_match is None:
40 return (None, None)
41 else:
42 return re_match.group(2, 3)
45 def _strip_if_not_none(txt):
46 return txt.strip() if txt is not None else ''
49 def _go_rss(elementTree):
50 title = _strip_if_not_none(elementTree.find("channel/title").text)
51 link = elementTree.find("channel/link").text
53 items = []
55 for i in elementTree.findall("channel/item")[:MAX_ITEMS]:
56 it_title = _strip_if_not_none(i.find("title").text)
57 it_link = i.find("link").text
59 items.append((it_title, it_link))
61 return (title, link, items)
64 def _go_atom(elementTree):
65 ns = "http://www.w3.org/2005/Atom"
67 title = _strip_if_not_none(elementTree.find("{%s}title" % ns).text)
68 link = ''
70 links = elementTree.findall("{%s}link" % ns)
71 for i in links:
72 if len(links) == 1 or i.get("rel") == "alternate":
73 link = i.get("href")
74 break
76 items = []
78 for i in elementTree.findall("{%s}entry" % ns)[:MAX_ITEMS]:
79 it_title = _strip_if_not_none(i.find("{%s}title" % ns).text)
80 it_link = ''
82 it_links = i.findall("{%s}link" % ns)
83 for j in it_links:
84 if len(it_links) == 1 or j.get("rel") == "alternate":
85 it_link = j.get("href")
86 break
88 items.append((it_title, it_link))
90 return (title, link, items)
93 def _go_purl_rss(elementTree):
94 ns = "http://purl.org/rss/1.0/"
96 title = _strip_if_not_none(elementTree.find("{%s}channel/{%s}title" % (ns, ns)).text)
97 link = elementTree.find("{%s}channel/{%s}link" % (ns, ns)).text
99 items = []
101 for i in elementTree.findall("{%s}item" % ns)[:MAX_ITEMS]:
102 it_title = _strip_if_not_none(i.find("{%s}title" % ns).text)
103 it_link = i.find("{%s}link" % ns).text
105 items.append((it_title, it_link))
107 return (title, link, items)
110 _STRIP_HTML_RE = re.compile(r"<.*?>")
111 _htmlParser = HTMLParser.HTMLParser()
113 def _strip_html(txt):
114 return _htmlParser.unescape(_STRIP_HTML_RE.sub('', txt))
117 def _to_html(dtnow, docstruct):
118 datetime_str = dtnow.strftime("%Y-%m-%d %H:%M %Z")
119 page_title = "myrss -- %s" % datetime_str
121 root = html.HTML("html")
123 header = root.header
124 header.title(page_title)
125 header.link(rel="stylesheet", type="text/css", href="index.css")
127 body = root.body
128 body.h1(page_title)
130 link_z = 0
132 for feed in docstruct:
133 if feed is None:
134 continue
136 (title, link, items) = feed
138 body.h2.a(_strip_html(title), href=link, klass="z%d" % (link_z % MAX_LINK_Z))
139 link_z += 1
140 p = body.p
142 for (i, (it_title, it_link)) in enumerate(items):
143 if i > 0:
144 p += " - "
146 if not it_title:
147 it_title = "(missing title)"
148 if it_link is not None:
149 p.a(_strip_html(it_title), href=it_link, klass="z%d" % (link_z % MAX_LINK_Z))
150 else:
151 p += _strip_html(it_title)
153 link_z += 1
155 dtdelta = datetime.datetime.now() - dtnow
156 root.div("%.3f" % (dtdelta.days*86400 + dtdelta.seconds + dtdelta.microseconds/1e6), klass="debug")
158 return unicode(root).encode("utf-8")
161 def _fetch_url(url):
162 try:
163 logging.info("processing %s" % url)
164 feed = urllib2.urlopen(urllib2.Request(url, headers={"User-Agent": "Mozilla/5.0"}), timeout=URLOPEN_TIMEOUT)
165 except urllib2.HTTPError as e:
166 logging.info("(%s) %s" % (url, e))
167 return None
169 return feed
172 def _process_feed(feed):
173 ret = None
175 elementTree = xml.etree.ElementTree.parse(feed)
176 root = elementTree.getroot()
178 parsed_root_tag = _parse_root_tag(root.tag)
180 if parsed_root_tag == (None, "rss"):
181 version = float(root.get("version", 0.0))
182 if version >= 2.0:
183 ret = _go_rss(elementTree)
184 else:
185 raise NotImplementedError("Unsupported rss version")
186 elif parsed_root_tag == ("http://www.w3.org/2005/Atom", "feed"):
187 ret = _go_atom(elementTree)
188 elif parsed_root_tag == ("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF"):
189 ret = _go_purl_rss(elementTree)
190 else:
191 raise NotImplementedError("Unknown root tag")
193 return ret
196 class WorkerThread(threading.Thread):
197 def __init__(self, *args, **kwargs):
198 self._input_queue = kwargs.pop("input_queue")
199 self._output_queue = kwargs.pop("output_queue")
200 threading.Thread.__init__(self, *args, **kwargs)
201 self.daemon = True
203 def run(self):
204 while True:
205 (idx, url) = self._input_queue.get()
206 docfeed = None
207 try:
208 feed = _fetch_url(url)
209 if feed is not None:
210 docfeed = _process_feed(feed)
211 except Exception as e:
212 logging.info("(%s) exception: %s" % (url, e))
213 self._output_queue.put((idx, docfeed))
216 def main(input_queue, output_queue, lock):
217 ret = ''
219 with lock:
220 epoch_now = time.time()
221 dtnow = datetime.datetime.fromtimestamp(epoch_now)
223 if os.path.exists(CACHE_HTML_FILE) and (epoch_now - os.stat(CACHE_HTML_FILE).st_mtime) < float(CACHE_LIFE):
224 with open(CACHE_HTML_FILE) as cache_html_file:
225 ret = cache_html_file.read()
227 else:
228 with open(FEEDS_FILE) as feeds_file:
229 feedlines = feeds_file.readlines()
231 docstruct = [None]*len(feedlines)
232 num_input = 0
233 for (i, l) in enumerate(feedlines):
234 if l[0] != '#':
235 l = l.strip()
236 input_queue.put((i, l))
237 num_input += 1
239 for _ in range(num_input):
240 (idx, docfeed) = output_queue.get()
241 docstruct[idx] = docfeed
243 ret = _to_html(dtnow, docstruct)
245 with open(CACHE_HTML_FILE, 'w') as cache_html_file:
246 cache_html_file.write(ret)
248 return ret
251 class MyRssApp:
252 def __init__(self):
253 self._iq = Queue.Queue(MAX_THREADS)
254 self._oq = Queue.Queue(MAX_THREADS)
255 self._main_lock = threading.Lock()
257 for _ in range(MAX_THREADS):
258 WorkerThread(input_queue=self._iq, output_queue=self._oq).start()
260 def __call__(self, environ, start_response):
261 response_code = "500 Internal Server Error"
262 response_type = "text/plain; charset=UTF-8"
264 try:
265 response_body = main(self._iq, self._oq, self._main_lock)
266 response_code = "200 OK"
267 response_type = "text/html; charset=UTF-8"
268 except:
269 response_body = traceback.format_exc()
271 response_headers = [
272 ("Content-Type", response_type),
273 ("Content-Length", str(len(response_body))),
274 ]
275 start_response(response_code, response_headers)
277 return [response_body]