]> git.openstreetmap.org Git - rails.git/blob - app/controllers/user_preference_controller.rb
68ea88eeac5922def89f7e7e947f73c68332e072
[rails.git] / app / controllers / user_preference_controller.rb
1 # Update and read user preferences, which are arbitrayr key/val pairs
2 class UserPreferenceController < ApplicationController
3   before_filter :authorize
4
5   def read_one
6     pref = UserPreference.find(@user.id, params[:preference_key])
7
8     render :text => pref.v.to_s
9   rescue ActiveRecord::RecordNotFound => ex
10     render :text => 'OH NOES! PREF NOT FOUND!', :status => :not_found
11   end
12
13   def update_one
14     begin
15       pref = UserPreference.find(@user.id, params[:preference_key])
16       pref.v = request.raw_post.chomp
17       pref.save
18     rescue ActiveRecord::RecordNotFound 
19       pref = UserPreference.new
20       pref.user = @user
21       pref.k = params[:preference_key]
22       pref.v = request.raw_post.chomp
23       pref.save
24     end
25
26     render :nothing => true
27   end
28
29   def delete_one
30     UserPreference.delete(@user.id, params[:preference_key])
31
32     render :nothing => true
33   rescue ActiveRecord::RecordNotFound => ex
34     render :text => "param: #{params[:preference_key]} not found", :status => :not_found
35   end
36
37   # print out all the preferences as a big xml block
38   def read
39     doc = OSM::API.new.get_xml_doc
40
41     prefs = @user.preferences
42
43     el1 = XML::Node.new 'preferences'
44
45     prefs.each do |pref|
46       el1 <<  pref.to_xml_node
47     end
48
49     doc.root << el1
50     render :text => doc.to_s, :content_type => "text/xml"
51   end
52
53   # update the entire set of preferences
54   def update
55     p = XML::Parser.string(request.raw_post)
56     doc = p.parse
57
58     prefs = []
59
60     keyhash = {}
61
62     doc.find('//preferences/preference').each do |pt|
63       pref = UserPreference.new
64
65       unless keyhash[pt['k']].nil? # already have that key
66         render :text => 'OH NOES! CAN HAS UNIQUE KEYS?', :status => :not_acceptable
67       end
68
69       keyhash[pt['k']] = 1
70
71       pref.k = pt['k']
72       pref.v = pt['v']
73       pref.user_id = @user.id
74       prefs << pref
75     end
76
77     if prefs.size > 150
78       render :text => 'Too many preferences', :status => :request_entity_too_large
79     end
80
81     # kill the existing ones
82     UserPreference.delete_all(['user_id = ?', @user.id])
83
84     # save the new ones
85     prefs.each do |pref|
86       pref.save!
87     end
88     render :nothing => true
89
90   rescue Exception => ex
91     render :text => 'OH NOES! FAIL!: ' + ex.to_s, :status => :internal_server_error
92   end
93 end