]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/notes_controller.rb
Actually use notification preferences
[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       raise OSM::APIModerationZoneError if current_user.nil? && ModerationZone.falls_within_any?(:lon => lon, :lat => lat)
93
94       # Get note's author info (for logged in users - user_id, for logged out users - IP address)
95       note_author_info = author_info
96
97       # Include in a transaction to ensure that there is always a note_comment for every note
98       Note.transaction do
99         # Create the note
100         @note = Note.create(:lat => lat, :lon => lon, :description => description, :user_id => note_author_info[:user_id], :user_ip => note_author_info[:user_ip])
101         raise OSM::APIBadUserInput, "The note is outside this world" unless @note.in_world?
102
103         # Save the note
104         @note.save!
105
106         # Add opening comment (description) to the note
107         add_comment(@note, description, "opened")
108       end
109
110       # Return a copy of the new note
111       respond_to do |format|
112         format.xml { render :action => :show }
113         format.json { render :action => :show }
114       end
115     end
116
117     ##
118     # Delete (hide) a note
119     def destroy
120       # Check the arguments are sane
121       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
122
123       # Extract the arguments
124       id = params[:id].to_i
125       comment = params[:text]
126
127       # Find the note and check it is valid
128       Note.transaction do
129         @note = Note.lock.find(id)
130         raise OSM::APINotFoundError unless @note
131         raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
132
133         # Mark the note as hidden
134         @note.status = "hidden"
135         @note.save
136
137         add_comment(@note, comment, "hidden", :notify => false)
138       end
139
140       # Return a copy of the updated note
141       respond_to do |format|
142         format.xml { render :action => :show }
143         format.json { render :action => :show }
144       end
145     end
146
147     ##
148     # Add a comment to an existing note
149     def comment
150       # Check the arguments are sane
151       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
152       raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
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.transaction do
160         @note = Note.lock.find(id)
161         raise OSM::APINotFoundError unless @note
162         raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
163         raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
164
165         # Add a comment to the note
166         add_comment(@note, comment, "commented")
167       end
168
169       # Return a copy of the updated note
170       respond_to do |format|
171         format.xml { render :action => :show }
172         format.json { render :action => :show }
173       end
174     end
175
176     ##
177     # Close a note
178     def close
179       # Check the arguments are sane
180       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
181
182       # Extract the arguments
183       id = params[:id].to_i
184       comment = params[:text]
185
186       # Find the note and check it is valid
187       Note.transaction do
188         @note = Note.lock.find_by(:id => id)
189         raise OSM::APINotFoundError unless @note
190         raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
191         raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
192
193         # Close the note and add a comment
194         @note.close
195
196         add_comment(@note, comment, "closed")
197       end
198
199       # Return a copy of the updated note
200       respond_to do |format|
201         format.xml { render :action => :show }
202         format.json { render :action => :show }
203       end
204     end
205
206     ##
207     # Reopen a note
208     def reopen
209       # Check the arguments are sane
210       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
211
212       # Extract the arguments
213       id = params[:id].to_i
214       comment = params[:text]
215
216       # Find the note and check it is valid
217       Note.transaction do
218         @note = Note.lock.find_by(:id => id)
219         raise OSM::APINotFoundError unless @note
220         raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || current_user.moderator?
221         raise OSM::APINoteAlreadyOpenError, @note unless @note.closed? || !@note.visible?
222
223         # Reopen the note and add a comment
224         @note.reopen
225
226         add_comment(@note, comment, "reopened")
227       end
228
229       # Return a copy of the updated note
230       respond_to do |format|
231         format.xml { render :action => :show }
232         format.json { render :action => :show }
233       end
234     end
235
236     ##
237     # Get a feed of recent notes and comments
238     def feed
239       # Get any conditions that need to be applied
240       notes = closed_condition(Note.all)
241       notes = bbox_condition(notes)
242
243       # Find the comments we want to return
244       @comments = NoteComment.where(:note => notes)
245                              .order(:created_at => :desc)
246       @comments = query_limit(@comments)
247       @comments = @comments.preload(:author, :note => { :comments => :author })
248
249       # Render the result
250       respond_to do |format|
251         format.rss
252       end
253     end
254
255     ##
256     # Return a list of notes matching a given string
257     def search
258       # Get the initial set of notes
259       @notes = closed_condition(Note.all)
260       @notes = bbox_condition(@notes)
261
262       # Add any user filter
263       user = query_conditions_user_value
264       @notes = @notes.joins(:comments).where(:note_comments => { :author_id => user }) if user
265
266       # Add any text filter
267       if params[:q]
268         matched_notes = @notes.where("to_tsvector('english', notes.description) @@ plainto_tsquery('english', ?)", params[:q])
269         matched_note_comments = @notes.joins(:comments).where("to_tsvector('english', note_comments.body) @@ plainto_tsquery('english', ?)", params[:q])
270
271         @notes = matched_notes.union_all(matched_note_comments)
272       end
273
274       # Add any date filter
275       time_filter_property = if params[:sort] == "updated_at"
276                                :updated_at
277                              else
278                                :created_at
279                              end
280       @notes = query_conditions_time(@notes, time_filter_property)
281
282       # Choose the sort order
283       @notes = if params[:sort] == "created_at"
284                  if params[:order] == "oldest"
285                    @notes.order(:created_at)
286                  else
287                    @notes.order(:created_at => :desc)
288                  end
289                else
290                  if params[:order] == "oldest"
291                    @notes.order(:updated_at)
292                  else
293                    @notes.order(:updated_at => :desc)
294                  end
295                end
296
297       # Find the notes we want to return
298       @notes = query_limit(@notes.distinct)
299       @notes = @notes.preload(:comments)
300
301       # Render the result
302       respond_to do |format|
303         format.rss { render :action => :index }
304         format.xml { render :action => :index }
305         format.json { render :action => :index }
306         format.gpx { render :action => :index }
307       end
308     end
309
310     private
311
312     #------------------------------------------------------------
313     # utility functions below.
314     #------------------------------------------------------------
315
316     ##
317     # Generate a condition to choose which notes we want based
318     # on their status and the user's request parameters
319     def closed_condition(notes)
320       closed_since = if params[:closed]
321                        params[:closed].to_i.days
322                      else
323                        Note::DEFAULT_FRESHLY_CLOSED_LIMIT
324                      end
325
326       if closed_since.negative?
327         notes.where.not(:status => "hidden")
328       elsif closed_since.positive?
329         notes.where(:status => "open")
330              .or(notes.where(:status => "closed")
331                       .where(notes.arel_table[:closed_at].gt(Time.now.utc - closed_since)))
332       else
333         notes.where(:status => "open")
334       end
335     end
336
337     ##
338     # Generate a condition to choose which notes we want based
339     # on the user's bounding box request parameters
340     def bbox_condition(notes)
341       if params[:bbox]
342         bbox = BoundingBox.from_bbox_params(params)
343
344         bbox.check_boundaries
345         bbox.check_size(Settings.max_note_request_area)
346
347         @min_lon = bbox.min_lon
348         @min_lat = bbox.min_lat
349         @max_lon = bbox.max_lon
350         @max_lat = bbox.max_lat
351
352         notes.bbox(bbox)
353       else
354         notes
355       end
356     end
357
358     ##
359     # Get author's information (for logged in users - user_id, for logged out users - IP address)
360     def author_info
361       if current_user
362         { :user_id => current_user.id }
363       else
364         { :user_ip => request.remote_ip }
365       end
366     end
367
368     ##
369     # Add a comment to a note
370     def add_comment(note, text, event, notify: true)
371       attributes = { :visible => true, :event => event, :body => text }
372
373       # Get note comment's author info (for logged in users - user_id, for logged out users - IP address)
374       note_comment_author_info = author_info
375
376       if note_comment_author_info[:user_ip].nil?
377         attributes[:author_id] = note_comment_author_info[:user_id]
378       else
379         attributes[:author_ip] = note_comment_author_info[:user_ip]
380       end
381
382       comment = note.comments.create!(attributes)
383
384       NoteCommentNotifier.with(:record => comment).deliver_later if notify
385
386       NoteSubscription.find_or_create_by(:note => note, :user => current_user) if current_user
387     end
388   end
389 end