001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.text.MessageFormat;
008import java.time.Instant;
009import java.util.ArrayList;
010import java.util.Collection;
011import java.util.Collections;
012import java.util.HashMap;
013import java.util.Map;
014import java.util.Map.Entry;
015import java.util.stream.Collectors;
016import java.util.stream.Stream;
017
018import org.openstreetmap.josm.data.Bounds;
019import org.openstreetmap.josm.data.UserIdentityManager;
020import org.openstreetmap.josm.data.coor.LatLon;
021import org.openstreetmap.josm.tools.CheckParameterUtil;
022import org.openstreetmap.josm.tools.Logging;
023import org.openstreetmap.josm.tools.UncheckedParseException;
024import org.openstreetmap.josm.tools.Utils;
025import org.openstreetmap.josm.tools.date.DateUtils;
026
027/**
028 * Data class to collect restrictions (parameters) for downloading changesets from the
029 * OSM API.
030 * @see <a href="https://wiki.openstreetmap.org/wiki/API_v0.6#Query:_GET_.2Fapi.2F0.6.2Fchangesets">OSM API 0.6 call "/changesets?"</a>
031 */
032public class ChangesetQuery {
033    private static final String ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL =
034            marktr("Unexpected value for ''{0}'' in changeset query url, got {1}");
035    private static final String DISPLAY_NAME = "display_name";
036
037    /**
038     * Maximum number of changesets returned by the OSM API call "/changesets?"
039     */
040    public static final int MAX_CHANGESETS_NUMBER = 100;
041
042    /** the user id this query is restricted to. null, if no restriction to a user id applies */
043    private Integer uid;
044    /** the user name this query is restricted to. null, if no restriction to a user name applies */
045    private String userName;
046    /** the bounding box this query is restricted to. null, if no restriction to a bounding box applies */
047    private Bounds bounds;
048    /** the date after which changesets have been closed this query is restricted to. null, if no restriction to closure date applies */
049    private Instant closedAfter;
050    /** the date before which changesets have been created this query is restricted to. null, if no restriction to creation date applies */
051    private Instant createdBefore;
052    /** indicates whether only open changesets are queried. null, if no restrictions regarding open changesets apply */
053    private Boolean open;
054    /** indicates whether only closed changesets are queried. null, if no restrictions regarding closed changesets apply */
055    private Boolean closed;
056    /** a collection of changeset ids to query for */
057    private Collection<Long> changesetIds;
058
059    /**
060     * Replies a changeset query object from the query part of a OSM API URL for querying changesets.
061     *
062     * @param query the query part
063     * @return the query object
064     * @throws ChangesetQueryUrlException if query doesn't consist of valid query parameters
065     */
066    public static ChangesetQuery buildFromUrlQuery(String query) throws ChangesetQueryUrlException {
067        return new ChangesetQueryUrlParser().parse(query);
068    }
069
070    /**
071     * Replies a changeset query object restricted to the current user, if known.
072     * @return a changeset query object restricted to the current user, if known
073     * @throws IllegalStateException if current user is anonymous
074     * @since 12495
075     */
076    public static ChangesetQuery forCurrentUser() {
077        UserIdentityManager im = UserIdentityManager.getInstance();
078        if (im.isAnonymous()) {
079            throw new IllegalStateException("anonymous user");
080        }
081        ChangesetQuery query = new ChangesetQuery();
082        if (im.isFullyIdentified()) {
083            return query.forUser(im.getUserId());
084        } else {
085            return query.forUser(im.getUserName());
086        }
087    }
088
089    /**
090     * Restricts the query to changesets owned by the user with id <code>uid</code>.
091     *
092     * @param uid the uid of the user. &gt; 0 expected.
093     * @return the query object with the applied restriction
094     * @throws IllegalArgumentException if uid &lt;= 0
095     * @see #forUser(String)
096     */
097    public ChangesetQuery forUser(int uid) {
098        if (uid <= 0)
099            throw new IllegalArgumentException(MessageFormat.format("Parameter ''{0}'' > 0 expected. Got ''{1}''.", "uid", uid));
100        this.uid = uid;
101        this.userName = null;
102        return this;
103    }
104
105    /**
106     * Restricts the query to changesets owned by the user with user name <code>username</code>.
107     * <p>
108     * Caveat: for historical reasons the username might not be unique! It is recommended to use
109     * {@link #forUser(int)} to restrict the query to a specific user.
110     *
111     * @param userName the username. Must not be null.
112     * @return the query object with the applied restriction
113     * @throws IllegalArgumentException if username is null.
114     * @see #forUser(int)
115     */
116    public ChangesetQuery forUser(String userName) {
117        CheckParameterUtil.ensureParameterNotNull(userName, "userName");
118        this.userName = userName;
119        this.uid = null;
120        return this;
121    }
122
123    /**
124     * Replies true if this query is restricted to user whom we only know the user name for.
125     *
126     * @return true if this query is restricted to user whom we only know the user name for
127     */
128    public boolean isRestrictedToPartiallyIdentifiedUser() {
129        return userName != null;
130    }
131
132    /**
133     * Replies true/false if this query is restricted to changesets which are or aren't open.
134     *
135     * @return whether changesets should or should not be open, or {@code null} if there is no restriction
136     * @since 14039
137     */
138    public Boolean getRestrictionToOpen() {
139        return open;
140    }
141
142    /**
143     * Replies true/false if this query is restricted to changesets which are or aren't closed.
144     *
145     * @return whether changesets should or should not be closed, or {@code null} if there is no restriction
146     * @since 14039
147     */
148    public Boolean getRestrictionToClosed() {
149        return closed;
150    }
151
152    /**
153     * Replies the date after which changesets have been closed this query is restricted to.
154     *
155     * @return the date after which changesets have been closed this query is restricted to.
156     *         {@code null}, if no restriction to closure date applies
157     * @since 14039
158     */
159    public Instant getClosedAfter() {
160        return closedAfter;
161    }
162
163    /**
164     * Replies the date before which changesets have been created this query is restricted to.
165     *
166     * @return the date before which changesets have been created this query is restricted to.
167     *         {@code null}, if no restriction to creation date applies
168     * @since 14039
169     */
170    public Instant getCreatedBefore() {
171        return createdBefore;
172    }
173
174    /**
175     * Replies the list of additional changeset ids to query.
176     * @return the list of additional changeset ids to query (never null)
177     * @since 14039
178     */
179    public final Collection<Long> getAdditionalChangesetIds() {
180        return changesetIds != null ? new ArrayList<>(changesetIds) : Collections.emptyList();
181    }
182
183    /**
184     * Replies the bounding box this query is restricted to.
185     * @return the bounding box this query is restricted to. null, if no restriction to a bounding box applies
186     * @since 14039
187     */
188    public final Bounds getBounds() {
189        return bounds;
190    }
191
192    /**
193     * Replies the user name which this query is restricted to. null, if this query isn't
194     * restricted to a user name, i.e. if {@link #isRestrictedToPartiallyIdentifiedUser()} is false.
195     *
196     * @return the user name which this query is restricted to
197     */
198    public String getUserName() {
199        return userName;
200    }
201
202    /**
203     * Replies true if this query is restricted to user whom know the user id for.
204     *
205     * @return true if this query is restricted to user whom know the user id for
206     */
207    public boolean isRestrictedToFullyIdentifiedUser() {
208        return uid > 0;
209    }
210
211    /**
212     * Replies a query which is restricted to a bounding box.
213     *
214     * @param minLon  min longitude of the bounding box. Valid longitude value expected.
215     * @param minLat  min latitude of the bounding box. Valid latitude value expected.
216     * @param maxLon  max longitude of the bounding box. Valid longitude value expected.
217     * @param maxLat  max latitude of the bounding box.  Valid latitude value expected.
218     *
219     * @return the restricted changeset query
220     * @throws IllegalArgumentException if either of the parameters isn't a valid longitude or
221     * latitude value
222     */
223    public ChangesetQuery inBbox(double minLon, double minLat, double maxLon, double maxLat) {
224        if (!LatLon.isValidLon(minLon))
225            throw new IllegalArgumentException(tr("Illegal longitude value for parameter ''{0}'', got {1}", "minLon", minLon));
226        if (!LatLon.isValidLon(maxLon))
227            throw new IllegalArgumentException(tr("Illegal longitude value for parameter ''{0}'', got {1}", "maxLon", maxLon));
228        if (!LatLon.isValidLat(minLat))
229            throw new IllegalArgumentException(tr("Illegal latitude value for parameter ''{0}'', got {1}", "minLat", minLat));
230        if (!LatLon.isValidLat(maxLat))
231            throw new IllegalArgumentException(tr("Illegal latitude value for parameter ''{0}'', got {1}", "maxLat", maxLat));
232
233        return inBbox(new LatLon(minLon, minLat), new LatLon(maxLon, maxLat));
234    }
235
236    /**
237     * Replies a query which is restricted to a bounding box.
238     *
239     * @param min the min lat/lon coordinates of the bounding box. Must not be null.
240     * @param max the max lat/lon coordinates of the bounding box. Must not be null.
241     *
242     * @return the restricted changeset query
243     * @throws IllegalArgumentException if min is null
244     * @throws IllegalArgumentException if max is null
245     */
246    public ChangesetQuery inBbox(LatLon min, LatLon max) {
247        CheckParameterUtil.ensureParameterNotNull(min, "min");
248        CheckParameterUtil.ensureParameterNotNull(max, "max");
249        this.bounds = new Bounds(min, max);
250        return this;
251    }
252
253    /**
254     *  Replies a query which is restricted to a bounding box given by <code>bbox</code>.
255     *
256     * @param bbox the bounding box. Must not be null.
257     * @return the changeset query
258     * @throws IllegalArgumentException if bbox is null.
259     */
260    public ChangesetQuery inBbox(Bounds bbox) {
261        CheckParameterUtil.ensureParameterNotNull(bbox, "bbox");
262        this.bounds = bbox;
263        return this;
264    }
265
266    /**
267     * Restricts the result to changesets which have been closed after the date given by <code>d</code>.
268     * <code>d</code> d is a date relative to the current time zone.
269     *
270     * @param d the date. Must not be null.
271     * @return the restricted changeset query
272     * @throws IllegalArgumentException if d is null
273     */
274    public ChangesetQuery closedAfter(Instant d) {
275        CheckParameterUtil.ensureParameterNotNull(d, "d");
276        this.closedAfter = d;
277        return this;
278    }
279
280    /**
281     * Restricts the result to changesets which have been closed after <code>closedAfter</code> and which
282     * have been created before <code>createdBefore</code>. Both dates are expressed relative to the current
283     * time zone.
284     *
285     * @param closedAfter only reply changesets closed after this date. Must not be null.
286     * @param createdBefore only reply changesets created before this date. Must not be null.
287     * @return the restricted changeset query
288     * @throws IllegalArgumentException if closedAfter is null
289     * @throws IllegalArgumentException if createdBefore is null
290     */
291    public ChangesetQuery closedAfterAndCreatedBefore(Instant closedAfter, Instant createdBefore) {
292        CheckParameterUtil.ensureParameterNotNull(closedAfter, "closedAfter");
293        CheckParameterUtil.ensureParameterNotNull(createdBefore, "createdBefore");
294        this.closedAfter = closedAfter;
295        this.createdBefore = createdBefore;
296        return this;
297    }
298
299    /**
300     * Restricts the result to changesets which are or aren't open, depending on the value of
301     * <code>isOpen</code>
302     *
303     * @param isOpen whether changesets should or should not be open
304     * @return the restricted changeset query
305     */
306    public ChangesetQuery beingOpen(boolean isOpen) {
307        this.open = isOpen;
308        return this;
309    }
310
311    /**
312     * Restricts the result to changesets which are or aren't closed, depending on the value of
313     * <code>isClosed</code>
314     *
315     * @param isClosed whether changesets should or should not be open
316     * @return the restricted changeset query
317     */
318    public ChangesetQuery beingClosed(boolean isClosed) {
319        this.closed = isClosed;
320        return this;
321    }
322
323    /**
324     * Restricts the query to the given changeset ids (which are added to previously added ones).
325     *
326     * @param changesetIds the changeset ids
327     * @return the query object with the applied restriction
328     * @throws IllegalArgumentException if changesetIds is null.
329     */
330    public ChangesetQuery forChangesetIds(Collection<Long> changesetIds) {
331        CheckParameterUtil.ensureParameterNotNull(changesetIds, "changesetIds");
332        if (changesetIds.size() > MAX_CHANGESETS_NUMBER) {
333            Logging.warn("Changeset query built with more than " + MAX_CHANGESETS_NUMBER + " changeset ids (" + changesetIds.size() + ')');
334        }
335        this.changesetIds = changesetIds;
336        return this;
337    }
338
339    /**
340     * Replies the query string to be used in a query URL for the OSM API.
341     *
342     * @return the query string
343     */
344    public String getQueryString() {
345        StringBuilder sb = new StringBuilder();
346        if (uid != null) {
347            sb.append("user=").append(uid);
348        } else if (userName != null) {
349            sb.append("display_name=").append(Utils.encodeUrl(userName));
350        }
351        if (bounds != null) {
352            if (sb.length() > 0) {
353                sb.append('&');
354            }
355            sb.append("bbox=").append(bounds.encodeAsString(","));
356        }
357        if (closedAfter != null && createdBefore != null) {
358            if (sb.length() > 0) {
359                sb.append('&');
360            }
361            sb.append("time=").append(closedAfter)
362                    .append(',').append(createdBefore);
363        } else if (closedAfter != null) {
364            if (sb.length() > 0) {
365                sb.append('&');
366            }
367            sb.append("time=").append(closedAfter);
368        }
369
370        if (open != null) {
371            if (sb.length() > 0) {
372                sb.append('&');
373            }
374            sb.append("open=").append(open);
375        } else if (closed != null) {
376            if (sb.length() > 0) {
377                sb.append('&');
378            }
379            sb.append("closed=").append(Boolean.toString(closed));
380        } else if (changesetIds != null) {
381            // since 2013-12-05, see https://github.com/openstreetmap/openstreetmap-website/commit/1d1f194d598e54a5d6fb4f38fb569d4138af0dc8
382            if (sb.length() > 0) {
383                sb.append('&');
384            }
385            sb.append("changesets=").append(changesetIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
386        }
387        return sb.toString();
388    }
389
390    @Override
391    public String toString() {
392        return getQueryString();
393    }
394
395    /**
396     * Exception thrown for invalid changeset queries.
397     */
398    public static class ChangesetQueryUrlException extends Exception {
399
400        /**
401         * Constructs a new {@code ChangesetQueryUrlException} with the specified detail message.
402         *
403         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
404         */
405        public ChangesetQueryUrlException(String message) {
406            super(message);
407        }
408
409        /**
410         * Constructs a new {@code ChangesetQueryUrlException} with the specified cause and detail message.
411         *
412         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
413         * @param  cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
414         *         (A <code>null</code> value is permitted, and indicates that the cause is nonexistent or unknown.)
415         */
416        public ChangesetQueryUrlException(String message, Throwable cause) {
417            super(message, cause);
418        }
419
420        /**
421         * Constructs a new {@code ChangesetQueryUrlException} with the specified cause and a detail message of
422         * <code>(cause==null ? null : cause.toString())</code> (which typically contains the class and detail message of <code>cause</code>).
423         *
424         * @param  cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
425         *         (A <code>null</code> value is permitted, and indicates that the cause is nonexistent or unknown.)
426         */
427        public ChangesetQueryUrlException(Throwable cause) {
428            super(cause);
429        }
430    }
431
432    /**
433     * Changeset query URL parser.
434     */
435    public static class ChangesetQueryUrlParser {
436        protected int parseUid(String value) throws ChangesetQueryUrlException {
437            if (Utils.isStripEmpty(value))
438                throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, "uid", value));
439            int id;
440            try {
441                id = Integer.parseInt(value);
442                if (id <= 0)
443                    throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, "uid", value));
444            } catch (NumberFormatException e) {
445                throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, "uid", value), e);
446            }
447            return id;
448        }
449
450        protected boolean parseBoolean(String value, String parameter) throws ChangesetQueryUrlException {
451            if (Utils.isStripEmpty(value))
452                throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, parameter, value));
453            switch (value) {
454            case "true":
455                return true;
456            case "false":
457                return false;
458            default:
459                throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, parameter, value));
460            }
461        }
462
463        protected Instant parseDate(String value, String parameter) throws ChangesetQueryUrlException {
464            if (Utils.isStripEmpty(value))
465                throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, parameter, value));
466            try {
467                return DateUtils.parseInstant(value);
468            } catch (UncheckedParseException e) {
469                throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, parameter, value), e);
470            }
471        }
472
473        protected Instant[] parseTime(String value) throws ChangesetQueryUrlException {
474            String[] dates = value.split(",", -1);
475            if (dates.length == 0 || dates.length > 2)
476                throw new ChangesetQueryUrlException(tr(ERROR_UNEXPECTED_VALUE_CHANGESET_QUERY_URL, "time", value));
477            if (dates.length == 1)
478                return new Instant[]{parseDate(dates[0], "time")};
479            // This will always have length 2, due to the (dates.length == 0 || dates.length > 2) check above.
480            return new Instant[]{parseDate(dates[0], "time"), parseDate(dates[1], "time")};
481        }
482
483        protected Collection<Long> parseLongs(String value) {
484            if (Utils.isEmpty(value)) {
485                return Collections.emptySet();
486            } else {
487                return Stream.of(value.split(",", -1)).map(Long::valueOf).collect(Collectors.toSet());
488            }
489        }
490
491        protected ChangesetQuery createFromMap(Map<String, String> queryParams) throws ChangesetQueryUrlException {
492            ChangesetQuery csQuery = new ChangesetQuery();
493
494            for (Entry<String, String> entry: queryParams.entrySet()) {
495                String k = entry.getKey();
496                switch (k) {
497                case "uid":
498                    if (queryParams.containsKey(DISPLAY_NAME))
499                        throw new ChangesetQueryUrlException(
500                                tr("Cannot create a changeset query including both the query parameters ''uid'' and ''display_name''"));
501                    csQuery.forUser(parseUid(queryParams.get("uid")));
502                    break;
503                case DISPLAY_NAME:
504                    if (queryParams.containsKey("uid"))
505                        throw new ChangesetQueryUrlException(
506                                tr("Cannot create a changeset query including both the query parameters ''uid'' and ''display_name''"));
507                    csQuery.forUser(queryParams.get(DISPLAY_NAME));
508                    break;
509                case "open":
510                    csQuery.beingOpen(parseBoolean(entry.getValue(), "open"));
511                    break;
512                case "closed":
513                    csQuery.beingClosed(parseBoolean(entry.getValue(), "closed"));
514                    break;
515                case "time":
516                    Instant[] dates = parseTime(entry.getValue());
517                    switch (dates.length) {
518                    case 1:
519                        csQuery.closedAfter(dates[0]);
520                        break;
521                    case 2:
522                        csQuery.closedAfterAndCreatedBefore(dates[0], dates[1]);
523                        break;
524                    default:
525                        Logging.warn("Unable to parse time: " + entry.getValue());
526                    }
527                    break;
528                case "bbox":
529                    try {
530                        csQuery.inBbox(new Bounds(entry.getValue(), ","));
531                    } catch (IllegalArgumentException e) {
532                        throw new ChangesetQueryUrlException(e);
533                    }
534                    break;
535                case "changesets":
536                    try {
537                        csQuery.forChangesetIds(parseLongs(entry.getValue()));
538                    } catch (NumberFormatException e) {
539                        throw new ChangesetQueryUrlException(e);
540                    }
541                    break;
542                default:
543                    throw new ChangesetQueryUrlException(
544                            tr("Unsupported parameter ''{0}'' in changeset query string", k));
545                }
546            }
547            return csQuery;
548        }
549
550        protected Map<String, String> createMapFromQueryString(String query) {
551            Map<String, String> queryParams = new HashMap<>();
552            String[] keyValuePairs = query.split("&", -1);
553            for (String keyValuePair: keyValuePairs) {
554                String[] kv = keyValuePair.split("=", -1);
555                queryParams.put(kv[0], kv.length > 1 ? kv[1] : "");
556            }
557            return queryParams;
558        }
559
560        /**
561         * Parses the changeset query given as URL query parameters and replies a {@link ChangesetQuery}.
562         * <p>
563         * <code>query</code> is the query part of an API url for querying changesets,
564         * see <a href="http://wiki.openstreetmap.org/wiki/API_v0.6#Query:_GET_.2Fapi.2F0.6.2Fchangesets">OSM API</a>.
565         * <p>
566         * Example for a query string:<br>
567         * <pre>
568         *    uid=1234&amp;open=true
569         * </pre>
570         *
571         * @param query the query string. If null, an empty query (identical to a query for all changesets) is assumed
572         * @return the changeset query
573         * @throws ChangesetQueryUrlException if the query string doesn't represent a legal query for changesets
574         */
575        public ChangesetQuery parse(String query) throws ChangesetQueryUrlException {
576            if (query == null)
577                return new ChangesetQuery();
578            String apiQuery = query.trim();
579            if (apiQuery.isEmpty())
580                return new ChangesetQuery();
581            return createFromMap(createMapFromQueryString(apiQuery));
582        }
583    }
584}