1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetController < ApplicationController
6 before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
7 before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
8 before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
9 after_filter :compress_output
11 # Help methods for checking boundary sanity and area size
14 # Helper methods for checking consistency
15 include ConsistencyValidations
17 # Create a changeset from XML.
20 cs = Changeset.from_xml(request.raw_post, true)
25 render :text => cs.id.to_s, :content_type => "text/plain"
27 render :nothing => true, :status => :bad_request
30 render :nothing => true, :status => :method_not_allowed
36 changeset = Changeset.find(params[:id])
37 render :text => changeset.to_xml.to_s, :content_type => "text/xml"
38 rescue ActiveRecord::RecordNotFound
39 render :nothing => true, :status => :not_found
44 # marks a changeset as closed. this may be called multiple times
45 # on the same changeset, so is idempotent.
48 render :nothing => true, :status => :method_not_allowed
52 changeset = Changeset.find(params[:id])
53 check_changeset_consistency(changeset, @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
61 render :nothing => true
62 rescue ActiveRecord::RecordNotFound
63 render :nothing => true, :status => :not_found
64 rescue OSM::APIError => ex
69 # insert a (set of) points into a changeset bounding box. this can only
70 # increase the size of the bounding box. this is a hint that clients can
71 # set either before uploading a large number of changes, or changes that
72 # the client (but not the server) knows will affect areas further away.
74 # only allow POST requests, because although this method is
75 # idempotent, there is no "document" to PUT really...
77 cs = Changeset.find(params[:id])
78 check_changeset_consistency(cs, @user)
80 # keep an array of lons and lats
84 # the request is in pseudo-osm format... this is kind-of an
85 # abuse, maybe should change to some other format?
86 doc = XML::Parser.string(request.raw_post).parse
87 doc.find("//osm/node").each do |n|
88 lon << n['lon'].to_f * GeoRecord::SCALE
89 lat << n['lat'].to_f * GeoRecord::SCALE
92 # add the existing bounding box to the lon-lat array
93 lon << cs.min_lon unless cs.min_lon.nil?
94 lat << cs.min_lat unless cs.min_lat.nil?
95 lon << cs.max_lon unless cs.max_lon.nil?
96 lat << cs.max_lat unless cs.max_lat.nil?
98 # collapse the arrays to minimum and maximum
99 cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat =
100 lon.min, lat.min, lon.max, lat.max
102 # save the larger bounding box and return the changeset, which
103 # will include the bigger bounding box.
105 render :text => cs.to_xml.to_s, :content_type => "text/xml"
108 render :nothing => true, :status => :method_not_allowed
111 rescue ActiveRecord::RecordNotFound
112 render :nothing => true, :status => :not_found
113 rescue OSM::APIError => ex
114 render ex.render_opts
118 # Upload a diff in a single transaction.
120 # This means that each change within the diff must succeed, i.e: that
121 # each version number mentioned is still current. Otherwise the entire
122 # transaction *must* be rolled back.
124 # Furthermore, each element in the diff can only reference the current
127 # Returns: a diffResult document, as described in
128 # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
130 # only allow POST requests, as the upload method is most definitely
131 # not idempotent, as several uploads with placeholder IDs will have
132 # different side-effects.
133 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
135 render :nothing => true, :status => :method_not_allowed
139 changeset = Changeset.find(params[:id])
140 check_changeset_consistency(changeset, @user)
142 diff_reader = DiffReader.new(request.raw_post, changeset)
143 Changeset.transaction do
144 result = diff_reader.commit
145 render :text => result.to_s, :content_type => "text/xml"
148 rescue ActiveRecord::RecordNotFound
149 render :nothing => true, :status => :not_found
150 rescue OSM::APIError => ex
151 render ex.render_opts
155 # download the changeset as an osmChange document.
157 # to make it easier to revert diffs it would be better if the osmChange
158 # format were reversible, i.e: contained both old and new versions of
159 # modified elements. but it doesn't at the moment...
161 # this method cannot order the database changes fully (i.e: timestamp and
162 # version number may be too coarse) so the resulting diff may not apply
163 # to a different database. however since changesets are not atomic this
164 # behaviour cannot be guaranteed anyway and is the result of a design
167 changeset = Changeset.find(params[:id])
169 # get all the elements in the changeset and stick them in a big array.
170 elements = [changeset.old_nodes,
172 changeset.old_relations].flatten
174 # sort the elements by timestamp and version number, as this is the
175 # almost sensible ordering available. this would be much nicer if
176 # global (SVN-style) versioning were used - then that would be
178 elements.sort! do |a, b|
179 if (a.timestamp == b.timestamp)
180 a.version <=> b.version
182 a.timestamp <=> b.timestamp
186 # create an osmChange document for the output
187 result = OSM::API.new.get_xml_doc
188 result.root.name = "osmChange"
190 # generate an output element for each operation. note: we avoid looking
191 # at the history because it is simpler - but it would be more correct to
192 # check these assertions.
193 elements.each do |elt|
195 if (elt.version == 1)
196 # first version, so it must be newly-created.
197 created = XML::Node.new "create"
198 created << elt.to_xml_node
200 # get the previous version from the element history
201 prev_elt = elt.class.find(:first, :conditions =>
202 ['id = ? and version = ?',
203 elt.id, elt.version])
205 # if the element isn't visible then it must have been deleted, so
206 # output the *previous* XML
207 deleted = XML::Node.new "delete"
208 deleted << prev_elt.to_xml_node
210 # must be a modify, for which we don't need the previous version
212 modified = XML::Node.new "modify"
213 modified << elt.to_xml_node
218 render :text => result.to_s, :content_type => "text/xml"
220 rescue ActiveRecord::RecordNotFound
221 render :nothing => true, :status => :not_found
222 rescue OSM::APIError => ex
223 render ex.render_opts
227 # query changesets by bounding box, time, user or open/closed status.
229 # create the conditions that the user asked for. some or all of
231 conditions = conditions_bbox(params['bbox'])
232 conditions = cond_merge conditions, conditions_user(params['user'])
233 conditions = cond_merge conditions, conditions_time(params['time'])
234 conditions = cond_merge conditions, conditions_open(params['open'])
236 # create the results document
237 results = OSM::API.new.get_xml_doc
239 # add all matching changesets to the XML results document
241 :conditions => conditions,
243 :order => 'created_at desc').each do |cs|
244 results.root << cs.to_xml_node
247 render :text => results.to_s, :content_type => "text/xml"
249 rescue ActiveRecord::RecordNotFound
250 render :nothing => true, :status => :not_found
251 rescue OSM::APIError => ex
252 render ex.render_opts
256 # updates a changeset's tags. none of the changeset's attributes are
257 # user-modifiable, so they will be ignored.
259 # changesets are not (yet?) versioned, so we don't have to deal with
260 # history tables here. changesets are locked to a single user, however.
262 # after succesful update, returns the XML of the changeset.
264 # request *must* be a PUT.
266 render :nothing => true, :status => :method_not_allowed
270 changeset = Changeset.find(params[:id])
271 new_changeset = Changeset.from_xml(request.raw_post)
273 unless new_changeset.nil?
274 check_changeset_consistency(changeset, @user)
275 changeset.update_from(new_changeset, @user)
276 render :text => changeset.to_xml, :mime_type => "text/xml"
279 render :nothing => true, :status => :bad_request
282 rescue ActiveRecord::RecordNotFound
283 render :nothing => true, :status => :not_found
284 rescue OSM::APIError => ex
285 render ex.render_opts
289 #------------------------------------------------------------
290 # utility functions below.
291 #------------------------------------------------------------
294 # merge two conditions
299 return [ a_str + " and " + b_str ] + a + b
308 # if a bounding box was specified then parse it and do some sanity
309 # checks. this is mostly the same as the map call, but without the
311 def conditions_bbox(bbox)
313 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
314 bbox = sanitise_boundaries(bbox.split(/,/))
315 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
316 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
317 return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
318 bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
325 # restrict changesets to those by a particular user
326 def conditions_user(user)
328 # user input checking, we don't have any UIDs < 1
329 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
331 u = User.find(user.to_i)
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 @user.nil? or @user.id != u.id
341 return ['user_id = ?', u.id]
348 # restrict changes to those during a particular time period
349 def conditions_time(time)
351 # if there is a range, i.e: comma separated, then the first is
352 # low, second is high - same as with bounding boxes.
353 if time.count(',') == 1
354 # check that we actually have 2 elements in the array
355 times = time.split(/,/)
356 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
358 from, to = times.collect { |t| DateTime.parse(t) }
359 return ['closed_at >= ? and created_at <= ?', from, to]
361 # if there is no comma, assume its a lower limit on time
362 return ['closed_at >= ?', DateTime.parse(time)]
367 # stupid DateTime seems to throw both of these for bad parsing, so
368 # we have to catch both and ensure the correct code path is taken.
369 rescue ArgumentError => ex
370 raise OSM::APIBadUserInput.new(ex.message.to_s)
371 rescue RuntimeError => ex
372 raise OSM::APIBadUserInput.new(ex.message.to_s)
376 # restrict changes to those which are open
377 def conditions_open(open)
378 return open.nil? ? nil : ['closed_at >= ?', DateTime.now]