2 # -*- coding: UTF-8 -*-
3 """Creates an Atom-Feed for single or multiple winterrodeln sled reports.
6 http://www.winterrodeln.org/feed/berichte/alle
7 http://www.winterrodeln.org/feed/berichte/bahn/kemater_alm
8 http://www.winterrodeln.org/feed/berichte/bahnen/5+280+251
9 http://www.winterrodeln.org/feed/berichte/region/osttirol
11 http://www.atompub.org/
12 http://effbot.org/zone/element.htm
13 http://www.winterrodeln.org/trac/wiki/UrlSchema
17 from xml.etree.ElementTree import Element, SubElement, tostring
19 from sqlalchemy.engine import create_engine
24 from pylons import request, response, session, config, tmpl_context as c, url
25 from pylons.controllers.util import abort, redirect
27 from wrfeed.lib.base import BaseController, render
29 log = logging.getLogger(__name__)
32 def create_feed(page_title=None, page_ids=None, region_name=None):
33 """If a page_title is given, only the reports for the given sledrun are shown.
34 If a list of page_ids is given, only the reports for the selected pages are shown.
35 If a region name (lower case) is given, the reports just for this region are shown.
36 Otherwise, all reports are shown."""
38 engine = create_engine(config['sqlalchemy.url'])
39 limit = int(config['feedentrylimit'])
40 conn = engine.connect()
42 select = 'select wrreport.page_id, wrreport.page_title, wrreport.id, date_report, date_entry, `condition`, description, author_name, author_userid, author_username, position_longitude, position_latitude from wrreport left outer join wrsledruncache on wrreport.page_id=wrsledruncache.page_id'
43 where = 'where date_invalid > now() and delete_date is null'
44 order = 'order by id desc'
45 limit = 'limit {0}'.format(limit)
48 if not page_title is None:
50 page_title = page_title.replace('_', ' ')
51 where += ' and lcase(wrreport.page_title) = lcase(%s)'
52 params += [page_title]
53 elif not page_ids is None:
54 # a list of page_ids is given
55 if len(page_ids) == 0:
56 raise webob.exc.HTTPBadRequest()
58 where += " or ".join(['wrreport.page_id=%s' for page_id in page_ids])
60 params += map(str, page_ids)
61 elif not region_name is None:
62 # a name of a region is given
63 # (1) find out whether the region exists
64 subselect = 'select aswkb(border) as border_wkb from wrregion where name=lcase(%s)'
65 subresult = conn.execute(subselect, region_name)
66 if subresult.rowcount == 0:
67 # no region with such a name
68 raise webob.exc.HTTPNotFound()
69 assert subresult.rowcount == 1
70 row = subresult.fetchone()
71 border_wkb = row['border_wkb'] # border as WKB
72 where += ' and contains(geomfromwkb(%s), point(position_longitude, position_latitude))'
73 params += [border_wkb]
75 # user wants to have all reports
77 sql = ' '.join([select, where, order, limit])
78 result = conn.execute(sql, *params)
80 feed = Element("feed", xmlns="http://www.w3.org/2005/Atom", attrib={'xmlns:georss': 'http://www.georss.org/georss', 'xmlns:wr': 'http://www.winterrodeln.org/schema/wrreport'})
81 feed_title = SubElement(feed, "title")
82 feed_title.text = "Winterrodeln Rodelbahnberichte"
83 feed_id = SubElement(feed, "id")
84 if not page_title is None:
85 feed_id.text = url(qualified=True, controller='berichte', action='bahn', id=page_title)
86 elif not page_ids is None:
87 feed_id.text = url(qualified=True, controller='berichte', action='bahnen', id="+".join(map(str, page_ids)))
88 elif not region_name is None:
89 feed_id.text = url(qualified=True, controller='berichte', action='region', id=region_name)
91 feed_id.text = url(qualified=True, controller='berichte', action='alle')
92 feed_updated = SubElement(feed, "updated")
93 feed.append(Element("link", rel="self", href=feed_id.text))
97 page_id, page_title, report_id, date_report, date_entry, condition, description, author_name, author_userid, author_username, lon, lat = row
98 page_title_url = page_title.replace(u' ', u'_')
99 entry = SubElement(feed, "entry")
100 entry_title = SubElement(entry, "title")
101 entry_title.text = page_title
102 entry.append(Element("link", rel="alternate", href=u"http://www.winterrodeln.org/wiki/{0}".format(page_title_url), type="text/html", hreflang="de"))
103 entry_id = SubElement(entry, "id")
104 entry_id.text = u"http://www.winterrodeln.org/wiki/{0}#{1}".format(page_title_url, report_id)
105 entry_updated = SubElement(entry, "updated")
106 entry_updated.text = date_entry.isoformat() + "+01:00"
107 if last_updated is None: last_updated = date_entry
108 # entry_summary = SubElement(entry, "summary")
109 # entry_summary.text = str(condition)
110 entry_content = SubElement(entry, "content")
111 entry_content.attrib["type"] = "xhtml"
112 entry_content_div = SubElement(entry_content, "div")
113 entry_content_div.attrib["xmlns"] = "http://www.w3.org/1999/xhtml"
114 entry_content_ul = SubElement(entry_content_div, "ul")
115 if not date_report is None:
116 entry_content_date = SubElement(entry_content_ul, "li")
117 entry_content_date.text = u"Bericht für " + date_report.isoformat()
118 if not condition is None:
119 entry_content_condition = SubElement(entry_content_ul, "li")
120 entry_content_condition.text = u"Schneelage: " + {1: u'Sehr gut', 2: u'Gut', 3: u'Mittelmäßig', 4: u'Schlecht', 5: u'Geht nicht'}[condition]
121 entry_content_description = SubElement(entry_content_ul, "li")
122 entry_content_description.text = description
123 entry_author = SubElement(entry, "author")
124 entry_author_name = SubElement(entry_author, "name")
125 if author_name is None or len(author_name.strip()) == 0: entry_author_name.text = "Anonymous user"
126 else: entry_author_name.text = author_name
127 if not lon is None and not lat is None:
128 entry_geo = SubElement(entry, "georss:point")
129 entry_geo.text = "{lat} {lon}".format(lat=lat, lon=lon)
130 entry_wrreport = SubElement(entry, "wr:report")
131 entry_wrreport.attrib['report_id'] = str(report_id)
132 entry_wrreport.attrib['page_id'] = str(page_id)
133 entry_wrreport.attrib['page_title'] = page_title
134 entry_wrreport.attrib['date_report'] = str(date_report)
135 entry_wrreport.attrib['date_entry'] = str(date_entry)
136 entry_wrreport.attrib['condition'] = "0" if condition is None else str(condition)
137 entry_wrreport.attrib['author_name'] = author_name
138 entry_wrreport.attrib['author_username'] = "" if author_userid is None else author_username
139 entry_wrreport.text = description
141 if last_updated is None: last_updated = datetime.datetime.now()
142 feed_updated.text = last_updated.isoformat() + "+01:00"
144 feed_xml = '<?xml version="1.0" encoding="utf-8"?>\n' + tostring(feed)
150 class BerichteController(BaseController):
154 http://127.0.0.1:5000/berichte/alle
155 http://www.winterrodeln.org/feed/berichte/alle
157 response.content_type = 'application/atom+xml'
163 http://127.0.0.1:5000/berichte/bahn/kemater_alm
164 http://www.winterrodeln.org/feed/berichte/bahn/kemater_alm
166 response.content_type = 'application/atom+xml'
167 return create_feed(page_title=id)
170 def bahnen(self, id):
172 http://127.0.0.1:5000/berichte/bahnen/5+280+251
173 http://www.winterrodeln.org/feed/berichte/bahnen/5+280+251
175 page_ids = id.split('+')
177 page_ids = [int(page_id) for page_id in page_ids]
179 abort(400) # bad request
180 response.content_type = 'application/atom+xml'
181 return create_feed(page_ids=page_ids)
183 def region(self, id):
185 http://www.winterrodeln.org/feed/berichte/region/osttirol
187 response.content_type = 'application/atom+xml'
188 return create_feed(region_name=id)