]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/blob - wrpylib/wrmwmarkup.py
Now using comment for nightlight_possible.
[philipp/winterrodeln/wrpylib.git] / wrpylib / wrmwmarkup.py
1 """This module contains winterrodeln specific functions that are processing the MediaWiki markup.
2 """
3 import re
4 import subprocess
5 import xml.etree.ElementTree
6 import collections
7 from typing import Tuple, Optional, List, OrderedDict, Union, Dict
8
9 import jinja2
10 from mwparserfromhell.nodes import Template, Wikilink
11
12 import wrpylib.wrvalidators
13 import wrpylib.mwmarkup
14 import wrpylib.wrmwdb
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
21
22
23 def split_lon_lat(value: Optional[LonLat]) -> Union[LonLat, Tuple[None, None]]:
24     if value is None:
25         return None, None
26     return value
27
28
29 def join_lon_lat(lon: Optional[float], lat: Optional[float]) -> Optional[LonLat]:
30     if lon is None or lat is None:
31         return None
32     return LonLat(lon, lat)
33
34
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
68     return sledrun
69
70
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
98     return value
99
100
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])
108         if v == '':
109             return None
110         return v
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
126     return inn
127
128
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')
149     return value
150
151
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())
156     return lonlat, ele
157
158
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)
165     return template
166
167
168 def lonlat_to_json(lonlat: LonLat) -> dict:
169     return {'longitude': lonlat.lon, 'latitude': lonlat.lat}
170
171
172 def lonlat_ele_to_json(lonlat: Optional[LonLat], ele: Optional[int]) -> dict:
173     result = {}
174     if lonlat is not None:
175         result['position'] = lonlat_to_json(lonlat)
176     if ele is not None:
177         result['elevation'] = ele
178     return result
179
180
181 class ParseError(RuntimeError):
182     """Exception used by some of the functions"""
183     pass
184
185
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.
188     47.12 N 11.87 E
189     47.13 N 11.70 E
190     ->
191     [[11.87, 47.12], [11.70, 47.13]]"""
192     result = []
193     pos = 0
194     for match in re.finditer(r'\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*', coords):
195         if match.start() != pos:
196             break
197         result.append([float(match.groups()[1]), float(match.groups()[0])])
198         pos = match.end()
199     else:
200         if pos == len(coords):
201             return result
202     raise RuntimeError(f'Wrong coordinate format: {coords}')
203
204
205 WRMAP_POINT_TYPES = ['gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt']
206 WRMAP_LINE_TYPES = ['rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie']
207
208
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.
215
216     :param wikitext: wikitext containing only the template. Example:
217
218     wikitext = '''
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>
223     <rodelbahn>
224         47.238587 11.203360
225         47.244951 11.230868
226         47.245470 11.237853
227     </rodelbahn>
228     </wrmap>
229     '''
230     :returns: GeoJSON as nested Python datatype
231     """
232     # parse XML
233     try:
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')
240
241     # convert XML to geojson (http://www.geojson.org/geojson-spec.html)
242     json_features = []
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}>.')
249
250         # point
251         if is_point:
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({
262                 'type': 'Feature',
263                 'geometry': {'type': 'Point', 'coordinates': coordinates[0]},
264                 'properties': properties})
265
266         # line
267         if is_line:
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:
278                 try:
279                     properties['strokeWidth'] = int(feature.attrib['dicke'])  # e.g. 6
280                 except ValueError:
281                     raise ParseError('The attribute "dicke" has to be an integer.')
282             json_features.append({
283                 'type': 'Feature',
284                 'geometry': {'type': 'LineString', 'coordinates': parse_wrmap_coordinates(feature.text)},
285                 'properties': properties})
286
287     # attributes
288     properties = {}
289     for k, v in wrmap_xml.attrib.items():
290         if k in ['lat', 'lon']:
291             try:
292                 properties[k] = float(v)
293             except ValueError:
294                 raise ParseError(f'Attribute "{k}" has to be a float value.')
295         elif k in ['zoom', 'width', 'height']:
296             try:
297                 properties[k] = int(v)
298             except ValueError:
299                 raise ParseError(f'Attribute "{k}" has to be an integer value.')
300         else:
301             raise ParseError(f'Unknown attribute "{k}".')
302
303     geojson = {
304         'type': 'FeatureCollection',
305         'features': json_features,
306         'properties': properties}
307
308     return geojson
309
310
311 def create_wrmap_coordinates(coords):
312     result = []
313     for coord in coords:
314         result.append(f'{coord[1]:.6f} N {coord[0]:.6f} E')
315     return '\n'.join(result)
316  
317
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}'
325         else:
326             wrmap_xml.attrib[k] = str(v)
327
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'
338         else:
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']
344         del feature_xml.attrib['type']
345
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')
349
350
351 def german_bool(value: Union[bool, jinja2.Undefined]) -> Union[str, jinja2.Undefined]:
352     if jinja2.is_undefined(value):
353         return value
354     return wrpylib.wrvalidators.bool_german_to_str(value)
355
356
357 class Jinja2Tools:
358     def create_wrmap(self, geojson: Dict) -> str:
359         return create_wrmap(geojson)
360
361     def json_position(self, value: dict) -> str:
362         lon_lat = LonLat(value['longitude'], value['latitude'])
363         return lonlat_to_str(lon_lat)
364
365     def json_pos_ele_position(self, value: dict) -> str:
366         pos = value.get('position')
367         if pos is None:
368             return ''
369         return self.json_position(pos)
370
371     def json_pos_ele_elevation(self, value: dict) -> str:
372         return value.get('elevation', '')
373
374     def json_wr_page(self, value: dict) -> str:
375         return str(Wikilink(value['title'], value.get('text')))
376
377     def list_template(self, name: str, value: List[str]) -> str:
378         return str(wrpylib.mwmarkup.create_template(name, value))
379
380     def json_template(self, value) -> str:
381         args = []
382         kwargs = {}
383         for p in value.get('parameter', []):
384             v = p.get('value', '')
385             if 'key' in p:
386                 kwargs[p['key']] = v
387             else:
388                 args.append(v)
389         return str(wrpylib.mwmarkup.create_template(value['name'], args, kwargs))
390
391
392 def create_sledrun_wiki(sledrun_json: Dict, map_json: Optional[Dict], impressions_title: Optional[str] = None) -> str:
393     env = jinja2.Environment(
394         loader=jinja2.PackageLoader("wrpylib"),
395         autoescape=jinja2.select_autoescape(),
396     )
397     env.filters["german_bool"] = german_bool
398     template = env.get_template("sledrun_wiki.txt")
399
400     def position_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
401         if value is not None:
402             lon = value.get('longitude')
403             lat = value.get('latitude')
404             if lon is not None and lat is not None:
405                 return LonLat(lon, lat)
406         return None
407
408     def position_ele_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
409         if value is not None:
410             return position_to_lon_lat(value.get("position"))
411         return None
412
413     def position_ele_to_ele(value: Optional[dict]) -> Optional[int]:
414         if value is not None:
415             ele = value.get('elevation')
416             if ele is not None:
417                 return int(ele)
418         return None
419
420     def aufstiegshilfe() -> Optional[List[Tuple[str, Optional[str]]]]:
421         ws = sledrun_json.get('walkup_supports')
422         if ws is None:
423             return None
424         return [(w['type'], w.get('comment')) for w in ws]
425
426     def rodelverleih() -> Optional[List[Tuple[str, Optional[str]]]]:
427         v = sledrun_json.get('sled_rental')
428         if v is None:
429             return None
430         w = []
431         for x in v:
432             n = x.get('name')
433             c = x.get('comment')
434             p = x.get('wr_page')
435             if p is not None:
436                 n = Jinja2Tools().json_wr_page(p)
437             w.append((n, c))
438         return w
439
440     def cachet() -> Optional[List]:
441         v = sledrun_json.get('cachet')
442         if v is not None:
443             if not v:
444                 return []
445         return None
446
447     def webauskunft() -> Tuple[Optional[bool], Optional[str]]:
448         info_web = sledrun_json.get('info_web')
449         if info_web is None:
450             return None, None
451         if len(info_web) == 0:
452             return False, None
453         return True, info_web[0]['url']
454
455     def telefonauskunft() -> Optional[List[Tuple[str, str]]]:
456         info_phone = sledrun_json.get('info_phone')
457         if info_phone is None:
458             return None
459         return [(pc['phone'], pc['name']) for pc in info_phone]
460
461     def betreiber() -> str:
462         has_operator = sledrun_json.get('has_operator')
463         if has_operator is None:
464             return sledrun_json.get('operator')
465         if has_operator:
466             return sledrun_json.get('operator')
467         return 'Nein'
468
469     sledrun_rbb_json = collections.OrderedDict([
470         ('Position', position_to_lon_lat(sledrun_json.get('position'))),
471         ('Position oben', position_ele_to_lon_lat(sledrun_json.get('top'))),
472         ('Höhe oben', position_ele_to_ele(sledrun_json.get('top'))),
473         ('Position unten', position_ele_to_lon_lat(sledrun_json.get('bottom'))),
474         ('Höhe unten', position_ele_to_ele(sledrun_json.get('bottom'))),
475         ('Länge', sledrun_json.get('length')),
476         ('Schwierigkeit', opt_difficulty_german_from_str(sledrun_json.get('difficulty', ''))),
477         ('Lawinen', opt_avalanches_german_from_str(sledrun_json.get('avalanches', ''))),
478         ('Betreiber', (sledrun_json.get('has_operator'), sledrun_json.get('operator'))),
479         ('Öffentliche Anreise', opt_public_transport_german_from_str(sledrun_json.get('public_transport', ''))),
480         ('Aufstieg möglich', sledrun_json.get('walkup_possible')),
481         ('Aufstieg getrennt', opt_tristate_german_comment_from_str(sledrun_json.get('walkup_separate', ''))),
482         ('Gehzeit', sledrun_json.get('walkup_time')),
483         ('Aufstiegshilfe', aufstiegshilfe()),
484         ('Beleuchtungsanlage', (opt_tristate_german_from_str(sledrun_json.get('nightlight_possible', '')),
485                                 sledrun_json.get('nightlight_possible_comment'))),
486         ('Beleuchtungstage', (sledrun_json.get('nightlight_weekdays_count'),
487                               sledrun_json.get('nightlight_weekdays_comment'))),
488         ('Rodelverleih', rodelverleih()),
489         ('Gütesiegel', cachet()),
490         ('Webauskunft', webauskunft()),
491         ('Telefonauskunft', telefonauskunft()),
492         ('Bild', sledrun_json.get('image')),
493         ('In Übersichtskarte', sledrun_json.get('show_in_overview')),
494         ('Forumid', sledrun_json.get('forum_id'))
495     ])
496
497     rodelbahnbox = rodelbahnbox_to_str(sledrun_rbb_json)
498
499     return template.render(sledrun_json=sledrun_json,
500                            rodelbahnbox=rodelbahnbox,
501                            map_json=map_json, impressions_title=impressions_title,
502                            h=Jinja2Tools(), **sledrun_json)