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 Subcommand definitions for API calls from the command line.
 
  12 from nominatim.tools.exec_utils import run_api_script
 
  13 from nominatim.errors import UsageError
 
  15 # Do not repeat documentation of subcommand classes.
 
  16 # pylint: disable=C0111
 
  18 LOG = logging.getLogger()
 
  21     ('street', 'housenumber and street'),
 
  22     ('city', 'city, town or village'),
 
  25     ('country', 'country'),
 
  26     ('postalcode', 'postcode')
 
  30     ('addressdetails', 'Include a breakdown of the address into elements'),
 
  31     ('extratags', ("Include additional information if available "
 
  32                    "(e.g. wikipedia link, opening hours)")),
 
  33     ('namedetails', 'Include a list of alternative names')
 
  37     ('addressdetails', 'Include a breakdown of the address into elements'),
 
  38     ('keywords', 'Include a list of name keywords and address keywords'),
 
  39     ('linkedplaces', 'Include a details of places that are linked with this one'),
 
  40     ('hierarchy', 'Include details of places lower in the address hierarchy'),
 
  41     ('group_hierarchy', 'Group the places by type'),
 
  42     ('polygon_geojson', 'Include geometry of result')
 
  45 def _add_api_output_arguments(parser):
 
  46     group = parser.add_argument_group('Output arguments')
 
  47     group.add_argument('--format', default='jsonv2',
 
  48                        choices=['xml', 'json', 'jsonv2', 'geojson', 'geocodejson'],
 
  49                        help='Format of result')
 
  50     for name, desc in EXTRADATA_PARAMS:
 
  51         group.add_argument('--' + name, action='store_true', help=desc)
 
  53     group.add_argument('--lang', '--accept-language', metavar='LANGS',
 
  54                        help='Preferred language order for presenting search results')
 
  55     group.add_argument('--polygon-output',
 
  56                        choices=['geojson', 'kml', 'svg', 'text'],
 
  57                        help='Output geometry of results as a GeoJSON, KML, SVG or WKT')
 
  58     group.add_argument('--polygon-threshold', type=float, metavar='TOLERANCE',
 
  59                        help=("Simplify output geometry."
 
  60                              "Parameter is difference tolerance in degrees."))
 
  63 def _run_api(endpoint, args, params):
 
  64     script_file = args.project_dir / 'website' / (endpoint + '.php')
 
  66     if not script_file.exists():
 
  67         LOG.error("Cannot find API script file.\n\n"
 
  68                   "Make sure to run 'nominatim' from the project directory \n"
 
  69                   "or use the option --project-dir.")
 
  70         raise UsageError("API script not found.")
 
  72     return run_api_script(endpoint, args.project_dir,
 
  73                           phpcgi_bin=args.phpcgi_path, params=params)
 
  77     Execute a search query.
 
  79     This command works exactly the same as if calling the /search endpoint on
 
  80     the web API. See the online documentation for more details on the
 
  82     https://nominatim.org/release-docs/latest/api/Search/
 
  87         group = parser.add_argument_group('Query arguments')
 
  88         group.add_argument('--query',
 
  89                            help='Free-form query string')
 
  90         for name, desc in STRUCTURED_QUERY:
 
  91             group.add_argument('--' + name, help='Structured query: ' + desc)
 
  93         _add_api_output_arguments(parser)
 
  95         group = parser.add_argument_group('Result limitation')
 
  96         group.add_argument('--countrycodes', metavar='CC,..',
 
  97                            help='Limit search results to one or more countries')
 
  98         group.add_argument('--exclude_place_ids', metavar='ID,..',
 
  99                            help='List of search object to be excluded')
 
 100         group.add_argument('--limit', type=int,
 
 101                            help='Limit the number of returned results')
 
 102         group.add_argument('--viewbox', metavar='X1,Y1,X2,Y2',
 
 103                            help='Preferred area to find search results')
 
 104         group.add_argument('--bounded', action='store_true',
 
 105                            help='Strictly restrict results to viewbox area')
 
 107         group = parser.add_argument_group('Other arguments')
 
 108         group.add_argument('--no-dedupe', action='store_false', dest='dedupe',
 
 109                            help='Do not remove duplicates from the result list')
 
 115             params = dict(q=args.query)
 
 117             params = {k: getattr(args, k) for k, _ in STRUCTURED_QUERY if getattr(args, k)}
 
 119         for param, _ in EXTRADATA_PARAMS:
 
 120             if getattr(args, param):
 
 122         for param in ('format', 'countrycodes', 'exclude_place_ids', 'limit', 'viewbox'):
 
 123             if getattr(args, param):
 
 124                 params[param] = getattr(args, param)
 
 126             params['accept-language'] = args.lang
 
 127         if args.polygon_output:
 
 128             params['polygon_' + args.polygon_output] = '1'
 
 129         if args.polygon_threshold:
 
 130             params['polygon_threshold'] = args.polygon_threshold
 
 132             params['bounded'] = '1'
 
 134             params['dedupe'] = '0'
 
 136         return _run_api('search', args, params)
 
 140     Execute API reverse query.
 
 142     This command works exactly the same as if calling the /reverse endpoint on
 
 143     the web API. See the online documentation for more details on the
 
 145     https://nominatim.org/release-docs/latest/api/Reverse/
 
 149     def add_args(parser):
 
 150         group = parser.add_argument_group('Query arguments')
 
 151         group.add_argument('--lat', type=float, required=True,
 
 152                            help='Latitude of coordinate to look up (in WGS84)')
 
 153         group.add_argument('--lon', type=float, required=True,
 
 154                            help='Longitude of coordinate to look up (in WGS84)')
 
 155         group.add_argument('--zoom', type=int,
 
 156                            help='Level of detail required for the address')
 
 158         _add_api_output_arguments(parser)
 
 163         params = dict(lat=args.lat, lon=args.lon, format=args.format)
 
 164         if args.zoom is not None:
 
 165             params['zoom'] = args.zoom
 
 167         for param, _ in EXTRADATA_PARAMS:
 
 168             if getattr(args, param):
 
 171             params['accept-language'] = args.lang
 
 172         if args.polygon_output:
 
 173             params['polygon_' + args.polygon_output] = '1'
 
 174         if args.polygon_threshold:
 
 175             params['polygon_threshold'] = args.polygon_threshold
 
 177         return _run_api('reverse', args, params)
 
 182     Execute API lookup query.
 
 184     This command works exactly the same as if calling the /lookup endpoint on
 
 185     the web API. See the online documentation for more details on the
 
 187     https://nominatim.org/release-docs/latest/api/Lookup/
 
 191     def add_args(parser):
 
 192         group = parser.add_argument_group('Query arguments')
 
 193         group.add_argument('--id', metavar='OSMID',
 
 194                            action='append', required=True, dest='ids',
 
 195                            help='OSM id to lookup in format <NRW><id> (may be repeated)')
 
 197         _add_api_output_arguments(parser)
 
 202         params = dict(osm_ids=','.join(args.ids), format=args.format)
 
 204         for param, _ in EXTRADATA_PARAMS:
 
 205             if getattr(args, param):
 
 208             params['accept-language'] = args.lang
 
 209         if args.polygon_output:
 
 210             params['polygon_' + args.polygon_output] = '1'
 
 211         if args.polygon_threshold:
 
 212             params['polygon_threshold'] = args.polygon_threshold
 
 214         return _run_api('lookup', args, params)
 
 219     Execute API details query.
 
 221     This command works exactly the same as if calling the /details endpoint on
 
 222     the web API. See the online documentation for more details on the
 
 224     https://nominatim.org/release-docs/latest/api/Details/
 
 228     def add_args(parser):
 
 229         group = parser.add_argument_group('Query arguments')
 
 230         objs = group.add_mutually_exclusive_group(required=True)
 
 231         objs.add_argument('--node', '-n', type=int,
 
 232                           help="Look up the OSM node with the given ID.")
 
 233         objs.add_argument('--way', '-w', type=int,
 
 234                           help="Look up the OSM way with the given ID.")
 
 235         objs.add_argument('--relation', '-r', type=int,
 
 236                           help="Look up the OSM relation with the given ID.")
 
 237         objs.add_argument('--place_id', '-p', type=int,
 
 238                           help='Database internal identifier of the OSM object to look up')
 
 239         group.add_argument('--class', dest='object_class',
 
 240                            help=("Class type to disambiguated multiple entries "
 
 241                                  "of the same object."))
 
 243         group = parser.add_argument_group('Output arguments')
 
 244         for name, desc in DETAILS_SWITCHES:
 
 245             group.add_argument('--' + name, action='store_true', help=desc)
 
 246         group.add_argument('--lang', '--accept-language', metavar='LANGS',
 
 247                            help='Preferred language order for presenting search results')
 
 252             params = dict(osmtype='N', osmid=args.node)
 
 254             params = dict(osmtype='W', osmid=args.node)
 
 256             params = dict(osmtype='R', osmid=args.node)
 
 258             params = dict(place_id=args.place_id)
 
 259         if args.object_class:
 
 260             params['class'] = args.object_class
 
 261         for name, _ in DETAILS_SWITCHES:
 
 262             params[name] = '1' if getattr(args, name) else '0'
 
 264             params['accept-language'] = args.lang
 
 266         return _run_api('details', args, params)
 
 271     Execute API status query.
 
 273     This command works exactly the same as if calling the /status endpoint on
 
 274     the web API. See the online documentation for more details on the
 
 276     https://nominatim.org/release-docs/latest/api/Status/
 
 280     def add_args(parser):
 
 281         group = parser.add_argument_group('API parameters')
 
 282         group.add_argument('--format', default='text', choices=['text', 'json'],
 
 283                            help='Format of result')
 
 287         return _run_api('status', args, dict(format=args.format))