2020-06-30 08:08:57 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class CustomEmoji < ApplicationRecord
|
2021-02-05 10:09:28 -05:00
|
|
|
NAME_REGEXP = /[a-z0-9_-]+/.freeze
|
|
|
|
|
2020-06-30 08:08:57 -04:00
|
|
|
belongs_to :namespace, inverse_of: :custom_emoji
|
|
|
|
|
2021-09-22 08:12:04 -04:00
|
|
|
belongs_to :group, -> { where(type: Group.sti_name) }, foreign_key: 'namespace_id'
|
2021-02-21 22:10:36 -05:00
|
|
|
belongs_to :creator, class_name: "User", inverse_of: :created_custom_emoji
|
2020-11-16 16:09:02 -05:00
|
|
|
|
|
|
|
# For now only external emoji are supported. See https://gitlab.com/gitlab-org/gitlab/-/issues/230467
|
|
|
|
validates :external, inclusion: { in: [true] }
|
|
|
|
|
|
|
|
validates :file, public_url: true, if: :external
|
|
|
|
|
2020-06-30 08:08:57 -04:00
|
|
|
validate :valid_emoji_name
|
|
|
|
|
2020-11-16 16:09:02 -05:00
|
|
|
validates :group, presence: true
|
2021-02-21 22:10:36 -05:00
|
|
|
validates :creator, presence: true
|
2020-06-30 08:08:57 -04:00
|
|
|
validates :name,
|
|
|
|
uniqueness: { scope: [:namespace_id, :name] },
|
|
|
|
presence: true,
|
|
|
|
length: { maximum: 36 },
|
2021-02-05 10:09:28 -05:00
|
|
|
|
2022-08-01 02:12:25 -04:00
|
|
|
format: { with: /\A#{NAME_REGEXP}\z/o }
|
2021-02-05 10:09:28 -05:00
|
|
|
|
|
|
|
scope :by_name, -> (names) { where(name: names) }
|
|
|
|
|
|
|
|
alias_attribute :url, :file # this might need a change in https://gitlab.com/gitlab-org/gitlab/-/issues/230467
|
2020-06-30 08:08:57 -04:00
|
|
|
|
2022-04-19 11:08:32 -04:00
|
|
|
# Find custom emoji for the given resource.
|
|
|
|
# A resource can be either a Project or a Group, or anything responding to #root_ancestor.
|
|
|
|
# Usually it's the return value of #resource_parent on any model.
|
|
|
|
scope :for_resource, -> (resource) do
|
|
|
|
return none if resource.nil?
|
|
|
|
|
|
|
|
namespace = resource.root_ancestor
|
|
|
|
|
|
|
|
return none if namespace.nil? || Feature.disabled?(:custom_emoji, namespace)
|
|
|
|
|
|
|
|
namespace.custom_emoji
|
|
|
|
end
|
|
|
|
|
2020-06-30 08:08:57 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def valid_emoji_name
|
2021-10-19 17:12:08 -04:00
|
|
|
if TanukiEmoji.find_by_alpha_code(name)
|
2020-06-30 08:08:57 -04:00
|
|
|
errors.add(:name, _('%{name} is already being used for another emoji') % { name: self.name })
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|