A platform for community discussion. Free, open, simple.
FIX: Validate event markup against the attributes that persist
Régis Hanol35bde6fca5cf
diff --git a/plugins/discourse-events/app/models/discourse_events/events/event.rb b/plugins/discourse-events/app/models/discourse_events/events/event.rbindex b5c60994565..7c3d45d275f 100644--- a/plugins/discourse-events/app/models/discourse_events/events/event.rb+++ b/plugins/discourse-events/app/models/discourse_events/events/event.rb@@ -12,7 +12,15 @@ module DiscourseEventsMAX_NAME_LENGTH = 255MAX_DESCRIPTION_LENGTH = 1000MAX_HOSTS = 10+ MAX_LOCATION_LENGTH = 1000+ MAX_URL_LENGTH = 1000+ MAX_RAW_INVITEES = 10+ MAX_ATTENDEES_LIMIT = 2_147_483_647+ DEFAULT_DURATION_SECONDS = 3600DEFAULT_TIMEZONE = "UTC"+ NOTIFICATION_REMINDER = "notification"+ BUMP_TOPIC_REMINDER = "bumpTopic"+ REMINDER_TYPES = [NOTIFICATION_REMINDER, BUMP_TOPIC_REMINDER]self.table_name = "discourse_post_event_events"self.ignored_columns = %w[starts_at ends_at]@@ -53,10 +61,13 @@ module DiscourseEvents},unless: ->(event) { event.name.blank? }validates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }+ validates :location, length: { maximum: MAX_LOCATION_LENGTH }+ validates :url, length: { maximum: MAX_URL_LENGTH }validates :max_attendees,numericality: {only_integer: true,greater_than: 0,+ less_than_or_equal_to: MAX_ATTENDEES_LIMIT,allow_nil: true,}@@ -121,25 +132,16 @@ module DiscourseEventsenddef destroy_topic_custom_field- if post && post.is_first_post?- TopicCustomField.where(- topic_id: post.topic_id,- name: TOPIC_POST_EVENT_STARTS_AT,- ).delete_all+ return if !post&.is_first_post?- TopicCustomField.where(topic_id: post.topic_id, name: TOPIC_POST_EVENT_ENDS_AT).delete_all-- TopicCustomField.where(topic_id: post.topic_id, name: TOPIC_POST_EVENT_ALL_DAY).delete_all- end+ TopicCustomField.where(+ topic_id: post.topic_id,+ name: [TOPIC_POST_EVENT_STARTS_AT, TOPIC_POST_EVENT_ENDS_AT, TOPIC_POST_EVENT_ALL_DAY],+ ).delete_allenddef create_or_update_event_date- starts_at_changed = saved_change_to_original_starts_at- ends_at_changed = saved_change_to_original_ends_at-- return if !starts_at_changed && !ends_at_changed-- set_next_date+ set_next_date if dates_changed?enddef set_next_date@@ -160,31 +162,50 @@ module DiscourseEventsdef set_topic_bumpreturn if closed- date = nil+ bump = parsed_reminders.find { |reminder| reminder[:type] == BUMP_TOPIC_REMINDER }+ return if bump.nil?++ bump_from = starts_at+ return if bump_from.nil?++ date = bump_from - Event.reminder_offset(bump)+ Jobs.enqueue(:discourse_post_event_bump_topic, topic_id: post.topic_id, date: date.iso8601)+ end- return if reminders.blank? || starts_at.nil?+ def parsed_remindersreminders+ .to_s.split(",")- .each do |reminder|- type, value, unit = reminder.split(".")- next if type != "bumpTopic" || !validate_reminder_unit(unit)- date = starts_at - value.to_i.public_send(unit)- break+ .filter_map do |reminder|+ unit, value, type = Event.split_reminder(reminder)+ next if !Event.valid_reminder_unit?(unit)++ { type: type.presence || NOTIFICATION_REMINDER, value: value.to_i, unit: unit }end+ end- return if date.blank?- Jobs.enqueue(:discourse_post_event_bump_topic, topic_id: post.topic_id, date: date.iso8601)+ def self.split_reminder(reminder)+ parts = reminder.strip.split(".")+ parts.reverse if parts.size.between?(2, 3)+ end++ def self.reminder_offset(reminder)+ reminder[:value].public_send(reminder[:unit])end- def validate_reminder_unit(input)- ActiveSupport::Duration::PARTS.any? { |part| part.to_s == input }+ def self.valid_reminder_unit?(unit)+ ActiveSupport::Duration::PARTS.any? { |part| part.to_s == unit }+ end++ def self.valid_reminder?(reminder)+ unit, value, type = split_reminder(reminder)++ valid_reminder_unit?(unit) && value.match?(/\A[+-]?\d+\z/) &&+ (type.nil? || REMINDER_TYPES.include?(type))enddef expired?- if recurring?- return false if recurrence_until.nil?- return Time.current > recurrence_until- end+ return recurrence_expired? if recurring?return true if starts_at.nil?(ends_at || starts_at.end_of_day) <= Time.now@@ -209,12 +230,12 @@ module DiscourseEventsenddef starts_at- return nil if recurring? && recurrence_until.present? && recurrence_until < Time.current+ return nil if recurring? && recurrence_expired?current_event_date&.starts_at || original_starts_atenddef ends_at- return nil if recurring? && recurrence_until.present? && recurrence_until < Time.current+ return nil if recurring? && recurrence_expired?current_event_date&.ends_at || original_ends_atend@@ -243,10 +264,13 @@ module DiscourseEventsenddef raw_invitees_length- if raw_invitees && raw_invitees.length > 10+ if raw_invitees && raw_invitees.length > MAX_RAW_INVITEESerrors.add(:base,- I18n.t("discourse_post_event.errors.models.event.raw_invitees_length", count: 10),+ I18n.t(+ "discourse_post_event.errors.models.event.raw_invitees_length",+ count: MAX_RAW_INVITEES,+ ),)endend@@ -385,6 +409,10 @@ module DiscourseEvents@statuses ||= Enum.new(standalone: 0, public: 1, private: 2)end+ def self.resolve_status(raw_status, fallback)+ statuses[raw_status&.to_sym] || fallback+ end+def public?status == Event.statuses[:public]end@@ -402,16 +430,15 @@ module DiscourseEventsenddef most_likely_going(limit = SiteSetting.displayed_invitees_limit)- going = invitees.order(%i[status created_at user_id]).limit(limit)+ going = invitees.order(%i[status created_at user_id]).limit(limit).to_a- if private? && going.count < limit+ if private? && going.size < limit# invitees are only created when an attendance is set# so we create a dummy invitee object with only what's needed for serializer- going =- going +- missing_users(going.pluck(:user_id))- .limit(limit - going.count)- .map { |user| Invitee.new(user: user, post_id: id) }+ going +=+ missing_users(going.map(&:user_id))+ .limit(limit - going.size)+ .map { |user| Invitee.new(user: user, post_id: id) }endgoing@@ -501,13 +528,10 @@ module DiscourseEventsenddef self.handle_post_event_webhooks(post, event_before)- had_event_before = event_before.present?-- if post.event && had_event_before- WebHook.enqueue_calendar_event_hooks(:calendar_event_updated, post.event)- elsif post.event && !had_event_before- WebHook.enqueue_calendar_event_hooks(:calendar_event_created, post.event)- elsif !post.event && had_event_before+ if post.event+ hook = event_before ? :calendar_event_updated : :calendar_event_created+ WebHook.enqueue_calendar_event_hooks(hook, post.event)+ elsif event_beforepayload = WebHook.build_calendar_event_payload(event_before)WebHook.enqueue_calendar_event_hooks(:calendar_event_destroyed, event_before, payload)end@@ -554,23 +578,11 @@ module DiscourseEventsenddef update_with_params!(params)- case params[:status] ? params[:status].to_i : status- when Event.statuses[:private]- if params.key?(:raw_invitees)- params = params.merge(raw_invitees: Array(params[:raw_invitees]) - [PUBLIC_GROUP])- else- params = params.merge(raw_invitees: Array(raw_invitees) - [PUBLIC_GROUP])- end- update!(params)- enforce_private_invitees!- when Event.statuses[:public]- update!(params.merge(raw_invitees: [PUBLIC_GROUP]))- when Event.statuses[:standalone]- update!(params.merge(raw_invitees: []))- invitees.destroy_all- end+ apply_params_for_status(params) { update!(it) }+ end- publish_update!+ def update_with_params(params)+ apply_params_for_status(params) { update(it) }enddef chat_channel_sync@@ -590,15 +602,7 @@ module DiscourseEventsnext_starts_at = calculate_next_recurring_datereturn nil unless next_starts_at- next_ends_at =- if original_ends_at- next_starts_at + (original_ends_at - original_starts_at)- elsif all_day- next_starts_at.end_of_day- else- next_starts_at + 3600- end- [next_starts_at, next_ends_at]+ [next_starts_at, derive_next_ends_at(next_starts_at)]enddef calculate_next_occurrence_from(from_time)@@ -610,21 +614,14 @@ module DiscourseEventsnext_starts_at = calculate_next_recurring_date_from(from_time)return nil unless next_starts_at- next_ends_at =- if original_ends_at- next_starts_at + (original_ends_at - original_starts_at)- elsif all_day- next_starts_at.end_of_day- else- next_starts_at + 3600- end- { starts_at: next_starts_at, ends_at: next_ends_at }+ { starts_at: next_starts_at, ends_at: derive_next_ends_at(next_starts_at) }enddef durationreturn nil unless original_starts_at- duration_seconds = original_ends_at ? original_ends_at - original_starts_at : 3600+ duration_seconds =+ original_ends_at ? original_ends_at - original_starts_at : DEFAULT_DURATION_SECONDShours = (duration_seconds / 3600)minutes = ((duration_seconds % 3600) / 60)seconds = (duration_seconds % 60)@@ -682,6 +679,26 @@ module DiscourseEventsassociation(:event_hosts).resetend+ def apply_params_for_status(params)+ case params[:status] ? params[:status].to_i : status+ when Event.statuses[:private]+ params =+ params.merge(+ raw_invitees: Array(params.fetch(:raw_invitees, raw_invitees)) - [PUBLIC_GROUP],+ )+ return self if !yield(params)+ enforce_private_invitees!+ when Event.statuses[:public]+ return self if !yield(params.merge(raw_invitees: [PUBLIC_GROUP]))+ when Event.statuses[:standalone]+ return self if !yield(params.merge(raw_invitees: []))+ invitees.destroy_all+ end++ publish_update!+ self+ end+def reset_invitees_topic_trackingtopic_id = post&.topic_idreturn if topic_id.nil?@@ -693,6 +710,20 @@ module DiscourseEventssaved_change_to_original_starts_at || saved_change_to_original_ends_atend+ def recurrence_expired?+ recurrence_until.present? && recurrence_until < Time.current+ end++ def derive_next_ends_at(next_starts_at)+ if original_ends_at+ next_starts_at + (original_ends_at - original_starts_at)+ elsif all_day+ next_starts_at.end_of_day+ else+ next_starts_at + DEFAULT_DURATION_SECONDS+ end+ end+def finish_previous_event_dates(current_starts_at)existing_date = event_dates.find_by(starts_at: current_starts_at)event_datesdiff --git a/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rbindex 92abbd4a301..ae4e60acc2f 100644--- a/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb+++ b/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb@@ -101,20 +101,14 @@ module DiscourseEventsenddef reminders- (object.reminders || "")- .split(",")- .map do |reminder|- unit, value, type = reminder.split(".").reverse- type ||= "notification"-- value = value.to_i- {- value: value.to_i.abs,- unit: unit,- period: value > 0 ? "before" : "after",- type: type,- }- end+ object.parsed_reminders.map do |reminder|+ {+ value: reminder[:value].abs,+ unit: reminder[:unit],+ period: reminder[:value] > 0 ? "before" : "after",+ type: reminder[:type],+ }+ endenddef is_expireddiff --git a/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rb b/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rbindex d2c346b2ddd..6dc476c42f8 100644--- a/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rb+++ b/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rb@@ -16,12 +16,12 @@ module DiscourseEventsdescription: raw_event[:description],location: raw_event[:location],recurrence: raw_event[:recurrence],- recurrence_until: parse_in_zone(raw_event[:"recurrence-until"]),+ recurrence_until:,timezone: raw_event[:timezone],show_local_time: raw_event[:"show-local-time"] == "true",- status: Event.statuses[raw_event[:status]&.to_sym] || current_status,+ status:,reminders: raw_event[:reminders],- raw_invitees: raw_event[:"allowed-groups"]&.split(","),+ raw_invitees:,minimal: raw_event[:minimal],closed: raw_event[:closed] || false,chat_enabled: raw_event[:"chat-enabled"]&.downcase == "true",@@ -33,6 +33,28 @@ module DiscourseEvents}end+ def starts_at+ return timezone.parse(raw_event[:start]) unless all_day?+ all_day_date(raw_event[:start])+ end++ def ends_at+ return parse_in_zone(raw_event[:end]) unless all_day?+ raw_event[:end] ? all_day_date(raw_event[:end]).end_of_day : nil+ end++ def recurrence_until+ parse_in_zone(raw_event[:"recurrence-until"])+ end++ def status+ Event.resolve_status(raw_event[:status], current_status)+ end++ def raw_invitees+ raw_event[:"allowed-groups"]&.split(",")+ end+private# Unknown usernames are dropped rather than rejected here; the validator@@ -54,21 +76,15 @@ module DiscourseEventsenddef timezone- ActiveSupport::TimeZone[raw_event[:timezone] || Event::DEFAULT_TIMEZONE]+ ActiveSupport::TimeZone[raw_event[:timezone].presence || Event::DEFAULT_TIMEZONE]enddef parse_in_zone(value)value ? timezone.parse(value) : nilend- def starts_at- return timezone.parse(raw_event[:start]) unless all_day?- Time.utc(*raw_event[:start].split("-").map(&:to_i))- end-- def ends_at- return parse_in_zone(raw_event[:end]) unless all_day?- raw_event[:end] ? Time.utc(*raw_event[:end].split("-").map(&:to_i)).end_of_day : nil+ def all_day_date(value)+ Date.parse(value).to_time(:utc)enddef custom_fieldsdiff --git a/plugins/discourse-events/app/services/discourse_events/events/event/sync_from_post.rb b/plugins/discourse-events/app/services/discourse_events/events/event/sync_from_post.rbindex 3d72c908d1d..8f03dfe6851 100644--- a/plugins/discourse-events/app/services/discourse_events/events/event/sync_from_post.rb+++ b/plugins/discourse-events/app/services/discourse_events/events/event/sync_from_post.rb@@ -54,8 +54,7 @@ module DiscourseEventsimage: raw_event[:image],post:,)&.id- event.update_with_params!(attributes)- event+ event.update_with_params(attributes)enddef schedule_topic_bump(event:)diff --git a/plugins/discourse-events/config/locales/server.en.yml b/plugins/discourse-events/config/locales/server.en.ymlindex 85b9c8c6b25..b56a5e51a41 100644--- a/plugins/discourse-events/config/locales/server.en.yml+++ b/plugins/discourse-events/config/locales/server.en.yml@@ -144,11 +144,14 @@ en:raw_invitees_length: "An event is limited to %{count} users/groups."raw_invitees:only_group: "An event accepts only group names."- ends_at_before_starts_at: "An event can't end before it starts."+ ends_at_before_starts_at: "An event must end after it starts."max_attendees_reached: "This event is full."start_must_be_present_and_a_valid_date: "An event requires a valid start date."end_must_be_a_valid_date: "End date must be a valid date."- invalid_recurrence: "Recurrence must be one of: every_month, every_week, every_two_weeks, every_four_weeks, every_day, every_weekday."+ recurrence_until_must_be_a_valid_date: "Recurrence end date must be a valid date."+ invalid_max_attendees: "Max attendees must be a number between 1 and %{maximum}."+ invalid_reminders: "Invalid reminders: %{reminders}."+ invalid_recurrence: "Recurrence must be one of: %{recurrences}."invalid_timezone: "Timezone not recognized."invalid_url: "URL must be a valid web address."acting_user_not_allowed_to_create_event: "Current user is not allowed to create events."@@ -162,6 +165,12 @@ en:custom_field_is_invalid: "The custom field `%{field}` is not allowed."name:length: "Event name length must be between %{minimum} and %{maximum} characters."+ description:+ length: "Event description is limited to %{maximum} characters."+ url:+ length: "Event URL is limited to %{maximum} characters."+ location:+ length: "Event location is limited to %{maximum} characters."discourse_push_notifications:popup:event_reminder: "Event Reminder"diff --git a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rbindex 9597e7bd5ee..e6b1456db61 100644--- a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb+++ b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb@@ -56,31 +56,22 @@ module Jobsenddef due_reminders(event_date)- return [] if event_date.event.reminders.blank?event_date.event- .reminders- .split(",")+ .parsed_reminders+ .reject do |reminder|+ reminder[:type] == DiscourseEvents::Events::Event::BUMP_TOPIC_REMINDER+ end.map do |reminder|- unit, value, type = reminder.split(".").reverse-- next if type === "bumpTopic" || !validate_reminder_unit(unit)- reminder = "notification.#{value}.#{unit}" if type.blank?-- date = event_date.starts_at - value.to_i.public_send(unit)- { description: reminder, date: date }+ {+ description: "#{reminder[:type]}.#{reminder[:value]}.#{reminder[:unit]}",+ date: event_date.starts_at - DiscourseEvents::Events::Event.reminder_offset(reminder),+ }end- .compact.select { |reminder| reminder[:date] <= Time.current }.sort_by { |reminder| reminder[:date] }.drop(event_date.reminder_counter)end-- private-- def validate_reminder_unit(input)- ActiveSupport::Duration::PARTS.any? { |part| part.to_s == input }- endendendenddiff --git a/plugins/discourse-events/lib/discourse_events/events/email_renderer.rb b/plugins/discourse-events/lib/discourse_events/events/email_renderer.rbindex c39ecff3285..f558ab6fae8 100644--- a/plugins/discourse-events/lib/discourse_events/events/email_renderer.rb+++ b/plugins/discourse-events/lib/discourse_events/events/email_renderer.rb@@ -180,7 +180,7 @@ module DiscourseEventsdef recurrence_labelrecurrence = @event&.recurrence- return nil if recurrence.blank? || Validator::VALID_RECURRENCES.exclude?(recurrence)+ return nil if recurrence.blank? || RRuleConfigurator::RECURRENCES.exclude?(recurrence)card_t("builder_modal.recurrence.#{recurrence}", **recurrence_context)rescue StandardErrordiff --git a/plugins/discourse-events/lib/discourse_events/events/rrule_configurator.rb b/plugins/discourse-events/lib/discourse_events/events/rrule_configurator.rbindex 82f81666d9a..ac7b7b37215 100644--- a/plugins/discourse-events/lib/discourse_events/events/rrule_configurator.rb+++ b/plugins/discourse-events/lib/discourse_events/events/rrule_configurator.rb@@ -3,6 +3,15 @@module DiscourseEventsmodule Eventsclass RRuleConfigurator+ RECURRENCES = %w[+ every_month+ every_week+ every_two_weeks+ every_four_weeks+ every_day+ every_weekday+ ]+def self.rule(recurrence:, starts_at:, recurrence_until: nil)rule =case recurrencediff --git a/plugins/discourse-events/lib/discourse_events/events/validator.rb b/plugins/discourse-events/lib/discourse_events/events/validator.rbindex 0290ad9827e..8cb48752223 100644--- a/plugins/discourse-events/lib/discourse_events/events/validator.rb+++ b/plugins/discourse-events/lib/discourse_events/events/validator.rb@@ -3,168 +3,142 @@module DiscourseEventsmodule Eventsclass Validator- VALID_RECURRENCES = %w[- every_month- every_week- every_two_weeks- every_four_weeks- every_day- every_weekday- ]+ MAX_LENGTHS = {+ description: Event::MAX_DESCRIPTION_LENGTH,+ url: Event::MAX_URL_LENGTH,+ location: Event::MAX_LOCATION_LENGTH,+ }def initialize(post)@post = postenddef validate_event- extracted_events = DiscourseEvents::Events::Parser.extract_events(@post)+ extracted_events = Parser.extract_events(@post)- return false if extracted_events.count == 0+ return if extracted_events.empty?- if extracted_events.count > 1- @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.only_one_event"))- return false+ if extracted_events.size > 1+ add_error("only_one_event")+ returnendif [email protected]_first_post?- @post.errors.add(- :base,- I18n.t("discourse_post_event.errors.models.event.must_be_in_first_post"),- )- return false+ add_error("must_be_in_first_post")+ returnendextracted_event = extracted_events.first+ attributes =+ Event::Action::AttributesFromRaw.new(+ raw_event: extracted_event,+ current_status: @post.event&.status || Event.statuses[:standalone],+ )++ group_names = attributes.raw_invitees.to_a+ invitees = group_names - [Event::PUBLIC_GROUP]- return false unless can_invite_groups?(extracted_event)- return false unless valid_hosts?(extracted_event)+ if attributes.status == Event.statuses[:private] && invitees.size > Event::MAX_RAW_INVITEES+ add_error("raw_invitees_length", count: Event::MAX_RAW_INVITEES)+ return+ end++ return unless can_invite_groups?(group_names)+ return unless valid_hosts?(extracted_event)if @post.acting_user && @post.eventif [email protected]_user.guardian.can_act_on_discourse_post_event?(@post.event)- @post.errors.add(- :base,- I18n.t(- "discourse_post_event.errors.models.event.acting_user_not_allowed_to_act_on_this_event",- ),- )- return false+ add_error("acting_user_not_allowed_to_act_on_this_event")+ returnendelseif [email protected]_user.guardian.can_create_discourse_post_event?- @post.errors.add(- :base,- I18n.t(- "discourse_post_event.errors.models.event.acting_user_not_allowed_to_create_event",- ),- )- return false+ add_error("acting_user_not_allowed_to_create_event")+ returnendend- if extracted_event[:start].blank? ||- (- begin- DateTime.parse(extracted_event[:start])- rescue StandardError- nil- end- ).nil?- @post.errors.add(- :base,- I18n.t(- "discourse_post_event.errors.models.event.start_must_be_present_and_a_valid_date",- ),- )- return false+ if extracted_event[:timezone].present? &&+ ActiveSupport::TimeZone[extracted_event[:timezone]].nil?+ add_error("invalid_timezone", timezone: extracted_event[:timezone])+ returnend- if extracted_event[:end].present? &&- (- begin- DateTime.parse(extracted_event[:end])- rescue StandardError- nil- end- ).nil?- @post.errors.add(- :base,- I18n.t("discourse_post_event.errors.models.event.end_must_be_a_valid_date"),- )- return false+ starts_at = parse_date { attributes.starts_at }++ if starts_at.nil?+ add_error("start_must_be_present_and_a_valid_date")+ returnend- if extracted_event[:start].present? && extracted_event[:end].present?- if Time.parse(extracted_event[:start]) > Time.parse(extracted_event[:end])- @post.errors.add(- :base,- I18n.t("discourse_post_event.errors.models.event.ends_at_before_starts_at"),- )- return false- end+ ends_at = parse_date { attributes.ends_at }++ if extracted_event[:end].present? && ends_at.nil?+ add_error("end_must_be_a_valid_date")+ returnend- if extracted_event[:name].present?- if !(Event::MIN_NAME_LENGTH..Event::MAX_NAME_LENGTH).cover?(extracted_event[:name].length)- @post.errors.add(- :base,- I18n.t(- "discourse_post_event.errors.models.event.name.length",- minimum: Event::MIN_NAME_LENGTH,- maximum: Event::MAX_NAME_LENGTH,- ),- )- return false- end+ if ends_at && ends_at <= starts_at+ add_error("ends_at_before_starts_at")+ returnend- if extracted_event[:recurrence].present?- if !VALID_RECURRENCES.include?(extracted_event[:recurrence].to_s)- @post.errors.add(- :base,- I18n.t("discourse_post_event.errors.models.event.invalid_recurrence"),- )+ if extracted_event[:name].present? &&+ !(Event::MIN_NAME_LENGTH..Event::MAX_NAME_LENGTH).cover?(extracted_event[:name].length)+ add_error("name.length", minimum: Event::MIN_NAME_LENGTH, maximum: Event::MAX_NAME_LENGTH)+ return+ end++ MAX_LENGTHS.each do |field, maximum|+ if extracted_event[field].present? && extracted_event[field].length > maximum+ add_error("#{field}.length", maximum:)endend- if extracted_event[:timezone].present?- if !ActiveSupport::TimeZone[extracted_event[:timezone]].present?- @post.errors.add(- :base,- I18n.t(- "discourse_post_event.errors.models.event.invalid_timezone",- timezone: extracted_event[:timezone],- ),- )+ if extracted_event[:"max-attendees"].present? &&+ !extracted_event[:"max-attendees"].to_i.between?(1, Event::MAX_ATTENDEES_LIMIT)+ add_error("invalid_max_attendees", maximum: Event::MAX_ATTENDEES_LIMIT)+ end++ if extracted_event[:"recurrence-until"].present? &&+ parse_date { attributes.recurrence_until }.nil?+ add_error("recurrence_until_must_be_a_valid_date")+ end++ if extracted_event[:reminders].present?+ invalid_reminders =+ extracted_event[:reminders].split(",").reject { |r| Event.valid_reminder?(r) }+ if invalid_reminders.any?+ add_error("invalid_reminders", reminders: invalid_reminders.join(", "))endend- if !Parser.valid_url?(extracted_event[:url])- @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.invalid_url"))+ if extracted_event[:recurrence].present? &&+ !RRuleConfigurator::RECURRENCES.include?(extracted_event[:recurrence].to_s)+ add_error("invalid_recurrence", recurrences: RRuleConfigurator::RECURRENCES.join(", "))end- true+ add_error("invalid_url") if !Parser.valid_url?(extracted_event[:url])endprivate+ def add_error(key, **args)+ @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.#{key}", **args))+ end+def valid_hosts?(event)usernames = extract_hosts(event)return true if usernames.empty?if usernames.length > Event::MAX_HOSTS- @post.errors.add(- :base,- I18n.t(- "discourse_post_event.errors.models.event.too_many_hosts",- count: Event::MAX_HOSTS,- ),- )+ add_error("too_many_hosts", count: Event::MAX_HOSTS)return falseendhosts = User.human_users.where(username_lower: usernames).to_aif hosts.length != usernames.length- @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.invalid_hosts"))+ add_error("invalid_hosts")return falseend@@ -176,7 +150,7 @@ module DiscourseEventsreturn true if added.all? { |host| eligible_host?(host) }- @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.invalid_hosts"))+ add_error("invalid_hosts")falseend@@ -198,38 +172,32 @@ module DiscourseEvents.uniqend- def can_invite_groups?(event)- return true unless event[:"allowed-groups"]+ def parse_date+ yield+ rescue StandardError+ nil+ end- event[:"allowed-groups"]- .split(",")- .each do |group_name|- group =- begin- Group.lookup_group(group_name.to_sym)- rescue ArgumentError- nil- end-- if !group || [email protected]_user.guardian.can_see_group?(group)- @post.errors.add(- :base,- I18n.t("discourse_post_event.errors.models.event.invalid_allowed_groups"),- )- return false+ def can_invite_groups?(group_names)+ group_names.each do |group_name|+ group =+ begin+ Group.lookup_group(group_name.to_sym)+ rescue ArgumentError+ nilend- if [email protected]_user.guardian.can_see_group_members?(group)- @post.errors.add(- :base,- I18n.t(- "discourse_post_event.errors.models.event.acting_user_not_allowed_to_invite_these_groups",- ),- )- return false- end+ if !group || [email protected]_user.guardian.can_see_group?(group)+ add_error("invalid_allowed_groups")+ return falseend+ if [email protected]_user.guardian.can_see_group_members?(group)+ add_error("acting_user_not_allowed_to_invite_these_groups")+ return false+ end+ end+trueendenddiff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rbindex 7d1f2ef43b4..99ad7a1419b 100644--- a/plugins/discourse-events/plugin.rb+++ b/plugins/discourse-events/plugin.rb@@ -432,19 +432,26 @@ after_initialize doendend- on(:post_created) do |post|- DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })+ sync_event_from_post = ->(post) do+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id }) do |result|+ on_failure do+ Rails.logger.error("Failed to sync event from post #{post.id}: #{result.inspect_steps}")+ end+ endpost.association(:event).reload- if SiteSetting.discourse_post_event_enabled && post.event- WebHook.enqueue_calendar_event_hooks(:calendar_event_created, post.event)+ end++ on(:post_created) do |post|+ sync_event_from_post.call(post)+ if SiteSetting.discourse_post_event_enabled+ DiscourseEvents::Events::Event.handle_post_event_webhooks(post, nil)endendon(:post_edited) do |post|event_before = post.eventhad_image_before = event_before&.image_upload_id.present?- DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })- post.association(:event).reload+ sync_event_from_post.call(post)if SiteSetting.discourse_post_event_enabledif post.event&.image_upload_iddiff --git a/plugins/discourse-events/spec/integration/post_spec.rb b/plugins/discourse-events/spec/integration/post_spec.rbindex 5171b2fbbbb..5e0f11cc451 100644--- a/plugins/discourse-events/spec/integration/post_spec.rb+++ b/plugins/discourse-events/spec/integration/post_spec.rb@@ -10,7 +10,7 @@ describe Post doSiteSetting.discourse_post_event_enabled = trueend- let(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }+ fab!(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }context "with a public event" dolet(:post_1) { Fabricate(:post) }@@ -240,9 +240,6 @@ describe Post dopost = create_post_with_event(user, 'status="private"').reloadexpect(post.event.raw_invitees).to eq([])-- post = create_post_with_event(user, 'status="private"').reload- expect(post.event.raw_invitees).to eq([])endit "works with localised automatic group names" do@@ -284,6 +281,21 @@ describe Post doexpect(post.event.custom_fields["baz"]).to eq(nil)endend++ it "creates a one-day all-day event with the same start and end date" do+ date = 1.day.from_now.strftime("%Y-%m-%d")++ post =+ PostCreator.create!(+ user,+ title: "Sell a boat party",+ raw: "[event allDay=\"true\" start=\"#{date}\" end=\"#{date}\"]\n[/event]",+ )++ event = post.reload.event+ expect(event.persisted?).to eq(true)+ expect(event.original_ends_at).to eq_time(Time.parse("#{date} 23:59:59.999999 UTC"))+ endendcontext "when the acting user has rights to create events" do@@ -356,7 +368,10 @@ describe Post docontext "when recurrence is invalid" doit "raises an error" doexpect { create_post_with_event(user, 'recurrence="foo"') }.to raise_error(- I18n.t("discourse_post_event.errors.models.event.invalid_recurrence"),+ I18n.t(+ "discourse_post_event.errors.models.event.invalid_recurrence",+ recurrences: DiscourseEvents::Events::RRuleConfigurator::RECURRENCES.join(", "),+ ),)endend@@ -387,6 +402,185 @@ describe Post do)endend++ context "when end is not after start" do+ let(:starts_at) { 1.day.from_now }++ def expect_rejected_end(ends_at)+ expect do+ create_post_with_event(user, "end=\"#{ends_at.utc.iso8601(3)}\"", starts_at)+ end.to(+ raise_error(ActiveRecord::RecordNotSaved).with_message(+ I18n.t("discourse_post_event.errors.models.event.ends_at_before_starts_at"),+ ),+ )+ end++ it "raises an error" do+ expect_rejected_end(starts_at)+ expect_rejected_end(starts_at - 1.hour)+ end+ end++ context "when dates omit an offset" do+ it "validates them in the event timezone" do+ post =+ PostCreator.create!(+ user,+ title: "Sell a boat party",+ raw:+ "[event start=\"2026-06-10T18:00:00-04:00\" end=\"2026-06-10 19:00\" timezone=\"America/New_York\"]\n[/event]",+ )++ event = post.reload.event+ expect(event.persisted?).to eq(true)+ expect(event.original_ends_at).to eq_time(Time.parse("2026-06-10 23:00 UTC"))+ end+ end++ context "when description is too long" do+ it "raises an error" do+ start = 1.day.from_now.utc.iso8601(3)+ description = "a" * (DiscourseEvents::Events::Event::MAX_DESCRIPTION_LENGTH + 1)++ expect do+ PostCreator.create!(+ user,+ title: "Sell a boat party",+ raw: "[event start=\"#{start}\"]\n#{description}\n[/event]",+ )+ end.to raise_error(+ I18n.t(+ "discourse_post_event.errors.models.event.description.length",+ maximum: DiscourseEvents::Events::Event::MAX_DESCRIPTION_LENGTH,+ ),+ )+ end+ end++ context "when max attendees is invalid" do+ def expect_rejected_max_attendees(value)+ expect { create_post_with_event(user, "maxAttendees=\"#{value}\"") }.to raise_error(+ I18n.t(+ "discourse_post_event.errors.models.event.invalid_max_attendees",+ maximum: DiscourseEvents::Events::Event::MAX_ATTENDEES_LIMIT,+ ),+ )+ end++ it "raises an error" do+ expect_rejected_max_attendees("0")+ expect_rejected_max_attendees("9999999999")+ expect_rejected_max_attendees("")+ end+ end++ context "when a private event has too many allowed groups" do+ fab!(:invited_groups) do+ Fabricate.times(DiscourseEvents::Events::Event::MAX_RAW_INVITEES + 1, :group)+ end++ let(:group_names) { invited_groups.map(&:name).join(",") }++ it "raises an error" do+ expect do+ create_post_with_event(user, "status=\"private\" allowedGroups=\"#{group_names}\"")+ end.to raise_error(+ I18n.t(+ "discourse_post_event.errors.models.event.raw_invitees_length",+ count: DiscourseEvents::Events::Event::MAX_RAW_INVITEES,+ ),+ )+ end++ it "creates the event when the status is public" do+ post =+ create_post_with_event(+ user,+ "status=\"public\" allowedGroups=\"#{group_names}\"",+ ).reload++ expect(post.event.persisted?).to eq(true)+ end++ it "does not count the public group toward the limit" do+ allowed = invited_groups.take(DiscourseEvents::Events::Event::MAX_RAW_INVITEES)+ group_names = ([DiscourseEvents::Events::Event::PUBLIC_GROUP] + allowed.map(&:name))++ post =+ create_post_with_event(+ user,+ "status=\"private\" allowedGroups=\"#{group_names.join(",")}\"",+ ).reload++ expect(post.event.persisted?).to eq(true)+ expect(post.event.raw_invitees).to match_array(allowed.map(&:name))+ end+ end++ context "when recurrence until is invalid" do+ it "raises an error" do+ expect do+ create_post_with_event(user, 'recurrence="every_week" recurrenceUntil="garbage"')+ end.to raise_error(+ I18n.t(+ "discourse_post_event.errors.models.event.recurrence_until_must_be_a_valid_date",+ ),+ )+ end+ end++ context "when reminders are invalid" do+ it "raises an error" do+ expect { create_post_with_event(user, 'reminders="notification.1.fortnights"') }.to(+ raise_error(+ I18n.t(+ "discourse_post_event.errors.models.event.invalid_reminders",+ reminders: "notification.1.fortnights",+ ),+ ),+ )+ end+ end++ context "when url is too long" do+ it "raises an error" do+ url = "https://example.com/#{"a" * DiscourseEvents::Events::Event::MAX_URL_LENGTH}"++ expect { create_post_with_event(user, "url=\"#{url}\"") }.to raise_error(+ I18n.t(+ "discourse_post_event.errors.models.event.url.length",+ maximum: DiscourseEvents::Events::Event::MAX_URL_LENGTH,+ ),+ )+ end+ end++ context "when location is too long" do+ it "raises an error" do+ location = "a" * (DiscourseEvents::Events::Event::MAX_LOCATION_LENGTH + 1)++ expect { create_post_with_event(user, "location=\"#{location}\"") }.to raise_error(+ I18n.t(+ "discourse_post_event.errors.models.event.location.length",+ maximum: DiscourseEvents::Events::Event::MAX_LOCATION_LENGTH,+ ),+ )+ end+ end+ end++ context "when the event sync fails unexpectedly" do+ it "logs the failure" do+ DiscourseEvents::Events::Event+ .any_instance+ .stubs(:update_with_params)+ .raises(ActiveRecord::RecordNotSaved.new("boom"))++ logger = track_log_messages { create_post_with_event(user) }++ expect(logger.errors).to include(match(/Failed to sync event/))+ endendcontext "when the post contains multiple events" dodiff --git a/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb b/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rbindex b158fb8952f..8eb6e764b3c 100644--- a/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb+++ b/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb@@ -20,6 +20,26 @@ describe DiscourseEvents::Events::Event do).is_at_most(DiscourseEvents::Events::Event::MAX_NAME_LENGTH)end+ it do+ is_expected.to validate_length_of(:location).is_at_most(+ DiscourseEvents::Events::Event::MAX_LOCATION_LENGTH,+ )+ end++ it do+ is_expected.to validate_length_of(:url).is_at_most(+ DiscourseEvents::Events::Event::MAX_URL_LENGTH,+ )+ end++ it do+ is_expected.to validate_numericality_of(:max_attendees)+ .only_integer+ .is_greater_than(0)+ .is_less_than_or_equal_to(DiscourseEvents::Events::Event::MAX_ATTENDEES_LIMIT)+ .allow_nil+ end+describe "#warm_livestream_onebox" dolet(:livestream_url) { "https://www.youtube.com/live/abc123" }@@ -367,10 +387,10 @@ describe DiscourseEvents::Events::Event doenddescribe "topic custom fields callback" do- let(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }- let!(:notified_user) { Fabricate(:user) }- let(:topic) { Fabricate(:topic, user: user) }- let!(:first_post) { Fabricate(:post, topic: topic) }+ fab!(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }+ fab!(:notified_user, :user)+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:first_post) { Fabricate(:post, topic: topic) }let(:second_post) { Fabricate(:post, topic: topic) }let!(:starts_at) { Time.zone.parse("2020-04-24 14:15:00") }let!(:ends_at) { Time.zone.parse("2020-04-24 16:15:00") }@@ -648,9 +668,9 @@ describe DiscourseEvents::Events::Event doenddescribe "#ongoing?" do- let(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }- let(:topic) { Fabricate(:topic, user: user) }- let!(:first_post) { Fabricate(:post, topic: topic) }+ fab!(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:first_post) { Fabricate(:post, topic: topic) }context "with ends_at" docontext "with starts_at < current date" do@@ -734,9 +754,9 @@ describe DiscourseEvents::Events::Event doenddescribe "#currently_within_event_timeframe?" do- let(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }- let(:topic) { Fabricate(:topic, user: user) }- let!(:first_post) { Fabricate(:post, topic: topic) }+ fab!(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:first_post) { Fabricate(:post, topic: topic) }def event_with(starts_at:, ends_at: nil, all_day: false)DiscourseEvents::Events::Event.create!(@@ -823,9 +843,9 @@ describe DiscourseEvents::Events::Event doenddescribe "#expired?" do- let(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }- let(:topic) { Fabricate(:topic, user: user) }- let!(:first_post) { Fabricate(:post, topic: topic) }+ fab!(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:first_post) { Fabricate(:post, topic: topic) }context "with ends_at" docontext "when starts_at < current date" do@@ -974,8 +994,78 @@ describe DiscourseEvents::Events::Event doendend+ describe "#parsed_reminders" do+ fab!(:post_1, :post)++ def event_with_reminders(reminders)+ Fabricate(:event, post: post_1, reminders: reminders)+ end++ it "parses type, value and unit" do+ event = event_with_reminders("notification.15.minutes,bumpTopic.3.days")++ expect(event.parsed_reminders).to eq(+ [+ { type: "notification", value: 15, unit: "minutes" },+ { type: "bumpTopic", value: 3, unit: "days" },+ ],+ )+ end++ it "defaults the type to notification for legacy reminders without one" do+ event = event_with_reminders("15.minutes")++ expect(event.parsed_reminders).to eq([{ type: "notification", value: 15, unit: "minutes" }])+ end++ it "keeps negative values used for reminders after the event" do+ event = event_with_reminders("notification.-30.minutes")++ expect(event.parsed_reminders).to eq([{ type: "notification", value: -30, unit: "minutes" }])+ end++ it "strips padding and plus signs" do+ event = event_with_reminders("notification.15.minutes, bumpTopic.+3.days")++ expect(event.parsed_reminders).to eq(+ [+ { type: "notification", value: 15, unit: "minutes" },+ { type: "bumpTopic", value: 3, unit: "days" },+ ],+ )+ end++ it "skips reminders with an unknown unit" do+ event = event_with_reminders("notification.1.fortnights,notification.1.hours")++ expect(event.parsed_reminders).to eq([{ type: "notification", value: 1, unit: "hours" }])+ end++ it "is empty without reminders" do+ expect(event_with_reminders(nil).parsed_reminders).to eq([])+ end+ end++ describe ".valid_reminder?" do+ it "accepts known types, legacy type-less reminders, padding and signed values" do+ expect(described_class.valid_reminder?("notification.15.minutes")).to eq(true)+ expect(described_class.valid_reminder?("bumpTopic.1.days")).to eq(true)+ expect(described_class.valid_reminder?("15.minutes")).to eq(true)+ expect(described_class.valid_reminder?(" notification.+15.minutes ")).to eq(true)+ expect(described_class.valid_reminder?("notification.-30.minutes")).to eq(true)+ end++ it "rejects unknown units, types, non-numeric values and wrong arity" do+ expect(described_class.valid_reminder?("notification.1.fortnights")).to eq(false)+ expect(described_class.valid_reminder?("notification.abc.minutes")).to eq(false)+ expect(described_class.valid_reminder?("foo.1.minutes")).to eq(false)+ expect(described_class.valid_reminder?("15")).to eq(false)+ expect(described_class.valid_reminder?("a.notification.15.minutes")).to eq(false)+ end+ end+describe "#duration" do- let!(:post_1) { Fabricate(:post) }+ fab!(:post_1, :post)context "when event has both starts_at and ends_at" doit "returns duration in HH:MM:SS format" do@@ -1017,8 +1107,8 @@ describe DiscourseEvents::Events::Event doenddescribe "#update_with_params!" do- let!(:post_1) { Fabricate(:post) }- let!(:user_1) { Fabricate(:user) }+ fab!(:post_1, :post)+ fab!(:user_1, :user)let(:group_1) doFabricate(:group).tap do |g|g.add(user_1)@@ -1115,11 +1205,11 @@ describe DiscourseEvents::Events::Event doenddescribe "#missing_users" do- let!(:post_1) { Fabricate(:post) }- let!(:user_1) { Fabricate(:user) }- let!(:user_2) { Fabricate(:user) }- let!(:user_3) { Fabricate(:user) }- let!(:group_1) do+ fab!(:post_1, :post)+ fab!(:user_1, :user)+ fab!(:user_2, :user)+ fab!(:user_3, :user)+ fab!(:group_1) doFabricate(:group).tap do |g|g.add(user_1)g.add(user_2)@@ -1127,13 +1217,13 @@ describe DiscourseEvents::Events::Event dog.save!endend- let!(:group_2) do+ fab!(:group_2) doFabricate(:group).tap do |g|g.add(user_2)g.save!endend- let!(:event_1) do+ fab!(:event_1) doFabricate(:event,post: post_1,@@ -1197,15 +1287,13 @@ describe DiscourseEvents::Events::Event dodescribe "#starts_at and #ends_at for expired recurring events" docontext "when recurring event has expired (past recurrence_until)" dolet(:expired_recurring_event) do- event =- Fabricate(- :event,- recurrence: "every_week",- recurrence_until: 1.day.ago,- original_starts_at: 1.week.ago,- original_ends_at: 1.week.ago + 2.hours,- )- event+ Fabricate(+ :event,+ recurrence: "every_week",+ recurrence_until: 1.day.ago,+ original_starts_at: 1.week.ago,+ original_ends_at: 1.week.ago + 2.hours,+ )endit "returns nil for starts_at since no future dates can be computed" dodiff --git a/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb b/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rbindex d122cdd9e3a..9ba27634b8e 100644--- a/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb+++ b/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb@@ -31,6 +31,24 @@ describe DiscourseEvents::Events::EventSerializer doendend+ context "with reminders" do+ def serialized_reminders(reminders)+ event = Fabricate(:event, post: post, reminders: reminders)+ DiscourseEvents::Events::EventSerializer.new(event, scope: Guardian.new).as_json[:event][+ :reminders+ ]+ end++ it "serializes value, unit, period and type" do+ expect(serialized_reminders("notification.15.minutes,bumpTopic.-3.days")).to eq(+ [+ { value: 15, unit: "minutes", period: "before", type: "notification" },+ { value: 3, unit: "days", period: "after", type: "bumpTopic" },+ ],+ )+ end+ end+context "with a private event" dofab!(:private_event) doFabricate(:event, post: post, status: DiscourseEvents::Events::Event.statuses[:private])@@ -316,7 +334,7 @@ describe DiscourseEvents::Events::EventSerializer dorecurring_event.reload,scope: Guardian.new,).as_json- starts_at = Time.parse(json[:event][:starts_at])+ starts_at = Time.find_zone("UTC").parse(json[:event][:starts_at])expect(starts_at).to be > Time.currentend@@ -326,7 +344,7 @@ describe DiscourseEvents::Events::EventSerializer dorecurring_event.reload,scope: Guardian.new,).as_json- ends_at = Time.parse(json[:event][:ends_at])+ ends_at = Time.find_zone("UTC").parse(json[:event][:ends_at])expect(ends_at).to be > Time.currentendenddiff --git a/plugins/discourse-events/spec/services/discourse_events/events/event/sync_from_post_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/event/sync_from_post_spec.rbindex 4a22e02e9dd..a9d349fc7f1 100644--- a/plugins/discourse-events/spec/services/discourse_events/events/event/sync_from_post_spec.rb+++ b/plugins/discourse-events/spec/services/discourse_events/events/event/sync_from_post_spec.rb@@ -123,7 +123,11 @@ RSpec.describe DiscourseEvents::Events::Event::SyncFromPost do}end- it { is_expected.to be_a_failure }+ it { is_expected.to fail_with_an_invalid_model(:event) }++ it "exposes the invalid event and its errors" do+ expect(result[:event].errors[:max_attendees]).to be_present+ endit "does not persist the event" doexpect { result }.not_to change { DiscourseEvents::Events::Event.count }