1 # The ChangesetController is the RESTful interface to Changeset objects
4 class ChangesetsController < ApiController
8 before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
12 before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
13 before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
14 before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :subscribe, :unsubscribe]
15 around_action :api_call_handle_error
16 around_action :api_call_timeout, :except => [:upload]
18 # Helper methods for checking consistency
19 include ConsistencyValidations
21 # Create a changeset from XML.
25 cs = Changeset.from_xml(request.raw_post, true)
27 # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
28 cs.user = current_user
31 # Subscribe user to changeset comments
32 cs.subscribers << current_user
34 render :plain => cs.id.to_s
38 # Return XML giving the basic info about the changeset. Does not
39 # return anything about the nodes, ways and relations in the changeset.
41 @changeset = Changeset.find(params[:id])
42 @include_discussion = params[:include_discussion].presence
47 # marks a changeset as closed. this may be called multiple times
48 # on the same changeset, so is idempotent.
52 changeset = Changeset.find(params[:id])
53 check_changeset_consistency(changeset, current_user)
55 # to close the changeset, we'll just set its closed_at time to
56 # now. this might not be enough if there are concurrency issues,
57 # but we'll have to wait and see.
58 changeset.set_closed_time_now
65 # insert a (set of) points into a changeset bounding box. this can only
66 # increase the size of the bounding box. this is a hint that clients can
67 # set either before uploading a large number of changes, or changes that
68 # the client (but not the server) knows will affect areas further away.
70 # only allow POST requests, because although this method is
71 # idempotent, there is no "document" to PUT really...
74 cs = Changeset.find(params[:id])
75 check_changeset_consistency(cs, current_user)
77 # keep an array of lons and lats
81 # the request is in pseudo-osm format... this is kind-of an
82 # abuse, maybe should change to some other format?
83 doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
84 doc.find("//osm/node").each do |n|
85 lon << n["lon"].to_f * GeoRecord::SCALE
86 lat << n["lat"].to_f * GeoRecord::SCALE
89 # add the existing bounding box to the lon-lat array
90 lon << cs.min_lon unless cs.min_lon.nil?
91 lat << cs.min_lat unless cs.min_lat.nil?
92 lon << cs.max_lon unless cs.max_lon.nil?
93 lat << cs.max_lat unless cs.max_lat.nil?
95 # collapse the arrays to minimum and maximum
96 cs.min_lon = lon.min.round
97 cs.min_lat = lat.min.round
98 cs.max_lon = lon.max.round
99 cs.max_lat = lat.max.round
101 # save the larger bounding box and return the changeset, which
102 # will include the bigger bounding box.
109 # Upload a diff in a single transaction.
111 # This means that each change within the diff must succeed, i.e: that
112 # each version number mentioned is still current. Otherwise the entire
113 # transaction *must* be rolled back.
115 # Furthermore, each element in the diff can only reference the current
118 # Returns: a diffResult document, as described in
119 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
121 # only allow POST requests, as the upload method is most definitely
122 # not idempotent, as several uploads with placeholder IDs will have
123 # different side-effects.
124 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
127 changeset = Changeset.find(params[:id])
128 check_changeset_consistency(changeset, current_user)
130 diff_reader = DiffReader.new(request.raw_post, changeset)
131 Changeset.transaction do
132 result = diff_reader.commit
133 render :xml => result.to_s
138 # download the changeset as an osmChange document.
140 # to make it easier to revert diffs it would be better if the osmChange
141 # format were reversible, i.e: contained both old and new versions of
142 # modified elements. but it doesn't at the moment...
144 # this method cannot order the database changes fully (i.e: timestamp and
145 # version number may be too coarse) so the resulting diff may not apply
146 # to a different database. however since changesets are not atomic this
147 # behaviour cannot be guaranteed anyway and is the result of a design
150 changeset = Changeset.find(params[:id])
152 # get all the elements in the changeset which haven't been redacted
153 # and stick them in a big array.
154 elements = [changeset.old_nodes.unredacted,
155 changeset.old_ways.unredacted,
156 changeset.old_relations.unredacted].flatten
158 # sort the elements by timestamp and version number, as this is the
159 # almost sensible ordering available. this would be much nicer if
160 # global (SVN-style) versioning were used - then that would be
162 elements.sort! do |a, b|
163 if a.timestamp == b.timestamp
164 a.version <=> b.version
166 a.timestamp <=> b.timestamp
170 # create changeset and user caches
172 user_display_name_cache = {}
174 # create an osmChange document for the output
175 result = OSM::API.new.get_xml_doc
176 result.root.name = "osmChange"
178 # generate an output element for each operation. note: we avoid looking
179 # at the history because it is simpler - but it would be more correct to
180 # check these assertions.
181 elements.each do |elt|
184 # first version, so it must be newly-created.
185 created = XML::Node.new "create"
186 created << elt.to_xml_node(changeset_cache, user_display_name_cache)
189 modified = XML::Node.new "modify"
190 modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
192 # if the element isn't visible then it must have been deleted
193 deleted = XML::Node.new "delete"
194 deleted << elt.to_xml_node(changeset_cache, user_display_name_cache)
198 render :xml => result.to_s
202 # query changesets by bounding box, time, user or open/closed status.
204 # find any bounding box
205 bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
207 # create the conditions that the user asked for. some or all of
209 changesets = Changeset.all
210 changesets = conditions_bbox(changesets, bbox)
211 changesets = conditions_user(changesets, params["user"], params["display_name"])
212 changesets = conditions_time(changesets, params["time"])
213 changesets = conditions_open(changesets, params["open"])
214 changesets = conditions_closed(changesets, params["closed"])
215 changesets = conditions_ids(changesets, params["changesets"])
217 # sort and limit the changesets
218 changesets = changesets.order("created_at DESC").limit(100)
220 # preload users, tags and comments, and render result
221 @changesets = changesets.preload(:user, :changeset_tags, :comments)
226 # updates a changeset's tags. none of the changeset's attributes are
227 # user-modifiable, so they will be ignored.
229 # changesets are not (yet?) versioned, so we don't have to deal with
230 # history tables here. changesets are locked to a single user, however.
232 # after succesful update, returns the XML of the changeset.
234 # request *must* be a PUT.
237 @changeset = Changeset.find(params[:id])
238 new_changeset = Changeset.from_xml(request.raw_post)
240 check_changeset_consistency(@changeset, current_user)
241 @changeset.update_from(new_changeset, current_user)
246 # Adds a subscriber to the changeset
248 # Check the arguments are sane
249 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
251 # Extract the arguments
252 id = params[:id].to_i
254 # Find the changeset and check it is valid
255 changeset = Changeset.find(id)
256 raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribers.exists?(current_user.id)
259 changeset.subscribers << current_user
261 # Return a copy of the updated changeset
262 @changeset = changeset
267 # Removes a subscriber from the changeset
269 # Check the arguments are sane
270 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
272 # Extract the arguments
273 id = params[:id].to_i
275 # Find the changeset and check it is valid
276 changeset = Changeset.find(id)
277 raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribers.exists?(current_user.id)
279 # Remove the subscriber
280 changeset.subscribers.delete(current_user)
282 # Return a copy of the updated changeset
283 @changeset = changeset
289 #------------------------------------------------------------
290 # utility functions below.
291 #------------------------------------------------------------
294 # if a bounding box was specified do some sanity checks.
295 # restrict changesets to those enclosed by a bounding box
296 # we need to return both the changesets and the bounding box
297 def conditions_bbox(changesets, bbox)
299 bbox.check_boundaries
300 bbox = bbox.to_scaled
302 changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
303 bbox.max_lon.to_i, bbox.min_lon.to_i,
304 bbox.max_lat.to_i, bbox.min_lat.to_i)
311 # restrict changesets to those by a particular user
312 def conditions_user(changesets, user, name)
313 if user.nil? && name.nil?
316 # shouldn't provide both name and UID
317 raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
319 # use either the name or the UID to find the user which we're selecting on.
321 # user input checking, we don't have any UIDs < 1
322 raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
324 u = User.find(user.to_i)
326 u = User.find_by(:display_name => name)
329 # make sure we found a user
330 raise OSM::APINotFoundError if u.nil?
332 # should be able to get changesets of public users only, or
333 # our own changesets regardless of public-ness.
334 unless u.data_public?
335 # get optional user auth stuff so that users can see their own
336 # changesets if they're non-public
339 raise OSM::APINotFoundError if current_user.nil? || current_user != u
342 changesets.where(:user_id => u.id)
347 # restrict changes to those closed during a particular time period
348 def conditions_time(changesets, time)
351 elsif time.count(",") == 1
352 # if there is a range, i.e: comma separated, then the first is
353 # low, second is high - same as with bounding boxes.
355 # check that we actually have 2 elements in the array
356 times = time.split(/,/)
357 raise OSM::APIBadUserInput, "bad time range" if times.size != 2
359 from, to = times.collect { |t| Time.parse(t) }
360 changesets.where("closed_at >= ? and created_at <= ?", from, to)
362 # if there is no comma, assume its a lower limit on time
363 changesets.where("closed_at >= ?", Time.parse(time))
365 # stupid Time seems to throw both of these for bad parsing, so
366 # we have to catch both and ensure the correct code path is taken.
367 rescue ArgumentError => e
368 raise OSM::APIBadUserInput, e.message.to_s
369 rescue RuntimeError => e
370 raise OSM::APIBadUserInput, e.message.to_s
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.getutc, 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.getutc, 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)