]> git.openstreetmap.org Git - rails.git/blob - app/controllers/user_preference_controller.rb
Use send_data for GPX traces intead of monkey patching send_file
[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   skip_before_action :verify_authenticity_token
4   before_action :authorize
5   before_action :require_allow_read_prefs, :only => [:read_one, :read]
6   before_action :require_allow_write_prefs, :except => [:read_one, :read]
7   around_action :api_call_handle_error
8
9   ##
10   # return all the preferences as an XML document
11   def read
12     doc = OSM::API.new.get_xml_doc
13
14     prefs = current_user.preferences
15
16     el1 = XML::Node.new "preferences"
17
18     prefs.each do |pref|
19       el1 << pref.to_xml_node
20     end
21
22     doc.root << el1
23     render :xml => doc.to_s
24   end
25
26   ##
27   # return the value for a single preference
28   def read_one
29     pref = UserPreference.find([current_user.id, params[:preference_key]])
30
31     render :plain => pref.v.to_s
32   end
33
34   # update the entire set of preferences
35   def update
36     old_preferences = current_user.preferences.each_with_object({}) do |preference, preferences|
37       preferences[preference.k] = preference
38     end
39
40     new_preferences = {}
41
42     doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
43
44     doc.find("//preferences/preference").each do |pt|
45       if preference = old_preferences.delete(pt["k"])
46         preference.v = pt["v"]
47       elsif new_preferences.include?(pt["k"])
48         raise OSM::APIDuplicatePreferenceError, pt["k"]
49       else
50         preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
51       end
52
53       new_preferences[preference.k] = preference
54     end
55
56     old_preferences.each_value(&:delete)
57
58     new_preferences.each_value(&:save!)
59
60     render :plain => ""
61   end
62
63   ##
64   # update the value of a single preference
65   def update_one
66     begin
67       pref = UserPreference.find([current_user.id, params[:preference_key]])
68     rescue ActiveRecord::RecordNotFound
69       pref = UserPreference.new
70       pref.user = current_user
71       pref.k = params[:preference_key]
72     end
73
74     pref.v = request.raw_post.chomp
75     pref.save!
76
77     render :plain => ""
78   end
79
80   ##
81   # delete a single preference
82   def delete_one
83     UserPreference.find([current_user.id, params[:preference_key]]).delete
84
85     render :plain => ""
86   end
87 end