1 # frozen_string_literal: true
 
   3 # Update and read user preferences, which are arbitrary key/val pairs
 
   5   class UserPreferencesController < ApiController
 
   6     before_action :check_api_writable, :only => [:update_all, :update, :destroy]
 
   7     before_action :authorize
 
  11     before_action :set_request_formats
 
  14     # return all the preferences
 
  16       @user_preferences = current_user.preferences
 
  18       respond_to do |format|
 
  25     # return the value for a single preference
 
  27       pref = UserPreference.find([current_user.id, params[:preference_key]])
 
  29       render :plain => pref.v.to_s
 
  32     # update the entire set of preferences
 
  34       old_preferences = current_user.preferences.index_by(&:k)
 
  38       doc = LibXML::XML::Parser.string(request.raw_post, :options => LibXML::XML::Parser::Options::NOERROR).parse
 
  40       doc.find("//preferences/preference").each do |pt|
 
  41         if preference = old_preferences.delete(pt["k"])
 
  42           preference.v = pt["v"]
 
  43         elsif new_preferences.include?(pt["k"])
 
  44           raise OSM::APIDuplicatePreferenceError, pt["k"]
 
  46           preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
 
  49         new_preferences[preference.k] = preference
 
  52       old_preferences.each_value(&:delete)
 
  54       new_preferences.each_value(&:save!)
 
  60     # update the value of a single preference
 
  63         pref = UserPreference.find([current_user.id, params[:preference_key]])
 
  64       rescue ActiveRecord::RecordNotFound
 
  65         pref = UserPreference.new
 
  66         pref.user = current_user
 
  67         pref.k = params[:preference_key]
 
  70       pref.v = request.raw_post.chomp.force_encoding("UTF-8")
 
  77     # delete a single preference
 
  79       UserPreference.find([current_user.id, params[:preference_key]]).delete