Class: Admin::ThemesController

Inherits:
AdminController
  • Object
show all
Defined in:
app/controllers/admin/themes_controller.rb

Constant Summary collapse

MAX_REMOTE_LENGTH =
10_000
THEME_CONTENT_TYPES =
%w[
  application/gzip
  application/x-gzip
  application/x-zip-compressed
  application/zip
]

Instance Method Summary collapse

Instance Method Details

#bulk_destroyObject



280
281
282
283
284
285
286
287
288
289
290
# File 'app/controllers/admin/themes_controller.rb', line 280

def bulk_destroy
  themes = Theme.where(id: params[:theme_ids])
  raise Discourse::InvalidParameters.new(:id) if themes.blank?

  ActiveRecord::Base.transaction do
    themes.each { |theme| StaffActionLogger.new(current_user).log_theme_destroy(theme) }
    themes.destroy_all
  end

  respond_to { |format| format.json { head :no_content } }
end

#createObject



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'app/controllers/admin/themes_controller.rb', line 186

def create
  ban_in_allowlist_mode!

  @theme =
    Theme.new(
      name: theme_params[:name],
      user_id: theme_user.id,
      user_selectable: theme_params[:user_selectable] || false,
      color_scheme_id: theme_params[:color_scheme_id],
      component: [true, "true"].include?(theme_params[:component]),
    )
  set_fields

  respond_to do |format|
    if @theme.save
      update_default_theme
      log_theme_change(nil, @theme)
      format.json { render json: serialize_data(@theme, ThemeSerializer), status: :created }
    else
      format.json { render json: @theme.errors, status: :unprocessable_entity }
    end
  end
end

#destroyObject



270
271
272
273
274
275
276
277
278
# File 'app/controllers/admin/themes_controller.rb', line 270

def destroy
  @theme = Theme.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless @theme

  StaffActionLogger.new(current_user).log_theme_destroy(@theme)
  @theme.destroy

  respond_to { |format| format.json { head :no_content } }
end

#exportObject



299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'app/controllers/admin/themes_controller.rb', line 299

def export
  @theme = Theme.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless @theme

  exporter = ThemeStore::ZipExporter.new(@theme)
  file_path = exporter.package_filename

  headers["Content-Length"] = File.size(file_path).to_s
  send_data File.read(file_path),
            filename: File.basename(file_path),
            content_type: "application/zip"
ensure
  exporter.cleanup!
end

#generate_key_pairObject



36
37
38
39
40
41
# File 'app/controllers/admin/themes_controller.rb', line 36

def generate_key_pair
  require "sshkey"
  k = SSHKey.generate
  Discourse.redis.setex("ssh_key_#{k.ssh_public_key}", 1.hour, k.private_key)
  render json: { public_key: k.ssh_public_key }
end

#get_translationsObject



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'app/controllers/admin/themes_controller.rb', line 314

def get_translations
  params.require(:locale)
  if I18n.available_locales.exclude?(params[:locale].to_sym)
    raise Discourse::InvalidParameters.new(:locale)
  end

  I18n.locale = params[:locale]

  @theme = Theme.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless @theme

  translations =
    @theme.translations.map do |translation|
      { key: translation.key, value: translation.value, default: translation.default }
    end

  render json: { translations: translations }, status: :ok
end

#importObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'app/controllers/admin/themes_controller.rb', line 50

def import
  @theme = nil
  if params[:theme] && params[:theme].content_type == "application/json"
    ban_in_allowlist_mode!

    # .dcstyle.json import. Deprecated, but still available to allow conversion
    json = JSON.parse(params[:theme].read)
    theme = json["theme"]

    @theme = Theme.new(name: theme["name"], user_id: theme_user.id, auto_update: false)
    theme["theme_fields"]&.each do |field|
      if field["raw_upload"]
        begin
          tmp = Tempfile.new
          tmp.binmode
          file = Base64.decode64(field["raw_upload"])
          tmp.write(file)
          tmp.rewind
          upload = UploadCreator.new(tmp, field["filename"]).create_for(theme_user.id)
          field["upload_id"] = upload.id
        ensure
          tmp.unlink
        end
      end

      @theme.set_field(
        target: field["target"],
        name: field["name"],
        value: field["value"],
        type_id: field["type_id"],
        upload_id: field["upload_id"],
      )
    end

    if @theme.save
      log_theme_change(nil, @theme)
      render json: serialize_data(@theme, ThemeSerializer), status: :created
    else
      render json: @theme.errors, status: :unprocessable_entity
    end
  elsif remote = params[:remote]
    if remote.length > MAX_REMOTE_LENGTH
      error =
        I18n.t("themes.import_error.not_allowed_theme", { repo: remote[0..MAX_REMOTE_LENGTH] })
      return render_json_error(error, status: 422)
    end

    begin
      guardian.ensure_allowed_theme_repo_import!(remote.strip)
    rescue Discourse::InvalidAccess
      render_json_error I18n.t("themes.import_error.not_allowed_theme", { repo: remote.strip }),
                        status: :forbidden
      return
    end

    hijack do
      begin
        branch = params[:branch] ? params[:branch] : nil
        private_key =
          params[:public_key] ? Discourse.redis.get("ssh_key_#{params[:public_key]}") : nil
        if params[:public_key].present? && private_key.blank?
          return render_json_error I18n.t("themes.import_error.ssh_key_gone")
        end

        @theme =
          RemoteTheme.import_theme(remote, theme_user, private_key: private_key, branch: branch)
        render json: serialize_data(@theme, ThemeSerializer), status: :created
      rescue RemoteTheme::ImportError => e
        if params[:force]
          theme_name = params[:remote].gsub(/.git\z/, "").split("/").last

          remote_theme = RemoteTheme.new
          remote_theme.private_key = private_key
          remote_theme.branch = params[:branch] ? params[:branch] : nil
          remote_theme.remote_url = params[:remote]
          remote_theme.save!

          @theme = Theme.new(user_id: theme_user&.id || -1, name: theme_name)
          @theme.remote_theme = remote_theme
          @theme.save!

          render json: serialize_data(@theme, ThemeSerializer), status: :created
        else
          render_json_error e.message
        end
      end
    end
  elsif params[:bundle] ||
        (params[:theme] && THEME_CONTENT_TYPES.include?(params[:theme].content_type))
    ban_in_allowlist_mode!

    # params[:bundle] used by theme CLI. params[:theme] used by admin UI
    bundle = params[:bundle] || params[:theme]
    theme_id = params[:theme_id]
    update_components = params[:components]
    run_migrations = !params[:skip_migrations]

    begin
      @theme =
        RemoteTheme.update_zipped_theme(
          bundle.path,
          bundle.original_filename,
          user: theme_user,
          theme_id:,
          update_components:,
          run_migrations:,
        )

      log_theme_change(nil, @theme)
      render json: serialize_data(@theme, ThemeSerializer), status: :created
    rescue RemoteTheme::ImportError => e
      render_json_error e.message
    end
  else
    render_json_error I18n.t("themes.import_error.unknown_file_type"),
                      status: :unprocessable_entity
  end
rescue Theme::SettingsMigrationError => err
  render_json_error err.message
end

#indexObject



171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'app/controllers/admin/themes_controller.rb', line 171

def index
  @themes = Theme.include_relations.order(:name)
  @color_schemes = ColorScheme.all.includes(:theme, color_scheme_colors: :color_scheme).to_a

  payload = {
    themes: serialize_data(@themes, ThemeSerializer),
    extras: {
      color_schemes: serialize_data(@color_schemes, ColorSchemeSerializer),
      locale: current_user.effective_locale,
    },
  }

  respond_to { |format| format.json { render json: payload } }
end

#objects_setting_metadataObject



360
361
362
363
364
365
366
367
368
# File 'app/controllers/admin/themes_controller.rb', line 360

def 
  theme = Theme.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless theme

  theme_setting = theme.settings[params[:setting_name].to_sym]
  raise Discourse::InvalidParameters.new(:setting_name) unless theme_setting

  render_serialized(theme_setting, ThemeObjectsSettingMetadataSerializer, root: false)
end

#previewObject



11
12
13
14
15
16
# File 'app/controllers/admin/themes_controller.rb', line 11

def preview
  theme = Theme.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless theme

  redirect_to path("/?preview_theme_id=#{theme.id}")
end

#schemaObject



357
358
# File 'app/controllers/admin/themes_controller.rb', line 357

def schema
end

#showObject



292
293
294
295
296
297
# File 'app/controllers/admin/themes_controller.rb', line 292

def show
  @theme = Theme.include_relations.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless @theme

  render_serialized(@theme, ThemeSerializer)
end

#updateObject



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'app/controllers/admin/themes_controller.rb', line 210

def update
  @theme = Theme.include_relations.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless @theme

  original_json = ThemeSerializer.new(@theme, root: false).to_json
  disables_component = [false, "false"].include?(theme_params[:enabled])
  enables_component = [true, "true"].include?(theme_params[:enabled])

  %i[name color_scheme_id user_selectable enabled auto_update].each do |field|
    @theme.public_send("#{field}=", theme_params[field]) if theme_params.key?(field)
  end

  @theme.child_theme_ids = theme_params[:child_theme_ids] if theme_params.key?(:child_theme_ids)

  @theme.parent_theme_ids = theme_params[:parent_theme_ids] if theme_params.key?(
    :parent_theme_ids,
  )

  set_fields
  update_settings
  update_translations
  handle_switch

  @theme.remote_theme.update_remote_version if params[:theme][:remote_check]

  if params[:theme][:remote_update]
    @theme.remote_theme.update_from_remote(raise_if_theme_save_fails: false)
  else
    @theme.save
  end

  respond_to do |format|
    if @theme.errors.blank?
      update_default_theme

      @theme = Theme.include_relations.find(@theme.id)

      if (!disables_component && !enables_component) || theme_params.keys.size > 1
        log_theme_change(original_json, @theme)
      end
      log_theme_component_disabled if disables_component
      log_theme_component_enabled if enables_component

      format.json { render json: serialize_data(@theme, ThemeSerializer), status: :ok }
    else
      format.json do
        error = @theme.errors.full_messages.join(", ").presence
        error = I18n.t("themes.bad_color_scheme") if @theme.errors[:color_scheme].present?
        error ||= I18n.t("themes.other_error")

        render json: { errors: [error] }, status: :unprocessable_entity
      end
    end
  end
rescue RemoteTheme::ImportError => e
  render_json_error e.message
rescue Theme::SettingsMigrationError => e
  render_json_error e.message
end

#update_single_settingObject



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'app/controllers/admin/themes_controller.rb', line 333

def update_single_setting
  params.require("name")
  @theme = Theme.find_by(id: params[:id])
  raise Discourse::InvalidParameters.new(:id) unless @theme

  setting_name = params[:name].to_sym
  new_value = params[:value] || nil

  previous_value = @theme.cached_settings[setting_name]

  begin
    @theme.update_setting(setting_name, new_value)
  rescue Discourse::InvalidParameters => e
    return render_json_error e.message
  end

  @theme.save

  log_theme_setting_change(setting_name, previous_value, new_value)

  updated_setting = @theme.cached_settings.select { |key, val| key == setting_name }
  render json: updated_setting, status: :ok
end

#upload_assetObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/controllers/admin/themes_controller.rb', line 18

def upload_asset
  ban_in_allowlist_mode!

  path = params[:file].path

  hijack do
    File.open(path) do |file|
      filename = params[:file]&.original_filename || File.basename(path)
      upload = UploadCreator.new(file, filename, for_theme: true).create_for(theme_user.id)
      if upload.errors.count > 0
        render_json_error upload
      else
        render json: { upload_id: upload.id }, status: :created
      end
    end
  end
end