admin_settings.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. bootstrap_timeline_accounts
  17. theme
  18. activity_api_enabled
  19. peers_api_enabled
  20. show_known_fediverse_at_about_page
  21. preview_sensitive_media
  22. custom_css
  23. profile_directory
  24. thumbnail
  25. hero
  26. mascot
  27. trends
  28. trendable_by_default
  29. show_domain_blocks
  30. show_domain_blocks_rationale
  31. noindex
  32. require_invite_text
  33. ).freeze
  34. BOOLEAN_KEYS = %i(
  35. open_deletion
  36. timeline_preview
  37. activity_api_enabled
  38. peers_api_enabled
  39. show_known_fediverse_at_about_page
  40. preview_sensitive_media
  41. profile_directory
  42. trends
  43. trendable_by_default
  44. noindex
  45. require_invite_text
  46. ).freeze
  47. UPLOAD_KEYS = %i(
  48. thumbnail
  49. hero
  50. mascot
  51. ).freeze
  52. attr_accessor(*KEYS)
  53. validates :site_short_description, :site_description, html: { wrap_with: :p }
  54. validates :site_extended_description, :site_terms, :closed_registrations_message, html: true
  55. validates :registrations_mode, inclusion: { in: %w(open approved none) }
  56. validates :site_contact_email, :site_contact_username, presence: true
  57. validates :site_contact_username, existing_username: true
  58. validates :bootstrap_timeline_accounts, existing_username: { multiple: true }
  59. validates :show_domain_blocks, inclusion: { in: %w(disabled users all) }
  60. validates :show_domain_blocks_rationale, inclusion: { in: %w(disabled users all) }
  61. def initialize(_attributes = {})
  62. super
  63. initialize_attributes
  64. end
  65. def save
  66. return false unless valid?
  67. KEYS.each do |key|
  68. value = instance_variable_get("@#{key}")
  69. if UPLOAD_KEYS.include?(key) && !value.nil?
  70. upload = SiteUpload.where(var: key).first_or_initialize(var: key)
  71. upload.update(file: value)
  72. else
  73. setting = Setting.where(var: key).first_or_initialize(var: key)
  74. setting.update(value: typecast_value(key, value))
  75. end
  76. end
  77. end
  78. private
  79. def initialize_attributes
  80. KEYS.each do |key|
  81. instance_variable_set("@#{key}", Setting.public_send(key)) if instance_variable_get("@#{key}").nil?
  82. end
  83. end
  84. def typecast_value(key, value)
  85. if BOOLEAN_KEYS.include?(key)
  86. value == '1'
  87. else
  88. value
  89. end
  90. end
  91. end