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
8 from mwparserfromhell.nodes import Template
10 import wrpylib.wrvalidators
11 import wrpylib.mwmarkup
13 from wrpylib.wrvalidators import LonLat, opt_lonlat_from_str, opt_lonlat_to_str, opt_uint_from_str, opt_uint_to_str, \
14 opt_str_opt_comment_enum_to_str, lift_german_to_str, webauskunft_to_str, cachet_german_to_str, \
15 opt_phone_comment_enum_to_str, lift_german_from_str, GASTHAUSBOX_DICT
18 def split_lon_lat(value: Optional[LonLat]) -> Union[LonLat, Tuple[None, None]]:
24 def join_lon_lat(lon: Optional[float], lat: Optional[float]) -> Optional[LonLat]:
25 if lon is None or lat is None:
27 return LonLat(lon, lat)
30 def sledrun_from_rodelbahnbox(value: OrderedDict, sledrun: object):
31 """Takes a Rodelbahnbox as returned by rodelbahnbox_from_str (that is, an OrderedDict) and
32 updates the sledrun instance with all values present in the Rodelbahnbox. Other values are not
33 updated. Does not validate the arguments."""
34 # sledrun.page_id = None # this field is not updated because it is not present in the RodelbahnBox
35 # sledrun.page_title = None # this field is not updated because it is not present in the RodelbahnBox
36 # sledrun.name_url = None # this field is not updated because it is not present in the RodelbahnBox
37 sledrun.position_longitude, sledrun.position_latitude = split_lon_lat(value['Position'])
38 sledrun.top_longitude, sledrun.top_latitude = split_lon_lat(value['Position oben'])
39 sledrun.top_elevation = value['Höhe oben']
40 sledrun.bottom_longitude, sledrun.bottom_latitude = split_lon_lat(value['Position unten'])
41 sledrun.bottom_elevation = value['Höhe unten']
42 sledrun.length = value['Länge']
43 sledrun.difficulty = value['Schwierigkeit']
44 sledrun.avalanches = value['Lawinen']
45 sledrun.operator = value['Betreiber']
46 sledrun.public_transport = value['Öffentliche Anreise']
47 sledrun.walkup_possible = value['Aufstieg möglich']
48 sledrun.walkup_time = value['Gehzeit']
49 sledrun.walkup_separate, sledrun.walkup_separate_comment = value['Aufstieg getrennt']
50 sledrun.lift = None if value['Aufstiegshilfe'] is None else len(value['Aufstiegshilfe']) > 0
51 sledrun.lift_details = lift_german_to_str(value['Aufstiegshilfe'])
52 sledrun.night_light, sledrun.night_light_comment = value['Beleuchtungsanlage']
53 sledrun.night_light_days, sledrun.night_light_days_comment = value['Beleuchtungstage']
54 sledrun.sled_rental = None if value['Rodelverleih'] is None else len(value['Rodelverleih']) > 0
55 sledrun.sled_rental_comment = opt_str_opt_comment_enum_to_str(value['Rodelverleih'])
56 sledrun.cachet = cachet_german_to_str(value['Gütesiegel'])
57 sledrun.information_web = webauskunft_to_str(value['Webauskunft'])
58 sledrun.information_phone = opt_phone_comment_enum_to_str(value['Telefonauskunft'])
59 sledrun.image = value['Bild']
60 sledrun.show_in_overview = value['In Übersichtskarte']
61 sledrun.forum_id = value['Forumid']
62 # sledrun.under_construction = None # this field is not updated because it is not present in the RodelbahnBox
66 def sledrun_to_rodelbahnbox(sledrun) -> collections.OrderedDict:
67 """Takes a sledrun instance that might come from the database and converts it to a OrderedDict ready
68 to be formatted as RodelbahnBox."""
69 value = collections.OrderedDict()
70 value['Position'] = join_lon_lat(sledrun.position_longitude, sledrun.position_latitude)
71 value['Position oben'] = join_lon_lat(sledrun.top_longitude, sledrun.top_latitude)
72 value['Höhe oben'] = sledrun.top_elevation
73 value['Position unten'] = join_lon_lat(sledrun.bottom_longitude, sledrun.bottom_latitude)
74 value['Höhe unten'] = sledrun.bottom_elevation
75 value['Länge'] = sledrun.length
76 value['Schwierigkeit'] = sledrun.difficulty
77 value['Lawinen'] = sledrun.avalanches
78 value['Betreiber'] = sledrun.operator
79 value['Öffentliche Anreise'] = sledrun.public_transport
80 value['Aufstieg möglich'] = sledrun.walkup_possible
81 value['Gehzeit'] = sledrun.walkup_time
82 value['Aufstieg getrennt'] = sledrun.walkup_separate, sledrun.walkup_separate_comment
83 value['Aufstiegshilfe'] = lift_german_from_str(sledrun.lift_details)
84 value['Beleuchtungsanlage'] = sledrun.night_light, sledrun.night_light_comment
85 value['Beleuchtungstage'] = sledrun.night_light_days, sledrun.night_light_days_comment
86 value['Rodelverleih'] = sledrun.sled_rental, sledrun.sled_rental_comment
87 value['Gütesiegel'] = sledrun.cachet
88 value['Webauskunft'] = sledrun.information_web
89 value['Telefonauskunft'] = sledrun.information_phone
90 value['Bild'] = sledrun.image
91 value['In Übersichtskarte'] = sledrun.show_in_overview
92 value['Forumid'] = sledrun.forum_id
96 def inn_from_gasthausbox(value, inn):
97 """Converts a dict with Gasthausbox properties to a Inn class. Does no validation.
98 value is a dict of properties as returned by gasthausbox_from_str."""
99 # page_id = None # this field is not updated because it is not present in the Gasthausbox
100 # page_title = None # this field is not updated because it is not present in the Gasthausbox
101 def convtodb(val, key):
102 v = GASTHAUSBOX_DICT[key].to_str(val[key])
106 inn.position_longitude, inn.position_latitude = split_lon_lat(value['Position'])
107 inn.position_elevation = value['Höhe']
108 inn.operator = value['Betreiber']
109 inn.seats = value['Sitzplätze']
110 inn.overnight, inn.overnight_comment = value['Übernachtung']
111 inn.smoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] < 0.9
112 inn.nonsmoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] > 0.1
113 inn.sled_rental, inn.sled_rental_comment = value['Rodelverleih']
114 inn.mobile_provider = convtodb(value, 'Handyempfang')
115 inn.homepage = convtodb(value, 'Homepage')
116 inn.email_list = convtodb(value, 'E-Mail')
117 inn.phone_list = convtodb(value, 'Telefon')
118 inn.image = value['Bild']
119 inn.sledding_list = convtodb(value, 'Rodelbahnen')
120 # under_construction = None # this field is not updated because it is not present in the GasthausBox
124 def inn_to_gasthausbox(inn) -> collections.OrderedDict:
125 """Converts an inn class to a dict of Gasthausbox properties. inn is an Inn instance."""
126 def convfromdb(val, key):
127 v = '' if val is None else val
128 return GASTHAUSBOX_DICT[key].from_str(v)
129 value = collections.OrderedDict()
130 value['Position'] = join_lon_lat(inn.position_longitude, inn.position_latitude)
131 value['Höhe'] = inn.position_elevation
132 value['Betreiber'] = inn.operator
133 value['Sitzplätze'] = inn.seats
134 value['Übernachtung'] = (inn.overnight, inn.overnight_comment)
135 value['Rauchfrei'] = {(False, True): 0.0, (True, True): 0.5, (True, False): 1.0} \
136 .get((inn.nonsmoker_area, inn.smoker_area), None)
137 value['Rodelverleih'] = (inn.sled_rental, inn.sled_rental_comment)
138 value['Handyempfang'] = convfromdb(inn.mobile_provider, 'Handyempfang')
139 value['Homepage'] = convfromdb(inn.homepage, 'Homepage')
140 value['E-Mail'] = convfromdb(inn.email_list, 'E-Mail')
141 value['Telefon'] = convfromdb(inn.phone_list, 'Telefon')
142 value['Bild'] = inn.image
143 value['Rodelbahnen'] = convfromdb(inn.sledding_list, 'Rodelbahnen')
147 def lonlat_ele_from_template(template) -> Tuple[LonLat, Optional[int]]:
148 """Template is a `mwparserfromhell.nodes.template.Template` instance. Returns (lonlat, ele)."""
149 lonlat = opt_lonlat_from_str(template.params[0].strip())
150 ele = opt_uint_from_str(template.params[1].strip())
154 def latlon_ele_to_template(lonlat_ele, name) -> Template:
155 lonlat, ele = lonlat_ele
156 template = Template(name)
157 template.add(1, opt_lonlat_to_str(lonlat))
158 template.add(2, opt_uint_to_str(ele))
159 wrpylib.mwmarkup.format_template_oneline(template)
163 class ParseError(RuntimeError):
164 """Exception used by some of the functions"""
168 def parse_wrmap_coordinates(coords: str) -> List[List[float]]:
169 """gets a string coordinates and returns an array of lon/lat coordinate pairs, e.g.
173 [[11.87, 47.12], [11.70, 47.13]]"""
176 for match in re.finditer(r'\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*', coords):
177 if match.start() != pos:
179 result.append([float(match.groups()[1]), float(match.groups()[0])])
182 if pos == len(coords):
184 raise RuntimeError(f'Wrong coordinate format: {coords}')
187 WRMAP_POINT_TYPES = ['gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt']
188 WRMAP_LINE_TYPES = ['rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie']
191 def parse_wrmap(wikitext):
192 """Parses the '<wrmap ...>content</wrmap>' of the Winterrodeln wrmap extension.
193 If wikitext does not contain the <wrmap> tag or if the <wrmap> tag contains
194 invalid formatted lines, a ParseError is raised.
195 Use wrpylib.mwmarkup.find_tag(wikitext, 'wrmap') to find the wrmap tag within an arbitrary
196 wikitext before using this function.
198 :param wikitext: wikitext containing only the template. Example:
201 <wrmap lat="47.2417134" lon="11.21408895" zoom="14" width="700" height="400">
202 <gasthaus name="Rosskogelhütte" wiki="Rosskogelhütte">47.240689 11.190454</gasthaus>
203 <parkplatz>47.245789 11.238971</parkplatz>
204 <haltestelle name="Oberperfuss Rangger Köpfl Lift">47.245711 11.238283</haltestelle>
212 :returns: GeoJSON as nested Python datatype
216 wrmap_xml = xml.etree.ElementTree.fromstring(wikitext)
217 except xml.etree.ElementTree.ParseError as e:
218 row, column = e.position
219 raise ParseError(f"XML parse error on row {row}, column {column}: {e}")
220 if wrmap_xml.tag not in ['wrmap', 'wrgmap']:
221 raise ParseError('No valid tag name')
223 # convert XML to geojson (http://www.geojson.org/geojson-spec.html)
225 for feature in wrmap_xml:
226 # determine feature type
227 is_point = feature.tag in WRMAP_POINT_TYPES
228 is_line = feature.tag in WRMAP_LINE_TYPES
229 if not is_point and not is_line:
230 raise ParseError(f'Unknown element <{feature.tag}>.')
234 properties = {'type': feature.tag}
235 allowed_properties = {'name', 'wiki'}
236 wrong_properties = set(feature.attrib.keys()) - allowed_properties
237 if len(wrong_properties) > 0:
238 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
239 properties.update(feature.attrib)
240 coordinates = parse_wrmap_coordinates(feature.text)
241 if len(coordinates) != 1:
242 raise ParseError(f'The element <{feature.tag}> has to have exactly one coordinate pair.')
243 json_features.append({
245 'geometry': {'type': 'Point', 'coordinates': coordinates[0]},
246 'properties': properties})
250 properties = {'type': feature.tag}
251 allowed_properties = {'farbe', 'dicke'}
252 wrong_properties = set(feature.attrib.keys()) - allowed_properties
253 if len(wrong_properties) > 0:
254 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
255 if 'farbe' in feature.attrib:
256 if not re.match('#[0-9a-fA-F]{6}$', feature.attrib['farbe']):
257 raise ParseError('The attribute "farbe" has to have a format like "#a0bb43".')
258 properties['strokeColor'] = feature.attrib['farbe'] # e.g. #a200b7
259 if 'dicke' in feature.attrib:
261 properties['strokeWidth'] = int(feature.attrib['dicke']) # e.g. 6
263 raise ParseError('The attribute "dicke" has to be an integer.')
264 json_features.append({
266 'geometry': {'type': 'LineString', 'coordinates': parse_wrmap_coordinates(feature.text)},
267 'properties': properties})
271 for k, v in wrmap_xml.attrib.items():
272 if k in ['lat', 'lon']:
274 properties[k] = float(v)
276 raise ParseError(f'Attribute "{k}" has to be a float value.')
277 elif k in ['zoom', 'width', 'height']:
279 properties[k] = int(v)
281 raise ParseError(f'Attribute "{k}" has to be an integer value.')
283 raise ParseError(f'Unknown attribute "{k}".')
286 'type': 'FeatureCollection',
287 'features': json_features,
288 'properties': properties}
293 def create_wrmap_coordinates(coords):
296 result.append(f'{coord[1]:.6f} N {coord[0]:.6f} E')
297 return '\n'.join(result)
300 def create_wrmap(geojson: Dict) -> str:
301 """Creates a <wrmap> wikitext from geojson (as python types)."""
302 wrmap_xml = xml.etree.ElementTree.Element('wrmap')
303 wrmap_xml.text = '\n\n'
304 for k, v in geojson['properties'].items():
305 if k in ['lon', 'lat']:
306 wrmap_xml.attrib[k] = f'{v:.6f}'
308 wrmap_xml.attrib[k] = str(v)
310 assert geojson['type'] == 'FeatureCollection'
311 json_features = geojson['features']
312 last_json_feature = None
313 for json_feature in json_features:
314 feature_xml = xml.etree.ElementTree.SubElement(wrmap_xml, json_feature['properties']['type'])
315 geo = json_feature['geometry']
316 if geo['type'] == 'Point':
317 feature_xml.text = create_wrmap_coordinates([geo['coordinates']])
318 if last_json_feature is not None:
319 last_json_feature.tail = '\n'
321 if last_json_feature is not None:
322 last_json_feature.tail = '\n\n'
323 feature_xml.text = '\n' + create_wrmap_coordinates(geo['coordinates']) + '\n'
324 last_json_feature = feature_xml
325 feature_xml.attrib = json_feature['properties']
326 del feature_xml.attrib['type']
328 if last_json_feature is not None:
329 last_json_feature.tail = '\n\n'
330 return xml.etree.ElementTree.tostring(wrmap_xml, encoding='utf-8').decode('utf-8')