admin_settings.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # frozen_string_literal: true
  2. class Form::AdminSettings
  3. include ActiveModel::Model
  4. KEYS = %i(
  5. site_contact_username
  6. site_contact_email
  7. site_title
  8. site_short_description
  9. site_description
  10. site_extended_description
  11. site_terms
  12. registrations_mode
  13. closed_registrations_message
  14. open_deletion
  15. timeline_preview
  16. show_staff_badge
  17. bootstrap_timeline_accounts
  18. theme
  19. min_invite_role
  20. activity_api_enabled
  21. peers_api_enabled
  22. show_known_fediverse_at_about_page
  23. preview_sensitive_media
  24. custom_css
  25. profile_directory
  26. thumbnail
  27. hero
  28. mascot
  29. spam_check_enabled
  30. ).freeze
  31. BOOLEAN_KEYS = %i(
  32. open_deletion
  33. timeline_preview
  34. show_staff_badge
  35. activity_api_enabled
  36. peers_api_enabled
  37. show_known_fediverse_at_about_page
  38. preview_sensitive_media
  39. profile_directory
  40. spam_check_enabled
  41. ).freeze
  42. UPLOAD_KEYS = %i(
  43. thumbnail
  44. hero
  45. mascot
  46. ).freeze
  47. attr_accessor(*KEYS)
  48. validates :site_short_description, :site_description, html: { wrap_with: :p }
  49. validates :site_extended_description, :site_terms, :closed_registrations_message, html: true
  50. validates :registrations_mode, inclusion: { in: %w(open approved none) }
  51. validates :min_invite_role, inclusion: { in: %w(disabled user moderator admin) }
  52. validates :site_contact_email, :site_contact_username, presence: true
  53. validates :site_contact_username, existing_username: true
  54. validates :bootstrap_timeline_accounts, existing_username: { multiple: true }
  55. def initialize(_attributes = {})
  56. super
  57. initialize_attributes
  58. end
  59. def save
  60. return false unless valid?
  61. KEYS.each do |key|
  62. value = instance_variable_get("@#{key}")
  63. if UPLOAD_KEYS.include?(key) && !value.nil?
  64. upload = SiteUpload.where(var: key).first_or_initialize(var: key)
  65. upload.update(file: value)
  66. else
  67. setting = Setting.where(var: key).first_or_initialize(var: key)
  68. setting.update(value: typecast_value(key, value))
  69. end
  70. end
  71. end
  72. private
  73. def initialize_attributes
  74. KEYS.each do |key|
  75. instance_variable_set("@#{key}", Setting.public_send(key)) if instance_variable_get("@#{key}").nil?
  76. end
  77. end
  78. def typecast_value(key, value)
  79. if BOOLEAN_KEYS.include?(key)
  80. value == '1'
  81. else
  82. value
  83. end
  84. end
  85. end