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             print("Bad response: ", page)
 
  68     def _parse_json(self):
 
  69         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
  74             self.header['json_func'] = m.group(1)
 
  75         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
 
  76         if isinstance(self.result, OrderedDict):
 
  77             self.result = [self.result]
 
  79     def _parse_geojson(self):
 
  81         if 'error' in self.result[0]:
 
  84             self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
 
  86     def _parse_geocodejson(self):
 
  88         if self.result is not None:
 
  89             self.result = [r['geocoding'] for r in self.result]
 
  91     def assert_field(self, idx, field, value):
 
  92         """ Check that result row `idx` has a field `field` with value `value`.
 
  93             Float numbers are matched approximately. When the expected value
 
  94             starts with a carat, regular expression matching is used.
 
  96         assert field in self.result[idx], \
 
  97                "Result row {} has no field '{}'.\nFull row: {}"\
 
  98                    .format(idx, field, json.dumps(self.result[idx], indent=4))
 
 100         if isinstance(value, float):
 
 101             assert Almost(value) == float(self.result[idx][field]), \
 
 102                    BadRowValueAssert(self, idx, field, value)
 
 103         elif value.startswith("^"):
 
 104             assert re.fullmatch(value, self.result[idx][field]), \
 
 105                    BadRowValueAssert(self, idx, field, value)
 
 107             assert str(self.result[idx][field]) == str(value), \
 
 108                    BadRowValueAssert(self, idx, field, value)
 
 110     def assert_address_field(self, idx, field, value):
 
 111         """ Check that result rows`idx` has a field `field` with value `value`
 
 112             in its address. If idx is None, then all results are checked.
 
 115             todo = range(len(self.result))
 
 120             assert 'address' in self.result[idx], \
 
 121                    "Result row {} has no field 'address'.\nFull row: {}"\
 
 122                        .format(idx, json.dumps(self.result[idx], indent=4))
 
 124             address = self.result[idx]['address']
 
 125             assert field in address, \
 
 126                    "Result row {} has no field '{}' in address.\nFull address: {}"\
 
 127                        .format(idx, field, json.dumps(address, indent=4))
 
 129             assert address[field] == value, \
 
 130                    "\nBad value for row {} field '{}' in address. Expected: {}, got: {}.\nFull address: {}"""\
 
 131                        .format(idx, field, value, address[field], json.dumps(address, indent=4))
 
 133     def match_row(self, row, context=None):
 
 134         """ Match the result fields against the given behave table row.
 
 136         if 'ID' in row.headings:
 
 137             todo = [int(row['ID'])]
 
 139             todo = range(len(self.result))
 
 142             for name, value in zip(row.headings, row.cells):
 
 146                     assert 'osm_type' in self.result[i], \
 
 147                            "Result row {} has no field 'osm_type'.\nFull row: {}"\
 
 148                                .format(i, json.dumps(self.result[i], indent=4))
 
 149                     assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
 
 150                            BadRowValueAssert(self, i, 'osm_type', value)
 
 151                     self.assert_field(i, 'osm_id', value[1:])
 
 152                 elif name == 'osm_type':
 
 153                     assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
 
 154                            BadRowValueAssert(self, i, 'osm_type', value)
 
 155                 elif name == 'centroid':
 
 157                         lon, lat = value.split(' ')
 
 158                     elif context is not None:
 
 159                         lon, lat = context.osm.grid_node(int(value))
 
 161                         raise RuntimeError("Context needed when using grid coordinates")
 
 162                     self.assert_field(i, 'lat', float(lat))
 
 163                     self.assert_field(i, 'lon', float(lon))
 
 165                     self.assert_field(i, name, value)
 
 167     def property_list(self, prop):
 
 168         return [x[prop] for x in self.result]
 
 171 class SearchResponse(GenericResponse):
 
 172     """ Specialised class for search and lookup responses.
 
 173         Transforms the xml response in a format similar to json.
 
 176     def _parse_xml(self):
 
 177         xml_tree = ET.fromstring(self.page)
 
 179         self.header = dict(xml_tree.attrib)
 
 181         for child in xml_tree:
 
 182             assert child.tag == "place"
 
 183             self.result.append(dict(child.attrib))
 
 187                 if sub.tag == 'extratags':
 
 188                     self.result[-1]['extratags'] = {}
 
 190                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 191                 elif sub.tag == 'namedetails':
 
 192                     self.result[-1]['namedetails'] = {}
 
 194                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
 
 195                 elif sub.tag == 'geokml':
 
 196                     self.result[-1][sub.tag] = True
 
 198                     address[sub.tag] = sub.text
 
 201                 self.result[-1]['address'] = address
 
 204 class ReverseResponse(GenericResponse):
 
 205     """ Specialised class for reverse responses.
 
 206         Transforms the xml response in a format similar to json.
 
 209     def _parse_xml(self):
 
 210         xml_tree = ET.fromstring(self.page)
 
 212         self.header = dict(xml_tree.attrib)
 
 215         for child in xml_tree:
 
 216             if child.tag == 'result':
 
 217                 assert not self.result, "More than one result in reverse result"
 
 218                 self.result.append(dict(child.attrib))
 
 219             elif child.tag == 'addressparts':
 
 222                     address[sub.tag] = sub.text
 
 223                 self.result[0]['address'] = address
 
 224             elif child.tag == 'extratags':
 
 225                 self.result[0]['extratags'] = {}
 
 227                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 228             elif child.tag == 'namedetails':
 
 229                 self.result[0]['namedetails'] = {}
 
 231                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
 
 232             elif child.tag == 'geokml':
 
 233                 self.result[0][child.tag] = True
 
 235                 assert child.tag == 'error', \
 
 236                        "Unknown XML tag {} on page: {}".format(child.tag, self.page)
 
 239 class StatusResponse(GenericResponse):
 
 240     """ Specialised class for status responses.
 
 241         Can also parse text responses.
 
 244     def _parse_text(self):