1 """This module contains winterrodeln specific functions that are processing the MediaWiki markup.
4 import xml.etree.ElementTree
6 from typing import Tuple, Optional, List, OrderedDict, Union, Dict, Any
9 from mwparserfromhell.nodes import Template, Wikilink
11 import wrpylib.wrvalidators
12 import wrpylib.mwmarkup
14 from wrpylib.lib_sledrun_wikitext_from_json import strip_eol
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, opt_public_transport_german_from_str, \
19 opt_tristate_german_comment_from_str, rodelbahnbox_to_str, lonlat_to_str, opt_no_or_str_to_str, \
20 opt_no_or_str_from_str, opt_tristate_german_from_str
23 def split_lon_lat(value: Optional[LonLat]) -> Union[LonLat, Tuple[None, None]]:
29 def join_lon_lat(lon: Optional[float], lat: Optional[float]) -> Optional[LonLat]:
30 if lon is None or lat is None:
32 return LonLat(lon, lat)
35 def sledrun_from_rodelbahnbox(value: OrderedDict, sledrun: object):
36 """Takes a Rodelbahnbox as returned by rodelbahnbox_from_str (that is, an OrderedDict) and
37 updates the sledrun instance with all values present in the Rodelbahnbox. Other values are not
38 updated. Does not validate the arguments."""
39 # sledrun.page_id = None # this field is not updated because it is not present in the RodelbahnBox
40 # sledrun.page_title = None # this field is not updated because it is not present in the RodelbahnBox
41 # sledrun.name_url = None # this field is not updated because it is not present in the RodelbahnBox
42 sledrun.position_longitude, sledrun.position_latitude = split_lon_lat(value['Position'])
43 sledrun.top_longitude, sledrun.top_latitude = split_lon_lat(value['Position oben'])
44 sledrun.top_elevation = value['Höhe oben']
45 sledrun.bottom_longitude, sledrun.bottom_latitude = split_lon_lat(value['Position unten'])
46 sledrun.bottom_elevation = value['Höhe unten']
47 sledrun.length = value['Länge']
48 sledrun.difficulty = value['Schwierigkeit']
49 sledrun.avalanches = value['Lawinen']
50 sledrun.operator = opt_no_or_str_to_str(value['Betreiber'])
51 sledrun.public_transport = value['Öffentliche Anreise']
52 sledrun.walkup_possible = value['Aufstieg möglich']
53 sledrun.walkup_time = value['Gehzeit']
54 sledrun.walkup_separate, sledrun.walkup_separate_comment = value['Aufstieg getrennt']
55 sledrun.lift = None if value['Aufstiegshilfe'] is None else len(value['Aufstiegshilfe']) > 0
56 sledrun.lift_details = lift_german_to_str(value['Aufstiegshilfe'])
57 sledrun.night_light, sledrun.night_light_comment = value['Beleuchtungsanlage']
58 sledrun.night_light_days, sledrun.night_light_days_comment = value['Beleuchtungstage']
59 sledrun.sled_rental = None if value['Rodelverleih'] is None else len(value['Rodelverleih']) > 0
60 sledrun.sled_rental_comment = opt_str_opt_comment_enum_to_str(value['Rodelverleih'])
61 sledrun.cachet = cachet_german_to_str(value['Gütesiegel'])
62 sledrun.information_web = webauskunft_to_str(value['Webauskunft'])
63 sledrun.information_phone = opt_phone_comment_enum_to_str(value['Telefonauskunft'])
64 sledrun.image = value['Bild']
65 sledrun.show_in_overview = value['In Übersichtskarte']
66 sledrun.forum_id = value['Forumid']
67 # sledrun.under_construction = None # this field is not updated because it is not present in the RodelbahnBox
71 def sledrun_to_rodelbahnbox(sledrun) -> collections.OrderedDict:
72 """Takes a sledrun instance that might come from the database and converts it to a OrderedDict ready
73 to be formatted as RodelbahnBox."""
74 value = collections.OrderedDict()
75 value['Position'] = join_lon_lat(sledrun.position_longitude, sledrun.position_latitude)
76 value['Position oben'] = join_lon_lat(sledrun.top_longitude, sledrun.top_latitude)
77 value['Höhe oben'] = sledrun.top_elevation
78 value['Position unten'] = join_lon_lat(sledrun.bottom_longitude, sledrun.bottom_latitude)
79 value['Höhe unten'] = sledrun.bottom_elevation
80 value['Länge'] = sledrun.length
81 value['Schwierigkeit'] = sledrun.difficulty
82 value['Lawinen'] = sledrun.avalanches
83 value['Betreiber'] = opt_no_or_str_from_str(sledrun.operator)
84 value['Öffentliche Anreise'] = sledrun.public_transport
85 value['Aufstieg möglich'] = sledrun.walkup_possible
86 value['Gehzeit'] = sledrun.walkup_time
87 value['Aufstieg getrennt'] = sledrun.walkup_separate, sledrun.walkup_separate_comment
88 value['Aufstiegshilfe'] = lift_german_from_str(sledrun.lift_details)
89 value['Beleuchtungsanlage'] = sledrun.night_light, sledrun.night_light_comment
90 value['Beleuchtungstage'] = sledrun.night_light_days, sledrun.night_light_days_comment
91 value['Rodelverleih'] = sledrun.sled_rental, sledrun.sled_rental_comment
92 value['Gütesiegel'] = sledrun.cachet
93 value['Webauskunft'] = sledrun.information_web
94 value['Telefonauskunft'] = sledrun.information_phone
95 value['Bild'] = sledrun.image
96 value['In Übersichtskarte'] = sledrun.show_in_overview
97 value['Forumid'] = sledrun.forum_id
101 def inn_from_gasthausbox(value, inn):
102 """Converts a dict with Gasthausbox properties to a Inn class. Does no validation.
103 value is a dict of properties as returned by gasthausbox_from_str."""
104 # page_id = None # this field is not updated because it is not present in the Gasthausbox
105 # page_title = None # this field is not updated because it is not present in the Gasthausbox
106 def convtodb(val, key):
107 v = GASTHAUSBOX_DICT[key].to_str(val[key])
111 inn.position_longitude, inn.position_latitude = split_lon_lat(value['Position'])
112 inn.position_elevation = value['Höhe']
113 inn.operator = value['Betreiber']
114 inn.seats = value['Sitzplätze']
115 inn.overnight, inn.overnight_comment = value['Übernachtung']
116 inn.smoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] < 0.9
117 inn.nonsmoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] > 0.1
118 inn.sled_rental, inn.sled_rental_comment = value['Rodelverleih']
119 inn.mobile_provider = convtodb(value, 'Handyempfang')
120 inn.homepage = convtodb(value, 'Homepage')
121 inn.email_list = convtodb(value, 'E-Mail')
122 inn.phone_list = convtodb(value, 'Telefon')
123 inn.image = value['Bild']
124 inn.sledding_list = convtodb(value, 'Rodelbahnen')
125 # under_construction = None # this field is not updated because it is not present in the GasthausBox
129 def inn_to_gasthausbox(inn) -> collections.OrderedDict:
130 """Converts an inn class to a dict of Gasthausbox properties. inn is an Inn instance."""
131 def convfromdb(val, key):
132 v = '' if val is None else val
133 return GASTHAUSBOX_DICT[key].from_str(v)
134 value = collections.OrderedDict()
135 value['Position'] = join_lon_lat(inn.position_longitude, inn.position_latitude)
136 value['Höhe'] = inn.position_elevation
137 value['Betreiber'] = inn.operator
138 value['Sitzplätze'] = inn.seats
139 value['Übernachtung'] = (inn.overnight, inn.overnight_comment)
140 value['Rauchfrei'] = {(False, True): 0.0, (True, True): 0.5, (True, False): 1.0} \
141 .get((inn.nonsmoker_area, inn.smoker_area), None)
142 value['Rodelverleih'] = (inn.sled_rental, inn.sled_rental_comment)
143 value['Handyempfang'] = convfromdb(inn.mobile_provider, 'Handyempfang')
144 value['Homepage'] = convfromdb(inn.homepage, 'Homepage')
145 value['E-Mail'] = convfromdb(inn.email_list, 'E-Mail')
146 value['Telefon'] = convfromdb(inn.phone_list, 'Telefon')
147 value['Bild'] = inn.image
148 value['Rodelbahnen'] = convfromdb(inn.sledding_list, 'Rodelbahnen')
152 def lonlat_ele_from_template(template) -> Tuple[Optional[LonLat], Optional[int]]:
153 """Template is a `mwparserfromhell.nodes.template.Template` instance. Returns (lonlat, ele)."""
154 lonlat = opt_lonlat_from_str(template.params[0].strip())
155 ele = opt_uint_from_str(template.params[1].strip())
159 def latlon_ele_to_template(lonlat_ele: Tuple[Optional[LonLat], Optional[int]], name: str) -> Template:
160 lonlat, ele = lonlat_ele
161 template = Template(name)
162 template.add(1, opt_lonlat_to_str(lonlat))
163 template.add(2, opt_uint_to_str(ele))
164 wrpylib.mwmarkup.format_template_oneline(template)
168 def lonlat_to_json(lonlat: LonLat) -> dict:
169 return {'longitude': lonlat.lon, 'latitude': lonlat.lat}
172 def lonlat_ele_to_json(lonlat: Optional[LonLat], ele: Optional[int]) -> dict:
174 if lonlat is not None:
175 result['position'] = lonlat_to_json(lonlat)
177 result['elevation'] = ele
181 class ParseError(RuntimeError):
182 """Exception used by some of the functions"""
186 def parse_wrmap_coordinates(coords: str) -> List[List[float]]:
187 """gets a string coordinates and returns an array of lon/lat coordinate pairs, e.g.
191 [[11.87, 47.12], [11.70, 47.13]]"""
194 for match in re.finditer(r'\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*', coords):
195 if match.start() != pos:
197 result.append([float(match.groups()[1]), float(match.groups()[0])])
200 if pos == len(coords):
202 raise RuntimeError(f'Wrong coordinate format: {coords}')
205 WRMAP_POINT_TYPES = ['gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt']
206 WRMAP_LINE_TYPES = ['rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie']
209 def parse_wrmap(wikitext: str) -> dict:
210 """Parses the '<wrmap ...>content</wrmap>' of the Winterrodeln wrmap extension.
211 If wikitext does not contain the <wrmap> tag or if the <wrmap> tag contains
212 invalid formatted lines, a ParseError is raised.
213 Use wrpylib.mwmarkup.find_tag(wikitext, 'wrmap') to find the wrmap tag within an arbitrary
214 wikitext before using this function.
216 :param wikitext: wikitext containing only the template. Example:
219 <wrmap lat="47.2417134" lon="11.21408895" zoom="14" width="700" height="400">
220 <gasthaus name="Rosskogelhütte" wiki="Rosskogelhütte">47.240689 11.190454</gasthaus>
221 <parkplatz>47.245789 11.238971</parkplatz>
222 <haltestelle name="Oberperfuss Rangger Köpfl Lift">47.245711 11.238283</haltestelle>
230 :returns: GeoJSON as nested Python datatype
234 wrmap_xml = xml.etree.ElementTree.fromstring(wikitext)
235 except xml.etree.ElementTree.ParseError as e:
236 row, column = e.position
237 raise ParseError(f"XML parse error on row {row}, column {column}: {e}")
238 if wrmap_xml.tag not in ['wrmap', 'wrgmap']:
239 raise ParseError('No valid tag name')
241 # convert XML to geojson (http://www.geojson.org/geojson-spec.html)
243 for feature in wrmap_xml:
244 # determine feature type
245 is_point = feature.tag in WRMAP_POINT_TYPES
246 is_line = feature.tag in WRMAP_LINE_TYPES
247 if not is_point and not is_line:
248 raise ParseError(f'Unknown element <{feature.tag}>.')
252 properties = {'type': feature.tag}
253 allowed_properties = {'name', 'wiki'}
254 wrong_properties = set(feature.attrib.keys()) - allowed_properties
255 if len(wrong_properties) > 0:
256 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
257 properties.update(feature.attrib)
258 coordinates = parse_wrmap_coordinates(feature.text)
259 if len(coordinates) != 1:
260 raise ParseError(f'The element <{feature.tag}> has to have exactly one coordinate pair.')
261 json_features.append({
263 'geometry': {'type': 'Point', 'coordinates': coordinates[0]},
264 'properties': properties})
268 properties = {'type': feature.tag}
269 allowed_properties = {'farbe', 'dicke'}
270 wrong_properties = set(feature.attrib.keys()) - allowed_properties
271 if len(wrong_properties) > 0:
272 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
273 if 'farbe' in feature.attrib:
274 if not re.match('#[0-9a-fA-F]{6}$', feature.attrib['farbe']):
275 raise ParseError('The attribute "farbe" has to have a format like "#a0bb43".')
276 properties['strokeColor'] = feature.attrib['farbe'] # e.g. #a200b7
277 if 'dicke' in feature.attrib:
279 properties['strokeWidth'] = int(feature.attrib['dicke']) # e.g. 6
281 raise ParseError('The attribute "dicke" has to be an integer.')
282 json_features.append({
284 'geometry': {'type': 'LineString', 'coordinates': parse_wrmap_coordinates(feature.text)},
285 'properties': properties})
289 for k, v in wrmap_xml.attrib.items():
290 if k in ['lat', 'lon']:
292 properties[k] = float(v)
294 raise ParseError(f'Attribute "{k}" has to be a float value.')
295 elif k in ['zoom', 'width', 'height']:
297 properties[k] = int(v)
299 raise ParseError(f'Attribute "{k}" has to be an integer value.')
301 raise ParseError(f'Unknown attribute "{k}".')
304 'type': 'FeatureCollection',
305 'features': json_features,
306 'properties': properties}
311 def create_wrmap_coordinates(coords):
314 result.append(f'{coord[1]:.6f} N {coord[0]:.6f} E')
315 return '\n'.join(result)
318 def create_wrmap(geojson: Dict) -> str:
319 """Creates a <wrmap> wikitext from geojson (as python types)."""
320 wrmap_xml = xml.etree.ElementTree.Element('wrmap')
321 wrmap_xml.text = '\n\n'
322 for k, v in geojson['properties'].items():
323 if k in ['lon', 'lat']:
324 wrmap_xml.attrib[k] = f'{v:.6f}'
326 wrmap_xml.attrib[k] = str(v)
328 assert geojson['type'] == 'FeatureCollection'
329 json_features = geojson['features']
330 last_json_feature = None
331 for json_feature in json_features:
332 feature_xml = xml.etree.ElementTree.SubElement(wrmap_xml, json_feature['properties']['type'])
333 geo = json_feature['geometry']
334 if geo['type'] == 'Point':
335 feature_xml.text = create_wrmap_coordinates([geo['coordinates']])
336 if last_json_feature is not None:
337 last_json_feature.tail = '\n'
339 if last_json_feature is not None:
340 last_json_feature.tail = '\n\n'
341 feature_xml.text = '\n' + create_wrmap_coordinates(geo['coordinates']) + '\n'
342 last_json_feature = feature_xml
343 feature_xml.attrib = json_feature['properties'].copy()
344 del feature_xml.attrib['type']
346 if last_json_feature is not None:
347 last_json_feature.tail = '\n\n'
348 return xml.etree.ElementTree.tostring(wrmap_xml, encoding='utf-8').decode('utf-8')
351 def german_bool(value: Union[bool, jinja2.Undefined]) -> Union[str, jinja2.Undefined]:
352 if jinja2.is_undefined(value):
354 return wrpylib.wrvalidators.bool_german_to_str(value)
358 def create_wrmap(self, geojson: Dict) -> str:
359 return create_wrmap(geojson)
361 def json_position(self, value: dict) -> str:
362 lon_lat = LonLat(value['longitude'], value['latitude'])
363 return lonlat_to_str(lon_lat)
365 def json_pos_ele_position(self, value: dict) -> str:
366 pos = value.get('position')
369 return self.json_position(pos)
371 def json_pos_ele_elevation(self, value: dict) -> str:
372 return value.get('elevation', '')
374 def json_wr_page(self, value: dict) -> str:
375 return str(Wikilink(value['title'], value.get('text')))
377 def list_template(self, name: str, value: List[str]) -> str:
378 return str(wrpylib.mwmarkup.create_template(name, value))
380 def key_value_template(self, name: str, value: Dict[str, Any], keep_empty: bool = False) -> str:
381 value = {k: str(v) for k, v in value.items()
382 if keep_empty or (v is not None and not isinstance(v, jinja2.Undefined) and str(v).strip() != '')}
383 return str(wrpylib.mwmarkup.create_template(name, [], value))
385 def json_template(self, value) -> str:
388 for p in value.get('parameter', []):
389 v = p.get('value', '')
394 return str(wrpylib.mwmarkup.create_template(value['name'], args, kwargs))
397 def create_sledrun_wiki(sledrun_json: Dict, map_json: Optional[Dict], impressions_title: Optional[str] = None) -> str:
398 env = jinja2.Environment(
399 loader=jinja2.PackageLoader("wrpylib"),
400 autoescape=jinja2.select_autoescape(),
402 env.filters["german_bool"] = german_bool
403 template = env.get_template("sledrun_wikitext.txt")
405 def position_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
406 if value is not None:
407 lon = value.get('longitude')
408 lat = value.get('latitude')
409 if lon is not None and lat is not None:
410 return LonLat(lon, lat)
413 def position_ele_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
414 if value is not None:
415 return position_to_lon_lat(value.get("position"))
418 def position_ele_to_ele(value: Optional[dict]) -> Optional[int]:
419 if value is not None:
420 ele = value.get('elevation')
425 def aufstiegshilfe() -> Optional[List[Tuple[str, Optional[str]]]]:
426 ws = sledrun_json.get('walkup_supports')
429 return [(w['type'], w.get('note')) for w in ws]
431 def rodelverleih() -> Optional[List[Tuple[str, Optional[str]]]]:
432 v = sledrun_json.get('sled_rental')
434 d = sledrun_json.get('sled_rental_direct')
436 return [("Ja", None)]
444 n = Jinja2Tools().json_wr_page(p)
448 def cachet() -> Optional[List]:
449 v = sledrun_json.get('cachet')
455 def webauskunft() -> Tuple[Optional[bool], Optional[str]]:
456 info_web = sledrun_json.get('info_web')
459 if len(info_web) == 0:
461 return True, info_web[0]['url']
463 def telefonauskunft() -> Optional[List[Tuple[str, str]]]:
464 info_phone = sledrun_json.get('info_phone')
465 if info_phone is None:
467 return [(pc['phone'], pc['name']) for pc in info_phone]
469 def betreiber() -> str:
470 has_operator = sledrun_json.get('has_operator')
471 if has_operator is None:
472 return sledrun_json.get('operator')
474 return sledrun_json.get('operator')
477 sledrun_rbb_json = collections.OrderedDict([
478 ('Position', position_to_lon_lat(sledrun_json.get('position'))),
479 ('Position oben', position_ele_to_lon_lat(sledrun_json.get('top'))),
480 ('Höhe oben', position_ele_to_ele(sledrun_json.get('top'))),
481 ('Position unten', position_ele_to_lon_lat(sledrun_json.get('bottom'))),
482 ('Höhe unten', position_ele_to_ele(sledrun_json.get('bottom'))),
483 ('Länge', sledrun_json.get('length')),
484 ('Schwierigkeit', opt_difficulty_german_from_str(sledrun_json.get('difficulty', ''))),
485 ('Lawinen', opt_avalanches_german_from_str(sledrun_json.get('avalanches', ''))),
486 ('Betreiber', (sledrun_json.get('has_operator', True if 'operator' in sledrun_json else None), sledrun_json.get('operator'))),
487 ('Öffentliche Anreise', opt_public_transport_german_from_str(sledrun_json.get('public_transport', ''))),
488 ('Aufstieg möglich', sledrun_json.get('walkup_possible')),
489 ('Aufstieg getrennt', opt_tristate_german_comment_from_str(sledrun_json.get('walkup_separate', ''))),
490 ('Gehzeit', sledrun_json.get('walkup_time')),
491 ('Aufstiegshilfe', aufstiegshilfe()),
492 ('Beleuchtungsanlage', (opt_tristate_german_from_str(sledrun_json.get('nightlight_possible', '')),
493 sledrun_json.get('nightlight_possible_note'))),
494 ('Beleuchtungstage', (sledrun_json.get('nightlight_weekdays_count'),
495 sledrun_json.get('nightlight_weekdays_note'))),
496 ('Rodelverleih', rodelverleih()),
497 ('Gütesiegel', cachet()),
498 ('Webauskunft', webauskunft()),
499 ('Telefonauskunft', telefonauskunft()),
500 ('Bild', sledrun_json.get('image')),
501 ('In Übersichtskarte', sledrun_json.get('show_in_overview')),
502 ('Forumid', sledrun_json.get('forum_id'))
505 rodelbahnbox = rodelbahnbox_to_str(sledrun_rbb_json)
507 text = template.render(sledrun_json=sledrun_json,
508 rodelbahnbox=rodelbahnbox,
509 map_json=map_json, impressions_title=impressions_title,
510 h=Jinja2Tools(), **sledrun_json)
511 return strip_eol(text)