]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/changesets_controller.rb
Merge remote-tracking branch 'upstream/pull/2696'
[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 < ApiController
5     require "xml/libxml"
6
7     before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
8
9     authorize_resource
10
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]
16
17     # Helper methods for checking consistency
18     include ConsistencyValidations
19
20     # Create a changeset from XML.
21     def create
22       assert_method :put
23
24       cs = Changeset.from_xml(request.raw_post, true)
25
26       # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
27       cs.user = current_user
28       cs.save_with_tags!
29
30       # Subscribe user to changeset comments
31       cs.subscribers << current_user
32
33       render :plain => cs.id.to_s
34     end
35
36     ##
37     # Return XML giving the basic info about the changeset. Does not
38     # return anything about the nodes, ways and relations in the changeset.
39     def show
40       @changeset = Changeset.find(params[:id])
41       @include_discussion = params[:include_discussion].presence
42       render "changeset"
43     end
44
45     ##
46     # marks a changeset as closed. this may be called multiple times
47     # on the same changeset, so is idempotent.
48     def close
49       assert_method :put
50
51       changeset = Changeset.find(params[:id])
52       check_changeset_consistency(changeset, current_user)
53
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
58
59       changeset.save!
60       head :ok
61     end
62
63     ##
64     # Upload a diff in a single transaction.
65     #
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.
69     #
70     # Furthermore, each element in the diff can only reference the current
71     # changeset.
72     #
73     # Returns: a diffResult document, as described in
74     # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
75     def upload
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
80       assert_method :post
81
82       changeset = Changeset.find(params[:id])
83       check_changeset_consistency(changeset, current_user)
84
85       diff_reader = DiffReader.new(request.raw_post, changeset)
86       Changeset.transaction do
87         result = diff_reader.commit
88         render :xml => result.to_s
89       end
90     end
91
92     ##
93     # download the changeset as an osmChange document.
94     #
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...
98     #
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
103     # choice.
104     def download
105       changeset = Changeset.find(params[:id])
106
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
112
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
116       # unambiguous.
117       elements.sort! do |a, b|
118         if a.timestamp == b.timestamp
119           a.version <=> b.version
120         else
121           a.timestamp <=> b.timestamp
122         end
123       end
124
125       # create changeset and user caches
126       changeset_cache = {}
127       user_display_name_cache = {}
128
129       # create an osmChange document for the output
130       result = OSM::API.new.get_xml_doc
131       result.root.name = "osmChange"
132
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|
137         result.root <<
138           if elt.version == 1
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)
142           elsif elt.visible
143             # must be a modify
144             modified = XML::Node.new "modify"
145             modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
146           else
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)
150           end
151       end
152
153       render :xml => result.to_s
154     end
155
156     ##
157     # query changesets by bounding box, time, user or open/closed status.
158     def query
159       # find any bounding box
160       bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
161
162       # create the conditions that the user asked for. some or all of
163       # these may be nil.
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"])
171
172       # sort and limit the changesets
173       changesets = changesets.order("created_at DESC").limit(100)
174
175       # preload users, tags and comments, and render result
176       @changesets = changesets.preload(:user, :changeset_tags, :comments)
177       render "changesets"
178     end
179
180     ##
181     # updates a changeset's tags. none of the changeset's attributes are
182     # user-modifiable, so they will be ignored.
183     #
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.
186     #
187     # after succesful update, returns the XML of the changeset.
188     def update
189       # request *must* be a PUT.
190       assert_method :put
191
192       @changeset = Changeset.find(params[:id])
193       new_changeset = Changeset.from_xml(request.raw_post)
194
195       check_changeset_consistency(@changeset, current_user)
196       @changeset.update_from(new_changeset, current_user)
197       render "changeset"
198     end
199
200     ##
201     # Adds a subscriber to the changeset
202     def subscribe
203       # Check the arguments are sane
204       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
205
206       # Extract the arguments
207       id = params[:id].to_i
208
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)
212
213       # Add the subscriber
214       changeset.subscribers << current_user
215
216       # Return a copy of the updated changeset
217       @changeset = changeset
218       render "changeset"
219     end
220
221     ##
222     # Removes a subscriber from the changeset
223     def unsubscribe
224       # Check the arguments are sane
225       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
226
227       # Extract the arguments
228       id = params[:id].to_i
229
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)
233
234       # Remove the subscriber
235       changeset.subscribers.delete(current_user)
236
237       # Return a copy of the updated changeset
238       @changeset = changeset
239       render "changeset"
240     end
241
242     private
243
244     #------------------------------------------------------------
245     # utility functions below.
246     #------------------------------------------------------------
247
248     ##
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)
253       if bbox
254         bbox.check_boundaries
255         bbox = bbox.to_scaled
256
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)
260       else
261         changesets
262       end
263     end
264
265     ##
266     # restrict changesets to those by a particular user
267     def conditions_user(changesets, user, name)
268       if user.nil? && name.nil?
269         changesets
270       else
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
273
274         # use either the name or the UID to find the user which we're selecting on.
275         u = if name.nil?
276               # user input checking, we don't have any UIDs < 1
277               raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
278
279               u = User.find(user.to_i)
280             else
281               u = User.find_by(:display_name => name)
282             end
283
284         # make sure we found a user
285         raise OSM::APINotFoundError if u.nil?
286
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
292           setup_user_auth
293
294           raise OSM::APINotFoundError if current_user.nil? || current_user != u
295         end
296
297         changesets.where(:user_id => u.id)
298       end
299     end
300
301     ##
302     # restrict changes to those closed during a particular time period
303     def conditions_time(changesets, time)
304       if time.nil?
305         changesets
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.
309
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
313
314         from, to = times.collect { |t| Time.parse(t) }
315         changesets.where("closed_at >= ? and created_at <= ?", from, to)
316       else
317         # if there is no comma, assume its a lower limit on time
318         changesets.where("closed_at >= ?", Time.parse(time))
319       end
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 => e
323       raise OSM::APIBadUserInput, e.message.to_s
324     rescue RuntimeError => e
325       raise OSM::APIBadUserInput, e.message.to_s
326     end
327
328     ##
329     # return changesets which are open (haven't been closed yet)
330     # we do this by seeing if the 'closed at' time is in the future. Also if we've
331     # hit the maximum number of changes then it counts as no longer open.
332     # if parameter 'open' is nill then open and closed changesets are returned
333     def conditions_open(changesets, open)
334       if open.nil?
335         changesets
336       else
337         changesets.where("closed_at >= ? and num_changes <= ?",
338                          Time.now.getutc, Changeset::MAX_ELEMENTS)
339       end
340     end
341
342     ##
343     # query changesets which are closed
344     # ('closed at' time has passed or changes limit is hit)
345     def conditions_closed(changesets, closed)
346       if closed.nil?
347         changesets
348       else
349         changesets.where("closed_at < ? or num_changes > ?",
350                          Time.now.getutc, Changeset::MAX_ELEMENTS)
351       end
352     end
353
354     ##
355     # query changesets by a list of ids
356     # (either specified as array or comma-separated string)
357     def conditions_ids(changesets, ids)
358       if ids.nil?
359         changesets
360       elsif ids.empty?
361         raise OSM::APIBadUserInput, "No changesets were given to search for"
362       else
363         ids = ids.split(",").collect(&:to_i)
364         changesets.where(:id => ids)
365       end
366     end
367   end
368 end