1 # The ChangesetController is the RESTful interface to Changeset objects
4 class ChangesetsController < ApiController
5 before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
6 before_action :setup_user_auth, :only => [:show]
7 before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
11 before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
12 before_action :set_request_formats, :except => [:create, :close, :upload]
14 skip_around_action :api_call_timeout, :only => [:upload]
16 # Helper methods for checking consistency
17 include ConsistencyValidations
20 # query changesets by bounding box, time, user or open/closed status.
22 raise OSM::APIBadUserInput, "cannot use order=oldest with time" if params[:time] && params[:order] == "oldest"
24 # find any bounding box
25 bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
27 # create the conditions that the user asked for. some or all of
29 changesets = Changeset.all
30 changesets = conditions_bbox(changesets, bbox)
31 changesets = conditions_user(changesets, params["user"], params["display_name"])
32 changesets = conditions_time(changesets, params["time"])
33 changesets = conditions_from_to(changesets, params["from"], params["to"])
34 changesets = conditions_open(changesets, params["open"])
35 changesets = conditions_closed(changesets, params["closed"])
36 changesets = conditions_ids(changesets, params["changesets"])
39 changesets = if params[:order] == "oldest"
40 changesets.order(:created_at => :asc)
42 changesets.order(:created_at => :desc)
46 changesets = changesets.limit(result_limit)
48 # preload users, tags and comments, and render result
49 @changesets = changesets.preload(:user, :changeset_tags, :comments)
51 respond_to do |format|
58 # Return XML giving the basic info about the changeset. Does not
59 # return anything about the nodes, ways and relations in the changeset.
61 @changeset = Changeset.find(params[:id])
62 if params[:include_discussion].presence
63 @comments = @changeset.comments
64 @comments = @comments.unscope(:where => :visible) if params[:show_hidden_comments].presence && can?(:restore, ChangesetComment)
65 @comments = @comments.includes(:author)
68 respond_to do |format|
74 # Create a changeset from XML.
76 cs = Changeset.from_xml(request.raw_post, :create => true)
78 # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
79 cs.user = current_user
82 # Subscribe user to changeset comments
83 cs.subscribe(current_user)
85 render :plain => cs.id.to_s
89 # marks a changeset as closed. this may be called multiple times
90 # on the same changeset, so is idempotent.
92 changeset = Changeset.find(params[:id])
93 check_changeset_consistency(changeset, current_user)
95 # to close the changeset, we'll just set its closed_at time to
96 # now. this might not be enough if there are concurrency issues,
97 # but we'll have to wait and see.
98 changeset.set_closed_time_now
105 # Upload a diff in a single transaction.
107 # This means that each change within the diff must succeed, i.e: that
108 # each version number mentioned is still current. Otherwise the entire
109 # transaction *must* be rolled back.
111 # Furthermore, each element in the diff can only reference the current
114 # Returns: a diffResult document, as described in
115 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
117 changeset = Changeset.find(params[:id])
118 check_changeset_consistency(changeset, current_user)
120 diff_reader = DiffReader.new(request.raw_post, changeset)
121 Changeset.transaction do
122 result = diff_reader.commit
123 # the number of changes in this changeset has already been
124 # updated and is visible in this transaction so we don't need
125 # to allow for any more when checking the limit
127 render :xml => result.to_s
132 # download the changeset as an osmChange document.
134 # to make it easier to revert diffs it would be better if the osmChange
135 # format were reversible, i.e: contained both old and new versions of
136 # modified elements. but it doesn't at the moment...
138 # this method cannot order the database changes fully (i.e: timestamp and
139 # version number may be too coarse) so the resulting diff may not apply
140 # to a different database. however since changesets are not atomic this
141 # behaviour cannot be guaranteed anyway and is the result of a design
144 changeset = Changeset.find(params[:id])
146 # get all the elements in the changeset which haven't been redacted
147 # and stick them in a big array.
148 elements = [changeset.old_nodes.unredacted,
149 changeset.old_ways.unredacted,
150 changeset.old_relations.unredacted].flatten
152 # sort the elements by timestamp and version number, as this is the
153 # almost sensible ordering available. this would be much nicer if
154 # global (SVN-style) versioning were used - then that would be
156 elements.sort_by! { |e| [e.timestamp, e.version] }
158 # generate an output element for each operation. note: we avoid looking
159 # at the history because it is simpler - but it would be more correct to
160 # check these assertions.
165 elements.each do |elt|
167 # first version, so it must be newly-created.
173 # if the element isn't visible then it must have been deleted
178 respond_to do |format|
184 # updates a changeset's tags. none of the changeset's attributes are
185 # user-modifiable, so they will be ignored.
187 # changesets are not (yet?) versioned, so we don't have to deal with
188 # history tables here. changesets are locked to a single user, however.
190 # after succesful update, returns the XML of the changeset.
192 @changeset = Changeset.find(params[:id])
193 new_changeset = Changeset.from_xml(request.raw_post)
195 check_changeset_consistency(@changeset, current_user)
196 @changeset.update_from(new_changeset, current_user)
199 respond_to do |format|
206 # Adds a subscriber to the changeset
208 # Check the arguments are sane
209 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
211 # Extract the arguments
212 id = params[:id].to_i
214 # Find the changeset and check it is valid
215 changeset = Changeset.find(id)
216 raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribed?(current_user)
219 changeset.subscribe(current_user)
221 # Return a copy of the updated changeset
222 @changeset = changeset
225 respond_to do |format|
232 # Removes a subscriber from the changeset
234 # Check the arguments are sane
235 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
237 # Extract the arguments
238 id = params[:id].to_i
240 # Find the changeset and check it is valid
241 changeset = Changeset.find(id)
242 raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribed?(current_user)
244 # Remove the subscriber
245 changeset.unsubscribe(current_user)
247 # Return a copy of the updated changeset
248 @changeset = changeset
251 respond_to do |format|
259 #------------------------------------------------------------
260 # utility functions below.
261 #------------------------------------------------------------
264 # if a bounding box was specified do some sanity checks.
265 # restrict changesets to those enclosed by a bounding box
266 def conditions_bbox(changesets, bbox)
268 bbox.check_boundaries
269 bbox = bbox.to_scaled
271 changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
272 bbox.max_lon.to_i, bbox.min_lon.to_i,
273 bbox.max_lat.to_i, bbox.min_lat.to_i)
280 # restrict changesets to those by a particular user
281 def conditions_user(changesets, user, name)
282 if user.nil? && name.nil?
285 # shouldn't provide both name and UID
286 raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
288 # use either the name or the UID to find the user which we're selecting on.
290 # user input checking, we don't have any UIDs < 1
291 raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
293 u = User.find_by(:id => user.to_i)
295 u = User.find_by(:display_name => name)
298 # make sure we found a user
299 raise OSM::APINotFoundError if u.nil?
301 # should be able to get changesets of public users only, or
302 # our own changesets regardless of public-ness.
303 unless u.data_public?
304 # get optional user auth stuff so that users can see their own
305 # changesets if they're non-public
308 raise OSM::APINotFoundError if current_user.nil? || current_user != u
311 changesets.where(:user => u)
316 # restrict changesets to those during a particular time period
317 def conditions_time(changesets, time)
320 elsif time.count(",") == 1
321 # if there is a range, i.e: comma separated, then the first is
322 # low, second is high - same as with bounding boxes.
324 # check that we actually have 2 elements in the array
325 times = time.split(",")
326 raise OSM::APIBadUserInput, "bad time range" if times.size != 2
328 from, to = times.collect { |t| Time.parse(t).utc }
329 changesets.where("closed_at >= ? and created_at <= ?", from, to)
331 # if there is no comma, assume its a lower limit on time
332 changesets.where(:closed_at => Time.parse(time).utc..)
334 # stupid Time seems to throw both of these for bad parsing, so
335 # we have to catch both and ensure the correct code path is taken.
336 rescue ArgumentError, RuntimeError => e
337 raise OSM::APIBadUserInput, e.message.to_s
341 # restrict changesets to those opened during a particular time period
342 # works similar to from..to of notes controller, including the requirement of 'from' when specifying 'to'
343 def conditions_from_to(changesets, from, to)
346 from = Time.parse(from).utc
348 raise OSM::APIBadUserInput, "Date #{from} is in a wrong format"
358 raise OSM::APIBadUserInput, "Date #{to} is in a wrong format"
361 changesets.where(:created_at => from..to)
368 # return changesets which are open (haven't been closed yet)
369 # we do this by seeing if the 'closed at' time is in the future. Also if we've
370 # hit the maximum number of changes then it counts as no longer open.
371 # if parameter 'open' is nill then open and closed changesets are returned
372 def conditions_open(changesets, open)
376 changesets.where("closed_at >= ? and num_changes <= ?",
377 Time.now.utc, Changeset::MAX_ELEMENTS)
382 # query changesets which are closed
383 # ('closed at' time has passed or changes limit is hit)
384 def conditions_closed(changesets, closed)
388 changesets.where("closed_at < ? or num_changes > ?",
389 Time.now.utc, Changeset::MAX_ELEMENTS)
394 # query changesets by a list of ids
395 # (either specified as array or comma-separated string)
396 def conditions_ids(changesets, ids)
400 raise OSM::APIBadUserInput, "No changesets were given to search for"
402 ids = ids.split(",").collect(&:to_i)
403 changesets.where(:id => ids)
408 # Get the maximum number of results to return
411 if params[:limit].to_i.positive? && params[:limit].to_i <= Settings.max_changeset_query_limit
414 raise OSM::APIBadUserInput, "Changeset limit must be between 1 and #{Settings.max_changeset_query_limit}"
417 Settings.default_changeset_query_limit