1 # The ChangesetController is the RESTful interface to Changeset objects
4 class ChangesetsController < ApiController
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 :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
13 before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :subscribe, :unsubscribe]
14 around_action :api_call_handle_error
15 around_action :api_call_timeout, :except => [:upload]
17 # Helper methods for checking consistency
18 include ConsistencyValidations
20 # Create a changeset from XML.
24 cs = Changeset.from_xml(request.raw_post, :create => true)
26 # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
27 cs.user = current_user
30 # Subscribe user to changeset comments
31 cs.subscribers << current_user
33 render :plain => cs.id.to_s
37 # Return XML giving the basic info about the changeset. Does not
38 # return anything about the nodes, ways and relations in the changeset.
40 @changeset = Changeset.find(params[:id])
41 @include_discussion = params[:include_discussion].presence
46 # marks a changeset as closed. this may be called multiple times
47 # on the same changeset, so is idempotent.
51 changeset = Changeset.find(params[:id])
52 check_changeset_consistency(changeset, current_user)
54 # to close the changeset, we'll just set its closed_at time to
55 # now. this might not be enough if there are concurrency issues,
56 # but we'll have to wait and see.
57 changeset.set_closed_time_now
64 # Upload a diff in a single transaction.
66 # This means that each change within the diff must succeed, i.e: that
67 # each version number mentioned is still current. Otherwise the entire
68 # transaction *must* be rolled back.
70 # Furthermore, each element in the diff can only reference the current
73 # Returns: a diffResult document, as described in
74 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
76 # only allow POST requests, as the upload method is most definitely
77 # not idempotent, as several uploads with placeholder IDs will have
78 # different side-effects.
79 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
82 changeset = Changeset.find(params[:id])
83 check_changeset_consistency(changeset, current_user)
85 diff_reader = DiffReader.new(request.raw_post, changeset)
86 Changeset.transaction do
87 result = diff_reader.commit
88 render :xml => result.to_s
93 # download the changeset as an osmChange document.
95 # to make it easier to revert diffs it would be better if the osmChange
96 # format were reversible, i.e: contained both old and new versions of
97 # modified elements. but it doesn't at the moment...
99 # this method cannot order the database changes fully (i.e: timestamp and
100 # version number may be too coarse) so the resulting diff may not apply
101 # to a different database. however since changesets are not atomic this
102 # behaviour cannot be guaranteed anyway and is the result of a design
105 changeset = Changeset.find(params[:id])
107 # get all the elements in the changeset which haven't been redacted
108 # and stick them in a big array.
109 elements = [changeset.old_nodes.unredacted,
110 changeset.old_ways.unredacted,
111 changeset.old_relations.unredacted].flatten
113 # sort the elements by timestamp and version number, as this is the
114 # almost sensible ordering available. this would be much nicer if
115 # global (SVN-style) versioning were used - then that would be
117 elements.sort! do |a, b|
118 if a.timestamp == b.timestamp
119 a.version <=> b.version
121 a.timestamp <=> b.timestamp
125 # create changeset and user caches
127 user_display_name_cache = {}
129 # create an osmChange document for the output
130 result = OSM::API.new.get_xml_doc
131 result.root.name = "osmChange"
133 # generate an output element for each operation. note: we avoid looking
134 # at the history because it is simpler - but it would be more correct to
135 # check these assertions.
136 elements.each do |elt|
139 # first version, so it must be newly-created.
140 created = XML::Node.new "create"
141 created << elt.to_xml_node(changeset_cache, user_display_name_cache)
144 modified = XML::Node.new "modify"
145 modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
147 # if the element isn't visible then it must have been deleted
148 deleted = XML::Node.new "delete"
149 deleted << elt.to_xml_node(changeset_cache, user_display_name_cache)
153 render :xml => result.to_s
157 # query changesets by bounding box, time, user or open/closed status.
159 # find any bounding box
160 bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
162 # create the conditions that the user asked for. some or all of
164 changesets = Changeset.all
165 changesets = conditions_bbox(changesets, bbox)
166 changesets = conditions_user(changesets, params["user"], params["display_name"])
167 changesets = conditions_time(changesets, params["time"])
168 changesets = conditions_open(changesets, params["open"])
169 changesets = conditions_closed(changesets, params["closed"])
170 changesets = conditions_ids(changesets, params["changesets"])
172 # sort and limit the changesets
173 changesets = changesets.order("created_at DESC").limit(100)
175 # preload users, tags and comments, and render result
176 @changesets = changesets.preload(:user, :changeset_tags, :comments)
181 # updates a changeset's tags. none of the changeset's attributes are
182 # user-modifiable, so they will be ignored.
184 # changesets are not (yet?) versioned, so we don't have to deal with
185 # history tables here. changesets are locked to a single user, however.
187 # after succesful update, returns the XML of the changeset.
189 # request *must* be a PUT.
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)
201 # Adds a subscriber to the changeset
203 # Check the arguments are sane
204 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
206 # Extract the arguments
207 id = params[:id].to_i
209 # Find the changeset and check it is valid
210 changeset = Changeset.find(id)
211 raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribers.exists?(current_user.id)
214 changeset.subscribers << current_user
216 # Return a copy of the updated changeset
217 @changeset = changeset
222 # Removes a subscriber from the changeset
224 # Check the arguments are sane
225 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
227 # Extract the arguments
228 id = params[:id].to_i
230 # Find the changeset and check it is valid
231 changeset = Changeset.find(id)
232 raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribers.exists?(current_user.id)
234 # Remove the subscriber
235 changeset.subscribers.delete(current_user)
237 # Return a copy of the updated changeset
238 @changeset = changeset
244 #------------------------------------------------------------
245 # utility functions below.
246 #------------------------------------------------------------
249 # if a bounding box was specified do some sanity checks.
250 # restrict changesets to those enclosed by a bounding box
251 # we need to return both the changesets and the bounding box
252 def conditions_bbox(changesets, bbox)
254 bbox.check_boundaries
255 bbox = bbox.to_scaled
257 changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
258 bbox.max_lon.to_i, bbox.min_lon.to_i,
259 bbox.max_lat.to_i, bbox.min_lat.to_i)
266 # restrict changesets to those by a particular user
267 def conditions_user(changesets, user, name)
268 if user.nil? && name.nil?
271 # shouldn't provide both name and UID
272 raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
274 # use either the name or the UID to find the user which we're selecting on.
276 # user input checking, we don't have any UIDs < 1
277 raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
279 u = User.find(user.to_i)
281 u = User.find_by(:display_name => name)
284 # make sure we found a user
285 raise OSM::APINotFoundError if u.nil?
287 # should be able to get changesets of public users only, or
288 # our own changesets regardless of public-ness.
289 unless u.data_public?
290 # get optional user auth stuff so that users can see their own
291 # changesets if they're non-public
294 raise OSM::APINotFoundError if current_user.nil? || current_user != u
297 changesets.where(:user_id => u.id)
302 # restrict changes to those closed during a particular time period
303 def conditions_time(changesets, time)
306 elsif time.count(",") == 1
307 # if there is a range, i.e: comma separated, then the first is
308 # low, second is high - same as with bounding boxes.
310 # check that we actually have 2 elements in the array
311 times = time.split(",")
312 raise OSM::APIBadUserInput, "bad time range" if times.size != 2
314 from, to = times.collect { |t| Time.parse(t) }
315 changesets.where("closed_at >= ? and created_at <= ?", from, to)
317 # if there is no comma, assume its a lower limit on time
318 changesets.where("closed_at >= ?", Time.parse(time))
320 # stupid Time seems to throw both of these for bad parsing, so
321 # we have to catch both and ensure the correct code path is taken.
322 rescue ArgumentError, RuntimeError => e
323 raise OSM::APIBadUserInput, e.message.to_s
327 # return changesets which are open (haven't been closed yet)
328 # we do this by seeing if the 'closed at' time is in the future. Also if we've
329 # hit the maximum number of changes then it counts as no longer open.
330 # if parameter 'open' is nill then open and closed changesets are returned
331 def conditions_open(changesets, open)
335 changesets.where("closed_at >= ? and num_changes <= ?",
336 Time.now.getutc, Changeset::MAX_ELEMENTS)
341 # query changesets which are closed
342 # ('closed at' time has passed or changes limit is hit)
343 def conditions_closed(changesets, closed)
347 changesets.where("closed_at < ? or num_changes > ?",
348 Time.now.getutc, Changeset::MAX_ELEMENTS)
353 # query changesets by a list of ids
354 # (either specified as array or comma-separated string)
355 def conditions_ids(changesets, ids)
359 raise OSM::APIBadUserInput, "No changesets were given to search for"
361 ids = ids.split(",").collect(&:to_i)
362 changesets.where(:id => ids)