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