]> ToastFreeware Gitweb - philipp/winterrodeln/wrfeed.git/blob - wrfeed/berichte.py
34cbb9d89e8fe8737741beb11db9efc41d459f19
[philipp/winterrodeln/wrfeed.git] / wrfeed / berichte.py
1 """Creates an Atom-Feed for single or multiple winterrodeln sled reports.
2
3 Format:
4     http://www.winterrodeln.org/feed/berichte/alle
5     http://www.winterrodeln.org/feed/berichte/bahn/kemater_alm
6     http://www.winterrodeln.org/feed/berichte/bahnen/5+280+251
7     http://www.winterrodeln.org/feed/berichte/region/osttirol
8 See:
9     http://www.atompub.org/
10     http://effbot.org/zone/element.htm
11     http://www.winterrodeln.org/trac/wiki/UrlSchema
12 """
13 import datetime
14 from xml.etree.ElementTree import Element, SubElement, tostring
15 from flask import url_for
16
17
18 class CreateFeedError(RuntimeError):
19     pass
20
21
22 class RegionNotFoundError(CreateFeedError):
23     pass
24
25
26 def create_feed(conn, limit, page_title=None, page_ids=None, region_name=None):
27     """If a page_title is given, only the reports for the given sledrun are shown.
28     If a list of page_ids is given, only the reports for the selected pages are shown.
29     If a region name (lower case) is given, the reports just for this region are shown.
30     Otherwise, all reports are shown."""
31     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'
32     where = 'where date_invalid > now() and delete_date is null'
33     order = 'order by id desc'
34     limit = 'limit {0}'.format(limit)
35     params = []
36
37     if not page_title is None:
38         # page_title is given
39         page_title = page_title.replace('_', ' ')
40         where += ' and lcase(wrreport.page_title) = lcase(%s)'
41         params += [page_title]
42     elif not page_ids is None:
43         # a list of page_ids is given
44         assert len(page_ids) > 0
45         where += ' and ('
46         where += " or ".join(['wrreport.page_id=%s' for page_id in page_ids])
47         where += ')'
48         params += list(map(str, page_ids))
49     elif not region_name is None:
50         # a name of a region is given
51         # (1) find out whether the region exists
52         subselect = 'select aswkb(border) as border_wkb from wrregion where name=lcase(%s)'
53         subresult = conn.execute(subselect, region_name)
54         if subresult.rowcount == 0:
55             # no region with such a name
56             raise RegionNotFoundError(region_name)
57         assert subresult.rowcount == 1
58         row = subresult.fetchone()
59         # (2) now we have the border
60         border_wkb = row['border_wkb'] # border as WKB
61         where += ' and contains(geomfromwkb(%s), point(position_longitude, position_latitude))'
62         params += [border_wkb]
63     else:
64         # user wants to have all reports
65         pass
66     sql = ' '.join([select, where, order, limit])
67     result = conn.execute(sql, *params)
68
69     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'})
70     feed_title = SubElement(feed, "title")
71     feed_title.text = "Winterrodeln Rodelbahnberichte"
72     feed_id = SubElement(feed, "id")
73     if not page_title is None:
74         feed_id.text = url_for('bahn', bahn=page_title, _external=True)
75     elif not page_ids is None:
76         feed_id.text = url_for('bahnen', bahnen="+".join(map(str, page_ids)), _external=True)
77     elif not region_name is None:
78         feed_id.text = url_for('region', region=region_name, _external=True)
79     else:
80         feed_id.text = url_for('alle', _external=True)
81     feed_updated = SubElement(feed, "updated")
82     feed.append(Element("link", rel="self", href=feed_id.text))
83
84     last_updated = None
85     for row in result:
86         page_id, page_title, report_id, date_report, date_entry, condition, description, author_name, author_userid, author_username, lon, lat = row
87
88         page_title_url = page_title.replace(' ', '_')
89         entry = SubElement(feed, "entry")
90         entry_title = SubElement(entry, "title")
91         entry_title.text = page_title
92         entry.append(Element("link", rel="alternate", href="http://www.winterrodeln.org/wiki/{0}".format(page_title_url), type="text/html", hreflang="de"))
93         entry_id = SubElement(entry, "id")
94         entry_id.text = "http://www.winterrodeln.org/wiki/{0}#{1}".format(page_title_url, report_id)
95         entry_updated = SubElement(entry, "updated")
96         entry_updated.text = date_entry.isoformat() + "+01:00"
97         if last_updated is None: last_updated = date_entry
98         # entry_summary = SubElement(entry, "summary")
99         # entry_summary.text = str(condition)
100         entry_content = SubElement(entry, "content")
101         entry_content.attrib["type"] = "xhtml"
102         entry_content_div = SubElement(entry_content, "div")
103         entry_content_div.attrib["xmlns"] = "http://www.w3.org/1999/xhtml"
104         entry_content_ul = SubElement(entry_content_div, "ul")
105         if not date_report is None:
106             entry_content_date = SubElement(entry_content_ul, "li")
107             entry_content_date.text = "Bericht für " + date_report.isoformat()
108         if not condition is None:
109             entry_content_condition = SubElement(entry_content_ul, "li")
110             entry_content_condition.text = "Schneelage: " + {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'}[condition]
111         entry_content_description = SubElement(entry_content_ul, "li")
112         entry_content_description.text = description
113         entry_author = SubElement(entry, "author")
114         entry_author_name = SubElement(entry_author, "name")
115         if author_name is None or len(author_name.strip()) == 0: entry_author_name.text = "Anonymous user"
116         else: entry_author_name.text = author_name
117         if not lon is None and not lat is None:
118             entry_geo = SubElement(entry, "georss:point")
119             entry_geo.text = "{lat} {lon}".format(lat=lat, lon=lon)
120         entry_wrreport = SubElement(entry, "wr:report")
121         entry_wrreport.attrib['report_id'] = str(report_id)
122         entry_wrreport.attrib['page_id'] = str(page_id)
123         entry_wrreport.attrib['page_title'] = page_title
124         entry_wrreport.attrib['date_report'] = str(date_report)
125         entry_wrreport.attrib['date_entry'] = str(date_entry)
126         entry_wrreport.attrib['condition'] = "0" if condition is None else str(condition)
127         entry_wrreport.attrib['author_name'] = author_name
128         entry_wrreport.attrib['author_username'] = "" if author_userid is None else author_username
129         entry_wrreport.text = description
130
131     if last_updated is None: last_updated = datetime.datetime.now()
132     feed_updated.text = last_updated.isoformat() + "+01:00"
133
134     return b'<?xml version="1.0" encoding="utf-8"?>\n' + tostring(feed)