1 # SPDX-License-Identifier: GPL-2.0-only
 
   3 # This file is part of Nominatim. (https://nominatim.org)
 
   5 # Copyright (C) 2023 by the Nominatim developer community.
 
   6 # For a full list of authors see the git log.
 
   8 Classes wrapping HTTP responses from the Nominatim API.
 
  12 import xml.etree.ElementTree as ET
 
  14 from check_functions import Almost, OsmType, Field, check_for_attributes
 
  17 class GenericResponse:
 
  18     """ Common base class for all API responses.
 
  20     def __init__(self, page, fmt, errorcode=200):
 
  27         self.errorcode = errorcode
 
  31         if errorcode == 200 and fmt != 'debug':
 
  32             getattr(self, '_parse_' + fmt)()
 
  34     def _parse_json(self):
 
  35         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
  40             self.header['json_func'] = m.group(1)
 
  41         self.result = json.JSONDecoder().decode(code)
 
  42         if isinstance(self.result, dict):
 
  43             if 'error' in self.result:
 
  46                 self.result = [self.result]
 
  49     def _parse_geojson(self):
 
  52             geojson = self.result[0]
 
  53             # check for valid geojson
 
  54             check_for_attributes(geojson, 'type,features')
 
  55             assert geojson['type'] == 'FeatureCollection'
 
  56             assert isinstance(geojson['features'], list)
 
  59             for result in geojson['features']:
 
  60                 check_for_attributes(result, 'type,properties,geometry')
 
  61                 assert result['type'] == 'Feature'
 
  62                 new = result['properties']
 
  63                 check_for_attributes(new, 'geojson', 'absent')
 
  64                 new['geojson'] = result['geometry']
 
  66                     check_for_attributes(new, 'boundingbox', 'absent')
 
  67                     # bbox is  minlon, minlat, maxlon, maxlat
 
  68                     # boundingbox is minlat, maxlat, minlon, maxlon
 
  69                     new['boundingbox'] = [result['bbox'][1],
 
  73                 for k, v in geojson.items():
 
  74                     if k not in ('type', 'features'):
 
  75                         check_for_attributes(new, '__' + k, 'absent')
 
  77                 self.result.append(new)
 
  80     def _parse_geocodejson(self):
 
  84                 assert set(r.keys()) == {'geocoding', 'geojson', '__geocoding'}, \
 
  85                        f"Unexpected keys in result: {r.keys()}"
 
  86                 check_for_attributes(r['geocoding'], 'geojson', 'absent')
 
  87                 inner = r.pop('geocoding')
 
  91     def assert_address_field(self, idx, field, value):
 
  92         """ Check that result rows`idx` has a field `field` with value `value`
 
  93             in its address. If idx is None, then all results are checked.
 
  96             todo = range(len(self.result))
 
 101             self.check_row(idx, 'address' in self.result[idx], "No field 'address'")
 
 103             address = self.result[idx]['address']
 
 104             self.check_row_field(idx, field, value, base=address)
 
 107     def match_row(self, row, context=None, field=None):
 
 108         """ Match the result fields against the given behave table row.
 
 110         if 'ID' in row.headings:
 
 111             todo = [int(row['ID'])]
 
 113             todo = range(len(self.result))
 
 116             subdict = self.result[i]
 
 117             if field is not None:
 
 118                 for key in field.split('.'):
 
 119                     self.check_row(i, key in subdict, f"Missing subfield {key}")
 
 120                     subdict = subdict[key]
 
 121                     self.check_row(i, isinstance(subdict, dict),
 
 122                                    f"Subfield {key} not a dict")
 
 124             for name, value in zip(row.headings, row.cells):
 
 128                     self.check_row_field(i, 'osm_type', OsmType(value[0]), base=subdict)
 
 129                     self.check_row_field(i, 'osm_id', Field(value[1:]), base=subdict)
 
 130                 elif name == 'centroid':
 
 132                         lon, lat = value.split(' ')
 
 133                     elif context is not None:
 
 134                         lon, lat = context.osm.grid_node(int(value))
 
 136                         raise RuntimeError("Context needed when using grid coordinates")
 
 137                     self.check_row_field(i, 'lat', Field(float(lat), abs_tol=1e-07), base=subdict)
 
 138                     self.check_row_field(i, 'lon', Field(float(lon), abs_tol=1e-07), base=subdict)
 
 140                     self.check_row_field(i, name, Field(value), base=subdict)
 
 143     def check_row(self, idx, check, msg):
 
 144         """ Assert for the condition 'check' and print 'msg' on fail together
 
 145             with the contents of the failing result.
 
 148             def __init__(self, row):
 
 152                 return f"{msg}. Full row {idx}:\n" \
 
 153                        + json.dumps(self.row, indent=4, ensure_ascii=False)
 
 155         assert check, _RowError(self.result[idx])
 
 158     def check_row_field(self, idx, field, expected, base=None):
 
 159         """ Check field 'field' of result 'idx' for the expected value
 
 160             and print a meaningful error if the condition fails.
 
 161             When 'base' is set to a dictionary, then the field is checked
 
 162             in that base. The error message will still report the contents
 
 166             base = self.result[idx]
 
 168         self.check_row(idx, field in base, f"No field '{field}'")
 
 171         self.check_row(idx, expected == value,
 
 172                        f"\nBad value for field '{field}'. Expected: {expected}, got: {value}")
 
 176 class SearchResponse(GenericResponse):
 
 177     """ Specialised class for search and lookup responses.
 
 178         Transforms the xml response in a format similar to json.
 
 181     def _parse_xml(self):
 
 182         xml_tree = ET.fromstring(self.page)
 
 184         self.header = dict(xml_tree.attrib)
 
 186         for child in xml_tree:
 
 187             assert child.tag == "place"
 
 188             self.result.append(dict(child.attrib))
 
 192                 if sub.tag == 'extratags':
 
 193                     self.result[-1]['extratags'] = {}
 
 195                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 196                 elif sub.tag == 'namedetails':
 
 197                     self.result[-1]['namedetails'] = {}
 
 199                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
 
 200                 elif sub.tag == 'geokml':
 
 201                     self.result[-1][sub.tag] = True
 
 203                     address[sub.tag] = sub.text
 
 206                 self.result[-1]['address'] = address
 
 209 class ReverseResponse(GenericResponse):
 
 210     """ Specialised class for reverse responses.
 
 211         Transforms the xml response in a format similar to json.
 
 214     def _parse_xml(self):
 
 215         xml_tree = ET.fromstring(self.page)
 
 217         self.header = dict(xml_tree.attrib)
 
 220         for child in xml_tree:
 
 221             if child.tag == 'result':
 
 222                 assert not self.result, "More than one result in reverse result"
 
 223                 self.result.append(dict(child.attrib))
 
 224                 check_for_attributes(self.result[0], 'display_name', 'absent')
 
 225                 self.result[0]['display_name'] = child.text
 
 226             elif child.tag == 'addressparts':
 
 227                 assert 'address' not in self.result[0], "More than one address in result"
 
 230                     assert len(sub) == 0, f"Address element '{sub.tag}' has subelements"
 
 231                     address[sub.tag] = sub.text
 
 232                 self.result[0]['address'] = address
 
 233             elif child.tag == 'extratags':
 
 234                 assert 'extratags' not in self.result[0], "More than one extratags in result"
 
 235                 self.result[0]['extratags'] = {}
 
 237                     assert len(tag) == 0, f"Extratags element '{tag.attrib['key']}' has subelements"
 
 238                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 239             elif child.tag == 'namedetails':
 
 240                 assert 'namedetails' not in self.result[0], "More than one namedetails in result"
 
 241                 self.result[0]['namedetails'] = {}
 
 243                     assert len(tag) == 0, f"Namedetails element '{tag.attrib['desc']}' has subelements"
 
 244                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
 
 245             elif child.tag == 'geokml':
 
 246                 assert 'geokml' not in self.result[0], "More than one geokml in result"
 
 247                 self.result[0]['geokml'] = ET.tostring(child, encoding='unicode')
 
 249                 assert child.tag == 'error', \
 
 250                        f"Unknown XML tag {child.tag} on page: {self.page}"
 
 253 class StatusResponse(GenericResponse):
 
 254     """ Specialised class for status responses.
 
 255         Can also parse text responses.
 
 258     def _parse_text(self):