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