]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/notes_controller.rb
Add bbox parameter to notes search api
[rails.git] / app / controllers / api / notes_controller.rb
1 module Api
2   class NotesController < ApiController
3     before_action :check_api_readable
4     before_action :check_api_writable, :only => [:create, :comment, :close, :reopen, :destroy]
5     before_action :setup_user_auth, :only => [:create, :show]
6     before_action :authorize, :only => [:close, :reopen, :destroy, :comment]
7
8     authorize_resource
9
10     before_action :set_locale
11     around_action :api_call_handle_error, :api_call_timeout
12     before_action :set_request_formats, :except => [:feed]
13
14     ##
15     # Return a list of notes in a given area
16     def index
17       # Figure out the bbox - we prefer a bbox argument but also
18       # support the old, deprecated, method with four arguments
19       if params[:bbox]
20         bbox = BoundingBox.from_bbox_params(params)
21       else
22         raise OSM::APIBadUserInput, "No l was given" unless params[:l]
23         raise OSM::APIBadUserInput, "No r was given" unless params[:r]
24         raise OSM::APIBadUserInput, "No b was given" unless params[:b]
25         raise OSM::APIBadUserInput, "No t was given" unless params[:t]
26
27         bbox = BoundingBox.from_lrbt_params(params)
28       end
29
30       # Get any conditions that need to be applied
31       notes = closed_condition(Note.all)
32
33       # Check that the boundaries are valid
34       bbox.check_boundaries
35
36       # Check the the bounding box is not too big
37       bbox.check_size(Settings.max_note_request_area)
38       @min_lon = bbox.min_lon
39       @min_lat = bbox.min_lat
40       @max_lon = bbox.max_lon
41       @max_lat = bbox.max_lat
42
43       # Find the notes we want to return
44       @notes = notes.bbox(bbox).order("updated_at DESC").limit(result_limit).preload(:comments)
45
46       # Render the result
47       respond_to do |format|
48         format.rss
49         format.xml
50         format.json
51         format.gpx
52       end
53     end
54
55     ##
56     # Read a note
57     def show
58       # Check the arguments are sane
59       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
60
61       # Find the note and check it is valid
62       @note = Note.find(params[:id])
63       raise OSM::APINotFoundError unless @note
64       raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || current_user&.moderator?
65
66       # Render the result
67       respond_to do |format|
68         format.xml
69         format.rss
70         format.json
71         format.gpx
72       end
73     end
74
75     ##
76     # Create a new note
77     def create
78       # Check the ACLs
79       raise OSM::APIAccessDenied if current_user.nil? && Acl.no_note_comment(request.remote_ip)
80
81       # Check the arguments are sane
82       raise OSM::APIBadUserInput, "No lat was given" unless params[:lat]
83       raise OSM::APIBadUserInput, "No lon was given" unless params[:lon]
84       raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
85
86       # Extract the arguments
87       lon = OSM.parse_float(params[:lon], OSM::APIBadUserInput, "lon was not a number")
88       lat = OSM.parse_float(params[:lat], OSM::APIBadUserInput, "lat was not a number")
89       comment = params[:text]
90
91       # Include in a transaction to ensure that there is always a note_comment for every note
92       Note.transaction do
93         # Create the note
94         @note = Note.create(:lat => lat, :lon => lon)
95         raise OSM::APIBadUserInput, "The note is outside this world" unless @note.in_world?
96
97         # Save the note
98         @note.save!
99
100         # Add a comment to the note
101         add_comment(@note, comment, "opened")
102       end
103
104       # Return a copy of the new note
105       respond_to do |format|
106         format.xml { render :action => :show }
107         format.json { render :action => :show }
108       end
109     end
110
111     ##
112     # Delete (hide) a note
113     def destroy
114       # Check the arguments are sane
115       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
116
117       # Extract the arguments
118       id = params[:id].to_i
119       comment = params[:text]
120
121       # Find the note and check it is valid
122       @note = Note.find(id)
123       raise OSM::APINotFoundError unless @note
124       raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
125
126       # Mark the note as hidden
127       Note.transaction do
128         @note.status = "hidden"
129         @note.save
130
131         add_comment(@note, comment, "hidden", :notify => false)
132       end
133
134       # Return a copy of the updated note
135       respond_to do |format|
136         format.xml { render :action => :show }
137         format.json { render :action => :show }
138       end
139     end
140
141     ##
142     # Add a comment to an existing note
143     def comment
144       # Check the ACLs
145       raise OSM::APIAccessDenied if current_user.nil? && Acl.no_note_comment(request.remote_ip)
146
147       # Check the arguments are sane
148       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
149       raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
150
151       # Extract the arguments
152       id = params[:id].to_i
153       comment = params[:text]
154
155       # Find the note and check it is valid
156       @note = Note.find(id)
157       raise OSM::APINotFoundError unless @note
158       raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
159       raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
160
161       # Add a comment to the note
162       Note.transaction do
163         add_comment(@note, comment, "commented")
164       end
165
166       # Return a copy of the updated note
167       respond_to do |format|
168         format.xml { render :action => :show }
169         format.json { render :action => :show }
170       end
171     end
172
173     ##
174     # Close a note
175     def close
176       # Check the arguments are sane
177       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
178
179       # Extract the arguments
180       id = params[:id].to_i
181       comment = params[:text]
182
183       # Find the note and check it is valid
184       @note = Note.find_by(:id => id)
185       raise OSM::APINotFoundError unless @note
186       raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
187       raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
188
189       # Close the note and add a comment
190       Note.transaction do
191         @note.close
192
193         add_comment(@note, comment, "closed")
194       end
195
196       # Return a copy of the updated note
197       respond_to do |format|
198         format.xml { render :action => :show }
199         format.json { render :action => :show }
200       end
201     end
202
203     ##
204     # Reopen a note
205     def reopen
206       # Check the arguments are sane
207       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
208
209       # Extract the arguments
210       id = params[:id].to_i
211       comment = params[:text]
212
213       # Find the note and check it is valid
214       @note = Note.find_by(:id => id)
215       raise OSM::APINotFoundError unless @note
216       raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || current_user.moderator?
217       raise OSM::APINoteAlreadyOpenError, @note unless @note.closed? || !@note.visible?
218
219       # Reopen the note and add a comment
220       Note.transaction do
221         @note.reopen
222
223         add_comment(@note, comment, "reopened")
224       end
225
226       # Return a copy of the updated note
227       respond_to do |format|
228         format.xml { render :action => :show }
229         format.json { render :action => :show }
230       end
231     end
232
233     ##
234     # Get a feed of recent notes and comments
235     def feed
236       # Get any conditions that need to be applied
237       notes = closed_condition(Note.all)
238       notes = bbox_condition(notes)
239
240       # Find the comments we want to return
241       @comments = NoteComment.where(:note => notes)
242                              .order(:created_at => :desc).limit(result_limit)
243                              .preload(:author, :note => { :comments => :author })
244
245       # Render the result
246       respond_to do |format|
247         format.rss
248       end
249     end
250
251     ##
252     # Return a list of notes matching a given string
253     def search
254       # Get the initial set of notes
255       @notes = closed_condition(Note.all)
256       @notes = bbox_condition(@notes)
257
258       # Add any user filter
259       if params[:display_name] || params[:user]
260         if params[:display_name]
261           @user = User.find_by(:display_name => params[:display_name])
262
263           raise OSM::APIBadUserInput, "User #{params[:display_name]} not known" unless @user
264         else
265           @user = User.find_by(:id => params[:user])
266
267           raise OSM::APIBadUserInput, "User #{params[:user]} not known" unless @user
268         end
269
270         @notes = @notes.joins(:comments).where(:note_comments => { :author_id => @user })
271       end
272
273       # Add any text filter
274       @notes = @notes.joins(:comments).where("to_tsvector('english', note_comments.body) @@ plainto_tsquery('english', ?)", params[:q]) if params[:q]
275
276       # Add any date filter
277       if params[:from]
278         begin
279           from = Time.parse(params[:from]).utc
280         rescue ArgumentError
281           raise OSM::APIBadUserInput, "Date #{params[:from]} is in a wrong format"
282         end
283
284         begin
285           to = if params[:to]
286                  Time.parse(params[:to]).utc
287                else
288                  Time.now.utc
289                end
290         rescue ArgumentError
291           raise OSM::APIBadUserInput, "Date #{params[:to]} is in a wrong format"
292         end
293
294         @notes = if params[:sort] == "updated_at"
295                    @notes.where(:updated_at => from..to)
296                  else
297                    @notes.where(:created_at => from..to)
298                  end
299       end
300
301       # Choose the sort order
302       @notes = if params[:sort] == "created_at"
303                  if params[:order] == "oldest"
304                    @notes.order("created_at ASC")
305                  else
306                    @notes.order("created_at DESC")
307                  end
308                else
309                  if params[:order] == "oldest"
310                    @notes.order("updated_at ASC")
311                  else
312                    @notes.order("updated_at DESC")
313                  end
314                end
315
316       # Find the notes we want to return
317       @notes = @notes.distinct.limit(result_limit).preload(:comments)
318
319       # Render the result
320       respond_to do |format|
321         format.rss { render :action => :index }
322         format.xml { render :action => :index }
323         format.json { render :action => :index }
324         format.gpx { render :action => :index }
325       end
326     end
327
328     private
329
330     #------------------------------------------------------------
331     # utility functions below.
332     #------------------------------------------------------------
333
334     ##
335     # Get the maximum number of results to return
336     def result_limit
337       if params[:limit]
338         if params[:limit].to_i.positive? && params[:limit].to_i <= Settings.max_note_query_limit
339           params[:limit].to_i
340         else
341           raise OSM::APIBadUserInput, "Note limit must be between 1 and #{Settings.max_note_query_limit}"
342         end
343       else
344         Settings.default_note_query_limit
345       end
346     end
347
348     ##
349     # Generate a condition to choose which notes we want based
350     # on their status and the user's request parameters
351     def closed_condition(notes)
352       closed_since = if params[:closed]
353                        params[:closed].to_i.days
354                      else
355                        Note::DEFAULT_FRESHLY_CLOSED_LIMIT
356                      end
357
358       if closed_since.negative?
359         notes.where.not(:status => "hidden")
360       elsif closed_since.positive?
361         notes.where(:status => "open")
362              .or(notes.where(:status => "closed")
363                       .where(notes.arel_table[:closed_at].gt(Time.now.utc - closed_since)))
364       else
365         notes.where(:status => "open")
366       end
367     end
368
369     ##
370     # Generate a condition to choose which notes we want based
371     # on the user's bounding box request parameters
372     def bbox_condition(notes)
373       if params[:bbox]
374         bbox = BoundingBox.from_bbox_params(params)
375
376         bbox.check_boundaries
377         bbox.check_size(Settings.max_note_request_area)
378
379         @min_lon = bbox.min_lon
380         @min_lat = bbox.min_lat
381         @max_lon = bbox.max_lon
382         @max_lat = bbox.max_lat
383
384         notes.bbox(bbox)
385       else
386         notes
387       end
388     end
389
390     ##
391     # Add a comment to a note
392     def add_comment(note, text, event, notify: true)
393       attributes = { :visible => true, :event => event, :body => text }
394
395       if current_user
396         attributes[:author_id] = current_user.id
397       else
398         attributes[:author_ip] = request.remote_ip
399       end
400
401       comment = note.comments.create!(attributes)
402
403       note.comments.map(&:author).uniq.each do |user|
404         UserMailer.note_comment_notification(comment, user).deliver_later if notify && user && user != current_user && user.visible?
405       end
406     end
407   end
408 end