]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/notes_controller.rb
Enable the ActionOrder cop for remaining controllers
[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
239       # Process any bbox
240       if params[:bbox]
241         bbox = BoundingBox.from_bbox_params(params)
242
243         bbox.check_boundaries
244         bbox.check_size(Settings.max_note_request_area)
245
246         notes = notes.bbox(bbox)
247         @min_lon = bbox.min_lon
248         @min_lat = bbox.min_lat
249         @max_lon = bbox.max_lon
250         @max_lat = bbox.max_lat
251       end
252
253       # Find the comments we want to return
254       @comments = NoteComment.where(:note_id => notes).order("created_at DESC").limit(result_limit).preload(:note)
255
256       # Render the result
257       respond_to do |format|
258         format.rss
259       end
260     end
261
262     ##
263     # Return a list of notes matching a given string
264     def search
265       # Get the initial set of notes
266       @notes = closed_condition(Note.all)
267
268       # Add any user filter
269       if params[:display_name] || params[:user]
270         if params[:display_name]
271           @user = User.find_by(:display_name => params[:display_name])
272
273           raise OSM::APIBadUserInput, "User #{params[:display_name]} not known" unless @user
274         else
275           @user = User.find_by(:id => params[:user])
276
277           raise OSM::APIBadUserInput, "User #{params[:user]} not known" unless @user
278         end
279
280         @notes = @notes.joins(:comments).where(:note_comments => { :author_id => @user })
281       end
282
283       # Add any text filter
284       @notes = @notes.joins(:comments).where("to_tsvector('english', note_comments.body) @@ plainto_tsquery('english', ?)", params[:q]) if params[:q]
285
286       # Add any date filter
287       if params[:from]
288         begin
289           from = Time.parse(params[:from]).utc
290         rescue ArgumentError
291           raise OSM::APIBadUserInput, "Date #{params[:from]} is in a wrong format"
292         end
293
294         begin
295           to = if params[:to]
296                  Time.parse(params[:to]).utc
297                else
298                  Time.now.utc
299                end
300         rescue ArgumentError
301           raise OSM::APIBadUserInput, "Date #{params[:to]} is in a wrong format"
302         end
303
304         @notes = if params[:sort] == "updated_at"
305                    @notes.where(:updated_at => from..to)
306                  else
307                    @notes.where(:created_at => from..to)
308                  end
309       end
310
311       # Choose the sort order
312       @notes = if params[:sort] == "created_at"
313                  if params[:order] == "oldest"
314                    @notes.order("created_at ASC")
315                  else
316                    @notes.order("created_at DESC")
317                  end
318                else
319                  if params[:order] == "oldest"
320                    @notes.order("updated_at ASC")
321                  else
322                    @notes.order("updated_at DESC")
323                  end
324                end
325
326       # Find the notes we want to return
327       @notes = @notes.distinct.limit(result_limit).preload(:comments)
328
329       # Render the result
330       respond_to do |format|
331         format.rss { render :action => :index }
332         format.xml { render :action => :index }
333         format.json { render :action => :index }
334         format.gpx { render :action => :index }
335       end
336     end
337
338     private
339
340     #------------------------------------------------------------
341     # utility functions below.
342     #------------------------------------------------------------
343
344     ##
345     # Get the maximum number of results to return
346     def result_limit
347       if params[:limit]
348         if params[:limit].to_i.positive? && params[:limit].to_i <= 10000
349           params[:limit].to_i
350         else
351           raise OSM::APIBadUserInput, "Note limit must be between 1 and 10000"
352         end
353       else
354         100
355       end
356     end
357
358     ##
359     # Generate a condition to choose which notes we want based
360     # on their status and the user's request parameters
361     def closed_condition(notes)
362       closed_since = if params[:closed]
363                        params[:closed].to_i
364                      else
365                        7
366                      end
367
368       if closed_since.negative?
369         notes.where.not(:status => "hidden")
370       elsif closed_since.positive?
371         notes.where(:status => "open")
372              .or(notes.where(:status => "closed")
373                       .where(notes.arel_table[:closed_at].gt(Time.now.utc - closed_since.days)))
374       else
375         notes.where(:status => "open")
376       end
377     end
378
379     ##
380     # Add a comment to a note
381     def add_comment(note, text, event, notify: true)
382       attributes = { :visible => true, :event => event, :body => text }
383
384       if current_user
385         attributes[:author_id] = current_user.id
386       else
387         attributes[:author_ip] = request.remote_ip
388       end
389
390       comment = note.comments.create!(attributes)
391
392       note.comments.map(&:author).uniq.each do |user|
393         UserMailer.note_comment_notification(comment, user).deliver_later if notify && user && user != current_user && user.visible?
394       end
395     end
396   end
397 end