]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/changesets_controller.rb
Prefer String#match? over butt ugly Regexp#match?
[rails.git] / app / controllers / api / changesets_controller.rb
1 # The ChangesetController is the RESTful interface to Changeset objects
2
3 module Api
4   class ChangesetsController < ApplicationController
5     layout "site"
6     require "xml/libxml"
7
8     skip_before_action :verify_authenticity_token
9     before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
10     before_action :api_deny_access_handler, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe, :expand_bbox]
11
12     authorize_resource
13
14     before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
15     before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
16     before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :subscribe, :unsubscribe]
17     before_action(:only => [:index, :feed]) { |c| c.check_database_readable(true) }
18     around_action :api_call_handle_error
19     around_action :api_call_timeout, :except => [:upload]
20
21     # Helper methods for checking consistency
22     include ConsistencyValidations
23
24     # Create a changeset from XML.
25     def create
26       assert_method :put
27
28       cs = Changeset.from_xml(request.raw_post, true)
29
30       # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
31       cs.user = current_user
32       cs.save_with_tags!
33
34       # Subscribe user to changeset comments
35       cs.subscribers << current_user
36
37       render :plain => cs.id.to_s
38     end
39
40     ##
41     # Return XML giving the basic info about the changeset. Does not
42     # return anything about the nodes, ways and relations in the changeset.
43     def show
44       changeset = Changeset.find(params[:id])
45
46       render :xml => changeset.to_xml(params[:include_discussion].presence).to_s
47     end
48
49     ##
50     # marks a changeset as closed. this may be called multiple times
51     # on the same changeset, so is idempotent.
52     def close
53       assert_method :put
54
55       changeset = Changeset.find(params[:id])
56       check_changeset_consistency(changeset, current_user)
57
58       # to close the changeset, we'll just set its closed_at time to
59       # now. this might not be enough if there are concurrency issues,
60       # but we'll have to wait and see.
61       changeset.set_closed_time_now
62
63       changeset.save!
64       head :ok
65     end
66
67     ##
68     # insert a (set of) points into a changeset bounding box. this can only
69     # increase the size of the bounding box. this is a hint that clients can
70     # set either before uploading a large number of changes, or changes that
71     # the client (but not the server) knows will affect areas further away.
72     def expand_bbox
73       # only allow POST requests, because although this method is
74       # idempotent, there is no "document" to PUT really...
75       assert_method :post
76
77       cs = Changeset.find(params[:id])
78       check_changeset_consistency(cs, current_user)
79
80       # keep an array of lons and lats
81       lon = []
82       lat = []
83
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, :options => XML::Parser::Options::NOERROR).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
90       end
91
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?
97
98       # collapse the arrays to minimum and maximum
99       cs.min_lon = lon.min
100       cs.min_lat = lat.min
101       cs.max_lon = lon.max
102       cs.max_lat = lat.max
103
104       # save the larger bounding box and return the changeset, which
105       # will include the bigger bounding box.
106       cs.save!
107       render :xml => cs.to_xml.to_s
108     end
109
110     ##
111     # Upload a diff in a single transaction.
112     #
113     # This means that each change within the diff must succeed, i.e: that
114     # each version number mentioned is still current. Otherwise the entire
115     # transaction *must* be rolled back.
116     #
117     # Furthermore, each element in the diff can only reference the current
118     # changeset.
119     #
120     # Returns: a diffResult document, as described in
121     # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
122     def upload
123       # only allow POST requests, as the upload method is most definitely
124       # not idempotent, as several uploads with placeholder IDs will have
125       # different side-effects.
126       # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
127       assert_method :post
128
129       changeset = Changeset.find(params[:id])
130       check_changeset_consistency(changeset, current_user)
131
132       diff_reader = DiffReader.new(request.raw_post, changeset)
133       Changeset.transaction do
134         result = diff_reader.commit
135         render :xml => result.to_s
136       end
137     end
138
139     ##
140     # download the changeset as an osmChange document.
141     #
142     # to make it easier to revert diffs it would be better if the osmChange
143     # format were reversible, i.e: contained both old and new versions of
144     # modified elements. but it doesn't at the moment...
145     #
146     # this method cannot order the database changes fully (i.e: timestamp and
147     # version number may be too coarse) so the resulting diff may not apply
148     # to a different database. however since changesets are not atomic this
149     # behaviour cannot be guaranteed anyway and is the result of a design
150     # choice.
151     def download
152       changeset = Changeset.find(params[:id])
153
154       # get all the elements in the changeset which haven't been redacted
155       # and stick them in a big array.
156       elements = [changeset.old_nodes.unredacted,
157                   changeset.old_ways.unredacted,
158                   changeset.old_relations.unredacted].flatten
159
160       # sort the elements by timestamp and version number, as this is the
161       # almost sensible ordering available. this would be much nicer if
162       # global (SVN-style) versioning were used - then that would be
163       # unambiguous.
164       elements.sort! do |a, b|
165         if a.timestamp == b.timestamp
166           a.version <=> b.version
167         else
168           a.timestamp <=> b.timestamp
169         end
170       end
171
172       # create changeset and user caches
173       changeset_cache = {}
174       user_display_name_cache = {}
175
176       # create an osmChange document for the output
177       result = OSM::API.new.get_xml_doc
178       result.root.name = "osmChange"
179
180       # generate an output element for each operation. note: we avoid looking
181       # at the history because it is simpler - but it would be more correct to
182       # check these assertions.
183       elements.each do |elt|
184         result.root <<
185           if elt.version == 1
186             # first version, so it must be newly-created.
187             created = XML::Node.new "create"
188             created << elt.to_xml_node(changeset_cache, user_display_name_cache)
189           elsif elt.visible
190             # must be a modify
191             modified = XML::Node.new "modify"
192             modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
193           else
194             # if the element isn't visible then it must have been deleted
195             deleted = XML::Node.new "delete"
196             deleted << elt.to_xml_node(changeset_cache, user_display_name_cache)
197           end
198       end
199
200       render :xml => result.to_s
201     end
202
203     ##
204     # query changesets by bounding box, time, user or open/closed status.
205     def query
206       # find any bounding box
207       bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
208
209       # create the conditions that the user asked for. some or all of
210       # these may be nil.
211       changesets = Changeset.all
212       changesets = conditions_bbox(changesets, bbox)
213       changesets = conditions_user(changesets, params["user"], params["display_name"])
214       changesets = conditions_time(changesets, params["time"])
215       changesets = conditions_open(changesets, params["open"])
216       changesets = conditions_closed(changesets, params["closed"])
217       changesets = conditions_ids(changesets, params["changesets"])
218
219       # sort and limit the changesets
220       changesets = changesets.order("created_at DESC").limit(100)
221
222       # preload users, tags and comments
223       changesets = changesets.preload(:user, :changeset_tags, :comments)
224
225       # create the results document
226       results = OSM::API.new.get_xml_doc
227
228       # add all matching changesets to the XML results document
229       changesets.order("created_at DESC").limit(100).each do |cs|
230         results.root << cs.to_xml_node
231       end
232
233       render :xml => results.to_s
234     end
235
236     ##
237     # updates a changeset's tags. none of the changeset's attributes are
238     # user-modifiable, so they will be ignored.
239     #
240     # changesets are not (yet?) versioned, so we don't have to deal with
241     # history tables here. changesets are locked to a single user, however.
242     #
243     # after succesful update, returns the XML of the changeset.
244     def update
245       # request *must* be a PUT.
246       assert_method :put
247
248       changeset = Changeset.find(params[:id])
249       new_changeset = Changeset.from_xml(request.raw_post)
250
251       check_changeset_consistency(changeset, current_user)
252       changeset.update_from(new_changeset, current_user)
253       render :xml => changeset.to_xml.to_s
254     end
255
256     ##
257     # Adds a subscriber to the changeset
258     def subscribe
259       # Check the arguments are sane
260       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
261
262       # Extract the arguments
263       id = params[:id].to_i
264
265       # Find the changeset and check it is valid
266       changeset = Changeset.find(id)
267       raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribers.exists?(current_user.id)
268
269       # Add the subscriber
270       changeset.subscribers << current_user
271
272       # Return a copy of the updated changeset
273       render :xml => changeset.to_xml.to_s
274     end
275
276     ##
277     # Removes a subscriber from the changeset
278     def unsubscribe
279       # Check the arguments are sane
280       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
281
282       # Extract the arguments
283       id = params[:id].to_i
284
285       # Find the changeset and check it is valid
286       changeset = Changeset.find(id)
287       raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribers.exists?(current_user.id)
288
289       # Remove the subscriber
290       changeset.subscribers.delete(current_user)
291
292       # Return a copy of the updated changeset
293       render :xml => changeset.to_xml.to_s
294     end
295
296     private
297
298     #------------------------------------------------------------
299     # utility functions below.
300     #------------------------------------------------------------
301
302     ##
303     # if a bounding box was specified do some sanity checks.
304     # restrict changesets to those enclosed by a bounding box
305     # we need to return both the changesets and the bounding box
306     def conditions_bbox(changesets, bbox)
307       if bbox
308         bbox.check_boundaries
309         bbox = bbox.to_scaled
310
311         changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
312                          bbox.max_lon.to_i, bbox.min_lon.to_i,
313                          bbox.max_lat.to_i, bbox.min_lat.to_i)
314       else
315         changesets
316       end
317     end
318
319     ##
320     # restrict changesets to those by a particular user
321     def conditions_user(changesets, user, name)
322       if user.nil? && name.nil?
323         changesets
324       else
325         # shouldn't provide both name and UID
326         raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
327
328         # use either the name or the UID to find the user which we're selecting on.
329         u = if name.nil?
330               # user input checking, we don't have any UIDs < 1
331               raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
332
333               u = User.find(user.to_i)
334             else
335               u = User.find_by(:display_name => name)
336             end
337
338         # make sure we found a user
339         raise OSM::APINotFoundError if u.nil?
340
341         # should be able to get changesets of public users only, or
342         # our own changesets regardless of public-ness.
343         unless u.data_public?
344           # get optional user auth stuff so that users can see their own
345           # changesets if they're non-public
346           setup_user_auth
347
348           raise OSM::APINotFoundError if current_user.nil? || current_user != u
349         end
350
351         changesets.where(:user_id => u.id)
352       end
353     end
354
355     ##
356     # restrict changes to those closed during a particular time period
357     def conditions_time(changesets, time)
358       if time.nil?
359         changesets
360       elsif time.count(",") == 1
361         # if there is a range, i.e: comma separated, then the first is
362         # low, second is high - same as with bounding boxes.
363
364         # check that we actually have 2 elements in the array
365         times = time.split(/,/)
366         raise OSM::APIBadUserInput, "bad time range" if times.size != 2
367
368         from, to = times.collect { |t| Time.parse(t) }
369         changesets.where("closed_at >= ? and created_at <= ?", from, to)
370       else
371         # if there is no comma, assume its a lower limit on time
372         changesets.where("closed_at >= ?", Time.parse(time))
373       end
374       # stupid Time seems to throw both of these for bad parsing, so
375       # we have to catch both and ensure the correct code path is taken.
376     rescue ArgumentError => ex
377       raise OSM::APIBadUserInput, ex.message.to_s
378     rescue RuntimeError => ex
379       raise OSM::APIBadUserInput, ex.message.to_s
380     end
381
382     ##
383     # return changesets which are open (haven't been closed yet)
384     # we do this by seeing if the 'closed at' time is in the future. Also if we've
385     # hit the maximum number of changes then it counts as no longer open.
386     # if parameter 'open' is nill then open and closed changesets are returned
387     def conditions_open(changesets, open)
388       if open.nil?
389         changesets
390       else
391         changesets.where("closed_at >= ? and num_changes <= ?",
392                          Time.now.getutc, Changeset::MAX_ELEMENTS)
393       end
394     end
395
396     ##
397     # query changesets which are closed
398     # ('closed at' time has passed or changes limit is hit)
399     def conditions_closed(changesets, closed)
400       if closed.nil?
401         changesets
402       else
403         changesets.where("closed_at < ? or num_changes > ?",
404                          Time.now.getutc, Changeset::MAX_ELEMENTS)
405       end
406     end
407
408     ##
409     # query changesets by a list of ids
410     # (either specified as array or comma-separated string)
411     def conditions_ids(changesets, ids)
412       if ids.nil?
413         changesets
414       elsif ids.empty?
415         raise OSM::APIBadUserInput, "No changesets were given to search for"
416       else
417         ids = ids.split(",").collect(&:to_i)
418         changesets.where(:id => ids)
419       end
420     end
421   end
422 end