]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/changesets_controller.rb
Remove non functioning changeset_cache, user_display_name_cache
[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     layout "site"
6     require "xml/libxml"
7
8     before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
9
10     authorize_resource
11
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]
17
18     # Helper methods for checking consistency
19     include ConsistencyValidations
20
21     # Create a changeset from XML.
22     def create
23       assert_method :put
24
25       cs = Changeset.from_xml(request.raw_post, true)
26
27       # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
28       cs.user = current_user
29       cs.save_with_tags!
30
31       # Subscribe user to changeset comments
32       cs.subscribers << current_user
33
34       render :plain => cs.id.to_s
35     end
36
37     ##
38     # Return XML giving the basic info about the changeset. Does not
39     # return anything about the nodes, ways and relations in the changeset.
40     def show
41       @changeset = Changeset.find(params[:id])
42       @include_discussion = params[:include_discussion].presence
43       render "changeset"
44     end
45
46     ##
47     # marks a changeset as closed. this may be called multiple times
48     # on the same changeset, so is idempotent.
49     def close
50       assert_method :put
51
52       changeset = Changeset.find(params[:id])
53       check_changeset_consistency(changeset, current_user)
54
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
59
60       changeset.save!
61       head :ok
62     end
63
64     ##
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.
69     def expand_bbox
70       # only allow POST requests, because although this method is
71       # idempotent, there is no "document" to PUT really...
72       assert_method :post
73
74       cs = Changeset.find(params[:id])
75       check_changeset_consistency(cs, current_user)
76
77       # keep an array of lons and lats
78       lon = []
79       lat = []
80
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
87       end
88
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?
94
95       # collapse the arrays to minimum and maximum
96       cs.min_lon = lon.min
97       cs.min_lat = lat.min
98       cs.max_lon = lon.max
99       cs.max_lat = lat.max
100
101       # save the larger bounding box and return the changeset, which
102       # will include the bigger bounding box.
103       cs.save!
104       @changeset = cs
105       render "changeset"
106     end
107
108     ##
109     # Upload a diff in a single transaction.
110     #
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.
114     #
115     # Furthermore, each element in the diff can only reference the current
116     # changeset.
117     #
118     # Returns: a diffResult document, as described in
119     # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
120     def upload
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
125       assert_method :post
126
127       changeset = Changeset.find(params[:id])
128       check_changeset_consistency(changeset, current_user)
129
130       diff_reader = DiffReader.new(request.raw_post, changeset)
131       Changeset.transaction do
132         result = diff_reader.commit
133         render :xml => result.to_s
134       end
135     end
136
137     ##
138     # download the changeset as an osmChange document.
139     #
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...
143     #
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
148     # choice.
149     def download
150       changeset = Changeset.find(params[:id])
151
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
157
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
161       # unambiguous.
162       elements.sort! do |a, b|
163         if a.timestamp == b.timestamp
164           a.version <=> b.version
165         else
166           a.timestamp <=> b.timestamp
167         end
168       end
169
170       # create changeset and user caches
171       changeset_cache = {}
172       user_display_name_cache = {}
173
174       # create an osmChange document for the output
175       result = OSM::API.new.get_xml_doc
176       result.root.name = "osmChange"
177
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|
182         result.root <<
183           if elt.version == 1
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)
187           elsif elt.visible
188             # must be a modify
189             modified = XML::Node.new "modify"
190             modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
191           else
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)
195           end
196       end
197
198       render :xml => result.to_s
199     end
200
201     ##
202     # query changesets by bounding box, time, user or open/closed status.
203     def query
204       # find any bounding box
205       bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
206
207       # create the conditions that the user asked for. some or all of
208       # these may be nil.
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"])
216
217       # sort and limit the changesets
218       changesets = changesets.order("created_at DESC").limit(100)
219
220       # preload users, tags and comments, and render result
221       @changesets = changesets.preload(:user, :changeset_tags, :comments)
222       render "changesets"
223     end
224
225     ##
226     # updates a changeset's tags. none of the changeset's attributes are
227     # user-modifiable, so they will be ignored.
228     #
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.
231     #
232     # after succesful update, returns the XML of the changeset.
233     def update
234       # request *must* be a PUT.
235       assert_method :put
236
237       @changeset = Changeset.find(params[:id])
238       new_changeset = Changeset.from_xml(request.raw_post)
239
240       check_changeset_consistency(@changeset, current_user)
241       @changeset.update_from(new_changeset, current_user)
242       render "changeset"
243     end
244
245     ##
246     # Adds a subscriber to the changeset
247     def subscribe
248       # Check the arguments are sane
249       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
250
251       # Extract the arguments
252       id = params[:id].to_i
253
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)
257
258       # Add the subscriber
259       changeset.subscribers << current_user
260
261       # Return a copy of the updated changeset
262       @changeset = changeset
263       render "changeset"
264     end
265
266     ##
267     # Removes a subscriber from the changeset
268     def unsubscribe
269       # Check the arguments are sane
270       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
271
272       # Extract the arguments
273       id = params[:id].to_i
274
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)
278
279       # Remove the subscriber
280       changeset.subscribers.delete(current_user)
281
282       # Return a copy of the updated changeset
283       @changeset = changeset
284       render "changeset"
285     end
286
287     private
288
289     #------------------------------------------------------------
290     # utility functions below.
291     #------------------------------------------------------------
292
293     ##
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)
298       if bbox
299         bbox.check_boundaries
300         bbox = bbox.to_scaled
301
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)
305       else
306         changesets
307       end
308     end
309
310     ##
311     # restrict changesets to those by a particular user
312     def conditions_user(changesets, user, name)
313       if user.nil? && name.nil?
314         changesets
315       else
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
318
319         # use either the name or the UID to find the user which we're selecting on.
320         u = if name.nil?
321               # user input checking, we don't have any UIDs < 1
322               raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
323
324               u = User.find(user.to_i)
325             else
326               u = User.find_by(:display_name => name)
327             end
328
329         # make sure we found a user
330         raise OSM::APINotFoundError if u.nil?
331
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
337           setup_user_auth
338
339           raise OSM::APINotFoundError if current_user.nil? || current_user != u
340         end
341
342         changesets.where(:user_id => u.id)
343       end
344     end
345
346     ##
347     # restrict changes to those closed during a particular time period
348     def conditions_time(changesets, time)
349       if time.nil?
350         changesets
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.
354
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
358
359         from, to = times.collect { |t| Time.parse(t) }
360         changesets.where("closed_at >= ? and created_at <= ?", from, to)
361       else
362         # if there is no comma, assume its a lower limit on time
363         changesets.where("closed_at >= ?", Time.parse(time))
364       end
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 => ex
368       raise OSM::APIBadUserInput, ex.message.to_s
369     rescue RuntimeError => ex
370       raise OSM::APIBadUserInput, ex.message.to_s
371     end
372
373     ##
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)
379       if open.nil?
380         changesets
381       else
382         changesets.where("closed_at >= ? and num_changes <= ?",
383                          Time.now.getutc, Changeset::MAX_ELEMENTS)
384       end
385     end
386
387     ##
388     # query changesets which are closed
389     # ('closed at' time has passed or changes limit is hit)
390     def conditions_closed(changesets, closed)
391       if closed.nil?
392         changesets
393       else
394         changesets.where("closed_at < ? or num_changes > ?",
395                          Time.now.getutc, Changeset::MAX_ELEMENTS)
396       end
397     end
398
399     ##
400     # query changesets by a list of ids
401     # (either specified as array or comma-separated string)
402     def conditions_ids(changesets, ids)
403       if ids.nil?
404         changesets
405       elsif ids.empty?
406         raise OSM::APIBadUserInput, "No changesets were given to search for"
407       else
408         ids = ids.split(",").collect(&:to_i)
409         changesets.where(:id => ids)
410       end
411     end
412   end
413 end