Class: RemoteTheme
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- RemoteTheme
- Defined in:
- app/models/remote_theme.rb
Defined Under Namespace
Classes: ImportError
Constant Summary collapse
- METADATA_PROPERTIES =
%i[ license_url about_url authors theme_version minimum_discourse_version maximum_discourse_version ]
- ALLOWED_FIELDS =
%w[ scss embedded_scss embedded_header head_tag header after_header body_tag footer ]
- GITHUB_REGEXP =
%r{\Ahttps?://github\.com/}
- GITHUB_SSH_REGEXP =
%r{\Assh://git@github\.com:}
- MAX_METADATA_FILE_SIZE =
Discourse::MAX_METADATA_FILE_SIZE
- MAX_ASSET_FILE_SIZE =
8.megabytes
- MAX_THEME_FILE_COUNT =
1024
- MAX_THEME_SIZE =
256.megabytes
- MAX_THEME_SCREENSHOT_FILE_SIZE =
1.megabyte
- MAX_THEME_SCREENSHOT_DIMENSIONS =
4K resolution
[3840, 2160]
- THEME_SCREENSHOT_ALLOWED_FILE_TYPES =
%w[.jpg .jpeg .gif .png].freeze
Class Method Summary collapse
- .extract_theme_info(importer) ⇒ Object
- .import_theme(url, user = Discourse.system_user, private_key: nil, branch: nil) ⇒ Object
- .import_theme_from_directory(directory) ⇒ Object
- .out_of_date_themes ⇒ Object
- .unreachable_themes ⇒ Object
- .update_zipped_theme(filename, original_filename, user: Discourse.system_user, theme_id: nil, update_components: nil, run_migrations: true) ⇒ Object
Instance Method Summary collapse
- #create_upload(path, relative_path) ⇒ Object
- #github_diff_link ⇒ Object
- #github_repo_url ⇒ Object
- #is_git? ⇒ Boolean
- #normalize_override(hex) ⇒ Object
- #out_of_date? ⇒ Boolean
- #update_from_remote(importer = nil, skip_update: false, raise_if_theme_save_fails: true, already_in_transaction: false, run_migrations: true) ⇒ Object
- #update_remote_version ⇒ Object
- #update_theme_color_schemes(theme, schemes) ⇒ Object
Class Method Details
.extract_theme_info(importer) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'app/models/remote_theme.rb', line 51 def self.extract_theme_info(importer) if importer.file_size("about.json") > MAX_METADATA_FILE_SIZE raise ImportError.new I18n.t( "themes.import_error.about_json_too_big", limit: ActiveSupport::NumberHelper.number_to_human_size( MAX_METADATA_FILE_SIZE, ), ) end begin json = JSON.parse(importer["about.json"]) json.fetch("name") json rescue TypeError, JSON::ParserError, KeyError raise ImportError.new I18n.t("themes.import_error.about_json") end end |
.import_theme(url, user = Discourse.system_user, private_key: nil, branch: nil) ⇒ Object
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
# File 'app/models/remote_theme.rb', line 163 def self.import_theme(url, user = Discourse.system_user, private_key: nil, branch: nil) importer = ThemeStore::GitImporter.new(url.strip, private_key: private_key, branch: branch) importer.import! theme_info = RemoteTheme.extract_theme_info(importer) component = [true, "true"].include?(theme_info["component"]) theme = Theme.new(user_id: user&.id || -1, name: theme_info["name"], component: component) theme.child_components = theme_info["components"].presence || [] remote_theme = new theme.remote_theme = remote_theme remote_theme.private_key = private_key remote_theme.branch = branch remote_theme.remote_url = importer.url remote_theme.update_from_remote(importer) theme ensure begin importer.cleanup! rescue => e Rails.logger.warn("Failed cleanup remote git #{e}") end end |
.import_theme_from_directory(directory) ⇒ Object
90 91 92 |
# File 'app/models/remote_theme.rb', line 90 def self.import_theme_from_directory(directory) update_theme(ThemeStore::DirectoryImporter.new(directory), update_components: "none") end |
.out_of_date_themes ⇒ Object
191 192 193 194 195 196 197 |
# File 'app/models/remote_theme.rb', line 191 def self.out_of_date_themes self .joined_remotes .where("commits_behind > 0 OR remote_version <> local_version") .where(themes: { enabled: true }) .pluck("themes.name", "themes.id") end |
.unreachable_themes ⇒ Object
199 200 201 |
# File 'app/models/remote_theme.rb', line 199 def self.unreachable_themes self.joined_remotes.where("last_error_text IS NOT NULL").pluck("themes.name", "themes.id") end |
.update_zipped_theme(filename, original_filename, user: Discourse.system_user, theme_id: nil, update_components: nil, run_migrations: true) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'app/models/remote_theme.rb', line 71 def self.update_zipped_theme( filename, original_filename, user: Discourse.system_user, theme_id: nil, update_components: nil, run_migrations: true ) update_theme( ThemeStore::ZipImporter.new(filename, original_filename), user:, theme_id:, update_components:, run_migrations:, ) end |
Instance Method Details
#create_upload(path, relative_path) ⇒ Object
526 527 528 529 530 531 532 533 534 535 536 537 |
# File 'app/models/remote_theme.rb', line 526 def create_upload(path, relative_path) new_path = "#{File.dirname(path)}/#{SecureRandom.hex}#{File.extname(path)}" # OptimizedImage has strict file name restrictions, so rename temporarily File.rename(path, new_path) UploadCreator.new( File.open(new_path), File.basename(relative_path), for_theme: true, ).create_for(theme.user_id) end |
#github_diff_link ⇒ Object
506 507 508 509 510 |
# File 'app/models/remote_theme.rb', line 506 def github_diff_link if github_repo_url.present? && local_version != remote_version "#{github_repo_url.gsub(/\.git\z/, "")}/compare/#{local_version}...#{remote_version}" end end |
#github_repo_url ⇒ Object
512 513 514 515 516 517 518 519 520 |
# File 'app/models/remote_theme.rb', line 512 def github_repo_url url = remote_url.strip return url if url.match?(GITHUB_REGEXP) if url.match?(GITHUB_SSH_REGEXP) org_repo = url.gsub(GITHUB_SSH_REGEXP, "") "https://github.com/#{org_repo}" end end |
#is_git? ⇒ Boolean
522 523 524 |
# File 'app/models/remote_theme.rb', line 522 def is_git? remote_url.present? end |
#normalize_override(hex) ⇒ Object
455 456 457 458 459 460 461 |
# File 'app/models/remote_theme.rb', line 455 def normalize_override(hex) return unless hex override = hex.downcase override = nil if override !~ /\A[0-9a-f]{6}\z/ override end |
#out_of_date? ⇒ Boolean
203 204 205 |
# File 'app/models/remote_theme.rb', line 203 def out_of_date? commits_behind > 0 || remote_version != local_version end |
#update_from_remote(importer = nil, skip_update: false, raise_if_theme_save_fails: true, already_in_transaction: false, run_migrations: true) ⇒ Object
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
# File 'app/models/remote_theme.rb', line 228 def update_from_remote( importer = nil, skip_update: false, raise_if_theme_save_fails: true, already_in_transaction: false, run_migrations: true ) cleanup = false unless importer cleanup = true importer = ThemeStore::GitImporter.new(remote_url, private_key: private_key, branch: branch) begin importer.import! rescue RemoteTheme::ImportError => err self.last_error_text = err. self.save! return self else self.last_error_text = nil end end theme_info = RemoteTheme.extract_theme_info(importer) updated_fields = [] theme_info["assets"]&.each do |name, relative_path| if path = importer.real_path(relative_path) upload = create_upload(path, relative_path) if !upload.errors.empty? raise ImportError, I18n.t( "themes.import_error.upload", name: name, errors: upload.errors..join(","), ) end updated_fields << theme.set_field( target: :common, name: name, type: :theme_upload_var, upload_id: upload.id, ) end end # TODO (martin): Until we are ready to roll this out more # widely, let's avoid doing this work for most sites. if SiteSetting.theme_download_screenshots theme_info["screenshots"] = Array.wrap(theme_info["screenshots"]).take(2) theme_info["screenshots"].each_with_index do |relative_path, idx| if path = importer.real_path(relative_path) if !THEME_SCREENSHOT_ALLOWED_FILE_TYPES.include?(File.extname(path)) raise ImportError, I18n.t( "themes.import_error.screenshot_invalid_type", file_name: File.basename(path), accepted_formats: THEME_SCREENSHOT_ALLOWED_FILE_TYPES.join(","), ) end if File.size(path) > MAX_THEME_SCREENSHOT_FILE_SIZE raise ImportError, I18n.t( "themes.import_error.screenshot_invalid_size", file_name: File.basename(path), max_size: ActiveSupport::NumberHelper.number_to_human_size( MAX_THEME_SCREENSHOT_FILE_SIZE, ), ) end screenshot_width, screenshot_height = FastImage.size(path) if (screenshot_width.nil? || screenshot_height.nil?) || screenshot_width > MAX_THEME_SCREENSHOT_DIMENSIONS[0] || screenshot_height > MAX_THEME_SCREENSHOT_DIMENSIONS[1] raise ImportError, I18n.t( "themes.import_error.screenshot_invalid_dimensions", file_name: File.basename(path), width: screenshot_width.to_i, height: screenshot_height.to_i, max_width: MAX_THEME_SCREENSHOT_DIMENSIONS[0], max_height: MAX_THEME_SCREENSHOT_DIMENSIONS[1], ) end upload = create_upload(path, relative_path) if !upload.errors.empty? raise ImportError, I18n.t( "themes.import_error.screenshot", errors: upload.errors..join(","), ) end updated_fields << theme.set_field( target: :common, name: "screenshot_#{idx + 1}", type: :theme_screenshot_upload_var, upload_id: upload.id, ) end end end # Update all theme attributes if this is just a placeholder if self.remote_url.present? && !self.local_version && !self.commits_behind self.theme.name = theme_info["name"] self.theme.component = [true, "true"].include?(theme_info["component"]) self.theme.child_components = theme_info["components"].presence || [] end METADATA_PROPERTIES.each do |property| self.public_send(:"#{property}=", theme_info[property.to_s]) end if !self.valid? raise ImportError, I18n.t( "themes.import_error.about_json_values", errors: self.errors..join(","), ) end ThemeModifierSet.modifiers.keys.each do |modifier_name| value = theme_info.dig("modifiers", modifier_name.to_s) if Hash === value && value["type"] == "setting" theme.theme_modifier_set.add_theme_setting_modifier(modifier_name, value["value"]) else theme.theme_modifier_set.public_send(:"#{modifier_name}=", value) end end if !theme.theme_modifier_set.valid? raise ImportError, I18n.t( "themes.import_error.modifier_values", errors: theme.theme_modifier_set.errors..join(","), ) end all_files = importer.all_files if all_files.size > MAX_THEME_FILE_COUNT raise ImportError, I18n.t( "themes.import_error.too_many_files", count: all_files.size, limit: MAX_THEME_FILE_COUNT, ) end theme_size = 0 all_files.each do |filename| next unless opts = ThemeField.opts_from_file_path(filename) file_size = importer.file_size(filename) if file_size > MAX_ASSET_FILE_SIZE raise ImportError, I18n.t( "themes.import_error.asset_too_big", filename: filename, limit: ActiveSupport::NumberHelper.number_to_human_size(MAX_ASSET_FILE_SIZE), ) end theme_size += file_size if theme_size > MAX_THEME_SIZE raise ImportError, I18n.t( "themes.import_error.theme_too_big", limit: ActiveSupport::NumberHelper.number_to_human_size(MAX_THEME_SIZE), ) end value = importer[filename] updated_fields << theme.set_field(**opts.merge(value: value)) end if !skip_update self.remote_updated_at = Time.zone.now self.remote_version = importer.version self.local_version = importer.version self.commits_behind = 0 end transaction_block = ->(*) do # Destroy fields that no longer exist in the remote theme field_ids_to_destroy = theme.theme_fields.pluck(:id) - updated_fields.map { |tf| tf&.id } ThemeField.where(id: field_ids_to_destroy).destroy_all update_theme_color_schemes(theme, theme_info["color_schemes"]) unless theme.component self.save! if raise_if_theme_save_fails theme.save! else raise ActiveRecord::Rollback if !theme.save end theme.migrate_settings(start_transaction: false) if run_migrations end if already_in_transaction transaction_block.call else self.transaction(&transaction_block) end theme.theme_modifier_set.save! if theme.theme_modifier_set.refresh_theme_setting_modifiers self ensure begin importer.cleanup! if cleanup rescue => e Rails.logger.warn("Failed cleanup remote git #{e}") end end |
#update_remote_version ⇒ Object
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'app/models/remote_theme.rb', line 207 def update_remote_version return unless is_git? importer = ThemeStore::GitImporter.new(remote_url, private_key: private_key, branch: branch) begin importer.import! rescue RemoteTheme::ImportError => err self.last_error_text = err. else self.updated_at = Time.zone.now self.remote_version, self.commits_behind = importer.commits_since(local_version) self.last_error_text = nil ensure self.save! begin importer.cleanup! rescue => e Rails.logger.warn("Failed cleanup remote git #{e}") end end end |
#update_theme_color_schemes(theme, schemes) ⇒ Object
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 |
# File 'app/models/remote_theme.rb', line 463 def update_theme_color_schemes(theme, schemes) missing_scheme_names = Hash[*theme.color_schemes.pluck(:name, :id).flatten] ordered_schemes = [] schemes&.each do |name, colors| missing_scheme_names.delete(name) scheme = theme.color_schemes.find_by(name: name) || theme.color_schemes.build(name: name) # Update main colors ColorScheme.base.colors_hashes.each do |color| override = normalize_override(colors[color[:name]]) color_scheme_color = scheme.color_scheme_colors.to_a.find { |c| c.name == color[:name] } || scheme.color_scheme_colors.build(name: color[:name]) color_scheme_color.hex = override || color[:hex] theme.notify_color_change(color_scheme_color) if color_scheme_color.hex_changed? end # Update advanced colors ColorScheme.color_transformation_variables.each do |variable_name| override = normalize_override(colors[variable_name]) color_scheme_color = scheme.color_scheme_colors.to_a.find { |c| c.name == variable_name } if override color_scheme_color ||= scheme.color_scheme_colors.build(name: variable_name) color_scheme_color.hex = override theme.notify_color_change(color_scheme_color) if color_scheme_color.hex_changed? elsif color_scheme_color # No longer specified in about.json, delete record scheme.color_scheme_colors.delete(color_scheme_color) theme.notify_color_change(nil, scheme: scheme) end end ordered_schemes << scheme end if missing_scheme_names.length > 0 ColorScheme.where(id: missing_scheme_names.values).delete_all # we may have stuff pointed at the incorrect scheme? end theme.color_scheme = ordered_schemes.first if theme.new_record? end |