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