1 # The ChangesetController is the RESTful interface to Changeset objects
4 class ChangesetsController < ApiController
7 before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
8 before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :subscribe, :unsubscribe]
9 before_action :setup_user_auth, :only => [:show]
10 before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
14 before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
15 before_action :set_request_formats, :except => [:create, :close, :upload]
17 around_action :api_call_handle_error
18 around_action :api_call_timeout, :except => [:upload]
20 # Helper methods for checking consistency
21 include ConsistencyValidations
24 # Return XML giving the basic info about the changeset. Does not
25 # return anything about the nodes, ways and relations in the changeset.
27 @changeset = Changeset.find(params[:id])
28 if params[:include_discussion].presence
29 @comments = @changeset.comments
30 @comments = @comments.unscope(:where => :visible) if params[:show_hidden_comments].presence && can?(:restore, ChangesetComment)
31 @comments = @comments.includes(:author)
35 respond_to do |format|
41 # Create a changeset from XML.
43 cs = Changeset.from_xml(request.raw_post, :create => true)
45 # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
46 cs.user = current_user
49 # Subscribe user to changeset comments
50 cs.subscribe(current_user)
52 render :plain => cs.id.to_s
56 # marks a changeset as closed. this may be called multiple times
57 # on the same changeset, so is idempotent.
59 changeset = Changeset.find(params[:id])
60 check_changeset_consistency(changeset, current_user)
62 # to close the changeset, we'll just set its closed_at time to
63 # now. this might not be enough if there are concurrency issues,
64 # but we'll have to wait and see.
65 changeset.set_closed_time_now
72 # Upload a diff in a single transaction.
74 # This means that each change within the diff must succeed, i.e: that
75 # each version number mentioned is still current. Otherwise the entire
76 # transaction *must* be rolled back.
78 # Furthermore, each element in the diff can only reference the current
81 # Returns: a diffResult document, as described in
82 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
84 changeset = Changeset.find(params[:id])
85 check_changeset_consistency(changeset, current_user)
87 diff_reader = DiffReader.new(request.raw_post, changeset)
88 Changeset.transaction do
89 result = diff_reader.commit
90 # the number of changes in this changeset has already been
91 # updated and is visible in this transaction so we don't need
92 # to allow for any more when checking the limit
94 render :xml => result.to_s
99 # download the changeset as an osmChange document.
101 # to make it easier to revert diffs it would be better if the osmChange
102 # format were reversible, i.e: contained both old and new versions of
103 # modified elements. but it doesn't at the moment...
105 # this method cannot order the database changes fully (i.e: timestamp and
106 # version number may be too coarse) so the resulting diff may not apply
107 # to a different database. however since changesets are not atomic this
108 # behaviour cannot be guaranteed anyway and is the result of a design
111 changeset = Changeset.find(params[:id])
113 # get all the elements in the changeset which haven't been redacted
114 # and stick them in a big array.
115 elements = [changeset.old_nodes.unredacted,
116 changeset.old_ways.unredacted,
117 changeset.old_relations.unredacted].flatten
119 # sort the elements by timestamp and version number, as this is the
120 # almost sensible ordering available. this would be much nicer if
121 # global (SVN-style) versioning were used - then that would be
123 elements.sort_by! { |e| [e.timestamp, e.version] }
125 # generate an output element for each operation. note: we avoid looking
126 # at the history because it is simpler - but it would be more correct to
127 # check these assertions.
132 elements.each do |elt|
134 # first version, so it must be newly-created.
140 # if the element isn't visible then it must have been deleted
145 respond_to do |format|
151 # query changesets by bounding box, time, user or open/closed status.
153 raise OSM::APIBadUserInput, "cannot use order=oldest with time" if params[:time] && params[:order] == "oldest"
155 # find any bounding box
156 bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
158 # create the conditions that the user asked for. some or all of
160 changesets = Changeset.all
161 changesets = conditions_bbox(changesets, bbox)
162 changesets = conditions_user(changesets, params["user"], params["display_name"])
163 changesets = conditions_time(changesets, params["time"])
164 changesets = conditions_from_to(changesets, params["from"], params["to"])
165 changesets = conditions_open(changesets, params["open"])
166 changesets = conditions_closed(changesets, params["closed"])
167 changesets = conditions_ids(changesets, params["changesets"])
169 # sort the changesets
170 changesets = if params[:order] == "oldest"
171 changesets.order(:created_at => :asc)
173 changesets.order(:created_at => :desc)
177 changesets = changesets.limit(result_limit)
179 # preload users, tags and comments, and render result
180 @changesets = changesets.preload(:user, :changeset_tags, :comments)
183 respond_to do |format|
190 # updates a changeset's tags. none of the changeset's attributes are
191 # user-modifiable, so they will be ignored.
193 # changesets are not (yet?) versioned, so we don't have to deal with
194 # history tables here. changesets are locked to a single user, however.
196 # after succesful update, returns the XML of the changeset.
198 @changeset = Changeset.find(params[:id])
199 new_changeset = Changeset.from_xml(request.raw_post)
201 check_changeset_consistency(@changeset, current_user)
202 @changeset.update_from(new_changeset, current_user)
205 respond_to do |format|
212 # Adds a subscriber to the changeset
214 # Check the arguments are sane
215 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
217 # Extract the arguments
218 id = params[:id].to_i
220 # Find the changeset and check it is valid
221 changeset = Changeset.find(id)
222 raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribed?(current_user)
225 changeset.subscribe(current_user)
227 # Return a copy of the updated changeset
228 @changeset = changeset
231 respond_to do |format|
238 # Removes a subscriber from the changeset
240 # Check the arguments are sane
241 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
243 # Extract the arguments
244 id = params[:id].to_i
246 # Find the changeset and check it is valid
247 changeset = Changeset.find(id)
248 raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribed?(current_user)
250 # Remove the subscriber
251 changeset.unsubscribe(current_user)
253 # Return a copy of the updated changeset
254 @changeset = changeset
257 respond_to do |format|
265 #------------------------------------------------------------
266 # utility functions below.
267 #------------------------------------------------------------
270 # if a bounding box was specified do some sanity checks.
271 # restrict changesets to those enclosed by a bounding box
272 def conditions_bbox(changesets, bbox)
274 bbox.check_boundaries
275 bbox = bbox.to_scaled
277 changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
278 bbox.max_lon.to_i, bbox.min_lon.to_i,
279 bbox.max_lat.to_i, bbox.min_lat.to_i)
286 # restrict changesets to those by a particular user
287 def conditions_user(changesets, user, name)
288 if user.nil? && name.nil?
291 # shouldn't provide both name and UID
292 raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
294 # use either the name or the UID to find the user which we're selecting on.
296 # user input checking, we don't have any UIDs < 1
297 raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
299 u = User.find_by(:id => user.to_i)
301 u = User.find_by(:display_name => name)
304 # make sure we found a user
305 raise OSM::APINotFoundError if u.nil?
307 # should be able to get changesets of public users only, or
308 # our own changesets regardless of public-ness.
309 unless u.data_public?
310 # get optional user auth stuff so that users can see their own
311 # changesets if they're non-public
314 raise OSM::APINotFoundError if current_user.nil? || current_user != u
317 changesets.where(:user => u)
322 # restrict changesets to those during a particular time period
323 def conditions_time(changesets, time)
326 elsif time.count(",") == 1
327 # if there is a range, i.e: comma separated, then the first is
328 # low, second is high - same as with bounding boxes.
330 # check that we actually have 2 elements in the array
331 times = time.split(",")
332 raise OSM::APIBadUserInput, "bad time range" if times.size != 2
334 from, to = times.collect { |t| Time.parse(t).utc }
335 changesets.where("closed_at >= ? and created_at <= ?", from, to)
337 # if there is no comma, assume its a lower limit on time
338 changesets.where("closed_at >= ?", Time.parse(time).utc)
340 # stupid Time seems to throw both of these for bad parsing, so
341 # we have to catch both and ensure the correct code path is taken.
342 rescue ArgumentError, RuntimeError => e
343 raise OSM::APIBadUserInput, e.message.to_s
347 # restrict changesets to those opened during a particular time period
348 # works similar to from..to of notes controller, including the requirement of 'from' when specifying 'to'
349 def conditions_from_to(changesets, from, to)
352 from = Time.parse(from).utc
354 raise OSM::APIBadUserInput, "Date #{from} is in a wrong format"
364 raise OSM::APIBadUserInput, "Date #{to} is in a wrong format"
367 changesets.where(:created_at => from..to)
374 # return changesets which are open (haven't been closed yet)
375 # we do this by seeing if the 'closed at' time is in the future. Also if we've
376 # hit the maximum number of changes then it counts as no longer open.
377 # if parameter 'open' is nill then open and closed changesets are returned
378 def conditions_open(changesets, open)
382 changesets.where("closed_at >= ? and num_changes <= ?",
383 Time.now.utc, Changeset::MAX_ELEMENTS)
388 # query changesets which are closed
389 # ('closed at' time has passed or changes limit is hit)
390 def conditions_closed(changesets, closed)
394 changesets.where("closed_at < ? or num_changes > ?",
395 Time.now.utc, Changeset::MAX_ELEMENTS)
400 # query changesets by a list of ids
401 # (either specified as array or comma-separated string)
402 def conditions_ids(changesets, ids)
406 raise OSM::APIBadUserInput, "No changesets were given to search for"
408 ids = ids.split(",").collect(&:to_i)
409 changesets.where(:id => ids)
414 # Get the maximum number of results to return
417 if params[:limit].to_i.positive? && params[:limit].to_i <= Settings.max_changeset_query_limit
420 raise OSM::APIBadUserInput, "Changeset limit must be between 1 and #{Settings.max_changeset_query_limit}"
423 Settings.default_changeset_query_limit