1 # SPDX-License-Identifier: GPL-2.0-only
 
   3 # This file is part of Nominatim. (https://nominatim.org)
 
   5 # Copyright (C) 2022 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.
 
  10 from collections import OrderedDict
 
  13 import xml.etree.ElementTree as ET
 
  15 from check_functions import Almost
 
  17 OSM_TYPE = {'N' : 'node', 'W' : 'way', 'R' : 'relation',
 
  18             'n' : 'node', 'w' : 'way', 'r' : 'relation',
 
  19             'node' : 'n', 'way' : 'w', 'relation' : 'r'}
 
  21 def _geojson_result_to_json_result(geojson_result):
 
  22     result = geojson_result['properties']
 
  23     result['geojson'] = geojson_result['geometry']
 
  24     if 'bbox' in geojson_result:
 
  25         # bbox is  minlon, minlat, maxlon, maxlat
 
  26         # boundingbox is minlat, maxlat, minlon, maxlon
 
  27         result['boundingbox'] = [geojson_result['bbox'][1],
 
  28                                  geojson_result['bbox'][3],
 
  29                                  geojson_result['bbox'][0],
 
  30                                  geojson_result['bbox'][2]]
 
  33 class BadRowValueAssert:
 
  34     """ Lazily formatted message for failures to find a field content.
 
  37     def __init__(self, response, idx, field, value):
 
  41         self.row = response.result[idx]
 
  44         return "\nBad value for row {} field '{}'. Expected: {}, got: {}.\nFull row: {}"""\
 
  45                    .format(self.idx, self.field, self.value,
 
  46                            self.row[self.field], json.dumps(self.row, indent=4))
 
  49 class GenericResponse:
 
  50     """ Common base class for all API responses.
 
  52     def __init__(self, page, fmt, errorcode=200):
 
  59         self.errorcode = errorcode
 
  63         if errorcode == 200 and fmt != 'debug':
 
  64             getattr(self, '_parse_' + fmt)()
 
  66     def _parse_json(self):
 
  67         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
  72             self.header['json_func'] = m.group(1)
 
  73         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
 
  74         if isinstance(self.result, OrderedDict):
 
  75             if 'error' in self.result:
 
  78                 self.result = [self.result]
 
  80     def _parse_geojson(self):
 
  83             self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
 
  85     def _parse_geocodejson(self):
 
  87         if self.result is not None:
 
  88             self.result = [r['geocoding'] for r in self.result]
 
  90     def assert_field(self, idx, field, value):
 
  91         """ Check that result row `idx` has a field `field` with value `value`.
 
  92             Float numbers are matched approximately. When the expected value
 
  93             starts with a carat, regular expression matching is used.
 
  95         assert field in self.result[idx], \
 
  96                "Result row {} has no field '{}'.\nFull row: {}"\
 
  97                    .format(idx, field, json.dumps(self.result[idx], indent=4))
 
  99         if isinstance(value, float):
 
 100             assert Almost(value) == float(self.result[idx][field]), \
 
 101                    BadRowValueAssert(self, idx, field, value)
 
 102         elif value.startswith("^"):
 
 103             assert re.fullmatch(value, self.result[idx][field]), \
 
 104                    BadRowValueAssert(self, idx, field, value)
 
 105         elif isinstance(self.result[idx][field], OrderedDict):
 
 106             assert self.result[idx][field] == eval('{' + value + '}'), \
 
 107                    BadRowValueAssert(self, idx, field, value)
 
 109             assert str(self.result[idx][field]) == str(value), \
 
 110                    BadRowValueAssert(self, idx, field, value)
 
 112     def assert_address_field(self, idx, field, value):
 
 113         """ Check that result rows`idx` has a field `field` with value `value`
 
 114             in its address. If idx is None, then all results are checked.
 
 117             todo = range(len(self.result))
 
 122             assert 'address' in self.result[idx], \
 
 123                    "Result row {} has no field 'address'.\nFull row: {}"\
 
 124                        .format(idx, json.dumps(self.result[idx], indent=4))
 
 126             address = self.result[idx]['address']
 
 127             assert field in address, \
 
 128                    "Result row {} has no field '{}' in address.\nFull address: {}"\
 
 129                        .format(idx, field, json.dumps(address, indent=4))
 
 131             assert address[field] == value, \
 
 132                    "\nBad value for row {} field '{}' in address. Expected: {}, got: {}.\nFull address: {}"""\
 
 133                        .format(idx, field, value, address[field], json.dumps(address, indent=4))
 
 135     def match_row(self, row, context=None):
 
 136         """ Match the result fields against the given behave table row.
 
 138         if 'ID' in row.headings:
 
 139             todo = [int(row['ID'])]
 
 141             todo = range(len(self.result))
 
 144             for name, value in zip(row.headings, row.cells):
 
 148                     assert 'osm_type' in self.result[i], \
 
 149                            "Result row {} has no field 'osm_type'.\nFull row: {}"\
 
 150                                .format(i, json.dumps(self.result[i], indent=4))
 
 151                     assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
 
 152                            BadRowValueAssert(self, i, 'osm_type', value)
 
 153                     self.assert_field(i, 'osm_id', value[1:])
 
 154                 elif name == 'osm_type':
 
 155                     assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
 
 156                            BadRowValueAssert(self, i, 'osm_type', value)
 
 157                 elif name == 'centroid':
 
 159                         lon, lat = value.split(' ')
 
 160                     elif context is not None:
 
 161                         lon, lat = context.osm.grid_node(int(value))
 
 163                         raise RuntimeError("Context needed when using grid coordinates")
 
 164                     self.assert_field(i, 'lat', float(lat))
 
 165                     self.assert_field(i, 'lon', float(lon))
 
 167                     self.assert_field(i, name, value)
 
 169     def property_list(self, prop):
 
 170         return [x[prop] for x in self.result]
 
 173 class SearchResponse(GenericResponse):
 
 174     """ Specialised class for search and lookup responses.
 
 175         Transforms the xml response in a format similar to json.
 
 178     def _parse_xml(self):
 
 179         xml_tree = ET.fromstring(self.page)
 
 181         self.header = dict(xml_tree.attrib)
 
 183         for child in xml_tree:
 
 184             assert child.tag == "place"
 
 185             self.result.append(dict(child.attrib))
 
 189                 if sub.tag == 'extratags':
 
 190                     self.result[-1]['extratags'] = {}
 
 192                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 193                 elif sub.tag == 'namedetails':
 
 194                     self.result[-1]['namedetails'] = {}
 
 196                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
 
 197                 elif sub.tag == 'geokml':
 
 198                     self.result[-1][sub.tag] = True
 
 200                     address[sub.tag] = sub.text
 
 203                 self.result[-1]['address'] = address
 
 206 class ReverseResponse(GenericResponse):
 
 207     """ Specialised class for reverse responses.
 
 208         Transforms the xml response in a format similar to json.
 
 211     def _parse_xml(self):
 
 212         xml_tree = ET.fromstring(self.page)
 
 214         self.header = dict(xml_tree.attrib)
 
 217         for child in xml_tree:
 
 218             if child.tag == 'result':
 
 219                 assert not self.result, "More than one result in reverse result"
 
 220                 self.result.append(dict(child.attrib))
 
 221             elif child.tag == 'addressparts':
 
 224                     address[sub.tag] = sub.text
 
 225                 self.result[0]['address'] = address
 
 226             elif child.tag == 'extratags':
 
 227                 self.result[0]['extratags'] = {}
 
 229                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 230             elif child.tag == 'namedetails':
 
 231                 self.result[0]['namedetails'] = {}
 
 233                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
 
 234             elif child.tag == 'geokml':
 
 235                 self.result[0][child.tag] = True
 
 237                 assert child.tag == 'error', \
 
 238                        "Unknown XML tag {} on page: {}".format(child.tag, self.page)
 
 241 class StatusResponse(GenericResponse):
 
 242     """ Specialised class for status responses.
 
 243         Can also parse text responses.
 
 246     def _parse_text(self):