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