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