2017-07-13 08:32:11 -04:00
|
|
|
class DiscourseChat::Channel < DiscourseChat::PluginModel
|
|
|
|
KEY_PREFIX = 'channel:'
|
|
|
|
|
|
|
|
# Setup ActiveRecord::Store to use the JSON field to read/write these values
|
2017-07-13 15:50:45 -04:00
|
|
|
store :value, accessors: [ :provider, :data ], coder: JSON
|
2017-07-13 11:09:34 -04:00
|
|
|
|
2017-07-13 15:50:45 -04:00
|
|
|
after_initialize :init_data
|
2017-07-13 11:09:34 -04:00
|
|
|
|
2017-07-13 15:50:45 -04:00
|
|
|
def init_data
|
|
|
|
self.data = {} if self.data.nil?
|
|
|
|
end
|
|
|
|
|
|
|
|
validate :provider_valid?, :data_valid?
|
|
|
|
|
|
|
|
def provider_valid?
|
2017-07-13 11:09:34 -04:00
|
|
|
# Validate provider
|
|
|
|
if not ::DiscourseChat::Provider.provider_names.include? provider
|
|
|
|
errors.add(:provider, "#{provider} is not a valid provider")
|
|
|
|
return
|
|
|
|
end
|
2017-07-13 15:50:45 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def data_valid?
|
|
|
|
# If provider is invalid, don't try and check data
|
|
|
|
return unless ::DiscourseChat::Provider.provider_names.include? provider
|
|
|
|
|
|
|
|
params = ::DiscourseChat::Provider.get_by_name(provider)::CHANNEL_PARAMETERS
|
|
|
|
|
|
|
|
unless params.keys.sort == data.keys.sort
|
|
|
|
errors.add(:data, "data does not match the required structure for provider #{provider}")
|
2017-07-13 11:09:34 -04:00
|
|
|
return
|
|
|
|
end
|
|
|
|
|
2017-07-13 15:50:45 -04:00
|
|
|
data.each do |key, value|
|
|
|
|
regex_string = params[key]
|
|
|
|
if !Regexp.new(regex_string).match?(value)
|
|
|
|
errors.add(:data, "data.#{key} is invalid")
|
2017-07-13 11:09:34 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def rules
|
|
|
|
DiscourseChat::Rule.with_channel_id(id)
|
|
|
|
end
|
|
|
|
|
|
|
|
scope :with_provider, ->(provider) { where("value::json->>'provider'=?", provider)}
|
2017-07-13 08:32:11 -04:00
|
|
|
|
2017-07-13 17:50:14 -04:00
|
|
|
scope :with_data_value, ->(key, value) { where("(value::json->>'data')::json->>?=?", key, value)}
|
|
|
|
|
2017-07-13 08:32:11 -04:00
|
|
|
end
|