1 """This module contains winterrodeln specific functions that are processing the MediaWiki markup.
5 import xml.etree.ElementTree
7 from typing import Tuple, Optional, List, OrderedDict, Union, Dict
10 from mwparserfromhell.nodes import Template
12 import wrpylib.wrvalidators
13 import wrpylib.mwmarkup
15 from wrpylib.wrvalidators import LonLat, opt_lonlat_from_str, opt_lonlat_to_str, opt_uint_from_str, opt_uint_to_str, \
16 opt_str_opt_comment_enum_to_str, lift_german_to_str, webauskunft_to_str, cachet_german_to_str, \
17 opt_phone_comment_enum_to_str, lift_german_from_str, GASTHAUSBOX_DICT, opt_difficulty_german_from_str, \
18 opt_avalanches_german_from_str, nightlightdays_from_str, opt_public_transport_german_from_str, \
19 opt_tristate_german_comment_from_str, rodelbahnbox_to_str, lonlat_to_str
22 def split_lon_lat(value: Optional[LonLat]) -> Union[LonLat, Tuple[None, None]]:
28 def join_lon_lat(lon: Optional[float], lat: Optional[float]) -> Optional[LonLat]:
29 if lon is None or lat is None:
31 return LonLat(lon, lat)
34 def sledrun_from_rodelbahnbox(value: OrderedDict, sledrun: object):
35 """Takes a Rodelbahnbox as returned by rodelbahnbox_from_str (that is, an OrderedDict) and
36 updates the sledrun instance with all values present in the Rodelbahnbox. Other values are not
37 updated. Does not validate the arguments."""
38 # sledrun.page_id = None # this field is not updated because it is not present in the RodelbahnBox
39 # sledrun.page_title = None # this field is not updated because it is not present in the RodelbahnBox
40 # sledrun.name_url = None # this field is not updated because it is not present in the RodelbahnBox
41 sledrun.position_longitude, sledrun.position_latitude = split_lon_lat(value['Position'])
42 sledrun.top_longitude, sledrun.top_latitude = split_lon_lat(value['Position oben'])
43 sledrun.top_elevation = value['Höhe oben']
44 sledrun.bottom_longitude, sledrun.bottom_latitude = split_lon_lat(value['Position unten'])
45 sledrun.bottom_elevation = value['Höhe unten']
46 sledrun.length = value['Länge']
47 sledrun.difficulty = value['Schwierigkeit']
48 sledrun.avalanches = value['Lawinen']
49 sledrun.operator = value['Betreiber']
50 sledrun.public_transport = value['Öffentliche Anreise']
51 sledrun.walkup_possible = value['Aufstieg möglich']
52 sledrun.walkup_time = value['Gehzeit']
53 sledrun.walkup_separate, sledrun.walkup_separate_comment = value['Aufstieg getrennt']
54 sledrun.lift = None if value['Aufstiegshilfe'] is None else len(value['Aufstiegshilfe']) > 0
55 sledrun.lift_details = lift_german_to_str(value['Aufstiegshilfe'])
56 sledrun.night_light, sledrun.night_light_comment = value['Beleuchtungsanlage']
57 sledrun.night_light_days, sledrun.night_light_days_comment = value['Beleuchtungstage']
58 sledrun.sled_rental = None if value['Rodelverleih'] is None else len(value['Rodelverleih']) > 0
59 sledrun.sled_rental_comment = opt_str_opt_comment_enum_to_str(value['Rodelverleih'])
60 sledrun.cachet = cachet_german_to_str(value['Gütesiegel'])
61 sledrun.information_web = webauskunft_to_str(value['Webauskunft'])
62 sledrun.information_phone = opt_phone_comment_enum_to_str(value['Telefonauskunft'])
63 sledrun.image = value['Bild']
64 sledrun.show_in_overview = value['In Übersichtskarte']
65 sledrun.forum_id = value['Forumid']
66 # sledrun.under_construction = None # this field is not updated because it is not present in the RodelbahnBox
70 def sledrun_to_rodelbahnbox(sledrun) -> collections.OrderedDict:
71 """Takes a sledrun instance that might come from the database and converts it to a OrderedDict ready
72 to be formatted as RodelbahnBox."""
73 value = collections.OrderedDict()
74 value['Position'] = join_lon_lat(sledrun.position_longitude, sledrun.position_latitude)
75 value['Position oben'] = join_lon_lat(sledrun.top_longitude, sledrun.top_latitude)
76 value['Höhe oben'] = sledrun.top_elevation
77 value['Position unten'] = join_lon_lat(sledrun.bottom_longitude, sledrun.bottom_latitude)
78 value['Höhe unten'] = sledrun.bottom_elevation
79 value['Länge'] = sledrun.length
80 value['Schwierigkeit'] = sledrun.difficulty
81 value['Lawinen'] = sledrun.avalanches
82 value['Betreiber'] = sledrun.operator
83 value['Öffentliche Anreise'] = sledrun.public_transport
84 value['Aufstieg möglich'] = sledrun.walkup_possible
85 value['Gehzeit'] = sledrun.walkup_time
86 value['Aufstieg getrennt'] = sledrun.walkup_separate, sledrun.walkup_separate_comment
87 value['Aufstiegshilfe'] = lift_german_from_str(sledrun.lift_details)
88 value['Beleuchtungsanlage'] = sledrun.night_light, sledrun.night_light_comment
89 value['Beleuchtungstage'] = sledrun.night_light_days, sledrun.night_light_days_comment
90 value['Rodelverleih'] = sledrun.sled_rental, sledrun.sled_rental_comment
91 value['Gütesiegel'] = sledrun.cachet
92 value['Webauskunft'] = sledrun.information_web
93 value['Telefonauskunft'] = sledrun.information_phone
94 value['Bild'] = sledrun.image
95 value['In Übersichtskarte'] = sledrun.show_in_overview
96 value['Forumid'] = sledrun.forum_id
100 def inn_from_gasthausbox(value, inn):
101 """Converts a dict with Gasthausbox properties to a Inn class. Does no validation.
102 value is a dict of properties as returned by gasthausbox_from_str."""
103 # page_id = None # this field is not updated because it is not present in the Gasthausbox
104 # page_title = None # this field is not updated because it is not present in the Gasthausbox
105 def convtodb(val, key):
106 v = GASTHAUSBOX_DICT[key].to_str(val[key])
110 inn.position_longitude, inn.position_latitude = split_lon_lat(value['Position'])
111 inn.position_elevation = value['Höhe']
112 inn.operator = value['Betreiber']
113 inn.seats = value['Sitzplätze']
114 inn.overnight, inn.overnight_comment = value['Übernachtung']
115 inn.smoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] < 0.9
116 inn.nonsmoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] > 0.1
117 inn.sled_rental, inn.sled_rental_comment = value['Rodelverleih']
118 inn.mobile_provider = convtodb(value, 'Handyempfang')
119 inn.homepage = convtodb(value, 'Homepage')
120 inn.email_list = convtodb(value, 'E-Mail')
121 inn.phone_list = convtodb(value, 'Telefon')
122 inn.image = value['Bild']
123 inn.sledding_list = convtodb(value, 'Rodelbahnen')
124 # under_construction = None # this field is not updated because it is not present in the GasthausBox
128 def inn_to_gasthausbox(inn) -> collections.OrderedDict:
129 """Converts an inn class to a dict of Gasthausbox properties. inn is an Inn instance."""
130 def convfromdb(val, key):
131 v = '' if val is None else val
132 return GASTHAUSBOX_DICT[key].from_str(v)
133 value = collections.OrderedDict()
134 value['Position'] = join_lon_lat(inn.position_longitude, inn.position_latitude)
135 value['Höhe'] = inn.position_elevation
136 value['Betreiber'] = inn.operator
137 value['Sitzplätze'] = inn.seats
138 value['Übernachtung'] = (inn.overnight, inn.overnight_comment)
139 value['Rauchfrei'] = {(False, True): 0.0, (True, True): 0.5, (True, False): 1.0} \
140 .get((inn.nonsmoker_area, inn.smoker_area), None)
141 value['Rodelverleih'] = (inn.sled_rental, inn.sled_rental_comment)
142 value['Handyempfang'] = convfromdb(inn.mobile_provider, 'Handyempfang')
143 value['Homepage'] = convfromdb(inn.homepage, 'Homepage')
144 value['E-Mail'] = convfromdb(inn.email_list, 'E-Mail')
145 value['Telefon'] = convfromdb(inn.phone_list, 'Telefon')
146 value['Bild'] = inn.image
147 value['Rodelbahnen'] = convfromdb(inn.sledding_list, 'Rodelbahnen')
151 def lonlat_ele_from_template(template) -> Tuple[LonLat, Optional[int]]:
152 """Template is a `mwparserfromhell.nodes.template.Template` instance. Returns (lonlat, ele)."""
153 lonlat = opt_lonlat_from_str(template.params[0].strip())
154 ele = opt_uint_from_str(template.params[1].strip())
158 def latlon_ele_to_template(lonlat_ele, name) -> Template:
159 lonlat, ele = lonlat_ele
160 template = Template(name)
161 template.add(1, opt_lonlat_to_str(lonlat))
162 template.add(2, opt_uint_to_str(ele))
163 wrpylib.mwmarkup.format_template_oneline(template)
167 class ParseError(RuntimeError):
168 """Exception used by some of the functions"""
172 def parse_wrmap_coordinates(coords: str) -> List[List[float]]:
173 """gets a string coordinates and returns an array of lon/lat coordinate pairs, e.g.
177 [[11.87, 47.12], [11.70, 47.13]]"""
180 for match in re.finditer(r'\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*', coords):
181 if match.start() != pos:
183 result.append([float(match.groups()[1]), float(match.groups()[0])])
186 if pos == len(coords):
188 raise RuntimeError(f'Wrong coordinate format: {coords}')
191 WRMAP_POINT_TYPES = ['gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt']
192 WRMAP_LINE_TYPES = ['rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie']
195 def parse_wrmap(wikitext):
196 """Parses the '<wrmap ...>content</wrmap>' of the Winterrodeln wrmap extension.
197 If wikitext does not contain the <wrmap> tag or if the <wrmap> tag contains
198 invalid formatted lines, a ParseError is raised.
199 Use wrpylib.mwmarkup.find_tag(wikitext, 'wrmap') to find the wrmap tag within an arbitrary
200 wikitext before using this function.
202 :param wikitext: wikitext containing only the template. Example:
205 <wrmap lat="47.2417134" lon="11.21408895" zoom="14" width="700" height="400">
206 <gasthaus name="Rosskogelhütte" wiki="Rosskogelhütte">47.240689 11.190454</gasthaus>
207 <parkplatz>47.245789 11.238971</parkplatz>
208 <haltestelle name="Oberperfuss Rangger Köpfl Lift">47.245711 11.238283</haltestelle>
216 :returns: GeoJSON as nested Python datatype
220 wrmap_xml = xml.etree.ElementTree.fromstring(wikitext)
221 except xml.etree.ElementTree.ParseError as e:
222 row, column = e.position
223 raise ParseError(f"XML parse error on row {row}, column {column}: {e}")
224 if wrmap_xml.tag not in ['wrmap', 'wrgmap']:
225 raise ParseError('No valid tag name')
227 # convert XML to geojson (http://www.geojson.org/geojson-spec.html)
229 for feature in wrmap_xml:
230 # determine feature type
231 is_point = feature.tag in WRMAP_POINT_TYPES
232 is_line = feature.tag in WRMAP_LINE_TYPES
233 if not is_point and not is_line:
234 raise ParseError(f'Unknown element <{feature.tag}>.')
238 properties = {'type': feature.tag}
239 allowed_properties = {'name', 'wiki'}
240 wrong_properties = set(feature.attrib.keys()) - allowed_properties
241 if len(wrong_properties) > 0:
242 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
243 properties.update(feature.attrib)
244 coordinates = parse_wrmap_coordinates(feature.text)
245 if len(coordinates) != 1:
246 raise ParseError(f'The element <{feature.tag}> has to have exactly one coordinate pair.')
247 json_features.append({
249 'geometry': {'type': 'Point', 'coordinates': coordinates[0]},
250 'properties': properties})
254 properties = {'type': feature.tag}
255 allowed_properties = {'farbe', 'dicke'}
256 wrong_properties = set(feature.attrib.keys()) - allowed_properties
257 if len(wrong_properties) > 0:
258 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
259 if 'farbe' in feature.attrib:
260 if not re.match('#[0-9a-fA-F]{6}$', feature.attrib['farbe']):
261 raise ParseError('The attribute "farbe" has to have a format like "#a0bb43".')
262 properties['strokeColor'] = feature.attrib['farbe'] # e.g. #a200b7
263 if 'dicke' in feature.attrib:
265 properties['strokeWidth'] = int(feature.attrib['dicke']) # e.g. 6
267 raise ParseError('The attribute "dicke" has to be an integer.')
268 json_features.append({
270 'geometry': {'type': 'LineString', 'coordinates': parse_wrmap_coordinates(feature.text)},
271 'properties': properties})
275 for k, v in wrmap_xml.attrib.items():
276 if k in ['lat', 'lon']:
278 properties[k] = float(v)
280 raise ParseError(f'Attribute "{k}" has to be a float value.')
281 elif k in ['zoom', 'width', 'height']:
283 properties[k] = int(v)
285 raise ParseError(f'Attribute "{k}" has to be an integer value.')
287 raise ParseError(f'Unknown attribute "{k}".')
290 'type': 'FeatureCollection',
291 'features': json_features,
292 'properties': properties}
297 def create_wrmap_coordinates(coords):
300 result.append(f'{coord[1]:.6f} N {coord[0]:.6f} E')
301 return '\n'.join(result)
304 def create_wrmap(geojson: Dict) -> str:
305 """Creates a <wrmap> wikitext from geojson (as python types)."""
306 wrmap_xml = xml.etree.ElementTree.Element('wrmap')
307 wrmap_xml.text = '\n\n'
308 for k, v in geojson['properties'].items():
309 if k in ['lon', 'lat']:
310 wrmap_xml.attrib[k] = f'{v:.6f}'
312 wrmap_xml.attrib[k] = str(v)
314 assert geojson['type'] == 'FeatureCollection'
315 json_features = geojson['features']
316 last_json_feature = None
317 for json_feature in json_features:
318 feature_xml = xml.etree.ElementTree.SubElement(wrmap_xml, json_feature['properties']['type'])
319 geo = json_feature['geometry']
320 if geo['type'] == 'Point':
321 feature_xml.text = create_wrmap_coordinates([geo['coordinates']])
322 if last_json_feature is not None:
323 last_json_feature.tail = '\n'
325 if last_json_feature is not None:
326 last_json_feature.tail = '\n\n'
327 feature_xml.text = '\n' + create_wrmap_coordinates(geo['coordinates']) + '\n'
328 last_json_feature = feature_xml
329 feature_xml.attrib = json_feature['properties']
330 del feature_xml.attrib['type']
332 if last_json_feature is not None:
333 last_json_feature.tail = '\n\n'
334 return xml.etree.ElementTree.tostring(wrmap_xml, encoding='utf-8').decode('utf-8')
338 def create_wrmap(self, geojson: Dict) -> str:
339 return create_wrmap(geojson)
341 def json_position(self, value: dict) -> str:
342 lon_lat = LonLat(value['longitude'], value['latitude'])
343 return lonlat_to_str(lon_lat)
345 def json_pos_ele_position(self, value: dict) -> str:
346 pos = value.get('position')
349 return self.json_position(pos)
351 def json_pos_ele_elevation(self, value: dict) -> str:
352 return value.get('elevation', '')
354 def list_template(self, name: str, value: List[str]) -> str:
355 return str(wrpylib.mwmarkup.create_template(name, value))
357 def json_template(self, value) -> str:
360 for p in value.get('parameter', []):
361 v = p.get('value', '')
366 return str(wrpylib.mwmarkup.create_template(value['name'], args, kwargs))
369 def create_sledrun_wiki(sledrun_json: Dict, map_json: Optional[Dict]) -> str:
370 env = jinja2.Environment(
371 loader=jinja2.PackageLoader("wrpylib"),
372 autoescape=jinja2.select_autoescape()
374 template = env.get_template("sledrun_wiki.txt")
376 def markdown_to_mediawiki(markdown: str) -> str:
377 return subprocess.check_output(['pandoc', '--to', 'mediawiki'], input=markdown, encoding='utf-8')
379 def position_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
380 if value is not None:
381 lon = value.get('longitude')
382 lat = value.get('latitude')
383 if lon is not None and lat is not None:
384 return LonLat(lon, lat)
387 def position_ele_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
388 if value is not None:
389 return position_to_lon_lat(value.get("position"))
392 def position_ele_to_ele(value: Optional[dict]) -> Optional[int]:
393 if value is not None:
394 ele = value.get('elevation')
399 def aufstiegshilfe() -> Optional[List[Tuple[str, Optional[str]]]]:
400 ws = sledrun_json.get('walkup_supports')
403 return [(w['type'], w.get('comment')) for w in ws]
405 def rodelverleih() -> Optional[List[Tuple[str, Optional[str]]]]:
406 sr = sledrun_json.get('sled_rental_direct')
409 return [('Ja', None)] if sr else []
411 def webauskunft() -> Tuple[Optional[bool], Optional[str]]:
412 info_web = sledrun_json.get('info_web')
415 if len(info_web) == 0:
417 return True, info_web[0]['url']
419 def telefonauskunft() -> Optional[List[Tuple[str, str]]]:
420 info_phone = sledrun_json.get('info_phone')
421 if info_phone is None:
423 return [(pc['phone'], pc['name']) for pc in info_phone]
425 def betreiber() -> str:
426 has_operator = sledrun_json.get('has_operator')
427 if has_operator is None:
428 return sledrun_json.get('operator')
430 return sledrun_json.get('operator')
433 sledrun_rbb_json = collections.OrderedDict([
434 ('Position', position_to_lon_lat(sledrun_json.get('position'))),
435 ('Position oben', position_ele_to_lon_lat(sledrun_json.get('top'))),
436 ('Höhe oben', position_ele_to_ele(sledrun_json.get('top'))),
437 ('Position unten', position_ele_to_lon_lat(sledrun_json.get('bottom'))),
438 ('Höhe unten', position_ele_to_ele(sledrun_json.get('bottom'))),
439 ('Länge', sledrun_json.get('length')),
440 ('Schwierigkeit', opt_difficulty_german_from_str(sledrun_json.get('difficulty', ''))),
441 ('Lawinen', opt_avalanches_german_from_str(sledrun_json.get('avalanches', ''))),
442 ('Betreiber', betreiber()),
443 ('Öffentliche Anreise', opt_public_transport_german_from_str(sledrun_json.get('public_transport', ''))),
444 ('Aufstieg möglich', sledrun_json.get('walkup_possible')),
445 ('Aufstieg getrennt', opt_tristate_german_comment_from_str(sledrun_json.get('walkup_separate', ''))),
446 ('Gehzeit', sledrun_json.get('walkup_time')),
447 ('Aufstiegshilfe', aufstiegshilfe()),
448 ('Beleuchtungsanlage', opt_tristate_german_comment_from_str(sledrun_json.get('nightlight_possible', ''))),
449 ('Beleuchtungstage', nightlightdays_from_str(sledrun_json.get('nightlight_weekdays', ''))),
450 ('Rodelverleih', rodelverleih()),
451 ('Gütesiegel', None),
452 ('Webauskunft', webauskunft()),
453 ('Telefonauskunft', telefonauskunft()),
454 ('Bild', sledrun_json.get('image')),
455 ('In Übersichtskarte', sledrun_json.get('show_in_overview')),
456 ('Forumid', sledrun_json.get('forum_id'))
459 def get_markdown_field(key: str) -> str:
460 if key in sledrun_json:
461 return markdown_to_mediawiki(sledrun_json[key])
464 description = get_markdown_field('description').strip()
465 night_light = get_markdown_field('night_light').strip()
466 sled_rental_description = get_markdown_field('sled_rental_description').strip()
468 rodelbahnbox = rodelbahnbox_to_str(sledrun_rbb_json)
470 return template.render(sledrun_json=sledrun_json,
471 rodelbahnbox=rodelbahnbox, description=description, night_light=night_light,
472 sled_rental_description=sled_rental_description, operator=betreiber(),
473 map_json=map_json, h=Jinja2Tools())