]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/notes_controller.rb
Fix string that was not translatable
[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         matched_notes = @notes.where("to_tsvector('english', notes.description) @@ plainto_tsquery('english', ?)", params[:q])
267         matched_note_comments = @notes.joins(:comments).where("to_tsvector('english', note_comments.body) @@ plainto_tsquery('english', ?)", params[:q])
268
269         @notes = matched_notes.union_all(matched_note_comments)
270       end
271
272       # Add any date filter
273       time_filter_property = if params[:sort] == "updated_at"
274                                :updated_at
275                              else
276                                :created_at
277                              end
278       @notes = query_conditions_time(@notes, time_filter_property)
279
280       # Choose the sort order
281       @notes = if params[:sort] == "created_at"
282                  if params[:order] == "oldest"
283                    @notes.order(:created_at)
284                  else
285                    @notes.order(:created_at => :desc)
286                  end
287                else
288                  if params[:order] == "oldest"
289                    @notes.order(:updated_at)
290                  else
291                    @notes.order(:updated_at => :desc)
292                  end
293                end
294
295       # Find the notes we want to return
296       @notes = query_limit(@notes.distinct)
297       @notes = @notes.preload(:comments)
298
299       # Render the result
300       respond_to do |format|
301         format.rss { render :action => :index }
302         format.xml { render :action => :index }
303         format.json { render :action => :index }
304         format.gpx { render :action => :index }
305       end
306     end
307
308     private
309
310     #------------------------------------------------------------
311     # utility functions below.
312     #------------------------------------------------------------
313
314     ##
315     # Generate a condition to choose which notes we want based
316     # on their status and the user's request parameters
317     def closed_condition(notes)
318       closed_since = if params[:closed]
319                        params[:closed].to_i.days
320                      else
321                        Note::DEFAULT_FRESHLY_CLOSED_LIMIT
322                      end
323
324       if closed_since.negative?
325         notes.where.not(:status => "hidden")
326       elsif closed_since.positive?
327         notes.where(:status => "open")
328              .or(notes.where(:status => "closed")
329                       .where(notes.arel_table[:closed_at].gt(Time.now.utc - closed_since)))
330       else
331         notes.where(:status => "open")
332       end
333     end
334
335     ##
336     # Generate a condition to choose which notes we want based
337     # on the user's bounding box request parameters
338     def bbox_condition(notes)
339       if params[:bbox]
340         bbox = BoundingBox.from_bbox_params(params)
341
342         bbox.check_boundaries
343         bbox.check_size(Settings.max_note_request_area)
344
345         @min_lon = bbox.min_lon
346         @min_lat = bbox.min_lat
347         @max_lon = bbox.max_lon
348         @max_lat = bbox.max_lat
349
350         notes.bbox(bbox)
351       else
352         notes
353       end
354     end
355
356     ##
357     # Get author's information (for logged in users - user_id, for logged out users - IP address)
358     def author_info
359       if current_user
360         { :user_id => current_user.id }
361       else
362         { :user_ip => request.remote_ip }
363       end
364     end
365
366     ##
367     # Add a comment to a note
368     def add_comment(note, text, event, notify: true)
369       attributes = { :visible => true, :event => event, :body => text }
370
371       # Get note comment's author info (for logged in users - user_id, for logged out users - IP address)
372       note_comment_author_info = author_info
373
374       if note_comment_author_info[:user_ip].nil?
375         attributes[:author_id] = note_comment_author_info[:user_id]
376       else
377         attributes[:author_ip] = note_comment_author_info[:user_ip]
378       end
379
380       comment = note.comments.create!(attributes)
381
382       NoteCommentNotifier.with(:record => comment).deliver_later if notify
383
384       NoteSubscription.find_or_create_by(:note => note, :user => current_user) if current_user
385     end
386   end
387 end