]> git.openstreetmap.org Git - rails.git/blob - app/controllers/note_controller.rb
Fix some bugs found by the note controller tests
[rails.git] / app / controllers / note_controller.rb
1 class NoteController < ApplicationController
2
3   layout 'site', :only => [:mine]
4
5   before_filter :check_api_readable
6   before_filter :authorize_web, :only => [:create, :close, :update, :delete, :mine]
7   before_filter :check_api_writable, :only => [:create, :close, :update, :delete]
8   before_filter :set_locale, :only => [:mine]
9   after_filter :compress_output
10   around_filter :api_call_handle_error, :api_call_timeout
11
12   ##
13   # Return a list of notes in a given area
14   def list
15     # Figure out the bbox - we prefer a bbox argument but also
16     # support the old, deprecated, method with four arguments
17     if params[:bbox]
18       bbox = BoundingBox.from_bbox_params(params)
19     else
20       raise OSM::APIBadUserInput.new("No l was given") unless params[:l]
21       raise OSM::APIBadUserInput.new("No r was given") unless params[:r]
22       raise OSM::APIBadUserInput.new("No b was given") unless params[:b]
23       raise OSM::APIBadUserInput.new("No t was given") unless params[:t]
24
25       bbox = BoundingBox.from_lrbt_params(params)
26     end
27
28     # Get any conditions that need to be applied
29     notes = closed_condition(Note.scoped)
30
31     # Check that the boundaries are valid
32     bbox.check_boundaries
33
34     # Check the the bounding box is not too big
35     bbox.check_size(MAX_NOTE_REQUEST_AREA)
36
37     # Find the notes we want to return
38     @notes = notes.bbox(bbox).order("updated_at DESC").limit(result_limit).preload(:comments)
39
40     # Render the result
41     respond_to do |format|
42       format.rss
43       format.xml
44       format.json
45       format.gpx
46     end
47   end
48
49   ##
50   # Create a new note
51   def create
52     # Check the arguments are sane
53     raise OSM::APIBadUserInput.new("No lat was given") unless params[:lat]
54     raise OSM::APIBadUserInput.new("No lon was given") unless params[:lon]
55     raise OSM::APIBadUserInput.new("No text was given") unless params[:text]
56
57     # Extract the arguments
58     lon = params[:lon].to_f
59     lat = params[:lat].to_f
60     comment = params[:text]
61     name = params[:name]
62
63     # Include in a transaction to ensure that there is always a note_comment for every note
64     Note.transaction do
65       # Create the note
66       @note = Note.create(:lat => lat, :lon => lon)
67       raise OSM::APIBadUserInput.new("The note is outside this world") unless @note.in_world?
68
69       #TODO: move this into a helper function
70       begin
71         url = "http://nominatim.openstreetmap.org/reverse?lat=" + lat.to_s + "&lon=" + lon.to_s + "&zoom=16" 
72         response = REXML::Document.new(Net::HTTP.get(URI.parse(url))) 
73                 
74         if result = response.get_text("reversegeocode/result") 
75           @note.nearby_place = result.to_s 
76         else 
77           @note.nearby_place = "unknown"
78         end
79       rescue Exception => err
80         @note.nearby_place = "unknown"
81       end
82
83       # Save the note
84       @note.save!
85
86       # Add a comment to the note
87       add_comment(@note, comment, name, "opened")
88     end
89
90     # Send an OK response
91     render_ok
92   end
93
94   ##
95   # Add a comment to an existing note
96   def update
97     # Check the arguments are sane
98     raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
99     raise OSM::APIBadUserInput.new("No text was given") unless params[:text]
100
101     # Extract the arguments
102     id = params[:id].to_i
103     comment = params[:text]
104     name = params[:name] or "NoName"
105
106     # Find the note and check it is valid
107     note = Note.find(id)
108     raise OSM::APINotFoundError unless note
109     raise OSM::APIAlreadyDeletedError unless note.visible?
110
111     # Add a comment to the note
112     Note.transaction do
113       add_comment(note, comment, name, "commented")
114     end
115
116     # Send an OK response
117     render_ok
118   end
119
120   ##
121   # Close a note
122   def close
123     # Check the arguments are sane
124     raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
125
126     # Extract the arguments
127     id = params[:id].to_i
128     name = params[:name]
129
130     # Find the note and check it is valid
131     note = Note.find_by_id(id)
132     raise OSM::APINotFoundError unless note
133     raise OSM::APIAlreadyDeletedError unless note.visible?
134
135     # Close the note and add a comment
136     Note.transaction do
137       note.close
138
139       add_comment(note, nil, name, "closed")
140     end
141
142     # Send an OK response
143     render_ok
144   end 
145
146   ##
147   # Get a feed of recent notes and comments
148   def rss
149     # Get any conditions that need to be applied
150     notes = closed_condition(Note.scoped)
151
152     # Process any bbox
153     if params[:bbox]
154       bbox = BoundingBox.from_bbox_params(params)
155
156       bbox.check_boundaries
157       bbox.check_size(MAX_NOTE_REQUEST_AREA)
158
159       notes = notes.bbox(bbox)
160     end
161
162     # Find the comments we want to return
163     @comments = NoteComment.where(:note_id => notes).order("created_at DESC").limit(result_limit).preload(:note)
164
165     # Render the result
166     respond_to do |format|
167       format.rss
168     end
169   end
170
171   ##
172   # Read a note
173   def read
174     # Check the arguments are sane
175     raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
176
177     # Find the note and check it is valid
178     @note = Note.find(params[:id])
179     raise OSM::APINotFoundError unless @note
180     raise OSM::APIAlreadyDeletedError unless @note.visible?
181     
182     # Render the result
183     respond_to do |format|
184       format.xml
185       format.rss
186       format.json
187       format.gpx
188     end
189   end
190
191   ##
192   # Delete (hide) a note
193   def delete
194     # Check the arguments are sane
195     raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
196
197     # Extract the arguments
198     id = params[:id].to_i
199     name = params[:name]
200
201     # Find the note and check it is valid
202     note = Note.find(id)
203     raise OSM::APINotFoundError unless note
204     raise OSM::APIAlreadyDeletedError unless note.visible?
205
206     # Mark the note as hidden
207     Note.transaction do
208       note.status = "hidden"
209       note.save
210
211       add_comment(note, nil, name, "hidden")
212     end
213
214     # Render the result
215     render :text => "ok\n", :content_type => "text/html" 
216   end
217
218   ##
219   # Return a list of notes matching a given string
220   def search
221     # Check the arguments are sane
222     raise OSM::APIBadUserInput.new("No query string was given") unless params[:q]
223
224     # Get any conditions that need to be applied
225     @notes = closed_condition(Note.scoped)
226     @notes = @notes.joins(:comments).where("note_comments.body ~ ?", params[:q])
227
228     # Find the notes we want to return
229     @notes = @notes.order("updated_at DESC").limit(result_limit).preload(:comments)
230
231     # Render the result
232     respond_to do |format|
233       format.rss { render :action => :list }
234       format.xml { render :action => :list }
235       format.json { render :action => :list }
236       format.gpx { render :action => :list }
237     end
238   end
239
240   def mine
241     if params[:display_name] 
242       @user2 = User.find_by_display_name(params[:display_name], :conditions => { :status => ["active", "confirmed"] }) 
243  
244       if @user2  
245         if @user2.data_public? or @user2 == @user 
246           conditions = ['note_comments.author_id = ?', @user2.id] 
247         else 
248           conditions = ['false'] 
249         end 
250       else #if request.format == :html 
251         @title = t 'user.no_such_user.title' 
252         @not_found_user = params[:display_name] 
253         render :template => 'user/no_such_user', :status => :not_found 
254         return
255       end 
256     end
257
258     if @user2 
259       user_link = render_to_string :partial => "user", :object => @user2 
260     end 
261     
262     @title =  t 'note.mine.title', :user => @user2.display_name 
263     @heading =  t 'note.mine.heading', :user => @user2.display_name 
264     @description = t 'note.mine.description', :user => user_link
265     
266     @page = (params[:page] || 1).to_i 
267     @page_size = 10
268
269     @notes = Note.find(:all, 
270                        :include => [:comments, {:comments => :author}],
271                        :joins => :comments,
272                        :order => "updated_at DESC",
273                        :conditions => conditions,
274                        :offset => (@page - 1) * @page_size, 
275                        :limit => @page_size).uniq
276   end
277
278 private 
279   #------------------------------------------------------------ 
280   # utility functions below. 
281   #------------------------------------------------------------   
282  
283   ##
284   # Render an OK response
285   def render_ok
286     if params[:format] == "js"
287       render :text => "osbResponse();", :content_type => "text/javascript" 
288     else
289       render :text => "ok " + @note.id.to_s + "\n", :content_type => "text/plain" if @note
290       render :text => "ok\n", :content_type => "text/plain" unless @note
291     end
292   end
293
294   ##
295   # Get the maximum number of results to return
296   def result_limit
297     if params[:limit] and params[:limit].to_i > 0 and params[:limit].to_i < 10000
298       params[:limit].to_i
299     else
300       100
301     end
302   end
303
304   ##
305   # Generate a condition to choose which bugs we want based
306   # on their status and the user's request parameters
307   def closed_condition(notes)
308     if params[:closed]
309       closed_since = params[:closed].to_i
310     else
311       closed_since = 7
312     end
313         
314     if closed_since < 0
315       notes = notes.where("status != 'hidden'")
316     elsif closed_since > 0
317       notes = notes.where("(status = 'open' OR (status = 'closed' AND closed_at > '#{Time.now - closed_since.days}'))")
318     else
319       notes = notes.where("status = 'open'")
320     end
321
322     return notes
323   end
324
325   ##
326   # Add a comment to a note
327   def add_comment(note, text, name, event)
328     name = "NoName" if name.nil?
329
330     attributes = { :visible => true, :event => event, :body => text }
331
332     if @user  
333       attributes[:author_id] = @user.id
334       attributes[:author_name] = @user.display_name
335     else  
336       attributes[:author_ip] = request.remote_ip
337       attributes[:author_name] = name + " (a)"
338     end
339
340     note.comments.create(attributes, :without_protection => true)
341
342     note.comments.map { |c| c.author }.uniq.each do |user|
343       if user and user != @user
344         Notifier.deliver_note_comment_notification(comment, user)
345       end
346     end
347   end
348 end