1 """This module contains winterrodeln specific functions that are processing the MediaWiki markup.
4 import xml.etree.ElementTree
6 import mwparserfromhell
7 import wrpylib.wrvalidators
8 import wrpylib.mwmarkup
10 from wrpylib.wrvalidators import LonLat, opt_lonlat_from_str, opt_lonlat_to_str, opt_uint_from_str, opt_uint_to_str, \
11 opt_str_opt_comment_enum_to_str, lift_german_to_str, webauskunft_to_str, cachet_german_to_str, \
12 opt_phone_comment_enum_to_str, lift_german_from_str, GASTHAUSBOX_DICT
15 def sledrun_from_rodelbahnbox(value, sledrun):
16 """Takes a Rodelbahnbox as returned by rodelbahnbox_from_str (that is, an OrderedDict) and
17 updates the sledrun instance with all values present in the Rodelbahnbox. Other values are not
18 updated. Does not validate the arguments."""
19 # sledrun.page_id = None # this field is not updated because it is not present in the RodelbahnBox
20 # sledrun.page_title = None # this field is not updated because it is not present in the RodelbahnBox
21 # sledrun.name_url = None # this field is not updated because it is not present in the RodelbahnBox
22 sledrun.position_longitude, sledrun.position_latitude = value['Position']
23 sledrun.top_longitude, sledrun.top_latitude = value['Position oben']
24 sledrun.top_elevation = value['Höhe oben']
25 sledrun.bottom_longitude, sledrun.bottom_latitude = value['Position unten']
26 sledrun.bottom_elevation = value['Höhe unten']
27 sledrun.length = value['Länge']
28 sledrun.difficulty = value['Schwierigkeit']
29 sledrun.avalanches = value['Lawinen']
30 sledrun.operator = value['Betreiber']
31 sledrun.public_transport = value['Öffentliche Anreise']
32 sledrun.walkup_possible = value['Aufstieg möglich']
33 sledrun.walkup_time = value['Gehzeit']
34 sledrun.walkup_separate, sledrun.walkup_separate_comment = value['Aufstieg getrennt']
35 sledrun.lift = None if value['Aufstiegshilfe'] is None else len(value['Aufstiegshilfe']) > 0
36 sledrun.lift_details = lift_german_to_str(value['Aufstiegshilfe'])
37 sledrun.night_light, sledrun.night_light_comment = value['Beleuchtungsanlage']
38 sledrun.night_light_days, sledrun.night_light_days_comment = value['Beleuchtungstage']
39 sledrun.sled_rental = None if value['Rodelverleih'] is None else len(value['Rodelverleih']) > 0
40 sledrun.sled_rental_comment = opt_str_opt_comment_enum_to_str(value['Rodelverleih'])
41 sledrun.cachet = cachet_german_to_str(value['Gütesiegel'])
42 sledrun.information_web = webauskunft_to_str(value['Webauskunft'])
43 sledrun.information_phone = opt_phone_comment_enum_to_str(value['Telefonauskunft'])
44 sledrun.image = value['Bild']
45 sledrun.show_in_overview = value['In Übersichtskarte']
46 sledrun.forum_id = value['Forumid']
47 # sledrun.under_construction = None # this field is not updated because it is not present in the RodelbahnBox
51 def sledrun_to_rodelbahnbox(sledrun):
52 """Takes a sledrun instance that might come from the database and converts it to a OrderedDict ready
53 to be formatted as RodelbahnBox."""
54 value = collections.OrderedDict()
55 value['Position'] = LonLat(sledrun.position_longitude, sledrun.position_latitude)
56 value['Position oben'] = LonLat(sledrun.top_longitude, sledrun.top_latitude)
57 value['Höhe oben'] = sledrun.top_elevation
58 value['Position unten'] = LonLat(sledrun.bottom_longitude, sledrun.bottom_latitude)
59 value['Höhe unten'] = sledrun.bottom_elevation
60 value['Länge'] = sledrun.length
61 value['Schwierigkeit'] = sledrun.difficulty
62 value['Lawinen'] = sledrun.avalanches
63 value['Betreiber'] = sledrun.operator
64 value['Öffentliche Anreise'] = sledrun.public_transport
65 value['Aufstieg möglich'] = sledrun.walkup_possible
66 value['Gehzeit'] = sledrun.walkup_time
67 value['Aufstieg getrennt'] = sledrun.walkup_separate, sledrun.walkup_separate_comment
68 value['Aufstiegshilfe'] = lift_german_from_str(sledrun.lift_details)
69 value['Beleuchtungsanlage'] = sledrun.night_light, sledrun.night_light_comment
70 value['Beleuchtungstage'] = sledrun.night_light_days, sledrun.night_light_days_comment
71 value['Rodelverleih'] = sledrun.sled_rental, sledrun.sled_rental_comment
72 value['Gütesiegel'] = sledrun.cachet
73 value['Webauskunft'] = sledrun.information_web
74 value['Telefonauskunft'] = sledrun.information_phone
75 value['Bild'] = sledrun.image
76 value['In Übersichtskarte'] = sledrun.show_in_overview
77 value['Forumid'] = sledrun.forum_id
81 def inn_from_gasthausbox(value, inn):
82 """Converts a dict with Gasthausbox properties to a Inn class. Does no validation.
83 value is a dict of properties as returned by gasthausbox_from_str."""
84 # page_id = None # this field is not updated because it is not present in the Gasthausbox
85 # page_title = None # this field is not updated because it is not present in the Gasthausbox
86 def convtodb(value, key):
87 v = GASTHAUSBOX_DICT[key].to_str(value[key])
91 inn.position_longitude, inn.position_latitude = value['Position']
92 inn.position_elevation = value['Höhe']
93 inn.operator = value['Betreiber']
94 inn.seats = value['Sitzplätze']
95 inn.overnight, inn.overnight_comment = value['Übernachtung']
96 inn.smoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] < 0.9
97 inn.nonsmoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] > 0.1
98 inn.sled_rental, inn.sled_rental_comment = value['Rodelverleih']
99 inn.mobile_provider = convtodb(value, 'Handyempfang')
100 inn.homepage = convtodb(value, 'Homepage')
101 inn.email_list = convtodb(value, 'E-Mail')
102 inn.phone_list = convtodb(value, 'Telefon')
103 inn.image = value['Bild']
104 inn.sledding_list = convtodb(value, 'Rodelbahnen')
105 # under_construction = None # this field is not updated because it is not present in the GasthausBox
109 def inn_to_gasthausbox(inn):
110 """Converts an inn class to a dict of Gasthausbox properties. value is an Inn instance."""
111 def convfromdb(value, key):
112 v = '' if value is None else value
113 return GASTHAUSBOX_DICT[key].from_str(v)
114 value = collections.OrderedDict()
115 value['Position'] = LonLat(inn.position_longitude, inn.position_latitude)
116 value['Höhe'] = inn.position_elevation
117 value['Betreiber'] = inn.operator
118 value['Sitzplätze'] = inn.seats
119 value['Übernachtung'] = (inn.overnight, inn.overnight_comment)
120 value['Rauchfrei'] = {(False, True): 0.0, (True, True): 0.5, (True, False): 1.0}.get((inn.nonsmoker_area, inn.smoker_area), None)
121 value['Rodelverleih'] = (inn.sled_rental, inn.sled_rental_comment)
122 value['Handyempfang'] = convfromdb(inn.mobile_provider, 'Handyempfang')
123 value['Homepage'] = convfromdb(inn.homepage, 'Homepage')
124 value['E-Mail'] = convfromdb(inn.email_list, 'E-Mail')
125 value['Telefon'] = convfromdb(inn.phone_list, 'Telefon')
126 value['Bild'] = inn.image
127 value['Rodelbahnen'] = convfromdb(inn.sledding_list, 'Rodelbahnen')
131 def lonlat_ele_from_template(template):
132 """Template is a mwparserfromhell.nodes.template.Template instance. Returns (lonlat, ele)."""
133 lonlat = opt_lonlat_from_str(template.params[0].strip())
134 ele = opt_uint_from_str(template.params[1].strip())
138 def latlon_ele_to_template(lonlat_ele, name):
139 lonlat, ele = lonlat_ele
140 template = mwparserfromhell.nodes.template.Template(name)
141 template.add(1, opt_lonlat_to_str(lonlat))
142 template.add(2, opt_uint_to_str(ele))
143 wrpylib.mwmarkup.format_template_oneline(template)
147 class ParseError(RuntimeError):
148 """Exception used by some of the functions"""
152 def parse_wrmap_coordinates(coords):
153 """gets a string coordinates and returns an array of lon/lat coordinate pairs, e.g.
157 [[11.87, 47.12], [11.70, 47.13]]"""
160 for match in re.finditer(r'\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*', coords):
161 if match.start() != pos:
163 result.append([float(match.groups()[1]), float(match.groups()[0])])
166 if pos == len(coords):
168 raise RuntimeError('Wrong coordinate format: {}'.format(coords))
171 WRMAP_POINT_TYPES = ['gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt']
172 WRMAP_LINE_TYPES = ['rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie']
175 def parse_wrmap(wikitext):
176 """Parses the '<wrmap ...>content</wrmap>' of the Winterrodeln wrmap extension.
177 If wikitext does not contain the <wrmap> tag or if the <wrmap> tag contains
178 invalid formatted lines, a ParseError is raised.
179 Use wrpylib.mwmarkup.find_tag(wikitext, 'wrmap') to find the wrmap tag within an arbitrary
180 wikitext before using this function.
182 :param wikitext: wikitext containing only the template. Example:
185 <wrmap lat="47.2417134" lon="11.21408895" zoom="14" width="700" height="400">
186 <gasthaus name="Rosskogelhütte" wiki="Rosskogelhütte">47.240689 11.190454</gasthaus>
187 <parkplatz>47.245789 11.238971</parkplatz>
188 <haltestelle name="Oberperfuss Rangger Köpfl Lift">47.245711 11.238283</haltestelle>
196 :returns: GeoJSON as nested Python datatype
200 wrmap_xml = xml.etree.ElementTree.fromstring(wikitext)
201 except xml.etree.ElementTree.ParseError as e:
202 row, column = e.position
203 raise ParseError("XML parse error on row {}, column {}: {}".format(row, column, e))
204 if wrmap_xml.tag not in ['wrmap', 'wrgmap']:
205 raise ParseError('No valid tag name')
207 # convert XML to geojson (http://www.geojson.org/geojson-spec.html)
209 for feature in wrmap_xml:
210 # determine feature type
211 is_point = feature.tag in WRMAP_POINT_TYPES
212 is_line = feature.tag in WRMAP_LINE_TYPES
213 if (not is_point and not is_line):
214 raise ParseError('Unknown element <{}>.'.format(feature.tag))
218 properties = {'type': feature.tag}
219 allowed_properties = {'name', 'wiki'}
220 wrong_properties = set(feature.attrib.keys()) - allowed_properties
221 if len(wrong_properties) > 0:
222 raise ParseError("The attribute '{}' is not allowed at <{}>.".format(list(wrong_properties)[0], feature.tag))
223 properties.update(feature.attrib)
224 coordinates = parse_wrmap_coordinates(feature.text)
225 if len(coordinates) != 1:
226 raise ParseError('The element <{}> has to have exactly one coordinate pair.'.format(feature.tag))
227 json_features.append({
229 'geometry': {'type': 'Point', 'coordinates': coordinates[0]},
230 'properties': properties})
234 properties = {'type': feature.tag}
235 allowed_properties = {'farbe', 'dicke'}
236 wrong_properties = set(feature.attrib.keys()) - allowed_properties
237 if len(wrong_properties) > 0:
238 raise ParseError("The attribute '{}' is not allowed at <{}>.".format(list(wrong_properties)[0], feature.tag))
239 if 'farbe' in feature.attrib:
240 if not re.match('#[0-9a-fA-F]{6}$', feature.attrib['farbe']):
241 raise ParseError('The attribute "farbe" has to have a format like "#a0bb43".')
242 properties['strokeColor'] = feature.attrib['farbe'] # e.g. #a200b7
243 if 'dicke' in feature.attrib:
245 properties['strokeWidth'] = int(feature.attrib['dicke']) # e.g. 6
247 raise ParseError('The attribute "dicke" has to be an integer.')
248 json_features.append({
250 'geometry': {'type': 'LineString', 'coordinates': parse_wrmap_coordinates(feature.text)},
251 'properties': properties})
255 for k, v in wrmap_xml.attrib.items():
256 if k in ['lat', 'lon']:
258 properties[k] = float(v)
260 raise ParseError('Attribute "{}" has to be a float value.'.format(k))
261 elif k in ['zoom', 'width', 'height']:
263 properties[k] = int(v)
265 raise ParseError('Attribute "{}" has to be an integer value.'.format(k))
267 raise ParseError('Unknown attribute "{}".'.format(k))
270 'type': 'FeatureCollection',
271 'features': json_features,
272 'properties': properties}
277 def create_wrmap_coordinates(coords):
280 result.append('{:.6f} N {:.6f} E'.format(coord[1], coord[0]))
281 return '\n'.join(result)
284 def create_wrmap(geojson):
285 """Creates a <wrmap> wikitext from geojson (as python types)."""
286 wrmap_xml = xml.etree.ElementTree.Element('wrmap')
287 wrmap_xml.text = '\n\n'
288 for k, v in geojson['properties'].items():
289 if k in ['lon', 'lat']:
290 wrmap_xml.attrib[k] = '{:.6f}'.format(v)
292 wrmap_xml.attrib[k] = str(v)
294 assert geojson['type'] == 'FeatureCollection'
295 json_features = geojson['features']
296 last_json_feature = None
297 for json_feature in json_features:
298 feature_xml = xml.etree.ElementTree.SubElement(wrmap_xml, json_feature['properties']['type'])
299 geo = json_feature['geometry']
300 if geo['type'] == 'Point':
301 feature_xml.text = create_wrmap_coordinates([geo['coordinates']])
302 if last_json_feature is not None:
303 last_json_feature.tail = '\n'
305 if last_json_feature is not None:
306 last_json_feature.tail = '\n\n'
307 feature_xml.text = '\n' + create_wrmap_coordinates(geo['coordinates']) + '\n'
308 last_json_feature = feature_xml
309 feature_xml.attrib = json_feature['properties']
310 del feature_xml.attrib['type']
312 if last_json_feature is not None:
313 last_json_feature.tail = '\n\n'
314 return xml.etree.ElementTree.tostring(wrmap_xml, encoding='utf-8').decode('utf-8')