Skip to content

A platform for community discussion. Free, open, simple.

DEV: update events plugin namespacing (#42549)

David Battersbyd7c6fcfcfe42
diff --git a/db/structure.sql b/db/structure.sql
index 9b77808f3fd..419f6b45efe 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -23364,6 +23364,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260821164114'),
('20260820171539'),
('20260820143851'),
+('20260819131113'),
('20260818143417'),
('20260818081537'),
('20260818045317'),
diff --git a/plugins/discourse-events/app/controllers/admin/discourse_calendar/admin_holidays_controller.rb b/plugins/discourse-events/app/controllers/admin/discourse_events/holidays_controller.rb
similarity index 63%
rename from plugins/discourse-events/app/controllers/admin/discourse_calendar/admin_holidays_controller.rb
rename to plugins/discourse-events/app/controllers/admin/discourse_events/holidays_controller.rb
index c153c123aa1..950208f13dd 100644
--- a/plugins/discourse-events/app/controllers/admin/discourse_calendar/admin_holidays_controller.rb
+++ b/plugins/discourse-events/app/controllers/admin/discourse_events/holidays_controller.rb
@@ -1,15 +1,15 @@
# frozen_string_literal: true
-module Admin::DiscourseCalendar
- class AdminHolidaysController < Admin::AdminController
- requires_plugin DiscourseCalendar::PLUGIN_NAME
+module Admin::DiscourseEvents
+ class HolidaysController < Admin::AdminController
+ requires_plugin DiscourseEvents::PLUGIN_NAME
def index
region_code = params[:region_code]
begin
- holidays = DiscourseCalendar::Holiday.find_holidays_for(region_code: region_code)
- rescue Holidays::InvalidRegion
+ holidays = DiscourseEvents::Holidays::Finder.find_holidays_for(region_code: region_code)
+ rescue ::Holidays::InvalidRegion
return(
render_json_error(
I18n.t("system_messages.discourse_calendar_holiday_region_invalid"),
@@ -22,8 +22,8 @@ module Admin::DiscourseCalendar
end
def disable
- DiscourseCalendar::DisabledHoliday.create!(disabled_holiday_params)
- CalendarEvent.destroy_by(
+ DiscourseEvents::Holidays::DisabledHoliday.create!(disabled_holiday_params)
+ DiscourseEvents::Calendar::Event.destroy_by(
description: disabled_holiday_params[:holiday_name],
region: disabled_holiday_params[:region_code],
)
@@ -32,7 +32,7 @@ module Admin::DiscourseCalendar
end
def enable
- if DiscourseCalendar::DisabledHoliday.destroy_by(disabled_holiday_params).present?
+ if DiscourseEvents::Holidays::DisabledHoliday.destroy_by(disabled_holiday_params).present?
render json: success_json
else
render_json_error(I18n.t("system_messages.discourse_calendar_enable_holiday_failed"), 422)
diff --git a/plugins/discourse-events/app/controllers/discourse_post_event/discourse_post_event_controller.rb b/plugins/discourse-events/app/controllers/discourse_events/base_controller.rb
similarity index 63%
rename from plugins/discourse-events/app/controllers/discourse_post_event/discourse_post_event_controller.rb
rename to plugins/discourse-events/app/controllers/discourse_events/base_controller.rb
index ab6efc05e73..01bd3235c8b 100644
--- a/plugins/discourse-events/app/controllers/discourse_post_event/discourse_post_event_controller.rb
+++ b/plugins/discourse-events/app/controllers/discourse_events/base_controller.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-module DiscoursePostEvent
- class DiscoursePostEventController < ::ApplicationController
- requires_plugin DiscourseCalendar::PLUGIN_NAME
+module DiscourseEvents
+ class BaseController < ::ApplicationController
+ requires_plugin DiscourseEvents::PLUGIN_NAME
before_action :ensure_discourse_post_event_enabled
private
diff --git a/plugins/discourse-events/app/controllers/discourse_post_event/events_controller.rb b/plugins/discourse-events/app/controllers/discourse_events/events_controller.rb
similarity index 87%
rename from plugins/discourse-events/app/controllers/discourse_post_event/events_controller.rb
rename to plugins/discourse-events/app/controllers/discourse_events/events_controller.rb
index d5050aa77ff..15d46eaa37e 100644
--- a/plugins/discourse-events/app/controllers/discourse_post_event/events_controller.rb
+++ b/plugins/discourse-events/app/controllers/discourse_events/events_controller.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-module DiscoursePostEvent
- class EventsController < DiscoursePostEventController
+module DiscourseEvents
+ class EventsController < BaseController
requires_login except: %i[index show]
skip_before_action :check_xhr, only: [:index], if: :ics_request?
@@ -14,7 +14,7 @@ module DiscoursePostEvent
end
@events =
- DiscoursePostEvent::EventFinder.search(current_user, search_params).includes(
+ DiscourseEvents::Events::Finder.search(current_user, search_params).includes(
:event_dates,
:image_upload,
post: {
@@ -33,7 +33,7 @@ module DiscoursePostEvent
@events.flat_map do |event|
if event.recurring?
expanded =
- DiscoursePostEvent::Action::ExpandOccurrences.call(
+ DiscourseEvents::Events::Action::ExpandOccurrences.call(
event: event,
after: after_time,
before: before_time,
@@ -54,12 +54,19 @@ module DiscoursePostEvent
format.json do
# The detailed serializer is currently not used anywhere in the frontend, but available via API
- serializer = params[:include_details] == "true" ? EventSerializer : BasicEventSerializer
+ serializer =
+ (
+ if params[:include_details] == "true"
+ Events::EventSerializer
+ else
+ Events::BasicEventSerializer
+ end
+ )
serialized_events =
@events.map do |event|
expanded =
- DiscoursePostEvent::Action::ExpandOccurrences.call(
+ DiscourseEvents::Events::Action::ExpandOccurrences.call(
event: event,
after: filtered_events_params[:after]&.to_datetime || Time.current,
before: filtered_events_params[:before]&.to_datetime,
@@ -90,7 +97,7 @@ module DiscoursePostEvent
end
def invite
- Invite.call(service_params.deep_merge(params: { event_id: params[:id] })) do
+ Events::Invite.call(service_params.deep_merge(params: { event_id: params[:id] })) do
on_success { render json: success_json }
on_model_not_found(:event) { raise Discourse::NotFound }
on_failed_policy(:can_act_on_event) { raise Discourse::InvalidAccess }
@@ -99,15 +106,15 @@ module DiscoursePostEvent
end
def show
- event = Event.includes(:image_upload).find(params[:id])
+ event = Events::Event.includes(:image_upload).find(params[:id])
guardian.ensure_can_see!(event.post)
- serializer = EventSerializer.new(event, scope: guardian)
+ serializer = Events::EventSerializer.new(event, scope: guardian)
render_json_dump(serializer)
end
def destroy
- DestroyEvent.call(service_params.deep_merge(params: { event_id: params[:id] })) do
+ Events::DestroyEvent.call(service_params.deep_merge(params: { event_id: params[:id] })) do
on_success { render json: success_json }
on_model_not_found(:event) { raise Discourse::NotFound }
on_failed_policy(:can_act_on_event) { raise Discourse::InvalidAccess }
@@ -121,7 +128,7 @@ module DiscoursePostEvent
# Render (don't raise) every outcome: exceptions raised inside `hijack`
# surface as a 500 instead of the intended status.
hijack do
- CsvBulkInvite.call(
+ Events::CsvBulkInvite.call(
service_params.deep_merge(params: { event_id: params[:id], file: file }),
) do
on_success { render json: success_json }
@@ -140,7 +147,7 @@ module DiscoursePostEvent
end
def bulk_invite
- BulkInvite.call(service_params.deep_merge(params: { event_id: params[:id] })) do
+ Events::BulkInvite.call(service_params.deep_merge(params: { event_id: params[:id] })) do
on_success { render json: success_json }
on_model_not_found(:event) { raise Discourse::NotFound }
on_failed_policy(:can_edit_post) { raise Discourse::InvalidAccess }
@@ -192,7 +199,7 @@ module DiscoursePostEvent
attending_user = User.find_by(username_lower: attending_username.downcase)
return Set.new if attending_user.blank?
- DiscoursePostEvent::Invitee
+ DiscourseEvents::Events::Invitee
.unscoped
.with_status(:going)
.where(post_id: @events.map(&:id), user_id: attending_user.id, recurring: false)
diff --git a/plugins/discourse-events/app/controllers/discourse_post_event/invitees_controller.rb b/plugins/discourse-events/app/controllers/discourse_events/invitees_controller.rb
similarity index 86%
rename from plugins/discourse-events/app/controllers/discourse_post_event/invitees_controller.rb
rename to plugins/discourse-events/app/controllers/discourse_events/invitees_controller.rb
index e7314024d57..516c7c9daf8 100644
--- a/plugins/discourse-events/app/controllers/discourse_post_event/invitees_controller.rb
+++ b/plugins/discourse-events/app/controllers/discourse_events/invitees_controller.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-module DiscoursePostEvent
- class InviteesController < DiscoursePostEventController
+module DiscourseEvents
+ class InviteesController < BaseController
requires_login except: %i[index]
def index
- DiscoursePostEvent::ListInvitees.call(
+ DiscourseEvents::Events::ListInvitees.call(
params: {
post_id: params[:post_id],
filter: params[:filter],
@@ -14,7 +14,7 @@ module DiscoursePostEvent
guardian:,
) do
on_success do |invitees:, suggested_users:|
- render json: InviteeListSerializer.new(invitees:, suggested_users:)
+ render json: Events::InviteeListSerializer.new(invitees:, suggested_users:)
end
on_failed_policy(:can_see_event) { raise Discourse::InvalidAccess }
on_model_not_found(:event) { raise Discourse::NotFound }
@@ -23,7 +23,7 @@ module DiscoursePostEvent
end
def update
- DiscoursePostEvent::UpdateInvitee.call(
+ DiscourseEvents::Events::UpdateInvitee.call(
params: {
status: params.dig(:invitee, :status),
recurring: params.dig(:invitee, :recurring) || false,
@@ -32,7 +32,7 @@ module DiscoursePostEvent
},
guardian:,
) do
- on_success { |invitee:| render json: InviteeSerializer.new(invitee) }
+ on_success { |invitee:| render json: Events::InviteeSerializer.new(invitee) }
on_failed_policy(:can_act_on_invitee) { raise Discourse::InvalidAccess }
on_failed_policy(:can_see_event) { raise Discourse::InvalidAccess }
on_failed_policy(:can_update_attendance) { raise Discourse::InvalidAccess }
@@ -50,7 +50,7 @@ module DiscoursePostEvent
end
def create
- DiscoursePostEvent::CreateInvitee.call(
+ DiscourseEvents::Events::CreateInvitee.call(
params: {
status: params[:invitee][:status],
recurring: params[:invitee][:recurring] || false,
@@ -59,7 +59,7 @@ module DiscoursePostEvent
},
guardian:,
) do
- on_success { |invitee:| render json: InviteeSerializer.new(invitee) }
+ on_success { |invitee:| render json: Events::InviteeSerializer.new(invitee) }
on_failed_policy(:can_see_event) { raise Discourse::InvalidAccess }
on_failed_policy(:can_update_attendance) { raise Discourse::InvalidAccess }
on_failed_policy(:can_invite_user) { raise Discourse::InvalidAccess }
@@ -77,7 +77,7 @@ module DiscoursePostEvent
end
def destroy
- DiscoursePostEvent::DestroyInvitee.call(
+ DiscourseEvents::Events::DestroyInvitee.call(
params: {
post_id: params[:post_id],
id: params[:id],
diff --git a/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb b/plugins/discourse-events/app/controllers/discourse_events/livestream_controller.rb
similarity index 95%
rename from plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb
rename to plugins/discourse-events/app/controllers/discourse_events/livestream_controller.rb
index 7c920a1e721..4ff7e358bae 100644
--- a/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb
+++ b/plugins/discourse-events/app/controllers/discourse_events/livestream_controller.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
class LivestreamController < ::ApplicationController
- requires_plugin DiscourseCalendar::PLUGIN_NAME
+ requires_plugin DiscourseEvents::PLUGIN_NAME
requires_login
skip_before_action :check_xhr, only: [:zoom_frame]
@@ -49,7 +49,7 @@ module DiscourseCalendar
end
def prepare_zoom_signature
- DiscourseCalendar::Livestream::PrepareZoomJoin.call(
+ DiscourseEvents::Livestream::PrepareZoomJoin.call(
service_params.deep_merge(params: { topic_id: params[:topic_id] }),
) do |result|
on_success { |zoom_join_payload:| render json: zoom_join_payload }
diff --git a/plugins/discourse-events/app/controllers/discourse_events/upcoming_events_controller.rb b/plugins/discourse-events/app/controllers/discourse_events/upcoming_events_controller.rb
new file mode 100644
index 00000000000..ab15baf0b42
--- /dev/null
+++ b/plugins/discourse-events/app/controllers/discourse_events/upcoming_events_controller.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ class UpcomingEventsController < BaseController
+ def index
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/controllers/discourse_post_event/upcoming_events_controller.rb b/plugins/discourse-events/app/controllers/discourse_post_event/upcoming_events_controller.rb
deleted file mode 100644
index 9c8e972b02d..00000000000
--- a/plugins/discourse-events/app/controllers/discourse_post_event/upcoming_events_controller.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class UpcomingEventsController < DiscoursePostEventController
- def index
- end
- end
-end
diff --git a/plugins/discourse-events/app/models/calendar_event.rb b/plugins/discourse-events/app/models/calendar_event.rb
deleted file mode 100644
index dcc1f484720..00000000000
--- a/plugins/discourse-events/app/models/calendar_event.rb
+++ /dev/null
@@ -1,131 +0,0 @@
-# frozen_string_literal: true
-
-class CalendarEvent < ActiveRecord::Base
- belongs_to :topic
- belongs_to :post
- belongs_to :user
-
- after_save do
- if SiteSetting.enable_user_status && is_holiday? && underway?
- DiscourseCalendar::HolidayStatus.set!(user, ends_at)
- end
- end
-
- after_destroy { DiscourseCalendar::HolidayStatus.clear!(user) if SiteSetting.enable_user_status }
-
- def ends_at
- end_date || (start_date + 24.hours)
- end
-
- def underway?
- now = Time.zone.now
- start_date <= now && now < ends_at
- end
-
- def is_holiday?
- SiteSetting.holiday_calendar_topic_id.to_i == topic_id
- end
-
- def in_future?
- start_date > Time.zone.now
- end
-
- def self.update(post)
- CalendarEvent.where(post_id: post.id).destroy_all
-
- dates = post.local_dates
- return if !dates || dates.size < 1 || dates.size > 2
-
- first_post = post.topic&.first_post
- return if !first_post || !first_post.custom_fields[DiscourseCalendar::CALENDAR_CUSTOM_FIELD]
-
- from = convert_to_date_time(dates[0])
- to = convert_to_date_time(dates[1]) if dates.size == 2
-
- adjust_to = !to || !dates[1]["time"]
- if !to && dates[0]["time"]
- to = from + 1.hour
- artificial_to = true
- end
-
- if SiteSetting.all_day_event_start_time.present? && SiteSetting.all_day_event_end_time.present?
- from = from.change(hour_adjustment(SiteSetting.all_day_event_start_time)) if !dates[0]["time"]
- to = (to || from).change(hour_adjustment(SiteSetting.all_day_event_end_time)) if adjust_to &&
- !artificial_to
- end
-
- doc = Nokogiri::HTML5.fragment(post.cooked)
- doc.css(".discourse-local-date").each(&:remove)
- html = doc.to_html.sub(/\s*→\s*/, "")
-
- description =
- PrettyText.excerpt(
- html,
- 1000,
- strip_links: true,
- text_entities: true,
- keep_emoji_images: true,
- )
- recurrence = dates[0]["recurring"].presence
- timezone = dates[0]["timezone"].presence
-
- CalendarEvent.create!(
- topic_id: post.topic_id,
- post_id: post.id,
- post_number: post.post_number,
- user_id: post.user_id,
- username: post.user.username,
- description: description,
- start_date: from,
- end_date: to,
- recurrence: recurrence,
- timezone: timezone,
- )
-
- post.publish_change_to_clients!(:calendar_change)
- end
-
- private
-
- def self.convert_to_date_time(value)
- return if value.blank?
-
- datetime = value["date"].to_s
- datetime << " #{value["time"]}" if value["time"]
- timezone = value["timezone"] || "UTC"
-
- ActiveSupport::TimeZone[timezone].parse(datetime)
- end
-
- def self.hour_adjustment(setting)
- setting = setting.split(":")
-
- { hour: setting.first, min: setting.last }
- end
-end
-
-# == Schema Information
-#
-# Table name: calendar_events
-#
-# id :bigint not null, primary key
-# description :string
-# end_date :datetime
-# post_number :integer
-# recurrence :string
-# region :string
-# start_date :datetime not null
-# timezone :string
-# username :string
-# created_at :datetime not null
-# updated_at :datetime not null
-# post_id :integer
-# topic_id :integer not null
-# user_id :integer
-#
-# Indexes
-#
-# index_calendar_events_on_post_id (post_id)
-# index_calendar_events_on_topic_id (topic_id)
-# index_calendar_events_on_user_id (user_id)
-#
diff --git a/plugins/discourse-events/app/models/discourse_events/calendar/event.rb b/plugins/discourse-events/app/models/discourse_events/calendar/event.rb
new file mode 100644
index 00000000000..26349ee9c58
--- /dev/null
+++ b/plugins/discourse-events/app/models/discourse_events/calendar/event.rb
@@ -0,0 +1,145 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Calendar
+ class Event < ActiveRecord::Base
+ # Pinned: the engine's `isolate_namespace` would otherwise derive
+ # "discourse_events_events" from the namespace.
+ self.table_name = "calendar_events"
+
+ belongs_to :topic
+ belongs_to :post
+ belongs_to :user
+
+ after_save do
+ if SiteSetting.enable_user_status && is_holiday? && underway?
+ DiscourseEvents::Holidays::Status.set!(user, ends_at)
+ end
+ end
+
+ after_destroy do
+ DiscourseEvents::Holidays::Status.clear!(user) if SiteSetting.enable_user_status
+ end
+
+ def ends_at
+ end_date || (start_date + 24.hours)
+ end
+
+ def underway?
+ now = Time.zone.now
+ start_date <= now && now < ends_at
+ end
+
+ def is_holiday?
+ SiteSetting.holiday_calendar_topic_id.to_i == topic_id
+ end
+
+ def in_future?
+ start_date > Time.zone.now
+ end
+
+ def self.update(post)
+ Event.where(post_id: post.id).destroy_all
+
+ dates = post.local_dates
+ return if !dates || dates.size < 1 || dates.size > 2
+
+ first_post = post.topic&.first_post
+ return if !first_post || !first_post.custom_fields[DiscourseEvents::CALENDAR_CUSTOM_FIELD]
+
+ from = convert_to_date_time(dates[0])
+ to = convert_to_date_time(dates[1]) if dates.size == 2
+
+ adjust_to = !to || !dates[1]["time"]
+ if !to && dates[0]["time"]
+ to = from + 1.hour
+ artificial_to = true
+ end
+
+ if SiteSetting.all_day_event_start_time.present? &&
+ SiteSetting.all_day_event_end_time.present?
+ from = from.change(hour_adjustment(SiteSetting.all_day_event_start_time)) if !dates[0][
+ "time"
+ ]
+ to =
+ (to || from).change(hour_adjustment(SiteSetting.all_day_event_end_time)) if adjust_to &&
+ !artificial_to
+ end
+
+ doc = Nokogiri::HTML5.fragment(post.cooked)
+ doc.css(".discourse-local-date").each(&:remove)
+ html = doc.to_html.sub(/\s*→\s*/, "")
+
+ description =
+ PrettyText.excerpt(
+ html,
+ 1000,
+ strip_links: true,
+ text_entities: true,
+ keep_emoji_images: true,
+ )
+ recurrence = dates[0]["recurring"].presence
+ timezone = dates[0]["timezone"].presence
+
+ Event.create!(
+ topic_id: post.topic_id,
+ post_id: post.id,
+ post_number: post.post_number,
+ user_id: post.user_id,
+ username: post.user.username,
+ description: description,
+ start_date: from,
+ end_date: to,
+ recurrence: recurrence,
+ timezone: timezone,
+ )
+
+ post.publish_change_to_clients!(:calendar_change)
+ end
+
+ private
+
+ def self.convert_to_date_time(value)
+ return if value.blank?
+
+ datetime = value["date"].to_s
+ datetime << " #{value["time"]}" if value["time"]
+ timezone = value["timezone"] || "UTC"
+
+ ActiveSupport::TimeZone[timezone].parse(datetime)
+ end
+
+ def self.hour_adjustment(setting)
+ setting = setting.split(":")
+
+ { hour: setting.first, min: setting.last }
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: calendar_events
+#
+# id :bigint not null, primary key
+# description :string
+# end_date :datetime
+# post_number :integer
+# recurrence :string
+# region :string
+# start_date :datetime not null
+# timezone :string
+# username :string
+# created_at :datetime not null
+# updated_at :datetime not null
+# post_id :integer
+# topic_id :integer not null
+# user_id :integer
+#
+# Indexes
+#
+# index_calendar_events_on_post_id (post_id)
+# index_calendar_events_on_topic_id (topic_id)
+# index_calendar_events_on_user_id (user_id)
+#
diff --git a/plugins/discourse-events/app/models/discourse_events/events/event.rb b/plugins/discourse-events/app/models/discourse_events/events/event.rb
new file mode 100644
index 00000000000..32e27b80963
--- /dev/null
+++ b/plugins/discourse-events/app/models/discourse_events/events/event.rb
@@ -0,0 +1,735 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class Event < ActiveRecord::Base
+ PUBLIC_GROUP = "trust_level_0"
+ # Keep in sync with the constants of the same name in the
+ # DiscoursePostEventEvent JS model.
+ EARLY_ACCESS_MINUTES = 30
+ GRACE_PERIOD_MINUTES = 10
+ MIN_NAME_LENGTH = 5
+ MAX_NAME_LENGTH = 255
+ MAX_DESCRIPTION_LENGTH = 1000
+ DEFAULT_TIMEZONE = "UTC"
+
+ self.table_name = "discourse_post_event_events"
+ self.ignored_columns = %w[starts_at ends_at]
+
+ has_many :event_dates, dependent: :destroy
+ # this is a cross plugin dependency, only called if chat is enabled
+ belongs_to :chat_channel, class_name: "Chat::Channel"
+ has_many :invitees, foreign_key: :post_id, dependent: :delete_all
+ belongs_to :post, foreign_key: :id
+ belongs_to :image_upload, class_name: "Upload", optional: true
+ has_many :upload_references, as: :target, dependent: :destroy
+
+ scope :visible, -> { where(deleted_at: nil) }
+ scope :open, -> { where(closed: false) }
+
+ before_validation :reset_invalid_livestream
+ before_save :chat_channel_sync
+ # prepend so it runs before `dependent: :delete_all` wipes the invitees
+ before_destroy :reset_invitees_topic_tracking, prepend: true
+ after_commit :create_livestream_chat_channel, on: %i[create update]
+ after_commit :enqueue_warm_livestream_onebox, on: %i[create update]
+ after_commit :destroy_topic_custom_field, on: %i[destroy]
+ after_commit :create_or_update_event_date, on: %i[create update]
+ after_save do
+ if saved_change_to_image_upload_id?
+ UploadReference.ensure_exist!(upload_ids: [image_upload_id], target: self)
+ end
+ end
+
+ validate :raw_invitees_are_groups
+ validates :original_starts_at, presence: true
+ validates :name,
+ length: {
+ in: MIN_NAME_LENGTH..MAX_NAME_LENGTH,
+ },
+ unless: ->(event) { event.name.blank? }
+ validates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }
+ validates :max_attendees,
+ numericality: {
+ only_integer: true,
+ greater_than: 0,
+ allow_nil: true,
+ }
+
+ validate :raw_invitees_length
+ validate :ends_before_start
+ validate :allowed_custom_fields
+ validate :url_is_a_uri, if: :url_changed?
+
+ def self.attributes_protected_by_default
+ super - %w[id]
+ end
+
+ def reset_invalid_livestream
+ return unless livestream?
+
+ self.livestream = false unless allowed_livestream_url? && post&.is_first_post?
+ end
+
+ def allowed_livestream_url?
+ DiscourseEvents::Livestream::AllowedHosts.allows_url?(livestream_url)
+ end
+
+ def create_livestream_chat_channel
+ return unless livestream? && SiteSetting.chat_enabled
+ return unless post&.is_first_post?
+ return if post.topic.blank?
+
+ DiscourseEvents::Livestream.handle_topic_chat_channel_creation(post.topic)
+ end
+
+ def has_cached_livestream_onebox?
+ livestream? && livestream_url.present? && Oneboxer.cached_onebox(livestream_url).present?
+ end
+
+ # Happens after the event record is saved to prepare the onebox
+ def enqueue_warm_livestream_onebox
+ return if !livestream? || livestream_url.blank?
+ if !saved_change_to_livestream? && !saved_change_to_location? && !saved_change_to_url?
+ return
+ end
+ return if has_cached_livestream_onebox?
+ Jobs.enqueue(:warm_livestream_onebox, event_id: id, url: livestream_url)
+ end
+
+ # Fetches the onebox and tells clients to re-render the post with it. Only
+ # ever called from the background job, never during a request.
+ def warm_livestream_onebox!
+ return if has_cached_livestream_onebox?
+ Oneboxer.onebox(livestream_url)
+ post&.publish_change_to_clients!(:revised)
+ end
+
+ def 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
+
+ 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
+ end
+
+ def 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
+ end
+
+ def set_next_date
+ return if closed
+
+ next_date_result = calculate_next_date
+
+ return event_dates.update_all(finished_at: Time.current) if next_date_result.nil?
+
+ starts_at, ends_at = next_date_result
+ finish_previous_event_dates(starts_at) if dates_changed?
+ upsert_event_date(starts_at, ends_at)
+ reset_invitee_notifications
+ notify_if_new_event
+ publish_update!
+ end
+
+ def set_topic_bump
+ return if closed
+
+ date = nil
+
+ return if reminders.blank? || starts_at.nil?
+ reminders
+ .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
+ end
+
+ return if date.blank?
+ Jobs.enqueue(:discourse_post_event_bump_topic, topic_id: post.topic_id, date: date.iso8601)
+ end
+
+ def validate_reminder_unit(input)
+ ActiveSupport::Duration::PARTS.any? { |part| part.to_s == input }
+ end
+
+ def expired?
+ if recurring?
+ return false if recurrence_until.nil?
+ return Time.current > recurrence_until
+ end
+
+ return true if starts_at.nil?
+ (ends_at || starts_at.end_of_day) <= Time.now
+ end
+
+ # Mirrors `currentlyWithinEventTimeframe` in the DiscoursePostEventEvent JS
+ # model: joining opens EARLY_ACCESS_MINUTES before the start and, when the
+ # event has an end time, closes GRACE_PERIOD_MINUTES after it.
+ def currently_within_event_timeframe?
+ return false if starts_at.nil?
+
+ now = Time.zone.now
+
+ if all_day
+ opens_at = starts_at.beginning_of_day
+ closes_at = (ends_at || starts_at).end_of_day
+ return opens_at <= now && now <= closes_at
+ end
+
+ return false if now < starts_at - EARLY_ACCESS_MINUTES.minutes
+ ends_at.nil? || now < ends_at + GRACE_PERIOD_MINUTES.minutes
+ end
+
+ def starts_at
+ return nil if recurring? && recurrence_until.present? && recurrence_until < Time.current
+ current_event_date&.starts_at || original_starts_at
+ end
+
+ def ends_at
+ return nil if recurring? && recurrence_until.present? && recurrence_until < Time.current
+ current_event_date&.ends_at || original_ends_at
+ end
+
+ def current_event_date
+ if association(:event_dates).loaded?
+ pending = event_dates.select { |d| d.finished_at.nil? }
+ pending.max_by(&:starts_at) || event_dates.max_by { |d| [d.updated_at, d.id] }
+ else
+ event_dates.current_first.first
+ end
+ end
+
+ def on_going_event_invitees
+ return [] if starts_at.nil? # Can't determine ongoing status without start time
+ if !ends_at && starts_at < Time.now && (!all_day || starts_at.end_of_day <= Time.now)
+ return []
+ end
+
+ if ends_at
+ extended_ends_at =
+ ends_at + SiteSetting.discourse_post_event_edit_notifications_time_extension.minutes
+ return [] if !(starts_at..extended_ends_at).cover?(Time.now)
+ end
+
+ invitees.where(status: DiscourseEvents::Events::Invitee.statuses[:going])
+ end
+
+ def raw_invitees_length
+ if raw_invitees && raw_invitees.length > 10
+ errors.add(
+ :base,
+ I18n.t("discourse_post_event.errors.models.event.raw_invitees_length", count: 10),
+ )
+ end
+ end
+
+ def raw_invitees_are_groups
+ return if raw_invitees.blank?
+
+ non_group_invitees = raw_invitees - Group.where(name: raw_invitees).pluck(:name)
+ return if non_group_invitees.blank?
+
+ if User.where(username: non_group_invitees).exists?
+ errors.add(
+ :base,
+ I18n.t("discourse_post_event.errors.models.event.raw_invitees.only_group"),
+ )
+ end
+ end
+
+ def ends_before_start
+ if original_starts_at && original_ends_at && original_starts_at >= original_ends_at
+ errors.add(
+ :base,
+ I18n.t("discourse_post_event.errors.models.event.ends_at_before_starts_at"),
+ )
+ end
+ end
+
+ def url_is_a_uri
+ return if Parser.valid_url?(url)
+
+ errors.add(:base, I18n.t("discourse_post_event.errors.models.event.invalid_url"))
+ end
+
+ def allowed_custom_fields
+ allowed_custom_fields = SiteSetting.discourse_post_event_allowed_custom_fields.split("|")
+ custom_fields.each do |key, value|
+ if !allowed_custom_fields.include?(key)
+ errors.add(
+ :base,
+ I18n.t(
+ "discourse_post_event.errors.models.event.custom_field_is_invalid",
+ field: key,
+ ),
+ )
+ end
+ end
+ end
+
+ def create_invitees(attrs)
+ timestamp = Time.now
+ attrs.map! do |attr|
+ { post_id: id, created_at: timestamp, updated_at: timestamp }.merge(attr)
+ end
+ result = invitees.insert_all!(attrs)
+
+ # batch event does not call callback
+ ChatChannelSync.sync(self) if chat_enabled?
+
+ result
+ end
+
+ def notify_invitees!(predefined_attendance: false)
+ invitees
+ .where(notified: false)
+ .find_each do |invitee|
+ create_notification!(invitee.user, post, predefined_attendance: predefined_attendance)
+ invitee.update!(notified: true)
+ end
+ end
+
+ def notify_missing_invitees!
+ missing_users.each { |user| create_notification!(user, post) } if private?
+ end
+
+ def create_notification!(user, post, predefined_attendance: false)
+ return if post.event.starts_at.nil? || post.event.starts_at < Time.current
+ return if !Guardian.new(user).can_see?(post)
+
+ message =
+ if predefined_attendance
+ "discourse_post_event.notifications.invite_user_predefined_attendance_notification"
+ else
+ "discourse_post_event.notifications.invite_user_notification"
+ end
+
+ attrs = {
+ notification_type: Notification.types[:event_invitation] || Notification.types[:custom],
+ topic_id: post.topic_id,
+ post_number: post.post_number,
+ data: {
+ user_id: user.id,
+ topic_title: name || post.topic.title,
+ display_username: post.user.username,
+ message: message,
+ event_name: name,
+ }.to_json,
+ }
+
+ user.notifications.consolidate_or_create!(attrs)
+ end
+
+ def ongoing?
+ return false if closed || expired? || starts_at.nil?
+ finishes_at = ends_at || starts_at.end_of_day
+ (starts_at..finishes_at).cover?(Time.now)
+ end
+
+ def going_count
+ invitees.where(status: Invitee.statuses[:going]).count
+ end
+
+ def at_capacity?
+ return false if max_attendees.blank?
+ going_count >= max_attendees
+ end
+
+ def self.statuses
+ @statuses ||= Enum.new(standalone: 0, public: 1, private: 2)
+ end
+
+ def public?
+ status == Event.statuses[:public]
+ end
+
+ def standalone?
+ status == Event.statuses[:standalone]
+ end
+
+ def private?
+ status == Event.statuses[:private]
+ end
+
+ def recurring?
+ recurrence.present?
+ end
+
+ def most_likely_going(limit = SiteSetting.displayed_invitees_limit)
+ going = invitees.order(%i[status created_at user_id]).limit(limit)
+
+ if private? && going.count < 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) }
+ end
+
+ going
+ end
+
+ def publish_update!
+ post.publish_message!("/discourse-post-event/#{post.topic_id}", id: id)
+ end
+
+ def fetch_users
+ @fetched_users ||= Invitee.extract_uniq_usernames(raw_invitees)
+ end
+
+ def enforce_private_invitees!
+ pruned = invitees.where.not(user_id: fetch_users.select(:id))
+ pruned_user_ids = pruned.pluck(:user_id)
+ pruned.delete_all
+ Invitee.reset_topic_tracking!(user_ids: pruned_user_ids, topic_id: post.topic_id)
+ unfollow_livestream_chat(pruned_user_ids)
+ end
+
+ # Unfollow users from the livestream chat channel once they are no longer
+ # attending (e.g. pruned when a private event's invited groups change). Chat
+ # following tracks attendance, so removed attendees should not keep the
+ # channel in their chat list.
+ def unfollow_livestream_chat(user_ids)
+ return if user_ids.blank?
+
+ channel = post.topic.topic_chat_channel&.chat_channel
+ return if channel.nil?
+
+ manager = Chat::ChannelMembershipManager.new(channel)
+ User
+ .where(id: user_ids)
+ .find_each do |user|
+ membership = manager.unfollow(user)
+ next if membership.nil?
+ DiscourseEvents::Livestream.publish_livestream_chat_status(membership, user:)
+ end
+ end
+
+ def user_in_invited_group?(user, group_names: nil)
+ return false if user.blank? || raw_invitees.blank?
+
+ return (Array(raw_invitees) & Array(group_names)).any? unless group_names.nil?
+
+ GroupUser.where(
+ user_id: user.id,
+ group_id: Group.where(name: raw_invitees).select(:id),
+ ).exists?
+ end
+
+ # Unlike can_user_update_attendance?, this stays true after the event
+ # closes or expires so attendees keep access to the livestream chat.
+ #
+ # Callers serializing many events at once (e.g. the chat channel list) can
+ # pass preloaded group_names to avoid a per-event query.
+ def can_access_livestream_chat?(user, group_names: nil)
+ return true if !private?
+ return false if user.blank?
+ return true if user.admin?
+
+ user_in_invited_group?(user, group_names:)
+ end
+
+ def can_user_update_attendance?(user, group_names: nil)
+ return false if user.blank? || closed || expired?
+ return true if public?
+
+ private? && user_in_invited_group?(user, group_names:)
+ end
+
+ def sync_image_to_post_and_topic(generate_thumbnails: false)
+ return unless image_upload_id
+
+ post.update_column(:image_upload_id, image_upload_id)
+ if post.is_first_post?
+ post.topic.update_column(:image_upload_id, image_upload_id)
+ if generate_thumbnails
+ extra_sizes =
+ ThemeModifierHelper.new(
+ theme_ids: Theme.user_selectable.pluck(:id),
+ ).topic_thumbnail_sizes
+ post.topic.generate_thumbnails!(extra_sizes: extra_sizes)
+ end
+ end
+ end
+
+ def 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
+ payload = WebHook.build_calendar_event_payload(event_before)
+ WebHook.enqueue_calendar_event_hooks(:calendar_event_destroyed, event_before, payload)
+ end
+ end
+
+ def missing_users(excluded_ids = invitees.select(:user_id))
+ users = User.real.activated.not_silenced.not_suspended.not_staged
+
+ if raw_invitees.present?
+ user_ids =
+ users
+ .joins(:groups)
+ .where("groups.name" => raw_invitees)
+ .where.not(id: excluded_ids)
+ .select(:id)
+ User.where(id: user_ids)
+ elsif private?
+ User.none
+ else
+ users.where.not(id: excluded_ids)
+ end
+ end
+
+ SUGGESTED_USERS_LIMIT = 10
+
+ # Users that could be invited to this event, ranked by how closely their
+ # username matches +filter+ (exact match first). Already-invited users are
+ # excluded, optionally narrowed to a given attendance +type+.
+ def suggested_users(filter, type: nil)
+ excluded = type ? invitees.with_status(type) : invitees
+
+ missing_users(excluded.select(:user_id))
+ .where(
+ "LOWER(username) LIKE :filter",
+ filter: "%#{User.sanitize_sql_like(filter.downcase)}%",
+ )
+ .order(
+ DB.sql_fragment(
+ "CASE WHEN LOWER(username) = ? THEN 0 ELSE 1 END ASC, LOWER(username) ASC",
+ filter.downcase,
+ ),
+ )
+ .limit(SUGGESTED_USERS_LIMIT)
+ end
+
+ def 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
+
+ publish_update!
+ end
+
+ def chat_channel_sync
+ if chat_enabled && chat_channel_id.blank? && post.last_editor_id.present?
+ DiscourseEvents::Events::ChatChannelSync.sync(
+ self,
+ guardian: Guardian.new(User.find_by(id: post.last_editor_id)),
+ )
+ end
+ end
+
+ def calculate_next_date
+ if recurrence.blank? || original_starts_at > Time.current
+ return original_starts_at, original_ends_at
+ end
+
+ next_starts_at = calculate_next_recurring_date
+ 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
+ [next_starts_at, next_ends_at]
+ end
+
+ def calculate_next_occurrence_from(from_time)
+ return nil if recurrence.blank?
+ if original_starts_at > from_time
+ return { starts_at: original_starts_at, ends_at: original_ends_at }
+ end
+
+ next_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 }
+ end
+
+ def duration
+ return nil unless original_starts_at
+
+ duration_seconds = original_ends_at ? original_ends_at - original_starts_at : 3600
+ hours = (duration_seconds / 3600)
+ minutes = ((duration_seconds % 3600) / 60)
+ seconds = (duration_seconds % 60)
+
+ sprintf("%02d:%02d:%02d", hours, minutes, seconds)
+ end
+
+ def rrule_timezone
+ timezone || DEFAULT_TIMEZONE
+ end
+
+ def livestream_url
+ location || url
+ end
+
+ def is_zoom_livestream?
+ return false unless SiteSetting.livestream_zoom_enabled
+ return false unless livestream?
+ DiscourseEvents::Livestream::ZoomUrlParser.zoom_url?(livestream_url)
+ end
+
+ private
+
+ def reset_invitees_topic_tracking
+ topic_id = post&.topic_id
+ return if topic_id.nil?
+
+ Invitee.reset_topic_tracking!(user_ids: invitees.pluck(:user_id), topic_id:)
+ end
+
+ def dates_changed?
+ saved_change_to_original_starts_at || saved_change_to_original_ends_at
+ end
+
+ def finish_previous_event_dates(current_starts_at)
+ existing_date = event_dates.find_by(starts_at: current_starts_at)
+ event_dates
+ .where.not(id: existing_date&.id)
+ .where(finished_at: nil)
+ .update_all(finished_at: Time.current)
+ end
+
+ def upsert_event_date(starts_at, ends_at)
+ finished_at = ends_at && ends_at < Time.current ? ends_at : nil
+
+ existing_date = event_dates.find_by(starts_at:)
+
+ if existing_date
+ # Only update if something actually changed
+ unless existing_date.ends_at == ends_at && existing_date.finished_at == finished_at
+ existing_date.update!(ends_at:, finished_at:)
+ end
+ else
+ event_dates.create!(starts_at:, ends_at:, finished_at:)
+ end
+ end
+
+ def reset_invitee_notifications
+ invitees.where(
+ "status != :going OR recurring = FALSE",
+ going: Invitee.statuses[:going],
+ ).update_all(status: nil, notified: false, recurring: false)
+ end
+
+ def notify_if_new_event
+ is_generating_future_recurrence = recurrence.present? && original_starts_at <= Time.current
+
+ unless is_generating_future_recurrence
+ notify_invitees!
+ notify_missing_invitees!
+ end
+ end
+
+ def calculate_next_recurring_date
+ timezone_starts_at = original_starts_at.in_time_zone(timezone)
+ timezone_recurrence_until = recurrence_until&.in_time_zone(timezone)
+
+ DiscourseEvents::Events::RRuleGenerator.generate(
+ starts_at: timezone_starts_at,
+ timezone: rrule_timezone,
+ recurrence: recurrence,
+ recurrence_until: timezone_recurrence_until,
+ dtstart: timezone_starts_at,
+ ).first
+ end
+
+ def calculate_next_recurring_date_from(from_time)
+ timezone_starts_at = original_starts_at.in_time_zone(timezone)
+ timezone_recurrence_until = recurrence_until&.in_time_zone(timezone)
+ from_time_in_tz = from_time.in_time_zone(timezone)
+
+ RRule::Rule
+ .new(
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence_until: timezone_recurrence_until,
+ recurrence: recurrence,
+ starts_at: timezone_starts_at,
+ ),
+ dtstart: timezone_starts_at,
+ tzid: rrule_timezone,
+ )
+ .between(from_time_in_tz - 1.hour, from_time_in_tz + 1.year)
+ .find { |date| date >= from_time_in_tz }
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_post_event_events
+#
+# id :bigint not null, primary key
+# all_day :boolean default(FALSE), not null
+# chat_enabled :boolean default(FALSE), not null
+# closed :boolean default(FALSE), not null
+# custom_fields :jsonb not null
+# deleted_at :datetime
+# description :string(1000)
+# livestream :boolean default(FALSE), not null
+# location :string(1000)
+# max_attendees :integer
+# minimal :boolean
+# name :string
+# original_ends_at :datetime
+# original_starts_at :datetime not null
+# raw_invitees :string is an Array
+# recurrence :string
+# recurrence_until :datetime
+# reminders :string
+# show_local_time :boolean default(FALSE), not null
+# status :integer default(0), not null
+# timezone :string
+# url :string(1000)
+# chat_channel_id :bigint
+# image_upload_id :bigint
+#
+# Indexes
+#
+# index_discourse_post_event_events_on_image_upload_id (image_upload_id)
+#
diff --git a/plugins/discourse-events/app/models/discourse_events/events/event_date.rb b/plugins/discourse-events/app/models/discourse_events/events/event_date.rb
new file mode 100644
index 00000000000..d5cdffa9fd7
--- /dev/null
+++ b/plugins/discourse-events/app/models/discourse_events/events/event_date.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class EventDate < ActiveRecord::Base
+ self.table_name = "discourse_calendar_post_event_dates"
+ belongs_to :event
+
+ scope :pending,
+ -> do
+ where(finished_at: nil).joins(:event).merge(
+ DiscourseEvents::Events::Event.visible.open,
+ )
+ end
+ scope :expired, -> { where("ends_at IS NOT NULL AND ends_at < ?", Time.now) }
+ scope :not_expired, -> { where("ends_at IS NULL OR ends_at > ?", Time.now) }
+
+ scope :current_first, -> { order(Arel.sql(current_ordering_sql)) }
+
+ def self.current_ordering_sql
+ <<~SQL.squish
+ finished_at IS NOT NULL,
+ CASE WHEN finished_at IS NULL THEN starts_at ELSE updated_at END DESC,
+ id DESC
+ SQL
+ end
+
+ after_commit :upsert_topic_custom_field, on: %i[create update]
+ def upsert_topic_custom_field
+ if event.post && event.post.is_first_post?
+ TopicCustomField.upsert(
+ {
+ topic_id: event.post.topic_id,
+ name: TOPIC_POST_EVENT_STARTS_AT,
+ value: starts_at,
+ created_at: Time.now,
+ updated_at: Time.now,
+ },
+ unique_by: "idx_topic_custom_fields_topic_post_event_starts_at",
+ )
+
+ TopicCustomField.upsert(
+ {
+ topic_id: event.post.topic_id,
+ name: TOPIC_POST_EVENT_ENDS_AT,
+ value: ends_at,
+ created_at: Time.now,
+ updated_at: Time.now,
+ },
+ unique_by: "idx_topic_custom_fields_topic_post_event_ends_at",
+ )
+
+ TopicCustomField.upsert(
+ {
+ topic_id: event.post.topic_id,
+ name: TOPIC_POST_EVENT_ALL_DAY,
+ value: event.all_day || false,
+ created_at: Time.now,
+ updated_at: Time.now,
+ },
+ unique_by: "idx_topic_custom_fields_topic_post_event_all_day",
+ )
+ end
+ end
+
+ def started?
+ starts_at <= Time.current
+ end
+
+ def ended?
+ (ends_at || starts_at.end_of_day) <= Time.current
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_calendar_post_event_dates
+#
+# id :bigint not null, primary key
+# ends_at :datetime
+# event_started_sent_at :datetime
+# event_will_start_sent_at :datetime
+# finished_at :datetime
+# reminder_counter :integer default(0)
+# starts_at :datetime
+# created_at :datetime not null
+# updated_at :datetime not null
+# event_id :integer
+#
+# Indexes
+#
+# idx_discourse_calendar_post_event_dates_event_id_starts_at_uniq (event_id,starts_at) UNIQUE
+# index_discourse_calendar_post_event_dates_on_event_id (event_id)
+# index_discourse_calendar_post_event_dates_on_event_id_and_dates (event_id,finished_at,starts_at DESC,updated_at DESC,id DESC)
+# index_discourse_calendar_post_event_dates_on_finished_at (finished_at)
+#
diff --git a/plugins/discourse-events/app/models/discourse_events/events/invitee.rb b/plugins/discourse-events/app/models/discourse_events/events/invitee.rb
new file mode 100644
index 00000000000..76527fcce77
--- /dev/null
+++ b/plugins/discourse-events/app/models/discourse_events/events/invitee.rb
@@ -0,0 +1,157 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class Invitee < ActiveRecord::Base
+ self.table_name = "discourse_post_event_invitees"
+
+ belongs_to :event, foreign_key: :post_id
+ belongs_to :user
+
+ default_scope do
+ joins(:user)
+ .includes(:user)
+ .merge(User.not_suspended)
+ .merge(User.not_silenced)
+ .merge(User.not_staged)
+ .where.not(users: { id: nil })
+ end
+ scope :with_status, ->(status) { where(status: Invitee.statuses[status]) }
+ scope :matching_username,
+ ->(filter) do
+ where(
+ "LOWER(users.username) LIKE :filter",
+ filter: "%#{sanitize_sql_like(filter.downcase)}%",
+ )
+ end
+
+ before_save :clear_recurring_unless_going
+ after_destroy :reset_topic_tracking!
+ after_commit :sync_chat_channel_members
+
+ def self.statuses
+ @statuses ||= Enum.new(going: 0, interested: 1, not_going: 2)
+ end
+
+ def self.create_attendance!(user_id, post_id, status, recurring: false)
+ status = status.to_sym
+ event = Event.find(post_id)
+
+ if status == :going && event.at_capacity?
+ raise Discourse::InvalidParameters.new(:max_attendees)
+ end
+
+ invitee = create!(post_id:, user_id:, status: statuses[status], recurring:)
+ invitee.publish_attendance_change!
+ invitee
+ rescue ActiveRecord::RecordNotUnique
+ # multiple attendances may be created concurrently — return the winning row
+ find_by(post_id:, user_id:)
+ end
+
+ def update_attendance!(status, recurring: false)
+ status = status&.to_sym
+
+ if status == :going && event.at_capacity? && !going?
+ raise Discourse::InvalidParameters.new(:max_attendees)
+ end
+
+ update!(status: self.class.statuses[status], recurring:)
+ publish_attendance_change!
+ self
+ end
+
+ def going?
+ status == Invitee.statuses[:going]
+ end
+
+ def publish_attendance_change!
+ event.publish_update!
+ update_topic_tracking!
+ DiscourseEvent.trigger(:discourse_calendar_post_event_invitee_status_changed, self)
+ end
+
+ def self.extract_uniq_usernames(groups)
+ User.real.where(
+ id: GroupUser.where(group_id: Group.where(name: groups).select(:id)).select(:user_id),
+ )
+ end
+
+ def self.reset_topic_tracking!(user_ids:, topic_id:)
+ user_ids = Array(user_ids)
+ return if user_ids.empty? || topic_id.nil?
+
+ TopicUser
+ .where(topic_id:, user_id: user_ids)
+ .where(
+ notification_level: [
+ TopicUser.notification_levels[:watching],
+ TopicUser.notification_levels[:tracking],
+ ],
+ )
+ .update_all(
+ notification_level: TopicUser.notification_levels[:regular],
+ notifications_reason_id: TopicUser.notification_reasons[:user_changed],
+ notifications_changed_at: Time.zone.now,
+ )
+ end
+
+ def sync_chat_channel_members
+ return if !event.chat_enabled?
+ ChatChannelSync.sync(event)
+ end
+
+ def update_topic_tracking!
+ tracking = :regular
+
+ case status
+ when Invitee.statuses[:going]
+ tracking = :watching
+ when Invitee.statuses[:interested]
+ tracking = :tracking
+ end
+
+ change_topic_tracking!(tracking)
+ end
+
+ def reset_topic_tracking!
+ self.class.reset_topic_tracking!(user_ids: user_id, topic_id: event&.post&.topic_id)
+ end
+
+ private
+
+ def change_topic_tracking!(tracking)
+ topic = event&.post&.topic
+ return if topic.nil?
+
+ TopicUser.change(
+ user_id,
+ topic.id,
+ notification_level: TopicUser.notification_levels[tracking],
+ )
+ end
+
+ def clear_recurring_unless_going
+ self.recurring = false unless going?
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_post_event_invitees
+#
+# id :bigint not null, primary key
+# notified :boolean default(FALSE), not null
+# recurring :boolean default(FALSE), not null
+# status :integer
+# created_at :datetime not null
+# updated_at :datetime not null
+# post_id :integer not null
+# user_id :integer not null
+#
+# Indexes
+#
+# discourse_post_event_invitees_post_id_user_id_idx (post_id,user_id) UNIQUE
+#
diff --git a/plugins/discourse-events/app/models/discourse_calendar/disabled_holiday.rb b/plugins/discourse-events/app/models/discourse_events/holidays/disabled_holiday.rb
similarity index 56%
rename from plugins/discourse-events/app/models/discourse_calendar/disabled_holiday.rb
rename to plugins/discourse-events/app/models/discourse_events/holidays/disabled_holiday.rb
index 1579224cd4a..0ecdd65194e 100644
--- a/plugins/discourse-events/app/models/discourse_calendar/disabled_holiday.rb
+++ b/plugins/discourse-events/app/models/discourse_events/holidays/disabled_holiday.rb
@@ -1,9 +1,15 @@
# frozen_string_literal: true
-module DiscourseCalendar
- class DisabledHoliday < ActiveRecord::Base
- validates :holiday_name, presence: true
- validates :region_code, presence: true
+module DiscourseEvents
+ module Holidays
+ class DisabledHoliday < ActiveRecord::Base
+ # Pinned: the engine's `isolate_namespace` would otherwise derive
+ # "discourse_events_disabled_holidays" from the namespace.
+ self.table_name = "discourse_calendar_disabled_holidays"
+
+ validates :holiday_name, presence: true
+ validates :region_code, presence: true
+ end
end
end
diff --git a/plugins/discourse-events/app/models/discourse_calendar/livestream/topic_chat_channel.rb b/plugins/discourse-events/app/models/discourse_events/livestream/topic_chat_channel.rb
similarity index 96%
rename from plugins/discourse-events/app/models/discourse_calendar/livestream/topic_chat_channel.rb
rename to plugins/discourse-events/app/models/discourse_events/livestream/topic_chat_channel.rb
index 632c7691061..c0e1dd6ff7f 100644
--- a/plugins/discourse-events/app/models/discourse_calendar/livestream/topic_chat_channel.rb
+++ b/plugins/discourse-events/app/models/discourse_events/livestream/topic_chat_channel.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Livestream
class TopicChatChannel < ActiveRecord::Base
self.table_name = "livestream_topic_chat_channels"
diff --git a/plugins/discourse-events/app/models/discourse_post_event/event.rb b/plugins/discourse-events/app/models/discourse_post_event/event.rb
deleted file mode 100644
index c21827bb968..00000000000
--- a/plugins/discourse-events/app/models/discourse_post_event/event.rb
+++ /dev/null
@@ -1,720 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class Event < ActiveRecord::Base
- PUBLIC_GROUP = "trust_level_0"
- # Keep in sync with the constants of the same name in the
- # DiscoursePostEventEvent JS model.
- EARLY_ACCESS_MINUTES = 30
- GRACE_PERIOD_MINUTES = 10
- MIN_NAME_LENGTH = 5
- MAX_NAME_LENGTH = 255
- MAX_DESCRIPTION_LENGTH = 1000
- DEFAULT_TIMEZONE = "UTC"
-
- self.table_name = "discourse_post_event_events"
- self.ignored_columns = %w[starts_at ends_at]
-
- has_many :event_dates, dependent: :destroy
- # this is a cross plugin dependency, only called if chat is enabled
- belongs_to :chat_channel, class_name: "Chat::Channel"
- has_many :invitees, foreign_key: :post_id, dependent: :delete_all
- belongs_to :post, foreign_key: :id
- belongs_to :image_upload, class_name: "Upload", optional: true
- has_many :upload_references, as: :target, dependent: :destroy
-
- scope :visible, -> { where(deleted_at: nil) }
- scope :open, -> { where(closed: false) }
-
- before_validation :reset_invalid_livestream
- before_save :chat_channel_sync
- # prepend so it runs before `dependent: :delete_all` wipes the invitees
- before_destroy :reset_invitees_topic_tracking, prepend: true
- after_commit :create_livestream_chat_channel, on: %i[create update]
- after_commit :enqueue_warm_livestream_onebox, on: %i[create update]
- after_commit :destroy_topic_custom_field, on: %i[destroy]
- after_commit :create_or_update_event_date, on: %i[create update]
- after_save do
- if saved_change_to_image_upload_id?
- UploadReference.ensure_exist!(upload_ids: [image_upload_id], target: self)
- end
- end
-
- validate :raw_invitees_are_groups
- validates :original_starts_at, presence: true
- validates :name,
- length: {
- in: MIN_NAME_LENGTH..MAX_NAME_LENGTH,
- },
- unless: ->(event) { event.name.blank? }
- validates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }
- validates :max_attendees, numericality: { only_integer: true, greater_than: 0, allow_nil: true }
-
- validate :raw_invitees_length
- validate :ends_before_start
- validate :allowed_custom_fields
- validate :url_is_a_uri, if: :url_changed?
-
- def self.attributes_protected_by_default
- super - %w[id]
- end
-
- def reset_invalid_livestream
- return unless livestream?
-
- self.livestream = false unless allowed_livestream_url? && post&.is_first_post?
- end
-
- def allowed_livestream_url?
- DiscourseCalendar::Livestream::AllowedHosts.allows_url?(livestream_url)
- end
-
- def create_livestream_chat_channel
- return unless livestream? && SiteSetting.chat_enabled
- return unless post&.is_first_post?
- return if post.topic.blank?
-
- DiscourseCalendar::Livestream.handle_topic_chat_channel_creation(post.topic)
- end
-
- def has_cached_livestream_onebox?
- livestream? && livestream_url.present? && Oneboxer.cached_onebox(livestream_url).present?
- end
-
- # Happens after the event record is saved to prepare the onebox
- def enqueue_warm_livestream_onebox
- return if !livestream? || livestream_url.blank?
- return if !saved_change_to_livestream? && !saved_change_to_location? && !saved_change_to_url?
- return if has_cached_livestream_onebox?
- Jobs.enqueue(:warm_livestream_onebox, event_id: id, url: livestream_url)
- end
-
- # Fetches the onebox and tells clients to re-render the post with it. Only
- # ever called from the background job, never during a request.
- def warm_livestream_onebox!
- return if has_cached_livestream_onebox?
- Oneboxer.onebox(livestream_url)
- post&.publish_change_to_clients!(:revised)
- end
-
- def 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
-
- 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
- end
-
- def 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
- end
-
- def set_next_date
- return if closed
-
- next_date_result = calculate_next_date
-
- return event_dates.update_all(finished_at: Time.current) if next_date_result.nil?
-
- starts_at, ends_at = next_date_result
- finish_previous_event_dates(starts_at) if dates_changed?
- upsert_event_date(starts_at, ends_at)
- reset_invitee_notifications
- notify_if_new_event
- publish_update!
- end
-
- def set_topic_bump
- return if closed
-
- date = nil
-
- return if reminders.blank? || starts_at.nil?
- reminders
- .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
- end
-
- return if date.blank?
- Jobs.enqueue(:discourse_post_event_bump_topic, topic_id: post.topic_id, date: date.iso8601)
- end
-
- def validate_reminder_unit(input)
- ActiveSupport::Duration::PARTS.any? { |part| part.to_s == input }
- end
-
- def expired?
- if recurring?
- return false if recurrence_until.nil?
- return Time.current > recurrence_until
- end
-
- return true if starts_at.nil?
- (ends_at || starts_at.end_of_day) <= Time.now
- end
-
- # Mirrors `currentlyWithinEventTimeframe` in the DiscoursePostEventEvent JS
- # model: joining opens EARLY_ACCESS_MINUTES before the start and, when the
- # event has an end time, closes GRACE_PERIOD_MINUTES after it.
- def currently_within_event_timeframe?
- return false if starts_at.nil?
-
- now = Time.zone.now
-
- if all_day
- opens_at = starts_at.beginning_of_day
- closes_at = (ends_at || starts_at).end_of_day
- return opens_at <= now && now <= closes_at
- end
-
- return false if now < starts_at - EARLY_ACCESS_MINUTES.minutes
- ends_at.nil? || now < ends_at + GRACE_PERIOD_MINUTES.minutes
- end
-
- def starts_at
- return nil if recurring? && recurrence_until.present? && recurrence_until < Time.current
- current_event_date&.starts_at || original_starts_at
- end
-
- def ends_at
- return nil if recurring? && recurrence_until.present? && recurrence_until < Time.current
- current_event_date&.ends_at || original_ends_at
- end
-
- def current_event_date
- if association(:event_dates).loaded?
- pending = event_dates.select { |d| d.finished_at.nil? }
- pending.max_by(&:starts_at) || event_dates.max_by { |d| [d.updated_at, d.id] }
- else
- event_dates.current_first.first
- end
- end
-
- def on_going_event_invitees
- return [] if starts_at.nil? # Can't determine ongoing status without start time
- if !ends_at && starts_at < Time.now && (!all_day || starts_at.end_of_day <= Time.now)
- return []
- end
-
- if ends_at
- extended_ends_at =
- ends_at + SiteSetting.discourse_post_event_edit_notifications_time_extension.minutes
- return [] if !(starts_at..extended_ends_at).cover?(Time.now)
- end
-
- invitees.where(status: DiscoursePostEvent::Invitee.statuses[:going])
- end
-
- def raw_invitees_length
- if raw_invitees && raw_invitees.length > 10
- errors.add(
- :base,
- I18n.t("discourse_post_event.errors.models.event.raw_invitees_length", count: 10),
- )
- end
- end
-
- def raw_invitees_are_groups
- return if raw_invitees.blank?
-
- non_group_invitees = raw_invitees - Group.where(name: raw_invitees).pluck(:name)
- return if non_group_invitees.blank?
-
- if User.where(username: non_group_invitees).exists?
- errors.add(
- :base,
- I18n.t("discourse_post_event.errors.models.event.raw_invitees.only_group"),
- )
- end
- end
-
- def ends_before_start
- if original_starts_at && original_ends_at && original_starts_at >= original_ends_at
- errors.add(
- :base,
- I18n.t("discourse_post_event.errors.models.event.ends_at_before_starts_at"),
- )
- end
- end
-
- def url_is_a_uri
- return if EventParser.valid_url?(url)
-
- errors.add(:base, I18n.t("discourse_post_event.errors.models.event.invalid_url"))
- end
-
- def allowed_custom_fields
- allowed_custom_fields = SiteSetting.discourse_post_event_allowed_custom_fields.split("|")
- custom_fields.each do |key, value|
- if !allowed_custom_fields.include?(key)
- errors.add(
- :base,
- I18n.t("discourse_post_event.errors.models.event.custom_field_is_invalid", field: key),
- )
- end
- end
- end
-
- def create_invitees(attrs)
- timestamp = Time.now
- attrs.map! do |attr|
- { post_id: id, created_at: timestamp, updated_at: timestamp }.merge(attr)
- end
- result = invitees.insert_all!(attrs)
-
- # batch event does not call callback
- ChatChannelSync.sync(self) if chat_enabled?
-
- result
- end
-
- def notify_invitees!(predefined_attendance: false)
- invitees
- .where(notified: false)
- .find_each do |invitee|
- create_notification!(invitee.user, post, predefined_attendance: predefined_attendance)
- invitee.update!(notified: true)
- end
- end
-
- def notify_missing_invitees!
- missing_users.each { |user| create_notification!(user, post) } if private?
- end
-
- def create_notification!(user, post, predefined_attendance: false)
- return if post.event.starts_at.nil? || post.event.starts_at < Time.current
- return if !Guardian.new(user).can_see?(post)
-
- message =
- if predefined_attendance
- "discourse_post_event.notifications.invite_user_predefined_attendance_notification"
- else
- "discourse_post_event.notifications.invite_user_notification"
- end
-
- attrs = {
- notification_type: Notification.types[:event_invitation] || Notification.types[:custom],
- topic_id: post.topic_id,
- post_number: post.post_number,
- data: {
- user_id: user.id,
- topic_title: name || post.topic.title,
- display_username: post.user.username,
- message: message,
- event_name: name,
- }.to_json,
- }
-
- user.notifications.consolidate_or_create!(attrs)
- end
-
- def ongoing?
- return false if closed || expired? || starts_at.nil?
- finishes_at = ends_at || starts_at.end_of_day
- (starts_at..finishes_at).cover?(Time.now)
- end
-
- def going_count
- invitees.where(status: Invitee.statuses[:going]).count
- end
-
- def at_capacity?
- return false if max_attendees.blank?
- going_count >= max_attendees
- end
-
- def self.statuses
- @statuses ||= Enum.new(standalone: 0, public: 1, private: 2)
- end
-
- def public?
- status == Event.statuses[:public]
- end
-
- def standalone?
- status == Event.statuses[:standalone]
- end
-
- def private?
- status == Event.statuses[:private]
- end
-
- def recurring?
- recurrence.present?
- end
-
- def most_likely_going(limit = SiteSetting.displayed_invitees_limit)
- going = invitees.order(%i[status created_at user_id]).limit(limit)
-
- if private? && going.count < 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) }
- end
-
- going
- end
-
- def publish_update!
- post.publish_message!("/discourse-post-event/#{post.topic_id}", id: id)
- end
-
- def fetch_users
- @fetched_users ||= Invitee.extract_uniq_usernames(raw_invitees)
- end
-
- def enforce_private_invitees!
- pruned = invitees.where.not(user_id: fetch_users.select(:id))
- pruned_user_ids = pruned.pluck(:user_id)
- pruned.delete_all
- Invitee.reset_topic_tracking!(user_ids: pruned_user_ids, topic_id: post.topic_id)
- unfollow_livestream_chat(pruned_user_ids)
- end
-
- # Unfollow users from the livestream chat channel once they are no longer
- # attending (e.g. pruned when a private event's invited groups change). Chat
- # following tracks attendance, so removed attendees should not keep the
- # channel in their chat list.
- def unfollow_livestream_chat(user_ids)
- return if user_ids.blank?
-
- channel = post.topic.topic_chat_channel&.chat_channel
- return if channel.nil?
-
- manager = Chat::ChannelMembershipManager.new(channel)
- User
- .where(id: user_ids)
- .find_each do |user|
- membership = manager.unfollow(user)
- next if membership.nil?
- DiscourseCalendar::Livestream.publish_livestream_chat_status(membership, user:)
- end
- end
-
- def user_in_invited_group?(user, group_names: nil)
- return false if user.blank? || raw_invitees.blank?
-
- return (Array(raw_invitees) & Array(group_names)).any? unless group_names.nil?
-
- GroupUser.where(
- user_id: user.id,
- group_id: Group.where(name: raw_invitees).select(:id),
- ).exists?
- end
-
- # Unlike can_user_update_attendance?, this stays true after the event
- # closes or expires so attendees keep access to the livestream chat.
- #
- # Callers serializing many events at once (e.g. the chat channel list) can
- # pass preloaded group_names to avoid a per-event query.
- def can_access_livestream_chat?(user, group_names: nil)
- return true if !private?
- return false if user.blank?
- return true if user.admin?
-
- user_in_invited_group?(user, group_names:)
- end
-
- def can_user_update_attendance?(user, group_names: nil)
- return false if user.blank? || closed || expired?
- return true if public?
-
- private? && user_in_invited_group?(user, group_names:)
- end
-
- def sync_image_to_post_and_topic(generate_thumbnails: false)
- return unless image_upload_id
-
- post.update_column(:image_upload_id, image_upload_id)
- if post.is_first_post?
- post.topic.update_column(:image_upload_id, image_upload_id)
- if generate_thumbnails
- extra_sizes =
- ThemeModifierHelper.new(
- theme_ids: Theme.user_selectable.pluck(:id),
- ).topic_thumbnail_sizes
- post.topic.generate_thumbnails!(extra_sizes: extra_sizes)
- end
- end
- end
-
- def 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
- payload = WebHook.build_calendar_event_payload(event_before)
- WebHook.enqueue_calendar_event_hooks(:calendar_event_destroyed, event_before, payload)
- end
- end
-
- def missing_users(excluded_ids = invitees.select(:user_id))
- users = User.real.activated.not_silenced.not_suspended.not_staged
-
- if raw_invitees.present?
- user_ids =
- users
- .joins(:groups)
- .where("groups.name" => raw_invitees)
- .where.not(id: excluded_ids)
- .select(:id)
- User.where(id: user_ids)
- elsif private?
- User.none
- else
- users.where.not(id: excluded_ids)
- end
- end
-
- SUGGESTED_USERS_LIMIT = 10
-
- # Users that could be invited to this event, ranked by how closely their
- # username matches +filter+ (exact match first). Already-invited users are
- # excluded, optionally narrowed to a given attendance +type+.
- def suggested_users(filter, type: nil)
- excluded = type ? invitees.with_status(type) : invitees
-
- missing_users(excluded.select(:user_id))
- .where(
- "LOWER(username) LIKE :filter",
- filter: "%#{User.sanitize_sql_like(filter.downcase)}%",
- )
- .order(
- DB.sql_fragment(
- "CASE WHEN LOWER(username) = ? THEN 0 ELSE 1 END ASC, LOWER(username) ASC",
- filter.downcase,
- ),
- )
- .limit(SUGGESTED_USERS_LIMIT)
- end
-
- def 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
-
- publish_update!
- end
-
- def chat_channel_sync
- if chat_enabled && chat_channel_id.blank? && post.last_editor_id.present?
- DiscoursePostEvent::ChatChannelSync.sync(
- self,
- guardian: Guardian.new(User.find_by(id: post.last_editor_id)),
- )
- end
- end
-
- def calculate_next_date
- if recurrence.blank? || original_starts_at > Time.current
- return original_starts_at, original_ends_at
- end
-
- next_starts_at = calculate_next_recurring_date
- 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
- [next_starts_at, next_ends_at]
- end
-
- def calculate_next_occurrence_from(from_time)
- return nil if recurrence.blank?
- if original_starts_at > from_time
- return { starts_at: original_starts_at, ends_at: original_ends_at }
- end
-
- next_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 }
- end
-
- def duration
- return nil unless original_starts_at
-
- duration_seconds = original_ends_at ? original_ends_at - original_starts_at : 3600
- hours = (duration_seconds / 3600)
- minutes = ((duration_seconds % 3600) / 60)
- seconds = (duration_seconds % 60)
-
- sprintf("%02d:%02d:%02d", hours, minutes, seconds)
- end
-
- def rrule_timezone
- timezone || DEFAULT_TIMEZONE
- end
-
- def livestream_url
- location || url
- end
-
- def is_zoom_livestream?
- return false unless SiteSetting.livestream_zoom_enabled
- return false unless livestream?
- DiscourseCalendar::Livestream::ZoomUrlParser.zoom_url?(livestream_url)
- end
-
- private
-
- def reset_invitees_topic_tracking
- topic_id = post&.topic_id
- return if topic_id.nil?
-
- Invitee.reset_topic_tracking!(user_ids: invitees.pluck(:user_id), topic_id:)
- end
-
- def dates_changed?
- saved_change_to_original_starts_at || saved_change_to_original_ends_at
- end
-
- def finish_previous_event_dates(current_starts_at)
- existing_date = event_dates.find_by(starts_at: current_starts_at)
- event_dates
- .where.not(id: existing_date&.id)
- .where(finished_at: nil)
- .update_all(finished_at: Time.current)
- end
-
- def upsert_event_date(starts_at, ends_at)
- finished_at = ends_at && ends_at < Time.current ? ends_at : nil
-
- existing_date = event_dates.find_by(starts_at:)
-
- if existing_date
- # Only update if something actually changed
- unless existing_date.ends_at == ends_at && existing_date.finished_at == finished_at
- existing_date.update!(ends_at:, finished_at:)
- end
- else
- event_dates.create!(starts_at:, ends_at:, finished_at:)
- end
- end
-
- def reset_invitee_notifications
- invitees.where(
- "status != :going OR recurring = FALSE",
- going: Invitee.statuses[:going],
- ).update_all(status: nil, notified: false, recurring: false)
- end
-
- def notify_if_new_event
- is_generating_future_recurrence = recurrence.present? && original_starts_at <= Time.current
-
- unless is_generating_future_recurrence
- notify_invitees!
- notify_missing_invitees!
- end
- end
-
- def calculate_next_recurring_date
- timezone_starts_at = original_starts_at.in_time_zone(timezone)
- timezone_recurrence_until = recurrence_until&.in_time_zone(timezone)
-
- RRuleGenerator.generate(
- starts_at: timezone_starts_at,
- timezone: rrule_timezone,
- recurrence: recurrence,
- recurrence_until: timezone_recurrence_until,
- dtstart: timezone_starts_at,
- ).first
- end
-
- def calculate_next_recurring_date_from(from_time)
- timezone_starts_at = original_starts_at.in_time_zone(timezone)
- timezone_recurrence_until = recurrence_until&.in_time_zone(timezone)
- from_time_in_tz = from_time.in_time_zone(timezone)
-
- RRule::Rule
- .new(
- RRuleConfigurator.rule(
- recurrence_until: timezone_recurrence_until,
- recurrence: recurrence,
- starts_at: timezone_starts_at,
- ),
- dtstart: timezone_starts_at,
- tzid: rrule_timezone,
- )
- .between(from_time_in_tz - 1.hour, from_time_in_tz + 1.year)
- .find { |date| date >= from_time_in_tz }
- end
- end
-end
-
-# == Schema Information
-#
-# Table name: discourse_post_event_events
-#
-# id :bigint not null, primary key
-# all_day :boolean default(FALSE), not null
-# chat_enabled :boolean default(FALSE), not null
-# closed :boolean default(FALSE), not null
-# custom_fields :jsonb not null
-# deleted_at :datetime
-# description :string(1000)
-# livestream :boolean default(FALSE), not null
-# location :string(1000)
-# max_attendees :integer
-# minimal :boolean
-# name :string
-# original_ends_at :datetime
-# original_starts_at :datetime not null
-# raw_invitees :string is an Array
-# recurrence :string
-# recurrence_until :datetime
-# reminders :string
-# show_local_time :boolean default(FALSE), not null
-# status :integer default(0), not null
-# timezone :string
-# url :string(1000)
-# chat_channel_id :bigint
-# image_upload_id :bigint
-#
-# Indexes
-#
-# index_discourse_post_event_events_on_image_upload_id (image_upload_id)
-#
diff --git a/plugins/discourse-events/app/models/discourse_post_event/event_date.rb b/plugins/discourse-events/app/models/discourse_post_event/event_date.rb
deleted file mode 100644
index f3ad063b52d..00000000000
--- a/plugins/discourse-events/app/models/discourse_post_event/event_date.rb
+++ /dev/null
@@ -1,92 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EventDate < ActiveRecord::Base
- self.table_name = "discourse_calendar_post_event_dates"
- belongs_to :event
-
- scope :pending,
- -> { where(finished_at: nil).joins(:event).merge(DiscoursePostEvent::Event.visible.open) }
- scope :expired, -> { where("ends_at IS NOT NULL AND ends_at < ?", Time.now) }
- scope :not_expired, -> { where("ends_at IS NULL OR ends_at > ?", Time.now) }
-
- scope :current_first, -> { order(Arel.sql(current_ordering_sql)) }
-
- def self.current_ordering_sql
- <<~SQL.squish
- finished_at IS NOT NULL,
- CASE WHEN finished_at IS NULL THEN starts_at ELSE updated_at END DESC,
- id DESC
- SQL
- end
-
- after_commit :upsert_topic_custom_field, on: %i[create update]
- def upsert_topic_custom_field
- if event.post && event.post.is_first_post?
- TopicCustomField.upsert(
- {
- topic_id: event.post.topic_id,
- name: TOPIC_POST_EVENT_STARTS_AT,
- value: starts_at,
- created_at: Time.now,
- updated_at: Time.now,
- },
- unique_by: "idx_topic_custom_fields_topic_post_event_starts_at",
- )
-
- TopicCustomField.upsert(
- {
- topic_id: event.post.topic_id,
- name: TOPIC_POST_EVENT_ENDS_AT,
- value: ends_at,
- created_at: Time.now,
- updated_at: Time.now,
- },
- unique_by: "idx_topic_custom_fields_topic_post_event_ends_at",
- )
-
- TopicCustomField.upsert(
- {
- topic_id: event.post.topic_id,
- name: TOPIC_POST_EVENT_ALL_DAY,
- value: event.all_day || false,
- created_at: Time.now,
- updated_at: Time.now,
- },
- unique_by: "idx_topic_custom_fields_topic_post_event_all_day",
- )
- end
- end
-
- def started?
- starts_at <= Time.current
- end
-
- def ended?
- (ends_at || starts_at.end_of_day) <= Time.current
- end
- end
-end
-
-# == Schema Information
-#
-# Table name: discourse_calendar_post_event_dates
-#
-# id :bigint not null, primary key
-# ends_at :datetime
-# event_started_sent_at :datetime
-# event_will_start_sent_at :datetime
-# finished_at :datetime
-# reminder_counter :integer default(0)
-# starts_at :datetime
-# created_at :datetime not null
-# updated_at :datetime not null
-# event_id :integer
-#
-# Indexes
-#
-# idx_discourse_calendar_post_event_dates_event_id_starts_at_uniq (event_id,starts_at) UNIQUE
-# index_discourse_calendar_post_event_dates_on_event_id (event_id)
-# index_discourse_calendar_post_event_dates_on_event_id_and_dates (event_id,finished_at,starts_at DESC,updated_at DESC,id DESC)
-# index_discourse_calendar_post_event_dates_on_finished_at (finished_at)
-#
diff --git a/plugins/discourse-events/app/models/discourse_post_event/invitee.rb b/plugins/discourse-events/app/models/discourse_post_event/invitee.rb
deleted file mode 100644
index 76fff4e4f5c..00000000000
--- a/plugins/discourse-events/app/models/discourse_post_event/invitee.rb
+++ /dev/null
@@ -1,155 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class Invitee < ActiveRecord::Base
- self.table_name = "discourse_post_event_invitees"
-
- belongs_to :event, foreign_key: :post_id
- belongs_to :user
-
- default_scope do
- joins(:user)
- .includes(:user)
- .merge(User.not_suspended)
- .merge(User.not_silenced)
- .merge(User.not_staged)
- .where.not(users: { id: nil })
- end
- scope :with_status, ->(status) { where(status: Invitee.statuses[status]) }
- scope :matching_username,
- ->(filter) do
- where(
- "LOWER(users.username) LIKE :filter",
- filter: "%#{sanitize_sql_like(filter.downcase)}%",
- )
- end
-
- before_save :clear_recurring_unless_going
- after_destroy :reset_topic_tracking!
- after_commit :sync_chat_channel_members
-
- def self.statuses
- @statuses ||= Enum.new(going: 0, interested: 1, not_going: 2)
- end
-
- def self.create_attendance!(user_id, post_id, status, recurring: false)
- status = status.to_sym
- event = Event.find(post_id)
-
- if status == :going && event.at_capacity?
- raise Discourse::InvalidParameters.new(:max_attendees)
- end
-
- invitee = create!(post_id:, user_id:, status: statuses[status], recurring:)
- invitee.publish_attendance_change!
- invitee
- rescue ActiveRecord::RecordNotUnique
- # multiple attendances may be created concurrently — return the winning row
- find_by(post_id:, user_id:)
- end
-
- def update_attendance!(status, recurring: false)
- status = status&.to_sym
-
- if status == :going && event.at_capacity? && !going?
- raise Discourse::InvalidParameters.new(:max_attendees)
- end
-
- update!(status: self.class.statuses[status], recurring:)
- publish_attendance_change!
- self
- end
-
- def going?
- status == Invitee.statuses[:going]
- end
-
- def publish_attendance_change!
- event.publish_update!
- update_topic_tracking!
- DiscourseEvent.trigger(:discourse_calendar_post_event_invitee_status_changed, self)
- end
-
- def self.extract_uniq_usernames(groups)
- User.real.where(
- id: GroupUser.where(group_id: Group.where(name: groups).select(:id)).select(:user_id),
- )
- end
-
- def self.reset_topic_tracking!(user_ids:, topic_id:)
- user_ids = Array(user_ids)
- return if user_ids.empty? || topic_id.nil?
-
- TopicUser
- .where(topic_id:, user_id: user_ids)
- .where(
- notification_level: [
- TopicUser.notification_levels[:watching],
- TopicUser.notification_levels[:tracking],
- ],
- )
- .update_all(
- notification_level: TopicUser.notification_levels[:regular],
- notifications_reason_id: TopicUser.notification_reasons[:user_changed],
- notifications_changed_at: Time.zone.now,
- )
- end
-
- def sync_chat_channel_members
- return if !event.chat_enabled?
- ChatChannelSync.sync(event)
- end
-
- def update_topic_tracking!
- tracking = :regular
-
- case status
- when Invitee.statuses[:going]
- tracking = :watching
- when Invitee.statuses[:interested]
- tracking = :tracking
- end
-
- change_topic_tracking!(tracking)
- end
-
- def reset_topic_tracking!
- self.class.reset_topic_tracking!(user_ids: user_id, topic_id: event&.post&.topic_id)
- end
-
- private
-
- def change_topic_tracking!(tracking)
- topic = event&.post&.topic
- return if topic.nil?
-
- TopicUser.change(
- user_id,
- topic.id,
- notification_level: TopicUser.notification_levels[tracking],
- )
- end
-
- def clear_recurring_unless_going
- self.recurring = false unless going?
- end
- end
-end
-
-# == Schema Information
-#
-# Table name: discourse_post_event_invitees
-#
-# id :bigint not null, primary key
-# notified :boolean default(FALSE), not null
-# recurring :boolean default(FALSE), not null
-# status :integer
-# created_at :datetime not null
-# updated_at :datetime not null
-# post_id :integer not null
-# user_id :integer not null
-#
-# Indexes
-#
-# discourse_post_event_invitees_post_id_user_id_idx (post_id,user_id) UNIQUE
-#
diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/basic_event_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/basic_event_serializer.rb
new file mode 100644
index 00000000000..f6497e2ed30
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/events/basic_event_serializer.rb
@@ -0,0 +1,130 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class BasicEventSerializer < ApplicationSerializer
+ attributes :id,
+ :category_id,
+ :name,
+ :recurrence,
+ :recurrence_until,
+ :starts_at,
+ :ends_at,
+ :rrule,
+ :show_local_time,
+ :timezone,
+ :post,
+ :duration,
+ :occurrences,
+ :all_day,
+ :custom_fields
+
+ def category_id
+ object.post&.topic&.category_id
+ end
+
+ def post
+ return nil if object.post.blank?
+
+ {
+ id: object.post.id,
+ post_number: object.post.post_number,
+ url: object.post.url,
+ category_slug:
+ (
+ if object.post.topic && object.post.topic.category
+ object.post.topic.category.slug_for_url
+ else
+ ""
+ end
+ ),
+ topic:
+ DiscourseEvents::Events::EventTopicSerializer.new(
+ object.post.topic,
+ scope:,
+ root: false,
+ ).as_json,
+ }
+ end
+
+ def include_rrule?
+ object.recurring?
+ end
+
+ def rrule
+ return nil unless include_rrule?
+
+ timezone_starts_at = object.original_starts_at.in_time_zone(object.timezone)
+ timezone_recurrence_until = object.recurrence_until&.in_time_zone(object.timezone)
+
+ DiscourseEvents::Events::RRuleGenerator.generate_string(
+ starts_at: timezone_starts_at,
+ recurrence: object.recurrence,
+ recurrence_until: timezone_recurrence_until,
+ dtstart: timezone_starts_at,
+ show_local_time: object.show_local_time,
+ )
+ end
+
+ def starts_at
+ return object.starts_at&.utc&.strftime("%Y-%m-%d") if object.all_day
+
+ if object.recurring? && object.recurrence_until.present? &&
+ object.recurrence_until < Time.current
+ return nil
+ end
+
+ timezone_time = object.starts_at&.in_time_zone(object.timezone)
+
+ if object.show_local_time
+ timezone_time&.strftime("%Y-%m-%dT%H:%M:%S")
+ else
+ timezone_time&.iso8601(3)
+ end
+ end
+
+ def ends_at
+ return object.ends_at&.utc&.strftime("%Y-%m-%d") if object.all_day
+
+ if object.recurring? && object.recurrence_until.present? &&
+ object.recurrence_until < Time.current
+ return nil
+ end
+
+ if object.show_local_time
+ ends_at = object.ends_at || (object.starts_at && object.starts_at + 1.hour)
+ timezone_ends_at = ends_at&.in_time_zone(object.timezone)
+ timezone_ends_at&.strftime("%Y-%m-%dT%H:%M:%S")
+ else
+ if object.ends_at
+ timezone_ends_at = object.ends_at&.in_time_zone(object.timezone)
+ timezone_ends_at&.iso8601(3)
+ else
+ base_starts_at = object.starts_at&.in_time_zone(object.timezone)
+ if base_starts_at
+ (base_starts_at + 1.hour).iso8601(3)
+ else
+ nil
+ end
+ end
+ end
+ end
+
+ def duration
+ object.duration
+ end
+
+ def include_duration?
+ object.duration.present?
+ end
+
+ def occurrences
+ @options[:occurrences]
+ end
+
+ def include_occurrences?
+ @options[:include_occurrences] != false
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb
new file mode 100644
index 00000000000..66a59f77ca0
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb
@@ -0,0 +1,227 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class EventSerializer < BasicEventSerializer
+ attributes :can_act_on_discourse_post_event
+ attributes :can_update_attendance
+ attributes :creator
+ attributes :is_closed
+ attributes :is_expired
+ attributes :is_ongoing
+ attributes :is_private
+ attributes :is_public
+ attributes :is_standalone
+ attributes :minimal
+ attributes :name
+ attributes :post
+ attributes :raw_invitees
+ attributes :recurrence
+ attributes :recurrence_until
+ attributes :reminders
+ attributes :sample_invitees
+ attributes :should_display_invitees
+ attributes :stats
+ attributes :status
+ attributes :url
+ attributes :description
+ attributes :description_html
+ attributes :location
+ attributes :location_html
+ attributes :url_restates_location
+ attributes :watching_invitee
+ attributes :chat_enabled
+ attributes :livestream
+ attributes :livestream_onebox
+ attributes :livestream_url
+ # TODO (martin) We need to merge this and the event channel ID which
+ # comes from chat_enabled on the event, we dont need 2 channels per event
+ attributes :livestream_chat_channel_id
+ attributes :is_zoom_livestream
+ attributes :channel
+ attributes :rrule
+ attributes :max_attendees
+ attributes :at_capacity
+
+ has_one :image_upload, embed: :object, serializer: UploadSerializer
+
+ def livestream_enabled
+ object.livestream? && object.livestream_url.present?
+ end
+
+ def include_livestream_onebox?
+ livestream_enabled && !object.is_zoom_livestream?
+ end
+
+ def include_livestream_chat_channel_id?
+ livestream_enabled
+ end
+
+ def include_livestream_url?
+ livestream_enabled
+ end
+
+ def is_zoom_livestream
+ object.is_zoom_livestream?
+ end
+
+ # Only ever reads the cache. Fetching here would put a blocking outbound
+ # request in the middle of serialization, once per event in a list. The
+ # `warm_livestream_onebox` job fills the cache and republishes the post.
+ def livestream_onebox
+ Oneboxer.cached_onebox(object.livestream_url).presence
+ end
+
+ def livestream_chat_channel_id
+ object.post.topic.topic_chat_channel&.id
+ end
+
+ def channel
+ ::Chat::ChannelSerializer.new(
+ object.chat_channel,
+ root: false,
+ scope:,
+ membership: object.chat_channel.membership_for(scope.current_user),
+ )
+ end
+
+ def include_channel?
+ object.chat_enabled && defined?(::Chat::ChannelSerializer) &&
+ object.chat_channel.present? && scope.can_chat? &&
+ scope.can_preview_chat_channel?(object.chat_channel)
+ end
+
+ def at_capacity
+ object.at_capacity?
+ end
+
+ def can_act_on_discourse_post_event
+ scope.can_act_on_discourse_post_event?(object)
+ end
+
+ def 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
+ end
+
+ def is_expired
+ object.expired?
+ end
+
+ def is_ongoing
+ object.ongoing?
+ end
+
+ def is_public
+ object.public?
+ end
+
+ def is_private
+ object.private?
+ end
+
+ def is_standalone
+ object.standalone?
+ end
+
+ def is_closed
+ object.closed
+ end
+
+ def status
+ Event.statuses[object.status]
+ end
+
+ def can_update_attendance
+ scope.current_user && object.can_user_update_attendance?(scope.current_user)
+ end
+
+ def creator
+ BasicUserSerializer.new(object.post.user, embed: :objects, root: false)
+ end
+
+ def stats
+ EventStatsSerializer.new(object, root: false).as_json
+ end
+
+ def watching_invitee
+ user = scope.current_user
+ if user && can_display_current_user_invitee?(user)
+ watching_invitee = Invitee.find_by(user_id: user.id, post_id: object.id)
+ end
+
+ InviteeSerializer.new(watching_invitee, root: false, scope:) if watching_invitee
+ end
+
+ def include_raw_invitees?
+ can_display_invitee_details?
+ end
+
+ def sample_invitees
+ invitees = object.most_likely_going
+ ActiveModel::ArraySerializer.new(invitees, each_serializer: InviteeSerializer, scope:)
+ end
+
+ def include_sample_invitees?
+ can_display_invitee_details?
+ end
+
+ def include_stats?
+ can_display_invitee_details?
+ end
+
+ def can_display_current_user_invitee?(user)
+ !object.private? || scope.can_act_on_discourse_post_event?(object) ||
+ object.user_in_invited_group?(user)
+ end
+
+ def can_display_invitee_details?
+ return @can_display_invitee_details if defined?(@can_display_invitee_details)
+ @can_display_invitee_details = scope.can_display_invitee_details?(object)
+ end
+
+ def should_display_invitees
+ (object.public? && object.invitees.count > 0) ||
+ (object.private? && can_display_invitee_details? && Array(object.raw_invitees).count > 0)
+ end
+
+ def include_url?
+ object.url.present?
+ end
+
+ def include_description_html?
+ object.description.present?
+ end
+
+ def description_html
+ Parser.cook_inline(object.description, post: object.post)
+ end
+
+ def include_location_html?
+ object.location.present?
+ end
+
+ def location_html
+ @location_html ||= Parser.cook_location(object.location, post: object.post)
+ end
+
+ def url_restates_location
+ return false if object.location.blank?
+
+ Parser.url_restates_location?(object.url, object.location, cooked_location: location_html)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/event_stats_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/event_stats_serializer.rb
new file mode 100644
index 00000000000..d58dc583d49
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/events/event_stats_serializer.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class EventStatsSerializer < ApplicationSerializer
+ attributes :going
+ attributes :going_recurring
+ attributes :interested
+ attributes :not_going
+ attributes :invited
+ attributes :capacity
+
+ def invited
+ unanswered = counts[nil] || 0
+
+ # when a group is private we know the list of possible users
+ # even if an invitee has not been created yet
+ unanswered += object.missing_users.count if object.private?
+
+ going + interested + not_going + unanswered
+ end
+
+ def going
+ @going ||= counts[Invitee.statuses[:going]] || 0
+ end
+
+ def going_recurring
+ @going_recurring ||=
+ object.invitees.where(status: Invitee.statuses[:going], recurring: true).count
+ end
+
+ def interested
+ @interested ||= counts[Invitee.statuses[:interested]] || 0
+ end
+
+ def not_going
+ @not_going ||= counts[Invitee.statuses[:not_going]] || 0
+ end
+
+ def counts
+ @counts ||= object.invitees.group(:status).count
+ end
+
+ def capacity
+ object.max_attendees
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/event_topic_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/event_topic_serializer.rb
new file mode 100644
index 00000000000..ec1f3c05e8d
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/events/event_topic_serializer.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class EventTopicSerializer < ApplicationSerializer
+ include TopicTagsMixin
+
+ attributes :id
+ attributes :title
+ attributes :slug
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/invitee_list_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/invitee_list_serializer.rb
new file mode 100644
index 00000000000..4762d2c3d6a
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/events/invitee_list_serializer.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class InviteeListSerializer < ApplicationSerializer
+ root false
+ attributes :meta
+ has_many :invitees, serializer: InviteeSerializer, embed: :objects
+
+ def invitees
+ object[:invitees]
+ end
+
+ def meta
+ {
+ suggested_users:
+ ActiveModel::ArraySerializer.new(
+ suggested_users,
+ each_serializer: BasicUserSerializer,
+ scope: scope,
+ ),
+ }
+ end
+
+ def include_meta?
+ suggested_users.present?
+ end
+
+ def suggested_users
+ object[:suggested_users]
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/invitee_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/invitee_serializer.rb
new file mode 100644
index 00000000000..30efef4a0ad
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/events/invitee_serializer.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class InviteeSerializer < ApplicationSerializer
+ attributes :id, :status, :recurring, :user, :post_id, :meta
+
+ def status
+ object.status ? Invitee.statuses[object.status] : nil
+ end
+
+ def include_id?
+ object.id
+ end
+
+ def user
+ BasicUserSerializer.new(object.user, embed: :objects, root: false)
+ end
+
+ def meta
+ {
+ event_should_display_invitees:
+ (object.event.public? && object.event.invitees.count > 0) ||
+ (object.event.private? && object.event.raw_invitees.count > 0),
+ event_stats: EventStatsSerializer.new(object.event, root: false),
+ }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/serializers/discourse_events/group_timezones/user_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/group_timezones/user_serializer.rb
new file mode 100644
index 00000000000..ec91a472d96
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/group_timezones/user_serializer.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module GroupTimezones
+ class UserSerializer < BasicUserSerializer
+ attributes :timezone, :on_holiday
+
+ def on_holiday
+ @options[:on_holiday] || false
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/serializers/discourse_post_event/basic_event_serializer.rb b/plugins/discourse-events/app/serializers/discourse_post_event/basic_event_serializer.rb
deleted file mode 100644
index 72565746682..00000000000
--- a/plugins/discourse-events/app/serializers/discourse_post_event/basic_event_serializer.rb
+++ /dev/null
@@ -1,128 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class BasicEventSerializer < ApplicationSerializer
- attributes :id,
- :category_id,
- :name,
- :recurrence,
- :recurrence_until,
- :starts_at,
- :ends_at,
- :rrule,
- :show_local_time,
- :timezone,
- :post,
- :duration,
- :occurrences,
- :all_day,
- :custom_fields
-
- def category_id
- object.post&.topic&.category_id
- end
-
- def post
- return nil if object.post.blank?
-
- {
- id: object.post.id,
- post_number: object.post.post_number,
- url: object.post.url,
- category_slug:
- (
- if object.post.topic && object.post.topic.category
- object.post.topic.category.slug_for_url
- else
- ""
- end
- ),
- topic:
- DiscoursePostEvent::EventTopicSerializer.new(
- object.post.topic,
- scope:,
- root: false,
- ).as_json,
- }
- end
-
- def include_rrule?
- object.recurring?
- end
-
- def rrule
- return nil unless include_rrule?
-
- timezone_starts_at = object.original_starts_at.in_time_zone(object.timezone)
- timezone_recurrence_until = object.recurrence_until&.in_time_zone(object.timezone)
-
- RRuleGenerator.generate_string(
- starts_at: timezone_starts_at,
- recurrence: object.recurrence,
- recurrence_until: timezone_recurrence_until,
- dtstart: timezone_starts_at,
- show_local_time: object.show_local_time,
- )
- end
-
- def starts_at
- return object.starts_at&.utc&.strftime("%Y-%m-%d") if object.all_day
-
- if object.recurring? && object.recurrence_until.present? &&
- object.recurrence_until < Time.current
- return nil
- end
-
- timezone_time = object.starts_at&.in_time_zone(object.timezone)
-
- if object.show_local_time
- timezone_time&.strftime("%Y-%m-%dT%H:%M:%S")
- else
- timezone_time&.iso8601(3)
- end
- end
-
- def ends_at
- return object.ends_at&.utc&.strftime("%Y-%m-%d") if object.all_day
-
- if object.recurring? && object.recurrence_until.present? &&
- object.recurrence_until < Time.current
- return nil
- end
-
- if object.show_local_time
- ends_at = object.ends_at || (object.starts_at && object.starts_at + 1.hour)
- timezone_ends_at = ends_at&.in_time_zone(object.timezone)
- timezone_ends_at&.strftime("%Y-%m-%dT%H:%M:%S")
- else
- if object.ends_at
- timezone_ends_at = object.ends_at&.in_time_zone(object.timezone)
- timezone_ends_at&.iso8601(3)
- else
- base_starts_at = object.starts_at&.in_time_zone(object.timezone)
- if base_starts_at
- (base_starts_at + 1.hour).iso8601(3)
- else
- nil
- end
- end
- end
- end
-
- def duration
- object.duration
- end
-
- def include_duration?
- object.duration.present?
- end
-
- def occurrences
- @options[:occurrences]
- end
-
- def include_occurrences?
- @options[:include_occurrences] != false
- end
- end
-end
diff --git a/plugins/discourse-events/app/serializers/discourse_post_event/event_serializer.rb b/plugins/discourse-events/app/serializers/discourse_post_event/event_serializer.rb
deleted file mode 100644
index db16bdcc734..00000000000
--- a/plugins/discourse-events/app/serializers/discourse_post_event/event_serializer.rb
+++ /dev/null
@@ -1,223 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EventSerializer < BasicEventSerializer
- attributes :can_act_on_discourse_post_event
- attributes :can_update_attendance
- attributes :creator
- attributes :is_closed
- attributes :is_expired
- attributes :is_ongoing
- attributes :is_private
- attributes :is_public
- attributes :is_standalone
- attributes :minimal
- attributes :name
- attributes :post
- attributes :raw_invitees
- attributes :recurrence
- attributes :recurrence_until
- attributes :reminders
- attributes :sample_invitees
- attributes :should_display_invitees
- attributes :stats
- attributes :status
- attributes :url
- attributes :description
- attributes :description_html
- attributes :location
- attributes :location_html
- attributes :url_restates_location
- attributes :watching_invitee
- attributes :chat_enabled
- attributes :livestream
- attributes :livestream_onebox
- attributes :livestream_url
- # TODO (martin) We need to merge this and the event channel ID which
- # comes from chat_enabled on the event, we dont need 2 channels per event
- attributes :livestream_chat_channel_id
- attributes :is_zoom_livestream
- attributes :channel
- attributes :rrule
- attributes :max_attendees
- attributes :at_capacity
-
- has_one :image_upload, embed: :object, serializer: UploadSerializer
-
- def livestream_enabled
- object.livestream? && object.livestream_url.present?
- end
-
- def include_livestream_onebox?
- livestream_enabled && !object.is_zoom_livestream?
- end
-
- def include_livestream_chat_channel_id?
- livestream_enabled
- end
-
- def include_livestream_url?
- livestream_enabled
- end
-
- def is_zoom_livestream
- object.is_zoom_livestream?
- end
-
- # Only ever reads the cache. Fetching here would put a blocking outbound
- # request in the middle of serialization, once per event in a list. The
- # `warm_livestream_onebox` job fills the cache and republishes the post.
- def livestream_onebox
- Oneboxer.cached_onebox(object.livestream_url).presence
- end
-
- def livestream_chat_channel_id
- object.post.topic.topic_chat_channel&.id
- end
-
- def channel
- ::Chat::ChannelSerializer.new(
- object.chat_channel,
- root: false,
- scope:,
- membership: object.chat_channel.membership_for(scope.current_user),
- )
- end
-
- def include_channel?
- object.chat_enabled && defined?(::Chat::ChannelSerializer) && object.chat_channel.present? &&
- scope.can_chat? && scope.can_preview_chat_channel?(object.chat_channel)
- end
-
- def at_capacity
- object.at_capacity?
- end
-
- def can_act_on_discourse_post_event
- scope.can_act_on_discourse_post_event?(object)
- end
-
- def 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
- end
-
- def is_expired
- object.expired?
- end
-
- def is_ongoing
- object.ongoing?
- end
-
- def is_public
- object.public?
- end
-
- def is_private
- object.private?
- end
-
- def is_standalone
- object.standalone?
- end
-
- def is_closed
- object.closed
- end
-
- def status
- Event.statuses[object.status]
- end
-
- def can_update_attendance
- scope.current_user && object.can_user_update_attendance?(scope.current_user)
- end
-
- def creator
- BasicUserSerializer.new(object.post.user, embed: :objects, root: false)
- end
-
- def stats
- EventStatsSerializer.new(object, root: false).as_json
- end
-
- def watching_invitee
- user = scope.current_user
- if user && can_display_current_user_invitee?(user)
- watching_invitee = Invitee.find_by(user_id: user.id, post_id: object.id)
- end
-
- InviteeSerializer.new(watching_invitee, root: false, scope:) if watching_invitee
- end
-
- def include_raw_invitees?
- can_display_invitee_details?
- end
-
- def sample_invitees
- invitees = object.most_likely_going
- ActiveModel::ArraySerializer.new(invitees, each_serializer: InviteeSerializer, scope:)
- end
-
- def include_sample_invitees?
- can_display_invitee_details?
- end
-
- def include_stats?
- can_display_invitee_details?
- end
-
- def can_display_current_user_invitee?(user)
- !object.private? || scope.can_act_on_discourse_post_event?(object) ||
- object.user_in_invited_group?(user)
- end
-
- def can_display_invitee_details?
- return @can_display_invitee_details if defined?(@can_display_invitee_details)
- @can_display_invitee_details = scope.can_display_invitee_details?(object)
- end
-
- def should_display_invitees
- (object.public? && object.invitees.count > 0) ||
- (object.private? && can_display_invitee_details? && Array(object.raw_invitees).count > 0)
- end
-
- def include_url?
- object.url.present?
- end
-
- def include_description_html?
- object.description.present?
- end
-
- def description_html
- EventParser.cook_inline(object.description, post: object.post)
- end
-
- def include_location_html?
- object.location.present?
- end
-
- def location_html
- @location_html ||= EventParser.cook_location(object.location, post: object.post)
- end
-
- def url_restates_location
- return false if object.location.blank?
-
- EventParser.url_restates_location?(
- object.url,
- object.location,
- cooked_location: location_html,
- )
- end
- end
-end
diff --git a/plugins/discourse-events/app/serializers/discourse_post_event/event_stats_serializer.rb b/plugins/discourse-events/app/serializers/discourse_post_event/event_stats_serializer.rb
deleted file mode 100644
index 801f803ba12..00000000000
--- a/plugins/discourse-events/app/serializers/discourse_post_event/event_stats_serializer.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EventStatsSerializer < ApplicationSerializer
- attributes :going
- attributes :going_recurring
- attributes :interested
- attributes :not_going
- attributes :invited
- attributes :capacity
-
- def invited
- unanswered = counts[nil] || 0
-
- # when a group is private we know the list of possible users
- # even if an invitee has not been created yet
- unanswered += object.missing_users.count if object.private?
-
- going + interested + not_going + unanswered
- end
-
- def going
- @going ||= counts[Invitee.statuses[:going]] || 0
- end
-
- def going_recurring
- @going_recurring ||=
- object.invitees.where(status: Invitee.statuses[:going], recurring: true).count
- end
-
- def interested
- @interested ||= counts[Invitee.statuses[:interested]] || 0
- end
-
- def not_going
- @not_going ||= counts[Invitee.statuses[:not_going]] || 0
- end
-
- def counts
- @counts ||= object.invitees.group(:status).count
- end
-
- def capacity
- object.max_attendees
- end
- end
-end
diff --git a/plugins/discourse-events/app/serializers/discourse_post_event/event_topic_serializer.rb b/plugins/discourse-events/app/serializers/discourse_post_event/event_topic_serializer.rb
deleted file mode 100644
index 48c81ce1330..00000000000
--- a/plugins/discourse-events/app/serializers/discourse_post_event/event_topic_serializer.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EventTopicSerializer < ApplicationSerializer
- include TopicTagsMixin
-
- attributes :id
- attributes :title
- attributes :slug
- end
-end
diff --git a/plugins/discourse-events/app/serializers/discourse_post_event/invitee_list_serializer.rb b/plugins/discourse-events/app/serializers/discourse_post_event/invitee_list_serializer.rb
deleted file mode 100644
index ac4c949d9f8..00000000000
--- a/plugins/discourse-events/app/serializers/discourse_post_event/invitee_list_serializer.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class InviteeListSerializer < ApplicationSerializer
- root false
- attributes :meta
- has_many :invitees, serializer: InviteeSerializer, embed: :objects
-
- def invitees
- object[:invitees]
- end
-
- def meta
- {
- suggested_users:
- ActiveModel::ArraySerializer.new(
- suggested_users,
- each_serializer: BasicUserSerializer,
- scope: scope,
- ),
- }
- end
-
- def include_meta?
- suggested_users.present?
- end
-
- def suggested_users
- object[:suggested_users]
- end
- end
-end
diff --git a/plugins/discourse-events/app/serializers/discourse_post_event/invitee_serializer.rb b/plugins/discourse-events/app/serializers/discourse_post_event/invitee_serializer.rb
deleted file mode 100644
index fabe3371ee5..00000000000
--- a/plugins/discourse-events/app/serializers/discourse_post_event/invitee_serializer.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class InviteeSerializer < ApplicationSerializer
- attributes :id, :status, :recurring, :user, :post_id, :meta
-
- def status
- object.status ? Invitee.statuses[object.status] : nil
- end
-
- def include_id?
- object.id
- end
-
- def user
- BasicUserSerializer.new(object.user, embed: :objects, root: false)
- end
-
- def meta
- {
- event_should_display_invitees:
- (object.event.public? && object.event.invitees.count > 0) ||
- (object.event.private? && object.event.raw_invitees.count > 0),
- event_stats: EventStatsSerializer.new(object.event, root: false),
- }
- end
- end
-end
diff --git a/plugins/discourse-events/app/serializers/user_timezone_serializer.rb b/plugins/discourse-events/app/serializers/user_timezone_serializer.rb
deleted file mode 100644
index f1625229132..00000000000
--- a/plugins/discourse-events/app/serializers/user_timezone_serializer.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-# frozen_string_literal: true
-
-class UserTimezoneSerializer < BasicUserSerializer
- attributes :timezone, :on_holiday
-
- def on_holiday
- @options[:on_holiday] || false
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_calendar/holiday.rb b/plugins/discourse-events/app/services/discourse_calendar/holiday.rb
deleted file mode 100644
index acb54346ea1..00000000000
--- a/plugins/discourse-events/app/services/discourse_calendar/holiday.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-# frozen_string_literal: true
-
-require "holidays"
-
-module DiscourseCalendar
- class Holiday
- def self.find_holidays_for(
- region_code:,
- start_date: Date.current.beginning_of_year,
- end_date: Date.current.end_of_year,
- show_holiday_observed_on_dates: false
- )
- holidays =
- Holidays.between(
- start_date,
- end_date,
- [region_code],
- show_holiday_observed_on_dates ? :observed : [],
- )
-
- holidays.map do |holiday|
- holiday[:disabled] = DiscourseCalendar::DisabledHoliday.where(
- region_code: region_code,
- ).exists?(holiday_name: holiday[:name])
- end
-
- holidays
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_calendar/categories/types/events.rb b/plugins/discourse-events/app/services/discourse_events/categories/types/events.rb
similarity index 99%
rename from plugins/discourse-events/app/services/discourse_calendar/categories/types/events.rb
rename to plugins/discourse-events/app/services/discourse_events/categories/types/events.rb
index 7bf777a18e4..5d69a2963df 100644
--- a/plugins/discourse-events/app/services/discourse_calendar/categories/types/events.rb
+++ b/plugins/discourse-events/app/services/discourse_events/categories/types/events.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Categories
module Types
class Events < ::Categories::Types::Base
diff --git a/plugins/discourse-events/app/services/discourse_events/events/action/expand_occurrences.rb b/plugins/discourse-events/app/services/discourse_events/events/action/expand_occurrences.rb
new file mode 100644
index 00000000000..bd666af64b3
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/action/expand_occurrences.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ module Action
+ class ExpandOccurrences < Service::ActionBase
+ MAX_LIMIT = 200
+
+ option :event
+ option :after
+ option :before, optional: true
+ option :limit, default: -> { 50 }
+ option :current_occurrence_only, default: -> { false }
+
+ def call
+ return non_recurring_result unless event.recurring?
+ return current_occurrence_result if current_occurrence_only
+
+ build_recurring_occurrences
+ end
+
+ private
+
+ def non_recurring_result
+ {
+ event: event,
+ occurrences: [{ starts_at: event.original_starts_at, ends_at: event.original_ends_at }],
+ }
+ end
+
+ def current_occurrence_result
+ starts_at = event.starts_at
+
+ return { event:, occurrences: [] } if starts_at.nil?
+ return { event:, occurrences: [] } if after && starts_at < after
+ return { event:, occurrences: [] } if before && starts_at >= before
+
+ { event:, occurrences: [{ starts_at:, ends_at: event.ends_at }] }
+ end
+
+ def build_recurring_occurrences
+ occurrences = []
+ current_time = after
+ count = 0
+ capped_limit = limit.clamp(1, MAX_LIMIT)
+
+ while count < capped_limit
+ occurrence = event.calculate_next_occurrence_from(current_time)
+ break unless occurrence
+
+ occurrence_starts_at = occurrence[:starts_at]
+ break if before && occurrence_starts_at >= before
+
+ occurrences << { starts_at: occurrence_starts_at, ends_at: occurrence[:ends_at] }
+ current_time = occurrence_starts_at + 1.second
+ count += 1
+ end
+
+ { event: event, occurrences: occurrences }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/action/parse_invitees_csv.rb b/plugins/discourse-events/app/services/discourse_events/events/action/parse_invitees_csv.rb
new file mode 100644
index 00000000000..199f7dc4392
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/action/parse_invitees_csv.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+require "csv"
+
+module DiscourseEvents
+ module Events
+ module Action
+ class ParseInviteesCsv < Service::ActionBase
+ DEFAULT_ATTENDANCE = "going"
+
+ option :file
+
+ def call
+ invitees = []
+ CSV.foreach(file.tempfile) do |identifier, attendance|
+ next if identifier.blank?
+ invitees << { identifier: identifier, attendance: attendance || DEFAULT_ATTENDANCE }
+ end
+ invitees
+ rescue StandardError
+ # A malformed or unreadable file yields no invitees; the empty result
+ # is surfaced as an upload error downstream.
+ []
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/bulk_invite.rb b/plugins/discourse-events/app/services/discourse_events/events/bulk_invite.rb
new file mode 100644
index 00000000000..991b879fa07
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/bulk_invite.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class BulkInvite
+ include Service::Base
+
+ params do
+ attribute :event_id, :integer
+ attribute :invitees, :array
+
+ before_validation { self.invitees = Array(invitees).reject(&:blank?) }
+
+ validates :event_id, presence: true
+ end
+
+ model :event
+ policy :can_edit_post
+ policy :can_create_event
+ policy :invitees_present
+
+ try { step :enqueue_bulk_invite }
+
+ private
+
+ def fetch_event(params:)
+ Event.find_by(id: params.event_id)
+ end
+
+ def can_edit_post(guardian:, event:)
+ guardian.can_edit?(event.post)
+ end
+
+ def can_create_event(guardian:)
+ guardian.can_create_discourse_post_event?
+ end
+
+ def invitees_present(params:)
+ params.invitees.present?
+ end
+
+ def enqueue_bulk_invite(event:, params:, guardian:)
+ Jobs.enqueue(
+ :discourse_post_event_bulk_invite,
+ event_id: event.id,
+ invitees: params.invitees,
+ current_user_id: guardian.user.id,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/create_invitee.rb b/plugins/discourse-events/app/services/discourse_events/events/create_invitee.rb
new file mode 100644
index 00000000000..a6ee1d465c8
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/create_invitee.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class CreateInvitee
+ include Service::Base
+
+ params do
+ attribute :event_id, :integer
+ attribute :status, :symbol
+ attribute :user_id, :integer
+ attribute :recurring, :boolean, default: false
+
+ validates :event_id, presence: true
+ validates :status, inclusion: { in: Invitee.statuses.keys }
+ end
+
+ model :event
+ policy :can_see_event
+ model :user
+ policy :can_update_attendance
+ policy :can_invite_user
+ policy :has_capacity
+
+ model :invitee, :create_invitee
+
+ private
+
+ def fetch_event(params:)
+ Event.find_by(id: params.event_id)
+ end
+
+ def can_see_event(guardian:, event:)
+ guardian.can_see?(event.post)
+ end
+
+ def fetch_user(params:, guardian:)
+ params.user_id ? User.find_by(id: params.user_id) : guardian.user
+ end
+
+ def can_update_attendance(event:, user:)
+ event.can_user_update_attendance?(user)
+ end
+
+ def can_invite_user(guardian:, event:, user:)
+ return true if guardian.user.id == user.id
+ guardian.can_act_on_discourse_post_event?(event)
+ end
+
+ def has_capacity(event:, params:)
+ params.status != :going || !event.at_capacity?
+ end
+
+ def create_invitee(user:, event:, params:)
+ Invitee.create_attendance!(user.id, event.id, params.status, recurring: params.recurring)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/csv_bulk_invite.rb b/plugins/discourse-events/app/services/discourse_events/events/csv_bulk_invite.rb
new file mode 100644
index 00000000000..764d752cbb6
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/csv_bulk_invite.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class CsvBulkInvite
+ include Service::Base
+
+ params do
+ attribute :event_id, :integer
+ # Declared only so the steps can read it; the contract drops any
+ # undeclared parameter.
+ attribute :file
+
+ validates :event_id, presence: true
+ end
+
+ model :event
+ policy :can_edit_post
+ policy :can_create_event
+ policy :file_present
+ model :invitees, :parse_invitees
+
+ try { step :enqueue_bulk_invite }
+
+ private
+
+ def fetch_event(params:)
+ Event.find_by(id: params.event_id)
+ end
+
+ def can_edit_post(guardian:, event:)
+ guardian.can_edit?(event.post)
+ end
+
+ def can_create_event(guardian:)
+ guardian.can_create_discourse_post_event?
+ end
+
+ def file_present(params:)
+ params.file.present?
+ end
+
+ def parse_invitees(params:)
+ Action::ParseInviteesCsv.call(file: params.file)
+ end
+
+ def enqueue_bulk_invite(event:, invitees:, guardian:)
+ Jobs.enqueue(
+ :discourse_post_event_bulk_invite,
+ event_id: event.id,
+ invitees: invitees,
+ current_user_id: guardian.user.id,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/destroy_event.rb b/plugins/discourse-events/app/services/discourse_events/events/destroy_event.rb
new file mode 100644
index 00000000000..bd66f86d043
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/destroy_event.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class DestroyEvent
+ include Service::Base
+
+ params do
+ attribute :event_id, :integer
+
+ validates :event_id, presence: true
+ end
+
+ model :event
+ policy :can_act_on_event
+
+ step :publish_event_update
+ model :webhook_payload, :build_webhook_payload
+ transaction { step :destroy_event }
+ step :enqueue_destroyed_webhooks
+
+ private
+
+ def fetch_event(params:)
+ Event.includes(:image_upload).find_by(id: params.event_id)
+ end
+
+ def can_act_on_event(guardian:, event:)
+ guardian.can_act_on_discourse_post_event?(event)
+ end
+
+ def publish_event_update(event:)
+ event.publish_update!
+ end
+
+ def build_webhook_payload(event:)
+ WebHook.build_calendar_event_payload(event)
+ end
+
+ def destroy_event(event:)
+ event.destroy!
+ end
+
+ def enqueue_destroyed_webhooks(event:, webhook_payload:)
+ WebHook.enqueue_calendar_event_hooks(:calendar_event_destroyed, event, webhook_payload)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/destroy_invitee.rb b/plugins/discourse-events/app/services/discourse_events/events/destroy_invitee.rb
new file mode 100644
index 00000000000..128fd826434
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/destroy_invitee.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class DestroyInvitee
+ include Service::Base
+
+ params do
+ attribute :post_id, :integer
+ attribute :id, :integer
+
+ validates :post_id, presence: true
+ validates :id, presence: true
+ end
+
+ model :event
+ model :invitee
+ policy :can_act_on_invitee
+ policy :can_see_event
+ policy :can_update_attendance
+
+ step :destroy
+ step :publish
+
+ private
+
+ def fetch_event(params:)
+ Event.find_by(id: params.post_id)
+ end
+
+ def fetch_invitee(event:, params:)
+ event.invitees.find_by(id: params.id)
+ end
+
+ def can_act_on_invitee(guardian:, invitee:)
+ guardian.can_act_on_invitee?(invitee)
+ end
+
+ def can_see_event(guardian:, event:)
+ guardian.can_see?(event.post)
+ end
+
+ def can_update_attendance(guardian:, event:)
+ event.can_user_update_attendance?(guardian.user)
+ end
+
+ def destroy(invitee:)
+ invitee.destroy!
+ end
+
+ def publish(event:)
+ event.publish_update!
+ end
+ end
+ end
+end
diff --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.rb
new file mode 100644
index 00000000000..dedd5566ad1
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ # Coerces the parsed event hash into the attributes accepted by Event#update_with_params!.
+ class Event::Action::AttributesFromRaw < Service::ActionBase
+ option :raw_event
+ option :current_status
+
+ def call
+ {
+ name: raw_event[:name],
+ original_starts_at: starts_at,
+ original_ends_at: ends_at,
+ url: raw_event[:url],
+ description: raw_event[:description],
+ location: raw_event[:location],
+ recurrence: raw_event[:recurrence],
+ recurrence_until: parse_in_zone(raw_event[:"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,
+ reminders: raw_event[:reminders],
+ raw_invitees: raw_event[:"allowed-groups"]&.split(","),
+ minimal: raw_event[:minimal],
+ closed: raw_event[:closed] || false,
+ chat_enabled: raw_event[:"chat-enabled"]&.downcase == "true",
+ livestream: raw_event[:livestream]&.downcase == "true",
+ max_attendees: raw_event[:"max-attendees"]&.to_i,
+ all_day: all_day?,
+ custom_fields: custom_fields,
+ }
+ end
+
+ private
+
+ def all_day?
+ raw_event[:"all-day"] == "true"
+ end
+
+ def timezone
+ ActiveSupport::TimeZone[raw_event[:timezone] || Event::DEFAULT_TIMEZONE]
+ end
+
+ def parse_in_zone(value)
+ value ? timezone.parse(value) : nil
+ end
+
+ 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
+ end
+
+ def custom_fields
+ SiteSetting
+ .discourse_post_event_allowed_custom_fields
+ .split("|")
+ .each_with_object({}) do |setting, fields|
+ value = raw_event[setting.to_sym]
+ fields[setting] = value if value.present?
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/event/action/resolve_image_upload.rb b/plugins/discourse-events/app/services/discourse_events/events/event/action/resolve_image_upload.rb
new file mode 100644
index 00000000000..c0de0811d9c
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/event/action/resolve_image_upload.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ # Resolves an event's image into an Upload, returning a secure upload only when the post author may use it.
+ class Event::Action::ResolveImageUpload < Service::ActionBase
+ option :image
+ option :post
+
+ def call
+ return if image.blank?
+
+ upload = find_upload
+ return if upload.nil?
+
+ upload if usable_by_author?(upload)
+ end
+
+ private
+
+ def find_upload
+ if image.start_with?("upload://")
+ sha1 = Upload.sha1_from_short_url(image)
+ Upload.find_by(sha1: sha1) if sha1
+ else
+ Upload.get_from_url(image)
+ end
+ end
+
+ def usable_by_author?(upload)
+ !upload.secure? || upload.user_id == post.user_id ||
+ UserUpload.exists?(upload_id: upload.id, user_id: post.user_id)
+ end
+ end
+ end
+end
diff --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.rb
new file mode 100644
index 00000000000..3d72c908d1d
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/event/sync_from_post.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ # Creates, updates or removes a post's event to match the `[event]` block in its raw.
+ class Event::SyncFromPost
+ include Service::Base
+
+ params do
+ attribute :post_id, :integer
+
+ validates :post_id, presence: true
+ end
+
+ model :post
+ model :raw_event, :parse_event, optional: true
+
+ only_if :event_removed do
+ step :remove_event
+ end
+
+ only_if :event_present do
+ model :event, :upsert_event
+ step :schedule_topic_bump
+ end
+
+ private
+
+ def fetch_post(params:)
+ Post.find_by(id: params.post_id)
+ end
+
+ def parse_event(post:)
+ Parser.extract_events(post).first
+ end
+
+ def event_removed(raw_event:, post:)
+ return if raw_event.present?
+ post.event.present?
+ end
+
+ def event_present(raw_event:)
+ raw_event.present?
+ end
+
+ def remove_event(post:)
+ post.event.destroy!
+ end
+
+ def upsert_event(post:, raw_event:)
+ event = post.event || Event.new(id: post.id)
+ attributes = Event::Action::AttributesFromRaw.call(raw_event:, current_status: event.status)
+ attributes[:image_upload_id] = Event::Action::ResolveImageUpload.call(
+ image: raw_event[:image],
+ post:,
+ )&.id
+ event.update_with_params!(attributes)
+ event
+ end
+
+ def schedule_topic_bump(event:)
+ event.set_topic_bump
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/invite.rb b/plugins/discourse-events/app/services/discourse_events/events/invite.rb
new file mode 100644
index 00000000000..47f002515da
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/invite.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class Invite
+ include Service::Base
+
+ params do
+ attribute :event_id, :integer
+ attribute :invites
+
+ before_validation { self.invites = Array(invites) }
+
+ validates :event_id, presence: true
+ end
+
+ model :event
+ policy :can_act_on_event
+ model :invited_users, optional: true
+
+ step :notify_invited_users
+
+ private
+
+ def fetch_event(params:)
+ Event.find_by(id: params.event_id)
+ end
+
+ def can_act_on_event(guardian:, event:)
+ guardian.can_act_on_discourse_post_event?(event)
+ end
+
+ def fetch_invited_users(params:)
+ User.real.where(username: params.invites)
+ end
+
+ def notify_invited_users(event:, invited_users:)
+ invited_users.each { |user| event.create_notification!(user, event.post) }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/list_invitees.rb b/plugins/discourse-events/app/services/discourse_events/events/list_invitees.rb
new file mode 100644
index 00000000000..8092f4be703
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/list_invitees.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class ListInvitees
+ include Service::Base
+
+ MAX_INVITEES = 200
+
+ params do
+ attribute :post_id, :integer
+ attribute :filter, :string
+ attribute :type, :symbol
+
+ validates :post_id, presence: true
+ validates :type, inclusion: { in: Invitee.statuses.keys }, allow_blank: true
+ end
+
+ model :event
+ policy :can_see_event
+ model :invitees, optional: true
+ model :suggested_users, optional: true
+
+ private
+
+ def fetch_event(params:)
+ Event.find_by(id: params.post_id)
+ end
+
+ def can_see_event(guardian:, event:)
+ guardian.can_see?(event.post) && guardian.can_display_invitee_details?(event)
+ end
+
+ def fetch_invitees(event:, params:)
+ invitees = event.invitees
+ invitees = invitees.with_status(params.type) if params.type.present?
+ invitees = invitees.matching_username(params.filter) if params.filter.present?
+ invitees.order(%i[status username_lower]).limit(MAX_INVITEES)
+ end
+
+ def fetch_suggested_users(guardian:, event:, params:)
+ return User.none if params.filter.blank?
+ return User.none unless guardian.can_act_on_discourse_post_event?(event)
+ event.suggested_users(params.filter, type: params.type)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_events/events/update_invitee.rb b/plugins/discourse-events/app/services/discourse_events/events/update_invitee.rb
new file mode 100644
index 00000000000..05438b841a7
--- /dev/null
+++ b/plugins/discourse-events/app/services/discourse_events/events/update_invitee.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class UpdateInvitee
+ include Service::Base
+
+ params do
+ attribute :event_id, :integer
+ attribute :invitee_id, :integer
+ attribute :status, :symbol
+ attribute :recurring, :boolean, default: false
+
+ validates :event_id, presence: true
+ validates :invitee_id, presence: true
+ validates :status, inclusion: { in: Invitee.statuses.keys }
+ end
+
+ model :invitee
+ policy :can_act_on_invitee
+ model :event
+ policy :can_see_event
+ policy :can_update_attendance
+ policy :has_capacity
+
+ step :update
+
+ private
+
+ def fetch_invitee(params:)
+ Invitee.find_by(id: params.invitee_id, post_id: params.event_id)
+ end
+
+ def can_act_on_invitee(guardian:, invitee:)
+ guardian.can_act_on_invitee?(invitee)
+ end
+
+ def fetch_event(invitee:)
+ invitee.event
+ end
+
+ def can_see_event(guardian:, event:)
+ guardian.can_see?(event.post)
+ end
+
+ def can_update_attendance(guardian:, event:)
+ event.can_user_update_attendance?(guardian.user)
+ end
+
+ def has_capacity(event:, invitee:, params:)
+ params.status != :going || !event.at_capacity? || invitee.status == Invitee.statuses[:going]
+ end
+
+ def update(invitee:, params:)
+ invitee.update_attendance!(params.status, recurring: params.recurring)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/app/services/discourse_calendar/livestream/prepare_zoom_join.rb b/plugins/discourse-events/app/services/discourse_events/livestream/prepare_zoom_join.rb
similarity index 89%
rename from plugins/discourse-events/app/services/discourse_calendar/livestream/prepare_zoom_join.rb
rename to plugins/discourse-events/app/services/discourse_events/livestream/prepare_zoom_join.rb
index f691250db9a..c3eb43025ea 100644
--- a/plugins/discourse-events/app/services/discourse_calendar/livestream/prepare_zoom_join.rb
+++ b/plugins/discourse-events/app/services/discourse_events/livestream/prepare_zoom_join.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-class DiscourseCalendar::Livestream::PrepareZoomJoin
+class DiscourseEvents::Livestream::PrepareZoomJoin
include Service::Base
params do
@@ -58,11 +58,11 @@ class DiscourseCalendar::Livestream::PrepareZoomJoin
end
def build_zoom_join_data(event:)
- DiscourseCalendar::Livestream::ZoomUrlParser.parse(event.livestream_url)
+ DiscourseEvents::Livestream::ZoomUrlParser.parse(event.livestream_url)
end
def build_zoom_join_payload(topic:, zoom_join_data:, guardian:)
- DiscourseCalendar::Livestream::ZoomPayloadBuilder.call(
+ DiscourseEvents::Livestream::ZoomPayloadBuilder.call(
topic:,
zoom_join_data:,
user: guardian.user,
diff --git a/plugins/discourse-events/app/services/discourse_calendar/livestream/zoom_payload_builder.rb b/plugins/discourse-events/app/services/discourse_events/livestream/zoom_payload_builder.rb
similarity index 93%
rename from plugins/discourse-events/app/services/discourse_calendar/livestream/zoom_payload_builder.rb
rename to plugins/discourse-events/app/services/discourse_events/livestream/zoom_payload_builder.rb
index 3ca86934349..916044f2c47 100644
--- a/plugins/discourse-events/app/services/discourse_calendar/livestream/zoom_payload_builder.rb
+++ b/plugins/discourse-events/app/services/discourse_events/livestream/zoom_payload_builder.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Livestream
# Builds the payload the client needs to join a Zoom meeting through the
# Meeting SDK, including a signed JWT auth token.
@@ -16,7 +16,7 @@ module DiscourseCalendar
# The user joining the zoom meeting as an attendee
option :user
- # Parsed from a zoom URL via DiscourseCalendar::Livestream::ZoomUrlParser
+ # Parsed from a zoom URL via DiscourseEvents::Livestream::ZoomUrlParser
option :zoom_join_data
def call
diff --git a/plugins/discourse-events/app/services/discourse_post_event/action/expand_occurrences.rb b/plugins/discourse-events/app/services/discourse_post_event/action/expand_occurrences.rb
deleted file mode 100644
index 29cc0884b43..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/action/expand_occurrences.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- module Action
- class ExpandOccurrences < Service::ActionBase
- MAX_LIMIT = 200
-
- option :event
- option :after
- option :before, optional: true
- option :limit, default: -> { 50 }
- option :current_occurrence_only, default: -> { false }
-
- def call
- return non_recurring_result unless event.recurring?
- return current_occurrence_result if current_occurrence_only
-
- build_recurring_occurrences
- end
-
- private
-
- def non_recurring_result
- {
- event: event,
- occurrences: [{ starts_at: event.original_starts_at, ends_at: event.original_ends_at }],
- }
- end
-
- def current_occurrence_result
- starts_at = event.starts_at
-
- return { event:, occurrences: [] } if starts_at.nil?
- return { event:, occurrences: [] } if after && starts_at < after
- return { event:, occurrences: [] } if before && starts_at >= before
-
- { event:, occurrences: [{ starts_at:, ends_at: event.ends_at }] }
- end
-
- def build_recurring_occurrences
- occurrences = []
- current_time = after
- count = 0
- capped_limit = limit.clamp(1, MAX_LIMIT)
-
- while count < capped_limit
- occurrence = event.calculate_next_occurrence_from(current_time)
- break unless occurrence
-
- occurrence_starts_at = occurrence[:starts_at]
- break if before && occurrence_starts_at >= before
-
- occurrences << { starts_at: occurrence_starts_at, ends_at: occurrence[:ends_at] }
- current_time = occurrence_starts_at + 1.second
- count += 1
- end
-
- { event: event, occurrences: occurrences }
- end
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/action/parse_invitees_csv.rb b/plugins/discourse-events/app/services/discourse_post_event/action/parse_invitees_csv.rb
deleted file mode 100644
index a185fdbcb65..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/action/parse_invitees_csv.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-# frozen_string_literal: true
-
-require "csv"
-
-module DiscoursePostEvent
- module Action
- class ParseInviteesCsv < Service::ActionBase
- DEFAULT_ATTENDANCE = "going"
-
- option :file
-
- def call
- invitees = []
- CSV.foreach(file.tempfile) do |identifier, attendance|
- next if identifier.blank?
- invitees << { identifier: identifier, attendance: attendance || DEFAULT_ATTENDANCE }
- end
- invitees
- rescue StandardError
- # A malformed or unreadable file yields no invitees; the empty result
- # is surfaced as an upload error downstream.
- []
- end
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/bulk_invite.rb b/plugins/discourse-events/app/services/discourse_post_event/bulk_invite.rb
deleted file mode 100644
index 5f18e6aa052..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/bulk_invite.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class BulkInvite
- include Service::Base
-
- params do
- attribute :event_id, :integer
- attribute :invitees, :array
-
- before_validation { self.invitees = Array(invitees).reject(&:blank?) }
-
- validates :event_id, presence: true
- end
-
- model :event
- policy :can_edit_post
- policy :can_create_event
- policy :invitees_present
-
- try { step :enqueue_bulk_invite }
-
- private
-
- def fetch_event(params:)
- Event.find_by(id: params.event_id)
- end
-
- def can_edit_post(guardian:, event:)
- guardian.can_edit?(event.post)
- end
-
- def can_create_event(guardian:)
- guardian.can_create_discourse_post_event?
- end
-
- def invitees_present(params:)
- params.invitees.present?
- end
-
- def enqueue_bulk_invite(event:, params:, guardian:)
- Jobs.enqueue(
- :discourse_post_event_bulk_invite,
- event_id: event.id,
- invitees: params.invitees,
- current_user_id: guardian.user.id,
- )
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/chat_channel_sync.rb b/plugins/discourse-events/app/services/discourse_post_event/chat_channel_sync.rb
deleted file mode 100644
index ab60caec6ce..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/chat_channel_sync.rb
+++ /dev/null
@@ -1,75 +0,0 @@
-# frozen_string_literal: true
-#
-module DiscoursePostEvent
- class ChatChannelSync
- def self.sync(event, guardian: nil)
- return if !event.chat_enabled?
- if !event.chat_channel_id && guardian&.can_create_chat_channel?
- ensure_chat_channel!(event, guardian:)
- end
- sync_chat_channel_members!(event) if event.chat_channel_id
- end
-
- def self.sync_chat_channel_members!(event)
- missing_members_sql = <<~SQL
- SELECT i.user_id
- FROM discourse_post_event_invitees i
- INNER JOIN users u ON u.id = i.user_id
- WHERE i.post_id = :post_id
- AND i.status IN (:statuses)
- AND (u.suspended_till IS NULL OR u.suspended_till <= :now)
- AND (u.silenced_till IS NULL OR u.silenced_till <= :now)
- AND u.staged = false
- AND i.user_id NOT IN (
- SELECT user_id
- FROM user_chat_channel_memberships
- WHERE chat_channel_id = :chat_channel_id
- )
- SQL
-
- missing_user_ids =
- DB.query_single(
- missing_members_sql,
- post_id: event.post.id,
- statuses: [
- DiscoursePostEvent::Invitee.statuses[:going],
- DiscoursePostEvent::Invitee.statuses[:interested],
- ],
- chat_channel_id: event.chat_channel_id,
- now: Time.zone.now,
- )
-
- if missing_user_ids.present?
- ActiveRecord::Base.transaction do
- missing_user_ids.each do |user_id|
- event.chat_channel.user_chat_channel_memberships.create!(
- user_id:,
- chat_channel_id: event.chat_channel_id,
- following: true,
- )
- end
- end
- end
- end
-
- def self.ensure_chat_channel!(event, guardian:)
- name = event.name || event.post.topic.title
-
- channel = nil
- Chat::CreateCategoryChannel.call(
- guardian:,
- params: {
- name:,
- emoji: "spiral_calendar",
- category_id: event.post.topic.category_id,
- },
- ) do |result|
- on_success { channel = result.channel }
- on_failure { raise StandardError, result.inspect_steps }
- end
-
- # event creator will be a member of the channel
- event.chat_channel_id = channel.id
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/create_invitee.rb b/plugins/discourse-events/app/services/discourse_post_event/create_invitee.rb
deleted file mode 100644
index bbd820e1e6c..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/create_invitee.rb
+++ /dev/null
@@ -1,57 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class CreateInvitee
- include Service::Base
-
- params do
- attribute :event_id, :integer
- attribute :status, :symbol
- attribute :user_id, :integer
- attribute :recurring, :boolean, default: false
-
- validates :event_id, presence: true
- validates :status, inclusion: { in: Invitee.statuses.keys }
- end
-
- model :event
- policy :can_see_event
- model :user
- policy :can_update_attendance
- policy :can_invite_user
- policy :has_capacity
-
- model :invitee, :create_invitee
-
- private
-
- def fetch_event(params:)
- Event.find_by(id: params.event_id)
- end
-
- def can_see_event(guardian:, event:)
- guardian.can_see?(event.post)
- end
-
- def fetch_user(params:, guardian:)
- params.user_id ? User.find_by(id: params.user_id) : guardian.user
- end
-
- def can_update_attendance(event:, user:)
- event.can_user_update_attendance?(user)
- end
-
- def can_invite_user(guardian:, event:, user:)
- return true if guardian.user.id == user.id
- guardian.can_act_on_discourse_post_event?(event)
- end
-
- def has_capacity(event:, params:)
- params.status != :going || !event.at_capacity?
- end
-
- def create_invitee(user:, event:, params:)
- Invitee.create_attendance!(user.id, event.id, params.status, recurring: params.recurring)
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/csv_bulk_invite.rb b/plugins/discourse-events/app/services/discourse_post_event/csv_bulk_invite.rb
deleted file mode 100644
index d2edf171d5a..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/csv_bulk_invite.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class CsvBulkInvite
- include Service::Base
-
- params do
- attribute :event_id, :integer
- # Declared only so the steps can read it; the contract drops any
- # undeclared parameter.
- attribute :file
-
- validates :event_id, presence: true
- end
-
- model :event
- policy :can_edit_post
- policy :can_create_event
- policy :file_present
- model :invitees, :parse_invitees
-
- try { step :enqueue_bulk_invite }
-
- private
-
- def fetch_event(params:)
- Event.find_by(id: params.event_id)
- end
-
- def can_edit_post(guardian:, event:)
- guardian.can_edit?(event.post)
- end
-
- def can_create_event(guardian:)
- guardian.can_create_discourse_post_event?
- end
-
- def file_present(params:)
- params.file.present?
- end
-
- def parse_invitees(params:)
- Action::ParseInviteesCsv.call(file: params.file)
- end
-
- def enqueue_bulk_invite(event:, invitees:, guardian:)
- Jobs.enqueue(
- :discourse_post_event_bulk_invite,
- event_id: event.id,
- invitees: invitees,
- current_user_id: guardian.user.id,
- )
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/destroy_event.rb b/plugins/discourse-events/app/services/discourse_post_event/destroy_event.rb
deleted file mode 100644
index 87d9c17304c..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/destroy_event.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class DestroyEvent
- include Service::Base
-
- params do
- attribute :event_id, :integer
-
- validates :event_id, presence: true
- end
-
- model :event
- policy :can_act_on_event
-
- step :publish_event_update
- model :webhook_payload, :build_webhook_payload
- transaction { step :destroy_event }
- step :enqueue_destroyed_webhooks
-
- private
-
- def fetch_event(params:)
- Event.includes(:image_upload).find_by(id: params.event_id)
- end
-
- def can_act_on_event(guardian:, event:)
- guardian.can_act_on_discourse_post_event?(event)
- end
-
- def publish_event_update(event:)
- event.publish_update!
- end
-
- def build_webhook_payload(event:)
- WebHook.build_calendar_event_payload(event)
- end
-
- def destroy_event(event:)
- event.destroy!
- end
-
- def enqueue_destroyed_webhooks(event:, webhook_payload:)
- WebHook.enqueue_calendar_event_hooks(:calendar_event_destroyed, event, webhook_payload)
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/destroy_invitee.rb b/plugins/discourse-events/app/services/discourse_post_event/destroy_invitee.rb
deleted file mode 100644
index 5b2bd6c8603..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/destroy_invitee.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class DestroyInvitee
- include Service::Base
-
- params do
- attribute :post_id, :integer
- attribute :id, :integer
-
- validates :post_id, presence: true
- validates :id, presence: true
- end
-
- model :event
- model :invitee
- policy :can_act_on_invitee
- policy :can_see_event
- policy :can_update_attendance
-
- step :destroy
- step :publish
-
- private
-
- def fetch_event(params:)
- Event.find_by(id: params.post_id)
- end
-
- def fetch_invitee(event:, params:)
- event.invitees.find_by(id: params.id)
- end
-
- def can_act_on_invitee(guardian:, invitee:)
- guardian.can_act_on_invitee?(invitee)
- end
-
- def can_see_event(guardian:, event:)
- guardian.can_see?(event.post)
- end
-
- def can_update_attendance(guardian:, event:)
- event.can_user_update_attendance?(guardian.user)
- end
-
- def destroy(invitee:)
- invitee.destroy!
- end
-
- def publish(event:)
- event.publish_update!
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/event/action/attributes_from_raw.rb b/plugins/discourse-events/app/services/discourse_post_event/event/action/attributes_from_raw.rb
deleted file mode 100644
index c33fefb6cd4..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/event/action/attributes_from_raw.rb
+++ /dev/null
@@ -1,68 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- # Coerces the parsed event hash into the attributes accepted by Event#update_with_params!.
- class Event::Action::AttributesFromRaw < Service::ActionBase
- option :raw_event
- option :current_status
-
- def call
- {
- name: raw_event[:name],
- original_starts_at: starts_at,
- original_ends_at: ends_at,
- url: raw_event[:url],
- description: raw_event[:description],
- location: raw_event[:location],
- recurrence: raw_event[:recurrence],
- recurrence_until: parse_in_zone(raw_event[:"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,
- reminders: raw_event[:reminders],
- raw_invitees: raw_event[:"allowed-groups"]&.split(","),
- minimal: raw_event[:minimal],
- closed: raw_event[:closed] || false,
- chat_enabled: raw_event[:"chat-enabled"]&.downcase == "true",
- livestream: raw_event[:livestream]&.downcase == "true",
- max_attendees: raw_event[:"max-attendees"]&.to_i,
- all_day: all_day?,
- custom_fields: custom_fields,
- }
- end
-
- private
-
- def all_day?
- raw_event[:"all-day"] == "true"
- end
-
- def timezone
- ActiveSupport::TimeZone[raw_event[:timezone] || Event::DEFAULT_TIMEZONE]
- end
-
- def parse_in_zone(value)
- value ? timezone.parse(value) : nil
- end
-
- 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
- end
-
- def custom_fields
- SiteSetting
- .discourse_post_event_allowed_custom_fields
- .split("|")
- .each_with_object({}) do |setting, fields|
- value = raw_event[setting.to_sym]
- fields[setting] = value if value.present?
- end
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/event/action/resolve_image_upload.rb b/plugins/discourse-events/app/services/discourse_post_event/event/action/resolve_image_upload.rb
deleted file mode 100644
index 2a236114b21..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/event/action/resolve_image_upload.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- # Resolves an event's image into an Upload, returning a secure upload only when the post author may use it.
- class Event::Action::ResolveImageUpload < Service::ActionBase
- option :image
- option :post
-
- def call
- return if image.blank?
-
- upload = find_upload
- return if upload.nil?
-
- upload if usable_by_author?(upload)
- end
-
- private
-
- def find_upload
- if image.start_with?("upload://")
- sha1 = Upload.sha1_from_short_url(image)
- Upload.find_by(sha1: sha1) if sha1
- else
- Upload.get_from_url(image)
- end
- end
-
- def usable_by_author?(upload)
- !upload.secure? || upload.user_id == post.user_id ||
- UserUpload.exists?(upload_id: upload.id, user_id: post.user_id)
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/event/sync_from_post.rb b/plugins/discourse-events/app/services/discourse_post_event/event/sync_from_post.rb
deleted file mode 100644
index 3d97fa02b85..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/event/sync_from_post.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- # Creates, updates or removes a post's event to match the `[event]` block in its raw.
- class Event::SyncFromPost
- include Service::Base
-
- params do
- attribute :post_id, :integer
-
- validates :post_id, presence: true
- end
-
- model :post
- model :raw_event, :parse_event, optional: true
-
- only_if :event_removed do
- step :remove_event
- end
-
- only_if :event_present do
- model :event, :upsert_event
- step :schedule_topic_bump
- end
-
- private
-
- def fetch_post(params:)
- Post.find_by(id: params.post_id)
- end
-
- def parse_event(post:)
- EventParser.extract_events(post).first
- end
-
- def event_removed(raw_event:, post:)
- return if raw_event.present?
- post.event.present?
- end
-
- def event_present(raw_event:)
- raw_event.present?
- end
-
- def remove_event(post:)
- post.event.destroy!
- end
-
- def upsert_event(post:, raw_event:)
- event = post.event || Event.new(id: post.id)
- attributes = Event::Action::AttributesFromRaw.call(raw_event:, current_status: event.status)
- attributes[:image_upload_id] = Event::Action::ResolveImageUpload.call(
- image: raw_event[:image],
- post:,
- )&.id
- event.update_with_params!(attributes)
- event
- end
-
- def schedule_topic_bump(event:)
- event.set_topic_bump
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/invite.rb b/plugins/discourse-events/app/services/discourse_post_event/invite.rb
deleted file mode 100644
index e724b00b43d..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/invite.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class Invite
- include Service::Base
-
- params do
- attribute :event_id, :integer
- attribute :invites
-
- before_validation { self.invites = Array(invites) }
-
- validates :event_id, presence: true
- end
-
- model :event
- policy :can_act_on_event
- model :invited_users, optional: true
-
- step :notify_invited_users
-
- private
-
- def fetch_event(params:)
- Event.find_by(id: params.event_id)
- end
-
- def can_act_on_event(guardian:, event:)
- guardian.can_act_on_discourse_post_event?(event)
- end
-
- def fetch_invited_users(params:)
- User.real.where(username: params.invites)
- end
-
- def notify_invited_users(event:, invited_users:)
- invited_users.each { |user| event.create_notification!(user, event.post) }
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/list_invitees.rb b/plugins/discourse-events/app/services/discourse_post_event/list_invitees.rb
deleted file mode 100644
index 731449f52e9..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/list_invitees.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class ListInvitees
- include Service::Base
-
- MAX_INVITEES = 200
-
- params do
- attribute :post_id, :integer
- attribute :filter, :string
- attribute :type, :symbol
-
- validates :post_id, presence: true
- validates :type, inclusion: { in: Invitee.statuses.keys }, allow_blank: true
- end
-
- model :event
- policy :can_see_event
- model :invitees, optional: true
- model :suggested_users, optional: true
-
- private
-
- def fetch_event(params:)
- Event.find_by(id: params.post_id)
- end
-
- def can_see_event(guardian:, event:)
- guardian.can_see?(event.post) && guardian.can_display_invitee_details?(event)
- end
-
- def fetch_invitees(event:, params:)
- invitees = event.invitees
- invitees = invitees.with_status(params.type) if params.type.present?
- invitees = invitees.matching_username(params.filter) if params.filter.present?
- invitees.order(%i[status username_lower]).limit(MAX_INVITEES)
- end
-
- def fetch_suggested_users(guardian:, event:, params:)
- return User.none if params.filter.blank?
- return User.none unless guardian.can_act_on_discourse_post_event?(event)
- event.suggested_users(params.filter, type: params.type)
- end
- end
-end
diff --git a/plugins/discourse-events/app/services/discourse_post_event/update_invitee.rb b/plugins/discourse-events/app/services/discourse_post_event/update_invitee.rb
deleted file mode 100644
index 6e3d35a9cc5..00000000000
--- a/plugins/discourse-events/app/services/discourse_post_event/update_invitee.rb
+++ /dev/null
@@ -1,57 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class UpdateInvitee
- include Service::Base
-
- params do
- attribute :event_id, :integer
- attribute :invitee_id, :integer
- attribute :status, :symbol
- attribute :recurring, :boolean, default: false
-
- validates :event_id, presence: true
- validates :invitee_id, presence: true
- validates :status, inclusion: { in: Invitee.statuses.keys }
- end
-
- model :invitee
- policy :can_act_on_invitee
- model :event
- policy :can_see_event
- policy :can_update_attendance
- policy :has_capacity
-
- step :update
-
- private
-
- def fetch_invitee(params:)
- Invitee.find_by(id: params.invitee_id, post_id: params.event_id)
- end
-
- def can_act_on_invitee(guardian:, invitee:)
- guardian.can_act_on_invitee?(invitee)
- end
-
- def fetch_event(invitee:)
- invitee.event
- end
-
- def can_see_event(guardian:, event:)
- guardian.can_see?(event.post)
- end
-
- def can_update_attendance(guardian:, event:)
- event.can_user_update_attendance?(guardian.user)
- end
-
- def has_capacity(event:, invitee:, params:)
- params.status != :going || !event.at_capacity? || invitee.status == Invitee.statuses[:going]
- end
-
- def update(invitee:, params:)
- invitee.update_attendance!(params.status, recurring: params.recurring)
- end
- end
-end
diff --git a/plugins/discourse-events/app/views/discourse_post_event/events/index.ics.erb b/plugins/discourse-events/app/views/discourse_events/events/index.ics.erb
similarity index 100%
rename from plugins/discourse-events/app/views/discourse_post_event/events/index.ics.erb
rename to plugins/discourse-events/app/views/discourse_events/events/index.ics.erb
diff --git a/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erb b/plugins/discourse-events/app/views/discourse_events/livestream/zoom_frame.html.erb
similarity index 100%
rename from plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erb
rename to plugins/discourse-events/app/views/discourse_events/livestream/zoom_frame.html.erb
diff --git a/plugins/discourse-events/config/routes.rb b/plugins/discourse-events/config/routes.rb
index ecacbb96d7c..c01403d45af 100644
--- a/plugins/discourse-events/config/routes.rb
+++ b/plugins/discourse-events/config/routes.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
-DiscoursePostEvent::Engine.routes.draw do
+# URL paths keep their original `discourse-post-event` / `discourse-calendar`
+# spellings: they are a public API surface, unlike the Ruby namespaces.
+DiscourseEvents::Engine.routes.draw do
get "/discourse-post-event/events" => "events#index",
:constraints => {
format: /(json|ics)/,
@@ -21,17 +23,13 @@ DiscoursePostEvent::Engine.routes.draw do
get "/upcoming-events" => "upcoming_events#index"
get "/upcoming-events/mine/:view/:year/:month/:day" => "upcoming_events#index"
get "/upcoming-events/mine" => "upcoming_events#index"
-end
-
-DiscourseCalendar::Engine.routes.draw do
get "/discourse-calendar/livestream/zoom/signature" => "livestream#prepare_zoom_signature",
:format => :json
get "/discourse-calendar/livestream/zoom/frame" => "livestream#zoom_frame"
end
Discourse::Application.routes.draw do
- mount DiscourseCalendar::Engine, at: "/"
- mount DiscoursePostEvent::Engine, at: "/"
+ mount DiscourseEvents::Engine, at: "/"
get "t/:slug/:topic_id/zoom" => "topics#show", :constraints => { topic_id: /\d+/ }
@@ -40,10 +38,8 @@ Discourse::Application.routes.draw do
get "/admin/plugins/discourse-events" => "admin/plugins#index"
get "/admin/plugins/discourse-events/holidays" => "admin/plugins#index"
get "/admin/discourse-calendar/holiday-regions/:region_code/holidays" =>
- "admin/discourse_calendar/admin_holidays#index"
- post "/admin/discourse-calendar/holidays/disable" =>
- "admin/discourse_calendar/admin_holidays#disable"
- delete "/admin/discourse-calendar/holidays/enable" =>
- "admin/discourse_calendar/admin_holidays#enable"
+ "admin/discourse_events/holidays#index"
+ post "/admin/discourse-calendar/holidays/disable" => "admin/discourse_events/holidays#disable"
+ delete "/admin/discourse-calendar/holidays/enable" => "admin/discourse_events/holidays#enable"
end
end
diff --git a/plugins/discourse-events/config/settings.yml b/plugins/discourse-events/config/settings.yml
index a950813b07f..e1867e72e9c 100644
--- a/plugins/discourse-events/config/settings.yml
+++ b/plugins/discourse-events/config/settings.yml
@@ -14,11 +14,11 @@ discourse_calendar:
all_day_event_start_time:
default: ""
client: true
- validator: "CalendarSettingsValidator"
+ validator: "DiscourseEvents::Configuration::TimeOfDayValidator"
all_day_event_end_time:
default: ""
client: true
- validator: "CalendarSettingsValidator"
+ validator: "DiscourseEvents::Configuration::TimeOfDayValidator"
calendar_categories:
type: list
list_type: simple
@@ -101,7 +101,7 @@ discourse_calendar:
list_type: simple
client: true
default: ""
- validator: "CalendarCustomFieldsValidator"
+ validator: "DiscourseEvents::Configuration::EventCustomFieldsValidator"
events_calendar_categories:
type: category_list
client: true
@@ -118,19 +118,19 @@ discourse_calendar:
map_events_to_color:
client: true
default: "[]"
- json_schema: DiscourseCalendar::SiteSettings::MapEventTagColorsJsonSchema
+ json_schema: DiscourseEvents::Configuration::MapEventTagColorsJsonSchema
map_events_title:
client: true
default: ""
- json_schema: DiscourseCalendar::SiteSettings::MapEventsTitleJsonSchema
+ json_schema: DiscourseEvents::Configuration::MapEventsTitleJsonSchema
calendar_first_day_of_week:
type: enum
- enum: "CalendarFirstDayOfWeek"
+ enum: "DiscourseEvents::Configuration::FirstDayOfWeek"
default: monday
client: true
calendar_upcoming_events_default_view:
type: enum
- enum: "CalendarUpcomingEventsDefaultView"
+ enum: "DiscourseEvents::Configuration::UpcomingEventsDefaultView"
default: month
client: true
enable_events_category_type_setup:
@@ -147,7 +147,7 @@ discourse_calendar:
default: "youtube.com|youtu.be|twitch.tv|zoom.us|kick.com|tiktok.com|instagram.com|facebook.com"
client: true
hidden: true
- validator: "DiscourseCalendar::Livestream::AllowedHostsValidator"
+ validator: "DiscourseEvents::Livestream::AllowedHostsValidator"
livestream_zoom_enabled:
default: false
client: true
diff --git a/plugins/discourse-events/db/migrate/20200226183018_create_calendar_events.rb b/plugins/discourse-events/db/migrate/20200226183018_create_calendar_events.rb
index 17531a7b1d6..fcd3e4adc4a 100644
--- a/plugins/discourse-events/db/migrate/20200226183018_create_calendar_events.rb
+++ b/plugins/discourse-events/db/migrate/20200226183018_create_calendar_events.rb
@@ -35,7 +35,9 @@ class CreateCalendarEvents < ActiveRecord::Migration[5.2]
# this is not ideal we should be using SQL here but this will work around bad schema
ActiveRecord::Base.connection.query_cache.clear
Post.reset_column_information # rubocop:disable Discourse/NoResetColumnInformationInMigrations
- Post.where(topic_id: calendar_topic_ids).each { |post| CalendarEvent.update(post) }
+ Post
+ .where(topic_id: calendar_topic_ids)
+ .each { |post| DiscourseEvents::Calendar::Event.update(post) }
execute "DELETE FROM post_custom_fields WHERE name = 'calendar-details' OR name = 'calendar-holidays'"
rescue => e
diff --git a/plugins/discourse-events/db/migrate/20200327195549_add_topic_custom_field_post_event_date_index.rb b/plugins/discourse-events/db/migrate/20200327195549_add_topic_custom_field_post_event_date_index.rb
index 4a3caa66d24..79128898dc7 100644
--- a/plugins/discourse-events/db/migrate/20200327195549_add_topic_custom_field_post_event_date_index.rb
+++ b/plugins/discourse-events/db/migrate/20200327195549_add_topic_custom_field_post_event_date_index.rb
@@ -6,6 +6,6 @@ class AddTopicCustomFieldPostEventDateIndex < ActiveRecord::Migration[6.0]
%i[name topic_id],
name: :idx_topic_custom_fields_post_event_starts_at,
unique: true,
- where: "name = '#{DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT}'"
+ where: "name = '#{DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT}'"
end
end
diff --git a/plugins/discourse-events/db/migrate/20200409120815_rename_topic_custom_field_topic_post_event_starts_at_index.rb b/plugins/discourse-events/db/migrate/20200409120815_rename_topic_custom_field_topic_post_event_starts_at_index.rb
index df6799c426d..ffa1393c5f0 100644
--- a/plugins/discourse-events/db/migrate/20200409120815_rename_topic_custom_field_topic_post_event_starts_at_index.rb
+++ b/plugins/discourse-events/db/migrate/20200409120815_rename_topic_custom_field_topic_post_event_starts_at_index.rb
@@ -8,7 +8,7 @@ class RenameTopicCustomFieldTopicPostEventStartsAtIndex < ActiveRecord::Migratio
%i[name topic_id],
name: :idx_topic_custom_fields_topic_post_event_starts_at,
unique: true,
- where: "name = '#{DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT}'"
+ where: "name = '#{DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT}'"
end
def down
diff --git a/plugins/discourse-events/db/migrate/20200926144256_add_unique_index_to_topic_event_ends_at_custom_field.rb b/plugins/discourse-events/db/migrate/20200926144256_add_unique_index_to_topic_event_ends_at_custom_field.rb
index c5fd1648e60..59c172cbf97 100644
--- a/plugins/discourse-events/db/migrate/20200926144256_add_unique_index_to_topic_event_ends_at_custom_field.rb
+++ b/plugins/discourse-events/db/migrate/20200926144256_add_unique_index_to_topic_event_ends_at_custom_field.rb
@@ -6,7 +6,7 @@ class AddUniqueIndexToTopicEventEndsAtCustomField < ActiveRecord::Migration[6.0]
%i[name topic_id],
name: :idx_topic_custom_fields_topic_post_event_ends_at,
unique: true,
- where: "name = '#{DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT}'"
+ where: "name = '#{DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT}'"
end
def down
diff --git a/plugins/discourse-events/db/post_migrate/20260819131113_update_upload_reference_target_type_for_events.rb b/plugins/discourse-events/db/post_migrate/20260819131113_update_upload_reference_target_type_for_events.rb
new file mode 100644
index 00000000000..703f78de042
--- /dev/null
+++ b/plugins/discourse-events/db/post_migrate/20260819131113_update_upload_reference_target_type_for_events.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+class UpdateUploadReferenceTargetTypeForEvents < ActiveRecord::Migration[8.0]
+ def up
+ execute <<~SQL
+ UPDATE upload_references
+ SET target_type = 'DiscourseEvents::Events::Event'
+ WHERE target_type = 'DiscoursePostEvent::Event'
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/bulk_invite.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/bulk_invite.rb
index a0e3eb996a9..803b626aed0 100644
--- a/plugins/discourse-events/jobs/regular/discourse_post_event/bulk_invite.rb
+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/bulk_invite.rb
@@ -19,7 +19,7 @@ module Jobs
@current_user = User.find_by(id: args[:current_user_id])
raise Discourse::InvalidParameters.new(:current_user_id) unless @current_user
- @event = DiscoursePostEvent::Event.find_by(id: args[:event_id])
+ @event = DiscourseEvents::Events::Event.find_by(id: args[:event_id])
raise Discourse::InvalidParameters.new(:event_id) unless @event
@guardian = Guardian.new(@current_user)
@@ -72,7 +72,7 @@ module Jobs
end
attendance = invitee["attendance"] || "going"
- status = DiscoursePostEvent::Invitee.statuses[attendance.to_sym]
+ status = DiscourseEvents::Events::Invitee.statuses[attendance.to_sym]
if status.nil?
save_log "Skipping '#{invitee["identifier"]}' due to unknown attendance: '#{attendance}'"
@@ -101,7 +101,7 @@ module Jobs
def create_attendance(user_id, post_id, status)
invitee =
- DiscoursePostEvent::Invitee.find_or_initialize_by(user_id: user_id, post_id: post_id)
+ DiscourseEvents::Events::Invitee.find_or_initialize_by(user_id: user_id, post_id: post_id)
invitee.notified = false
invitee.status = status
invitee.save!
diff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/event_started.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/event_started.rb
index 21273be7f76..44373a0ac10 100644
--- a/plugins/discourse-events/jobs/regular/discourse_post_event/event_started.rb
+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/event_started.rb
@@ -6,7 +6,7 @@ module Jobs
def execute(args)
raise Discourse::InvalidParameters.new(:event_id) if args[:event_id].blank?
- event = DiscoursePostEvent::Event.find(args[:event_id])
+ event = DiscourseEvents::Events::Event.find(args[:event_id])
MessageBus.publish("/topic/#{event.post.topic_id}", reload_topic: true, refresh_stream: true)
DiscourseEvent.trigger(:discourse_post_event_event_started, event)
end
diff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rb
index 553db37162c..25eaa39c9d9 100644
--- a/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rb
+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rb
@@ -9,15 +9,17 @@ module Jobs
raise Discourse::InvalidParameters.new(:reminder) if args[:reminder].blank?
event =
- DiscoursePostEvent::Event.includes(post: [:topic], invitees: [:user]).find(args[:event_id])
+ DiscourseEvents::Events::Event.includes(post: [:topic], invitees: [:user]).find(
+ args[:event_id],
+ )
return unless event.post
invitees =
event.invitees.where(
status: [
- DiscoursePostEvent::Invitee.statuses[:going],
- DiscoursePostEvent::Invitee.statuses[:interested],
+ DiscourseEvents::Events::Invitee.statuses[:going],
+ DiscourseEvents::Events::Invitee.statuses[:interested],
],
)
diff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rb
index a9ece0c130b..4919de10e6c 100644
--- a/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rb
+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rb
@@ -8,7 +8,7 @@ module Jobs
url = args[:url]
return if url.blank?
- event = DiscoursePostEvent::Event.find_by(id: args[:event_id])
+ event = DiscourseEvents::Events::Event.find_by(id: args[:event_id])
return if event.blank? || event.livestream_url != url
event.warm_livestream_onebox!
end
diff --git a/plugins/discourse-events/jobs/scheduled/create_holiday_events.rb b/plugins/discourse-events/jobs/scheduled/create_holiday_events.rb
index cce52843230..561f632f194 100644
--- a/plugins/discourse-events/jobs/scheduled/create_holiday_events.rb
+++ b/plugins/discourse-events/jobs/scheduled/create_holiday_events.rb
@@ -18,7 +18,7 @@ module Jobs
regions_and_user_ids = Hash.new { |h, k| h[k] = [] }
UserCustomField
- .where(name: ::DiscourseCalendar::REGION_CUSTOM_FIELD)
+ .where(name: ::DiscourseEvents::REGION_CUSTOM_FIELD)
.pluck(:user_id, :value)
.each { |user_id, region| regions_and_user_ids[region] << user_id if region.present? }
@@ -52,27 +52,30 @@ module Jobs
.to_h
# Remove holidays for deactivated/suspended/silenced users
- CalendarEvent.where(post_id: nil).where.not(user_id: usernames.keys).destroy_all
+ DiscourseEvents::Calendar::Event
+ .where(post_id: nil)
+ .where.not(user_id: usernames.keys)
+ .destroy_all
# Remove future holidays when users changed their region
- CalendarEvent
+ DiscourseEvents::Calendar::Event
.joins(user: :_custom_fields)
.where(post_id: nil)
.where("start_date > ?", today)
- .where("user_custom_fields.name = ?", ::DiscourseCalendar::REGION_CUSTOM_FIELD)
+ .where("user_custom_fields.name = ?", ::DiscourseEvents::REGION_CUSTOM_FIELD)
.where("LENGTH(COALESCE(user_custom_fields.value, '')) > 0")
.where("user_custom_fields.value != calendar_events.region")
.destroy_all
regions_and_user_ids.each do |region, user_ids|
- if Holidays.available_regions.exclude?(region.to_sym)
+ if ::Holidays.available_regions.exclude?(region.to_sym)
Rails.logger.warn(
"Skipping invalid region '#{region}' for users: #{user_ids.join(", ")}.",
)
next
end
- ::DiscourseCalendar::Holiday
+ ::DiscourseEvents::Holidays::Finder
.find_holidays_for(
region_code: region,
start_date: today,
@@ -92,7 +95,7 @@ module Jobs
end
event =
- CalendarEvent
+ DiscourseEvents::Calendar::Event
.where(topic_id: topic_id, user_id: user_id, description: holiday[:name])
.where(
"start_date >= :from AND start_date <= :to",
diff --git a/plugins/discourse-events/jobs/scheduled/delete_expired_event_posts.rb b/plugins/discourse-events/jobs/scheduled/delete_expired_event_posts.rb
index 98c93fefc63..1305abc9c1b 100644
--- a/plugins/discourse-events/jobs/scheduled/delete_expired_event_posts.rb
+++ b/plugins/discourse-events/jobs/scheduled/delete_expired_event_posts.rb
@@ -14,11 +14,11 @@ module Jobs
calendar_topic_ids =
Post
.joins(:_custom_fields)
- .where(post_custom_fields: { name: ::DiscourseCalendar::CALENDAR_CUSTOM_FIELD })
+ .where(post_custom_fields: { name: ::DiscourseEvents::CALENDAR_CUSTOM_FIELD })
.pluck(:topic_id)
post_events =
- CalendarEvent
+ DiscourseEvents::Calendar::Event
.joins(:post, :topic)
.where(topic_id: calendar_topic_ids)
.where("TRIM(COALESCE(calendar_events.recurrence, '')) = ''")
diff --git a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb
index 4ca3d84e274..689da3350b5 100644
--- a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb
+++ b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb
@@ -6,7 +6,7 @@ module Jobs
every 1.minute
def execute(args)
- DiscoursePostEvent::EventDate.pending.find_each do |event_date|
+ DiscourseEvents::Events::EventDate.pending.find_each do |event_date|
send_reminder(event_date)
trigger_events(event_date)
finish(event_date)
diff --git a/plugins/discourse-events/jobs/scheduled/update_holiday_usernames.rb b/plugins/discourse-events/jobs/scheduled/update_holiday_usernames.rb
index ce08b4faba6..73d1a55fa24 100644
--- a/plugins/discourse-events/jobs/scheduled/update_holiday_usernames.rb
+++ b/plugins/discourse-events/jobs/scheduled/update_holiday_usernames.rb
@@ -9,10 +9,10 @@ module Jobs
return unless SiteSetting.discourse_events_enabled
return unless topic_id = SiteSetting.holiday_calendar_topic_id.presence
- events = CalendarEvent.where(topic_id: topic_id)
- users_on_holiday = ::DiscourseCalendar::UsersOnHoliday.from(events)
+ events = DiscourseEvents::Calendar::Event.where(topic_id: topic_id)
+ users_on_holiday = ::DiscourseEvents::Holidays::UsersOnHoliday.from(events)
- ::DiscourseCalendar.users_on_holiday = users_on_holiday.values.map { |u| u[:username] }
+ ::DiscourseEvents.users_on_holiday = users_on_holiday.values.map { |u| u[:username] }
synchronize_user_custom_fields(users_on_holiday)
set_holiday_statuses(users_on_holiday)
end
@@ -20,7 +20,7 @@ module Jobs
private
def synchronize_user_custom_fields(users_on_holiday)
- custom_field_name = ::DiscourseCalendar::HOLIDAY_CUSTOM_FIELD
+ custom_field_name = ::DiscourseEvents::HOLIDAY_CUSTOM_FIELD
if users_on_holiday.present?
user_ids = users_on_holiday.keys
@@ -48,7 +48,9 @@ module Jobs
User
.where(id: users_on_holiday.keys)
.includes(:user_status)
- .each { |u| ::DiscourseCalendar::HolidayStatus.set!(u, users_on_holiday[u.id][:ends_at]) }
+ .each do |u|
+ ::DiscourseEvents::Holidays::Status.set!(u, users_on_holiday[u.id][:ends_at])
+ end
end
end
end
diff --git a/plugins/discourse-events/lib/calendar.rb b/plugins/discourse-events/lib/calendar.rb
deleted file mode 100644
index cde41ddb583..00000000000
--- a/plugins/discourse-events/lib/calendar.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseCalendar
- class Calendar
- DATA_PREFIX = "data-calendar-"
-
- def self.extract(post)
- cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
-
- Nokogiri
- .HTML(cooked)
- .css("div.calendar")
- .map do |cooked_calendar|
- calendar = {}
-
- cooked_calendar.attributes.values.each do |attribute|
- if attribute.name.start_with?(DATA_PREFIX)
- calendar[attribute.name[DATA_PREFIX.length..-1]] = CGI.escapeHTML(
- attribute.value || "",
- )
- end
- end
-
- calendar
- end
- end
-
- def self.update(post)
- calendar = extract(post)
- return destroy(post) if calendar.size != 1
- calendar = calendar.first
-
- post.custom_fields[DiscourseCalendar::CALENDAR_CUSTOM_FIELD] = calendar.delete("type") ||
- "dynamic"
- post.save_custom_fields
-
- Post.where(topic_id: post.topic_id).each { |p| CalendarEvent.update(p) }
- end
-
- def self.destroy(post)
- return if post.custom_fields[DiscourseCalendar::CALENDAR_CUSTOM_FIELD].blank?
-
- post.custom_fields.delete(DiscourseCalendar::CALENDAR_CUSTOM_FIELD)
- post.save_custom_fields
-
- CalendarEvent.where(topic_id: post.topic_id).destroy_all
- end
- end
-end
diff --git a/plugins/discourse-events/lib/calendar_custom_fields_validator.rb b/plugins/discourse-events/lib/calendar_custom_fields_validator.rb
deleted file mode 100644
index 0ddd69243f1..00000000000
--- a/plugins/discourse-events/lib/calendar_custom_fields_validator.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-# frozen_string_literal: true
-
-class CalendarCustomFieldsValidator
- NAME_FORMAT = /\A[a-z0-9]+([_.-][a-z0-9]+)*\z/i
-
- def initialize(opts = {})
- @opts = opts
- end
-
- def valid_value?(val)
- @error_message = nil
- return true if val.blank?
-
- names = val.split("|").reject(&:blank?)
- attributes =
- names.index_with { |name| DiscoursePostEvent::EventParser.custom_field_data_attribute(name) }
- errors = []
-
- malformed = names.reject { |name| name.match?(NAME_FORMAT) }
- errors << error(:invalid, malformed) if malformed.any?
-
- colliding =
- names.group_by { |name| attributes[name] }.values.select { |group| group.size > 1 }.flatten
- errors << error(:collision, colliding) if colliding.any?
-
- reserved = DiscoursePostEvent::EventParser.valid_option_attributes
- reserved_names = names.select { |name| reserved.include?(attributes[name]) }
- errors << error(:reserved, reserved_names) if reserved_names.any?
-
- return true if errors.empty?
-
- @error_message = errors.join(" ")
- false
- end
-
- def error_message
- @error_message
- end
-
- private
-
- def error(key, names)
- I18n.t(
- "site_settings.discourse_post_event_allowed_custom_fields_#{key}",
- names: names.join(", "),
- )
- end
-end
diff --git a/plugins/discourse-events/lib/calendar_first_day_of_week.rb b/plugins/discourse-events/lib/calendar_first_day_of_week.rb
deleted file mode 100644
index 090e0ba863d..00000000000
--- a/plugins/discourse-events/lib/calendar_first_day_of_week.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-# frozen_string_literal: true
-
-require_dependency "enum_site_setting"
-
-class CalendarFirstDayOfWeek < EnumSiteSetting
- def self.valid_value?(val)
- values.any? { |v| v[:value].to_s == val.to_s }
- end
-
- def self.values
- @values ||= [
- { name: "user.notification_schedule.saturday", value: "saturday" },
- { name: "user.notification_schedule.sunday", value: "sunday" },
- { name: "user.notification_schedule.monday", value: "monday" },
- ]
- end
-
- def self.translate_names?
- true
- end
-end
diff --git a/plugins/discourse-events/lib/calendar_settings_validator.rb b/plugins/discourse-events/lib/calendar_settings_validator.rb
deleted file mode 100644
index ebb43200411..00000000000
--- a/plugins/discourse-events/lib/calendar_settings_validator.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-# frozen_string_literal: true
-
-class CalendarSettingsValidator
- def initialize(opts = {})
- @opts = opts
- end
-
- def valid_value?(val)
- return true if val == ""
-
- split = val.split(":")
- return false if split.count != 2
-
- hour = split.first
- return false if hour.length != 2
- return false if hour.to_i < 0 || hour.to_i >= 24
-
- minutes = split.second
- return false if minutes.length != 2
- return false if minutes.to_i < 0 || minutes.to_i >= 60
- true
- end
-
- def error_message
- I18n.t("site_settings.all_day_event_time_error")
- end
-end
diff --git a/plugins/discourse-events/lib/calendar_upcoming_events_default_view.rb b/plugins/discourse-events/lib/calendar_upcoming_events_default_view.rb
deleted file mode 100644
index a2ed2035ac0..00000000000
--- a/plugins/discourse-events/lib/calendar_upcoming_events_default_view.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# frozen_string_literal: true
-
-require_dependency "enum_site_setting"
-
-class CalendarUpcomingEventsDefaultView < EnumSiteSetting
- def self.valid_value?(val)
- values.any? { |v| v[:value].to_s == val.to_s }
- end
-
- def self.values
- @values ||= [
- { name: "discourse_calendar.toolbar_button.day", value: "day" },
- { name: "discourse_calendar.toolbar_button.week", value: "week" },
- { name: "discourse_calendar.toolbar_button.month", value: "month" },
- { name: "discourse_calendar.toolbar_button.year", value: "year" },
- ]
- end
-
- def self.translate_names?
- true
- end
-end
diff --git a/plugins/discourse-events/lib/calendar_validator.rb b/plugins/discourse-events/lib/calendar_validator.rb
deleted file mode 100644
index 032255eb719..00000000000
--- a/plugins/discourse-events/lib/calendar_validator.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseCalendar
- class CalendarValidator
- def initialize(post)
- @post = post
- end
-
- def validate_calendar
- extracted_calendars = DiscourseCalendar::Calendar.extract(@post)
-
- return false if extracted_calendars.count == 0
-
- if extracted_calendars.count > 1
- @post.errors.add(:base, I18n.t("discourse_calendar.more_than_one_calendar"))
- return false
- end
-
- if [email protected]_first_post?
- @post.errors.add(:base, I18n.t("discourse_calendar.calendar_must_be_in_first_post"))
- return false
- end
-
- true
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_events/calendar/event_validator.rb b/plugins/discourse-events/lib/discourse_events/calendar/event_validator.rb
new file mode 100644
index 00000000000..1524217efed
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/calendar/event_validator.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Calendar
+ class EventValidator
+ def initialize(post)
+ @post = post
+ @first_post = post.topic.first_post
+ end
+
+ def validate_event
+ dates_count = count_dates(@post)
+ calendar_type = @first_post.custom_fields[DiscourseEvents::CALENDAR_CUSTOM_FIELD]
+
+ if @post.whisper? && dates_count > 0
+ @post.errors.add(:base, I18n.t("discourse_calendar.whisper_not_allowed"))
+ return false
+ end
+
+ if calendar_type == "dynamic" && dates_count > 2
+ @post.errors.add(:base, I18n.t("discourse_calendar.more_than_two_dates"))
+ return false
+ end
+
+ return false if calendar_type == "static" && dates_count > 0
+
+ dates_count > 0
+ end
+
+ private
+
+ def count_dates(post)
+ cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
+ Nokogiri.HTML(cooked).css("span.discourse-local-date").count
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/calendar/extractor.rb b/plugins/discourse-events/lib/discourse_events/calendar/extractor.rb
new file mode 100644
index 00000000000..91168f43e8a
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/calendar/extractor.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Calendar
+ class Extractor
+ DATA_PREFIX = "data-calendar-"
+
+ def self.extract(post)
+ cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
+
+ Nokogiri
+ .HTML(cooked)
+ .css("div.calendar")
+ .map do |cooked_calendar|
+ calendar = {}
+
+ cooked_calendar.attributes.values.each do |attribute|
+ if attribute.name.start_with?(DATA_PREFIX)
+ calendar[attribute.name[DATA_PREFIX.length..-1]] = CGI.escapeHTML(
+ attribute.value || "",
+ )
+ end
+ end
+
+ calendar
+ end
+ end
+
+ def self.update(post)
+ calendar = extract(post)
+ return destroy(post) if calendar.size != 1
+ calendar = calendar.first
+
+ post.custom_fields[DiscourseEvents::CALENDAR_CUSTOM_FIELD] = calendar.delete("type") ||
+ "dynamic"
+ post.save_custom_fields
+
+ Post.where(topic_id: post.topic_id).each { |p| DiscourseEvents::Calendar::Event.update(p) }
+ end
+
+ def self.destroy(post)
+ return if post.custom_fields[DiscourseEvents::CALENDAR_CUSTOM_FIELD].blank?
+
+ post.custom_fields.delete(DiscourseEvents::CALENDAR_CUSTOM_FIELD)
+ post.save_custom_fields
+
+ DiscourseEvents::Calendar::Event.where(topic_id: post.topic_id).destroy_all
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/calendar/validator.rb b/plugins/discourse-events/lib/discourse_events/calendar/validator.rb
new file mode 100644
index 00000000000..82f8ff65760
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/calendar/validator.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Calendar
+ class Validator
+ def initialize(post)
+ @post = post
+ end
+
+ def validate_calendar
+ extracted_calendars = DiscourseEvents::Calendar::Extractor.extract(@post)
+
+ return false if extracted_calendars.count == 0
+
+ if extracted_calendars.count > 1
+ @post.errors.add(:base, I18n.t("discourse_calendar.more_than_one_calendar"))
+ return false
+ end
+
+ if [email protected]_first_post?
+ @post.errors.add(:base, I18n.t("discourse_calendar.calendar_must_be_in_first_post"))
+ return false
+ end
+
+ true
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/configuration/event_custom_fields_validator.rb b/plugins/discourse-events/lib/discourse_events/configuration/event_custom_fields_validator.rb
new file mode 100644
index 00000000000..a448b7813b6
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/configuration/event_custom_fields_validator.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Configuration
+ class EventCustomFieldsValidator
+ NAME_FORMAT = /\A[a-z0-9]+([_.-][a-z0-9]+)*\z/i
+
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(val)
+ @error_message = nil
+ return true if val.blank?
+
+ names = val.split("|").reject(&:blank?)
+ attributes =
+ names.index_with do |name|
+ DiscourseEvents::Events::Parser.custom_field_data_attribute(name)
+ end
+ errors = []
+
+ malformed = names.reject { |name| name.match?(NAME_FORMAT) }
+ errors << error(:invalid, malformed) if malformed.any?
+
+ colliding =
+ names
+ .group_by { |name| attributes[name] }
+ .values
+ .select { |group| group.size > 1 }
+ .flatten
+ errors << error(:collision, colliding) if colliding.any?
+
+ reserved = DiscourseEvents::Events::Parser.valid_option_attributes
+ reserved_names = names.select { |name| reserved.include?(attributes[name]) }
+ errors << error(:reserved, reserved_names) if reserved_names.any?
+
+ return true if errors.empty?
+
+ @error_message = errors.join(" ")
+ false
+ end
+
+ def error_message
+ @error_message
+ end
+
+ private
+
+ def error(key, names)
+ I18n.t(
+ "site_settings.discourse_post_event_allowed_custom_fields_#{key}",
+ names: names.join(", "),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/configuration/first_day_of_week.rb b/plugins/discourse-events/lib/discourse_events/configuration/first_day_of_week.rb
new file mode 100644
index 00000000000..9f4a10b19b3
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/configuration/first_day_of_week.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+require_dependency "enum_site_setting"
+
+module DiscourseEvents
+ module Configuration
+ class FirstDayOfWeek < EnumSiteSetting
+ def self.valid_value?(val)
+ values.any? { |v| v[:value].to_s == val.to_s }
+ end
+
+ def self.values
+ @values ||= [
+ { name: "user.notification_schedule.saturday", value: "saturday" },
+ { name: "user.notification_schedule.sunday", value: "sunday" },
+ { name: "user.notification_schedule.monday", value: "monday" },
+ ]
+ end
+
+ def self.translate_names?
+ true
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_calendar/site_settings/map_event_tag_colors_json_schema.rb b/plugins/discourse-events/lib/discourse_events/configuration/map_event_tag_colors_json_schema.rb
similarity index 95%
rename from plugins/discourse-events/lib/discourse_calendar/site_settings/map_event_tag_colors_json_schema.rb
rename to plugins/discourse-events/lib/discourse_events/configuration/map_event_tag_colors_json_schema.rb
index 9d5918933d6..b593190aeb3 100644
--- a/plugins/discourse-events/lib/discourse_calendar/site_settings/map_event_tag_colors_json_schema.rb
+++ b/plugins/discourse-events/lib/discourse_events/configuration/map_event_tag_colors_json_schema.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-module DiscourseCalendar
- module SiteSettings
+module DiscourseEvents
+ module Configuration
class MapEventTagColorsJsonSchema
def self.schema
@schema ||= {
diff --git a/plugins/discourse-events/lib/discourse_calendar/site_settings/map_events_title_json_schema.rb b/plugins/discourse-events/lib/discourse_events/configuration/map_events_title_json_schema.rb
similarity index 94%
rename from plugins/discourse-events/lib/discourse_calendar/site_settings/map_events_title_json_schema.rb
rename to plugins/discourse-events/lib/discourse_events/configuration/map_events_title_json_schema.rb
index 0c439e7dc2b..0b66e5c16b3 100644
--- a/plugins/discourse-events/lib/discourse_calendar/site_settings/map_events_title_json_schema.rb
+++ b/plugins/discourse-events/lib/discourse_events/configuration/map_events_title_json_schema.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-module DiscourseCalendar
- module SiteSettings
+module DiscourseEvents
+ module Configuration
class MapEventsTitleJsonSchema
def self.schema
@schema ||= {
diff --git a/plugins/discourse-events/lib/discourse_events/configuration/time_of_day_validator.rb b/plugins/discourse-events/lib/discourse_events/configuration/time_of_day_validator.rb
new file mode 100644
index 00000000000..25c5c7c9c0f
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/configuration/time_of_day_validator.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Configuration
+ class TimeOfDayValidator
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(val)
+ return true if val == ""
+
+ split = val.split(":")
+ return false if split.count != 2
+
+ hour = split.first
+ return false if hour.length != 2
+ return false if hour.to_i < 0 || hour.to_i >= 24
+
+ minutes = split.second
+ return false if minutes.length != 2
+ return false if minutes.to_i < 0 || minutes.to_i >= 60
+ true
+ end
+
+ def error_message
+ I18n.t("site_settings.all_day_event_time_error")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/configuration/upcoming_events_default_view.rb b/plugins/discourse-events/lib/discourse_events/configuration/upcoming_events_default_view.rb
new file mode 100644
index 00000000000..8bf1b634a4d
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/configuration/upcoming_events_default_view.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+require_dependency "enum_site_setting"
+
+module DiscourseEvents
+ module Configuration
+ class UpcomingEventsDefaultView < EnumSiteSetting
+ def self.valid_value?(val)
+ values.any? { |v| v[:value].to_s == val.to_s }
+ end
+
+ def self.values
+ @values ||= [
+ { name: "discourse_calendar.toolbar_button.day", value: "day" },
+ { name: "discourse_calendar.toolbar_button.week", value: "week" },
+ { name: "discourse_calendar.toolbar_button.month", value: "month" },
+ { name: "discourse_calendar.toolbar_button.year", value: "year" },
+ ]
+ end
+
+ def self.translate_names?
+ true
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_calendar/engine.rb b/plugins/discourse-events/lib/discourse_events/engine.rb
similarity index 61%
rename from plugins/discourse-events/lib/discourse_calendar/engine.rb
rename to plugins/discourse-events/lib/discourse_events/engine.rb
index 5efdc1f0aaf..84db227323c 100644
--- a/plugins/discourse-events/lib/discourse_calendar/engine.rb
+++ b/plugins/discourse-events/lib/discourse_events/engine.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
class Engine < ::Rails::Engine
engine_name PLUGIN_NAME
- isolate_namespace DiscourseCalendar
+ isolate_namespace DiscourseEvents
end
end
diff --git a/plugins/discourse-events/lib/discourse_events/events/chat_channel_sync.rb b/plugins/discourse-events/lib/discourse_events/events/chat_channel_sync.rb
new file mode 100644
index 00000000000..ab72bed5f9c
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/chat_channel_sync.rb
@@ -0,0 +1,77 @@
+# frozen_string_literal: true
+#
+module DiscourseEvents
+ module Events
+ class ChatChannelSync
+ def self.sync(event, guardian: nil)
+ return if !event.chat_enabled?
+ if !event.chat_channel_id && guardian&.can_create_chat_channel?
+ ensure_chat_channel!(event, guardian:)
+ end
+ sync_chat_channel_members!(event) if event.chat_channel_id
+ end
+
+ def self.sync_chat_channel_members!(event)
+ missing_members_sql = <<~SQL
+ SELECT i.user_id
+ FROM discourse_post_event_invitees i
+ INNER JOIN users u ON u.id = i.user_id
+ WHERE i.post_id = :post_id
+ AND i.status IN (:statuses)
+ AND (u.suspended_till IS NULL OR u.suspended_till <= :now)
+ AND (u.silenced_till IS NULL OR u.silenced_till <= :now)
+ AND u.staged = false
+ AND i.user_id NOT IN (
+ SELECT user_id
+ FROM user_chat_channel_memberships
+ WHERE chat_channel_id = :chat_channel_id
+ )
+ SQL
+
+ missing_user_ids =
+ DB.query_single(
+ missing_members_sql,
+ post_id: event.post.id,
+ statuses: [
+ DiscourseEvents::Events::Invitee.statuses[:going],
+ DiscourseEvents::Events::Invitee.statuses[:interested],
+ ],
+ chat_channel_id: event.chat_channel_id,
+ now: Time.zone.now,
+ )
+
+ if missing_user_ids.present?
+ ActiveRecord::Base.transaction do
+ missing_user_ids.each do |user_id|
+ event.chat_channel.user_chat_channel_memberships.create!(
+ user_id:,
+ chat_channel_id: event.chat_channel_id,
+ following: true,
+ )
+ end
+ end
+ end
+ end
+
+ def self.ensure_chat_channel!(event, guardian:)
+ name = event.name || event.post.topic.title
+
+ channel = nil
+ Chat::CreateCategoryChannel.call(
+ guardian:,
+ params: {
+ name:,
+ emoji: "spiral_calendar",
+ category_id: event.post.topic.category_id,
+ },
+ ) do |result|
+ on_success { channel = result.channel }
+ on_failure { raise StandardError, result.inspect_steps }
+ end
+
+ # event creator will be a member of the channel
+ event.chat_channel_id = channel.id
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/email_renderer.rb b/plugins/discourse-events/lib/discourse_events/events/email_renderer.rb
new file mode 100644
index 00000000000..c39ecff3285
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/email_renderer.rb
@@ -0,0 +1,223 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class EmailRenderer
+ RECURRENCE_ORDINALS = %w[first second third fourth]
+
+ def self.render(event_node, post)
+ new(event_node, post).to_html
+ end
+
+ def initialize(event_node, post)
+ @event_node = event_node
+ @post = post
+ @event =
+ DiscourseEvents::Events::Event.includes(:image_upload, :event_dates).find_by(id: post.id)
+ @starts_at = event_node["data-start"]
+ @timezone = event_node["data-timezone"] || "UTC"
+ @all_day = event_node["data-all-day"] == "true"
+ end
+
+ def to_html
+ rows = [
+ image_row,
+ name_row,
+ status_and_creator_row,
+ dates_row,
+ recurrence_row,
+ location_row,
+ url_row,
+ invitees_row,
+ description_row,
+ ].join
+
+ <<~HTML
+ <table cellspacing="0" cellpadding="0" border="0" style="border: 1px solid #dedede; margin-bottom: 10px; width: 100%;">
+ #{rows}
+ </table>
+ HTML
+ end
+
+ private
+
+ attr_reader :event_node, :post, :starts_at, :timezone
+
+ def image_row
+ return "" if @event&.image_upload_id.blank?
+
+ image_url = UrlHelper.absolute(@event.image_upload.url)
+ <<~HTML
+ <tr>
+ <td style="padding: 0;">
+ <img src="#{CGI.escape_html(image_url)}" style="width: 100%; max-height: 400px; object-fit: cover; display: block;" />
+ </td>
+ </tr>
+ HTML
+ end
+
+ def name_row
+ name = event_node["data-name"] || post.topic.title
+ name = CGI.escape_html(Emoji.gsub_emoji_to_unicode(name))
+ <<~HTML
+ <tr>
+ <td style="padding: 12px;">
+ <a href="#{post.full_url}" style="font-weight: bold; font-size: 1.1em;">#{name}</a>
+ </td>
+ </tr>
+ HTML
+ end
+
+ def muted_row(content)
+ return "" if content.blank?
+
+ <<~HTML
+ <tr>
+ <td style="padding: 0 12px 12px; color: #666;">#{content}</td>
+ </tr>
+ HTML
+ end
+
+ def status_and_creator_row
+ muted_row([status_label, creator_label].compact.join(" · "))
+ end
+
+ def dates_row
+ muted_row(CGI.escape_html(dates))
+ end
+
+ def recurrence_row
+ label = recurrence_label
+ muted_row(label && CGI.escape_html(label))
+ end
+
+ def cooked_location
+ @cooked_location ||= Parser.cook_location(event_node["data-location"], post:)
+ end
+
+ def location_row
+ return "" if event_node["data-location"].blank?
+
+ muted_row(cooked_location)
+ end
+
+ def url_row
+ url = event_node["data-url"].to_s.strip
+ location = event_node["data-location"]
+ return "" if url.blank?
+ if location.present? && Parser.url_restates_location?(url, location, cooked_location:)
+ return ""
+ end
+
+ href = Parser.linkable_url?(url) ? url : "https://#{url}"
+ <<~HTML
+ <tr>
+ <td style="padding: 0 12px 12px;"><a href="#{CGI.escape_html(href)}">#{CGI.escape_html(Parser.display_link(url))}</a></td>
+ </tr>
+ HTML
+ end
+
+ def invitees_row
+ return "" if @event.nil? || @event.standalone? || @event.minimal
+
+ muted_row(
+ CGI.escape_html(card_t("models.invitee.status.going_count", count: @event.going_count)),
+ )
+ end
+
+ def description_row
+ return "" if @event&.description.blank?
+
+ muted_row(Parser.cook_inline(@event.description, post:))
+ end
+
+ def dates
+ return "-" if @event&.expired? && @event.recurring?
+
+ suffix = timezone_suffix
+ formatted = "#{format_date(starts_at)}#{suffix}"
+
+ ends_at = event_node["data-end"]
+ formatted = "#{formatted} → #{format_date(ends_at)}#{suffix}" if ends_at
+
+ formatted
+ end
+
+ def format_date(value)
+ format = all_day? ? "%B %-d, %Y" : "%B %-d, %Y %-I:%M %p"
+ DateTime.parse(value).strftime(format)
+ rescue StandardError
+ value
+ end
+
+ def timezone_suffix
+ all_day? ? "" : " (#{timezone})"
+ end
+
+ def status_label
+ return nil if @event.nil?
+ return card_t("models.event.expired") if @event.expired?
+ return card_t("models.event.closed") if @event.closed
+
+ key =
+ if @event.standalone?
+ "standalone"
+ elsif @event.private?
+ "private"
+ else
+ "public"
+ end
+ card_t("models.event.status.#{key}.title")
+ end
+
+ def creator_label
+ user = post.user
+ return nil if user.nil?
+
+ name = SiteSetting.enable_names? ? user.display_name : user.username
+ "#{card_t("created_by")} #{CGI.escape_html(name)}"
+ end
+
+ def recurrence_label
+ recurrence = @event&.recurrence
+ return nil if recurrence.blank? || Validator::VALID_RECURRENCES.exclude?(recurrence)
+
+ card_t("builder_modal.recurrence.#{recurrence}", **recurrence_context)
+ rescue StandardError
+ nil
+ end
+
+ def recurrence_context
+ ref = recurrence_ref
+ return {} if ref.nil?
+
+ { weekday: ref.strftime("%A"), ordinal: recurrence_ordinal(ref) }
+ end
+
+ def recurrence_ref
+ return Date.parse(starts_at) if all_day?
+
+ zone = ActiveSupport::TimeZone[timezone] || ActiveSupport::TimeZone["UTC"]
+ zone.parse(starts_at)
+ rescue StandardError
+ nil
+ end
+
+ def recurrence_ordinal(ref)
+ # Mirrors RRuleConfigurator: a fifth occurrence is expressed as "last",
+ # since not every month has one.
+ nth = (ref.mday / 7.0).ceil
+ key = nth == 5 ? "last" : RECURRENCE_ORDINALS[nth - 1]
+ card_t("builder_modal.recurrence.ordinals.#{key}")
+ end
+
+ def card_t(key, **options)
+ I18n.t("js.discourse_post_event.#{key}", **options)
+ end
+
+ def all_day?
+ @all_day
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/excerpt.rb b/plugins/discourse-events/lib/discourse_events/events/excerpt.rb
new file mode 100644
index 00000000000..48023d1771b
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/excerpt.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ # Replaces each event node in an excerpt fragment (see PrettyText.excerpt)
+ # with a short plain-text summary — "📅 name · dates · location"
+ class Excerpt
+ def self.call(fragment, post: nil)
+ new(fragment, post: post).call
+ end
+
+ def initialize(fragment, post: nil)
+ @fragment = fragment
+ @topic_title = post&.topic&.title
+ end
+
+ def call
+ @fragment
+ .css(".discourse-post-event")
+ .each { |event_node| event_node.replace(CGI.escape_html(summary(event_node))) }
+ end
+
+ private
+
+ def summary(event_node)
+ event_name = event_node["data-name"].presence
+ location = event_node["data-location"].presence
+ location = Parser.inline_text(location) if location
+
+ parts = []
+ # only repeat the name when it differs from the topic title, which is
+ # already shown alongside the excerpt (e.g. in the topic onebox)
+ parts << event_name if event_name && event_name != @topic_title
+ parts << dates(event_node)
+ parts << location
+
+ summary = parts.compact.join(t("separator"))
+ summary.present? ? t("summary", summary: summary) : ""
+ end
+
+ def dates(event_node)
+ starts_at = event_node["data-start"]
+ return if starts_at.blank?
+
+ all_day = event_node["data-all-day"] == "true"
+ ends_at = event_node["data-end"]
+ timezone = event_node["data-timezone"] || "UTC"
+
+ dates = format_date(starts_at, all_day)
+ dates = t("date_range", from: dates, to: format_date(ends_at, all_day)) if ends_at.present?
+ dates = t("date_with_timezone", date: dates, timezone: timezone) unless all_day
+ dates
+ end
+
+ def format_date(value, all_day)
+ I18n.l(DateTime.parse(value), format: t(all_day ? "date_format" : "datetime_format"))
+ rescue StandardError
+ value
+ end
+
+ def t(key, **args)
+ I18n.t("discourse_post_event.event_excerpt.#{key}", **args)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/export_csv_controller_extension.rb b/plugins/discourse-events/lib/discourse_events/events/export_csv_controller_extension.rb
new file mode 100644
index 00000000000..3a13809f6e3
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/export_csv_controller_extension.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ module ExportCsvControllerExtension
+ def export_entity
+ if post_event_export? && ensure_can_export_post_event
+ Jobs.enqueue(
+ :export_csv_file,
+ entity: export_params[:entity],
+ user_id: current_user.id,
+ args: export_params[:args],
+ )
+ StaffActionLogger.new(current_user).log_entity_export(export_params[:entity])
+ render json: success_json
+ else
+ super
+ end
+ end
+
+ private
+
+ def export_params
+ if post_event_export?
+ @_export_params ||=
+ begin
+ params.require(:entity)
+ params.permit(:entity, args: %i[id]).to_h
+ end
+ else
+ super
+ end
+ end
+
+ def post_event_export?
+ params[:entity] === "post_event"
+ end
+
+ def ensure_can_export_post_event
+ return if !SiteSetting.discourse_post_event_enabled
+
+ post_event = DiscourseEvents::Events::Event.find(export_params[:args][:id])
+ post_event && guardian.can_act_on_discourse_post_event?(post_event)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/export_csv_report_extension.rb b/plugins/discourse-events/lib/discourse_events/events/export_csv_report_extension.rb
new file mode 100644
index 00000000000..c043c8c1528
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/export_csv_report_extension.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ module ExportCsvReportExtension
+ def post_event_export(&block)
+ return enum_for(:post_event_export) unless block_given?
+
+ guardian = Guardian.new(current_user)
+
+ event = DiscourseEvents::Events::Event.includes(invitees: :user).find(@extra[:id])
+
+ guardian.ensure_can_act_on_discourse_post_event!(event)
+
+ event
+ .invitees
+ .order(:id)
+ .each do |invitee|
+ yield(
+ [
+ invitee.user.username,
+ DiscourseEvents::Events::Invitee.statuses[invitee.status],
+ invitee.created_at,
+ invitee.updated_at,
+ ]
+ )
+ end
+ end
+
+ def get_header(entity)
+ if SiteSetting.discourse_post_event_enabled && entity === "post_event"
+ %w[username status first_answered_at last_updated_at]
+ else
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/finder.rb b/plugins/discourse-events/lib/discourse_events/events/finder.rb
new file mode 100644
index 00000000000..826b7a896d9
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/finder.rb
@@ -0,0 +1,212 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class Finder
+ def self.search(user, params = {})
+ guardian = Guardian.new(user)
+
+ build_base_query(guardian, user, params)
+ .then { |query| filter_by_post_id(query, params) }
+ .then { |query| filter_by_topic_id(query, params) }
+ .then { |query| filter_by_attending_user(query, params, guardian, user) }
+ .then { |query| filter_by_dates(query, params) }
+ .then { |query| filter_by_category(query, params) }
+ .then { |query| apply_ordering(query, params) }
+ .then { |query| apply_limit(query, params) }
+ end
+
+ private
+
+ def self.build_base_query(guardian, user, params)
+ topics = listable_topics(guardian)
+ pms = private_messages(user)
+
+ scope = DiscourseEvents::Events::Event.visible
+ scope = scope.open if params[:include_closed].blank?
+
+ scope
+ .joins(post: :topic)
+ .merge(Post.secured(guardian))
+ .merge(topics.or(pms))
+ .joins(latest_event_date_join)
+ .select(
+ "discourse_post_event_events.*, latest_event_dates.starts_at, latest_event_dates.ends_at, latest_event_dates.finished_at",
+ )
+ .where(
+ "(discourse_post_event_events.recurrence IS NOT NULL) OR (latest_event_dates.starts_at IS NOT NULL) OR (discourse_post_event_events.original_starts_at IS NOT NULL)",
+ )
+ .group(
+ "discourse_post_event_events.id, latest_event_dates.starts_at, latest_event_dates.ends_at, latest_event_dates.finished_at",
+ )
+ end
+
+ def self.latest_event_date_join
+ <<~SQL
+ LEFT JOIN (
+ SELECT DISTINCT ON (event_id)
+ event_id,
+ starts_at,
+ ends_at,
+ finished_at
+ FROM discourse_calendar_post_event_dates
+ ORDER BY event_id, #{DiscourseEvents::Events::EventDate.current_ordering_sql}
+ ) latest_event_dates ON latest_event_dates.event_id = discourse_post_event_events.id
+ SQL
+ end
+
+ def self.filter_by_post_id(events, params)
+ return events if params[:post_id].blank?
+ events.where(id: params[:post_id])
+ end
+
+ def self.filter_by_topic_id(events, params)
+ return events if params[:topic_id].blank?
+ events.where(topics: { id: params[:topic_id] })
+ end
+
+ def self.filter_by_attending_user(events, params, guardian, user)
+ return events if params[:attending_user].blank?
+
+ attending_user = User.find_by(username_lower: params[:attending_user].downcase)
+ return events.none if !attending_user
+
+ statuses = [DiscourseEvents::Events::Invitee.statuses[:going]]
+ if params[:include_interested].present? &&
+ can_include_interested?(guardian, user, attending_user)
+ statuses << DiscourseEvents::Events::Invitee.statuses[:interested]
+ end
+
+ events =
+ events.joins(:invitees).where(
+ discourse_post_event_invitees: {
+ user_id: attending_user.id,
+ status: statuses,
+ },
+ )
+
+ guardian.is_admin? ? events : apply_privacy_restrictions(events, user)
+ end
+
+ def self.can_include_interested?(guardian, user, attending_user)
+ guardian.is_admin? || user&.id == attending_user.id
+ end
+
+ def self.apply_privacy_restrictions(events, user)
+ private_status = DiscourseEvents::Events::Event.statuses[:private]
+
+ # If no user, can only see non-private events
+ return events.where.not(status: private_status) if user.nil?
+
+ # User can see private events if they still belong to an invited group.
+ events.where(<<~SQL, private_status, private_status, user.id)
+ discourse_post_event_events.status != ?
+ OR (
+ discourse_post_event_events.status = ?
+ AND EXISTS (
+ SELECT 1
+ FROM group_users
+ INNER JOIN groups ON groups.id = group_users.group_id
+ WHERE group_users.user_id = ?
+ AND groups.name = ANY(discourse_post_event_events.raw_invitees)
+ )
+ )
+ SQL
+ end
+
+ def self.filter_by_dates(events, params)
+ return events if params[:before].blank? && params[:after].blank?
+
+ before_date = params[:before] == "now" ? Time.current : params[:before]&.to_datetime
+ after_date = params[:after] == "now" ? Time.current : params[:after]&.to_datetime
+ include_ongoing = params[:include_ongoing].present?
+
+ recurring_scope = build_recurring_date_scope(after_date, before_date)
+ non_recurring_scope =
+ build_non_recurring_date_scope(after_date, before_date, include_ongoing:)
+
+ # Apply the combined scope using OR logic
+ events.merge(recurring_scope.or(non_recurring_scope))
+ end
+
+ private
+
+ def self.build_recurring_date_scope(after_date, before_date)
+ scope = DiscourseEvents::Events::Event.where.not(recurrence: nil)
+
+ if after_date
+ # For recurring events: original start date OR recurrence_until should be >= after_date
+ scope =
+ scope.where(
+ "original_starts_at >= ? OR recurrence_until IS NULL OR recurrence_until >= ?",
+ after_date,
+ after_date,
+ )
+ end
+
+ if before_date
+ # For recurring events: original start date should be < before_date
+ scope = scope.where("original_starts_at < ?", before_date)
+ end
+
+ scope
+ end
+
+ def self.build_non_recurring_date_scope(after_date, before_date, include_ongoing: false)
+ scope = DiscourseEvents::Events::Event.where(recurrence: nil)
+ if after_date
+ if include_ongoing
+ scope =
+ scope.where(
+ "latest_event_dates.starts_at >= ? OR (latest_event_dates.ends_at IS NOT NULL AND latest_event_dates.ends_at >= ?)",
+ after_date,
+ after_date,
+ )
+ else
+ scope = scope.where("latest_event_dates.starts_at >= ?", after_date)
+ end
+ end
+ scope = scope.where("latest_event_dates.starts_at < ?", before_date) if before_date
+ scope
+ end
+
+ def self.filter_by_category(events, params)
+ return events if params[:category_id].blank?
+
+ category_id = params[:category_id].to_i
+ category_ids =
+ (
+ if params[:include_subcategories].present?
+ Category.subcategory_ids(category_id)
+ else
+ [category_id]
+ end
+ )
+
+ events.where(topics: { category_id: category_ids })
+ end
+
+ def self.apply_ordering(events, params)
+ order_direction = params[:order] == "desc" ? "DESC" : "ASC"
+ events.order(
+ "latest_event_dates.starts_at #{order_direction}, discourse_post_event_events.id #{order_direction}",
+ )
+ end
+
+ def self.apply_limit(events, params)
+ limit = params[:limit]&.to_i || 200
+ events.limit(limit.clamp(1, 200))
+ end
+
+ def self.listable_topics(guardian)
+ topics = Topic.listable_topics.secured(guardian)
+ topics = topics.visible unless guardian.can_see_unlisted_topics?
+ topics
+ end
+
+ def self.private_messages(user)
+ user ? Topic.private_messages_for_user(user) : Topic.none
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/guardian_extensions.rb b/plugins/discourse-events/lib/discourse_events/events/guardian_extensions.rb
new file mode 100644
index 00000000000..9def24ed7c5
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/guardian_extensions.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ module GuardianExtensions
+ def can_act_on_invitee?(invitee)
+ return false if anonymous?
+ user.id == invitee.user_id || can_act_on_discourse_post_event?(invitee.event)
+ end
+
+ def can_create_discourse_post_event?
+ return false if anonymous?
+ @can_create_discourse_post_event ||=
+ user.in_any_groups?(SiteSetting.discourse_post_event_allowed_on_groups_map)
+ end
+
+ def can_act_on_discourse_post_event?(event)
+ return false if anonymous?
+ can_create_discourse_post_event? && can_edit_post?(event.post)
+ end
+
+ def can_display_invitee_details?(event)
+ return true if !event.private? || can_act_on_discourse_post_event?(event)
+
+ raw_invitees = Array(event.raw_invitees).uniq
+
+ return true if user && event.user_in_invited_group?(user)
+ return false if raw_invitees.blank?
+
+ Group
+ .visible_groups(user)
+ .members_visible_groups(user)
+ .where(name: raw_invitees)
+ .distinct
+ .count == raw_invitees.length
+ end
+
+ def can_export_entity?(entity, entity_id = nil, args = nil)
+ if entity == "post_event"
+ return false if !SiteSetting.discourse_post_event_enabled
+
+ event_id = args&.[](:id) || args&.[]("id")
+ event = DiscourseEvents::Events::Event.find_by(id: event_id)
+
+ return event.present? && can_act_on_discourse_post_event?(event)
+ end
+
+ super
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/onebox_data.rb b/plugins/discourse-events/lib/discourse_events/events/onebox_data.rb
new file mode 100644
index 00000000000..f53185fb982
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/onebox_data.rb
@@ -0,0 +1,107 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ # Builds, per post, the data needed to render an interactive event card for the
+ # internal topic oneboxes that point at an event topic. Mirrors
+ # ContentLocalization::OneboxLocalizer: batched via TopicLink and surfaced on
+ # the post serializer (see TopicView.on_preload + PostSerializer#event_oneboxes)
+ # so the client renders the card from inline data instead of fetching each
+ # event individually.
+ #
+ # Returns { source_post_id => { linked_topic_id => serialized_event } }. It's
+ # keyed by topic id so the client can match each `aside.quote[data-topic]`
+ # onebox to its event (mirrors how core's localized_oneboxes are matched).
+ class OneboxData
+ def self.build(posts:, guardian:)
+ new(posts:, guardian:).build
+ end
+
+ def initialize(posts:, guardian:)
+ @posts = posts
+ @guardian = guardian
+ end
+
+ def build
+ return {} if @posts.blank?
+
+ # cross-topic internal links (indexed lookup, no cooked scan). TopicLink
+ # does not record a topic that links itself, so same-topic oneboxes are
+ # detected from cooked further down.
+ links =
+ TopicLink
+ .where(post_id: @posts.map(&:id), internal: true, reflection: false)
+ .where.not(link_topic_id: nil)
+ .pluck(:post_id, :link_topic_id)
+ .uniq
+
+ # the topic being viewed, only when it's itself an event (cheap custom-field
+ # check, so non-event topic views do no extra work)
+ topic = @posts.first.topic
+ own_topic_id = topic&.event_starts_at ? topic.id : nil
+
+ topic_ids = links.map(&:last)
+ topic_ids << own_topic_id if own_topic_id
+ topic_ids.uniq!
+ return {} if topic_ids.empty?
+
+ first_post_ids = Post.where(topic_id: topic_ids, post_number: 1, deleted_at: nil).pluck(:id)
+ return {} if first_post_ids.empty?
+
+ events_by_topic =
+ DiscourseEvents::Events::Event
+ .where(id: first_post_ids)
+ .includes(:image_upload, post: [:user, { topic: :category }])
+ .index_by { |event| event.post.topic_id }
+ return {} if events_by_topic.empty?
+
+ @serialized = {}
+ result = {}
+
+ links.each do |source_post_id, link_topic_id|
+ event = events_by_topic[link_topic_id]
+ next if event.nil? || [email protected]_see?(event.post)
+ (result[source_post_id] ||= {})[link_topic_id] = serialize(event)
+ end
+
+ own_event = own_topic_id && events_by_topic[own_topic_id]
+ if own_event && @guardian.can_see?(own_event.post)
+ each_self_onebox_post(own_topic_id) do |post_id|
+ (result[post_id] ||= {})[own_topic_id] = serialize(own_event)
+ end
+ end
+
+ result
+ end
+
+ private
+
+ def serialize(event)
+ @serialized[event.id] ||= DiscourseEvents::Events::EventSerializer.new(
+ event,
+ scope: @guardian,
+ root: false,
+ ).as_json
+ end
+
+ # yields the id of each post whose cooked oneboxes its own (event) topic. A
+ # same-topic onebox is `aside.quote[data-post="1"]` without a data-username
+ # (which would mark a manual quote); the cheap include? skips parsing posts
+ # that don't reference the topic at all.
+ def each_self_onebox_post(topic_id)
+ marker = %{data-topic="#{topic_id}"}
+ @posts.each do |post|
+ next if post.cooked.blank? || !post.cooked.include?(marker)
+
+ onebox =
+ Nokogiri::HTML5
+ .fragment(post.cooked)
+ .css(%{aside.quote[data-topic="#{topic_id}"][data-post="1"]})
+ .any? { |aside| aside["data-username"].blank? }
+
+ yield(post.id) if onebox
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/parser.rb b/plugins/discourse-events/lib/discourse_events/events/parser.rb
new file mode 100644
index 00000000000..e084251940e
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/parser.rb
@@ -0,0 +1,213 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class Parser
+ VALID_OPTIONS = [
+ :start,
+ :end,
+ :status,
+ :"allowed-groups",
+ :url,
+ :location,
+ :name,
+ :reminders,
+ :recurrence,
+ :"recurrence-until",
+ :timezone,
+ :"show-local-time",
+ :minimal,
+ :closed,
+ :"chat-enabled",
+ :livestream,
+ :"max-attendees",
+ :"all-day",
+ :image,
+ ]
+
+ LEGACY_ESCAPED_ATTRS = %w[data-location]
+ SCHEME_PREFIX = /\A[a-z][a-z0-9+.\-]*:/i
+
+ def self.extract_events(post)
+ cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
+ valid_options = valid_option_attributes
+
+ valid_custom_fields =
+ SiteSetting
+ .discourse_post_event_allowed_custom_fields
+ .split("|")
+ .map do |setting|
+ { original: "data-#{setting}", normalized: custom_field_data_attribute(setting) }
+ end
+
+ Nokogiri
+ .HTML(cooked)
+ .css("div.discourse-post-event")
+ .map do |doc|
+ event = nil
+ doc.attributes.values.each do |attribute|
+ name = attribute.name
+ value = attribute.value
+
+ if value && valid_options.include?(name)
+ event ||= {}
+ value = CGI.unescapeHTML(value) if LEGACY_ESCAPED_ATTRS.include?(name)
+ event[name.sub("data-", "").to_sym] = case name
+ when "data-name", "data-url", "data-image", "data-location"
+ value
+ else
+ CGI.escapeHTML(value)
+ end
+ end
+
+ valid_custom_fields.each do |valid_custom_field|
+ if value && valid_custom_field[:normalized] == name
+ event ||= {}
+ event[valid_custom_field[:original].sub("data-", "").to_sym] = CGI.escapeHTML(
+ value,
+ )
+ end
+ end
+ end
+ event[:description] = to_markdown(doc) if event
+ event
+ end
+ .compact
+ end
+
+ def self.valid_option_attributes
+ VALID_OPTIONS.map { |option| "data-#{option}" }
+ end
+
+ def self.custom_field_data_attribute(setting)
+ camelized = setting.downcase.gsub(/[-.]/, "_").gsub(/_(.)/) { $1.upcase }
+ dasherized = camelized.gsub(/[A-Z]/) { |char| "-#{char.downcase}" }.sub(/\A-/, "")
+ "data-#{dasherized}"
+ end
+
+ INLINE_MARKDOWN_FEATURES = %w[emoji linkify]
+ INLINE_MARKDOWN_IT_RULES = %w[link linkify entity escape newline]
+ INLINE_CACHE_VERSION = 2
+
+ def self.cook_inline(text, post: nil)
+ text = text.to_s
+ add_nofollow = post.nil? || post.add_nofollow?
+
+ Discourse
+ .cache
+ .fetch(
+ "post-event-inline:#{INLINE_CACHE_VERSION}:#{Digest::SHA1.hexdigest(text)}:#{add_nofollow}",
+ expires_in: 1.week,
+ ) do
+ cooked =
+ PrettyText.cook(
+ text,
+ features_override: INLINE_MARKDOWN_FEATURES,
+ markdown_it_rules: INLINE_MARKDOWN_IT_RULES,
+ omit_nofollow: !add_nofollow,
+ )
+ fragment = Nokogiri::HTML5.fragment(cooked)
+ content = fragment.children.reject(&:blank?)
+ if content.length == 1 && content.first.name == "p"
+ content.first.inner_html
+ else
+ fragment.to_html
+ end
+ end
+ end
+
+ def self.cook_location(text, post: nil)
+ text = text.to_s
+ add_nofollow = post.nil? || post.add_nofollow?
+
+ Discourse
+ .cache
+ .fetch(
+ "post-event-location:#{INLINE_CACHE_VERSION}:#{Digest::SHA1.hexdigest(text)}:#{add_nofollow}",
+ expires_in: 1.week,
+ ) { normalize_links(cook_inline(text, post:)) }
+ end
+
+ def self.inline_text(text)
+ cooked = cook_inline(text)
+ PrettyText.excerpt(cooked, cooked.length, strip_links: true, text_entities: true)
+ end
+
+ def self.linkable_url?(url)
+ url = url.to_s.downcase
+ schemes = %w[http https mailto] | SiteSetting.allowed_href_schemes.split("|")
+ schemes.any? { |scheme| url.start_with?("#{scheme}:") }
+ end
+
+ def self.valid_url?(value)
+ value = value.to_s.strip
+ return true if value.blank?
+ # Rejected before encoding, which would otherwise make a CR/LF payload parse.
+ return false if value.match?(/\s/)
+
+ candidate = value.match?(SCHEME_PREFIX) ? value : "https://#{value}"
+ uri = URI.parse(UrlHelper.encode(candidate))
+ uri.scheme == "mailto" ? uri.opaque.present? : uri.host.present?
+ rescue URI::Error, Addressable::URI::InvalidURIError
+ false
+ end
+
+ def self.normalize_link(value)
+ value.to_s.strip.downcase.sub(%r{\Ahttps?://}, "").sub(%r{/+\z}, "")
+ end
+
+ def self.display_link(value)
+ value.to_s.strip.sub(%r{\Ahttps?://}i, "")
+ end
+
+ # A location is cooked, so its links arrive as anchors. Present them the same
+ # way the url row is presented: no scheme on screen, https when the author
+ # did not write one. Anchors carrying custom text are left alone.
+ def self.normalize_links(html)
+ fragment = Nokogiri::HTML5.fragment(html.to_s)
+ anchors =
+ fragment.css("a[href]").select { |a| [a.text, "http://#{a.text}"].include?(a["href"]) }
+ return html if anchors.empty?
+
+ anchors.each do |anchor|
+ text = anchor.text
+ if anchor["href"] == text
+ anchor.content = display_link(text)
+ else
+ anchor["href"] = "https://#{text}"
+ end
+ end
+
+ fragment.to_html
+ end
+
+ def self.url_restates_location?(url, location, cooked_location: nil)
+ return false if url.blank? || location.blank?
+
+ target = normalize_link(url)
+ return true if normalize_link(location) == target
+
+ Nokogiri::HTML5
+ .fragment(cooked_location || cook_location(location))
+ .css("a[href]")
+ .any? { |anchor| normalize_link(anchor["href"]) == target }
+ end
+
+ def self.to_markdown(node)
+ fragment = node.dup
+ fragment
+ .css("img.emoji")
+ .each { |img| img.replace(img.document.create_text_node(img["alt"].to_s)) }
+ fragment
+ .css("a[href]")
+ .each do |a|
+ href = a["href"].to_s
+ next if !linkable_url?(href)
+ markdown = a.text == href ? href : "[#{a.text}](#{href})"
+ a.replace(a.document.create_text_node(markdown))
+ end
+ fragment.text.strip
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/post_extension.rb b/plugins/discourse-events/lib/discourse_events/events/post_extension.rb
new file mode 100644
index 00000000000..b93e62b07b3
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/post_extension.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ module PostExtension
+ extend ActiveSupport::Concern
+
+ prepended do
+ has_one :event,
+ dependent: :destroy,
+ class_name: "DiscourseEvents::Events::Event",
+ foreign_key: :id
+
+ validate :valid_event
+ end
+
+ def valid_event
+ return unless raw_changed?
+
+ validator = DiscourseEvents::Events::Validator.new(self)
+ validator.validate_event
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/rrule_configurator.rb b/plugins/discourse-events/lib/discourse_events/events/rrule_configurator.rb
new file mode 100644
index 00000000000..82f81666d9a
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/rrule_configurator.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class RRuleConfigurator
+ def self.rule(recurrence:, starts_at:, recurrence_until: nil)
+ rule =
+ case recurrence
+ when "every_day"
+ "FREQ=DAILY"
+ when "every_month"
+ weekday = starts_at.strftime("%A")
+ nth = ((starts_at.day - 1) / 7) + 1
+
+ # Every month has at least four of each weekday, so the first four
+ # positions are safe. A fifth only exists in some months, so anchor it
+ # to -1 ("last") instead, otherwise the rule would skip months.
+ byday_count = nth == 5 ? -1 : nth
+
+ "FREQ=MONTHLY;BYDAY=#{byday_count}#{weekday.upcase[0, 2]}"
+ when "every_weekday"
+ "FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"
+ when "every_two_weeks"
+ "FREQ=WEEKLY;INTERVAL=2"
+ when "every_four_weeks"
+ "FREQ=WEEKLY;INTERVAL=4"
+ else
+ byday = starts_at.strftime("%A").upcase[0, 2]
+ "FREQ=WEEKLY;BYDAY=#{byday}"
+ end
+
+ rule += ";UNTIL=#{recurrence_until.strftime("%Y%m%dT%H%M%S")}" if recurrence_until
+ rule
+ end
+
+ def self.how_many_recurring_events(recurrence:, max_years: nil)
+ return 1 if !max_years
+ per_year =
+ case recurrence
+ when "every_month"
+ 12
+ when "every_four_weeks"
+ 13
+ when "every_two_weeks"
+ 26
+ when "every_weekday"
+ 260
+ when "every_week"
+ 52
+ when "every_day"
+ 365
+ end
+ per_year * max_years
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/rrule_generator.rb b/plugins/discourse-events/lib/discourse_events/events/rrule_generator.rb
new file mode 100644
index 00000000000..f695afee5f3
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/rrule_generator.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+require "rrule"
+
+module DiscourseEvents
+ module Events
+ class RRuleGenerator
+ def self.generate(
+ starts_at:,
+ timezone: "UTC",
+ max_years: nil,
+ recurrence: "every_week",
+ recurrence_until: nil,
+ dtstart: nil
+ )
+ rrule =
+ generate_hash(
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence_until:,
+ recurrence:,
+ starts_at:,
+ ),
+ )
+ rrule = set_mandatory_options(rrule, starts_at)
+
+ ::RRule::Rule
+ .new(stringify(rrule), dtstart: starts_at, tzid: timezone)
+ .between(Time.current, 14.months.from_now)
+ .first(
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence:,
+ max_years:,
+ ),
+ )
+ end
+
+ def self.generate_string(
+ starts_at:,
+ recurrence: "every_week",
+ recurrence_until: nil,
+ dtstart: nil,
+ show_local_time: false
+ )
+ rrule =
+ generate_hash(
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence_until:,
+ recurrence:,
+ starts_at:,
+ ),
+ )
+ rrule = set_mandatory_options(rrule, starts_at)
+ rrule_line = "RRULE:#{stringify(rrule)}"
+
+ if dtstart
+ if show_local_time
+ dtstart_line = "DTSTART:#{dtstart.strftime("%Y%m%dT%H%M%S")}"
+ else
+ dtstart_line = "DTSTART:#{dtstart.utc.strftime("%Y%m%dT%H%M%SZ")}"
+ end
+ "#{dtstart_line}\n#{rrule_line}"
+ else
+ rrule_line
+ end
+ end
+
+ private
+
+ def self.stringify(rrule)
+ rrule.map { |k, v| "#{k}=#{v}" }.join(";")
+ end
+
+ def self.generate_hash(rrule)
+ rrule
+ .split(";")
+ .each_with_object({}) do |rr, h|
+ key, value = rr.split("=")
+ h[key] = value
+ end
+ end
+
+ def self.set_mandatory_options(rrule, time)
+ rrule["INTERVAL"] ||= 1
+ rrule["WKST"] = "MO" # considers Monday as the first day of the week
+ rrule
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/topic_extension.rb b/plugins/discourse-events/lib/discourse_events/events/topic_extension.rb
new file mode 100644
index 00000000000..65364185020
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/topic_extension.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ module TopicExtension
+ def move_posts(moved_by, post_ids, opts)
+ ensure_event_invariants!(post_ids, opts)
+ super
+ end
+
+ private
+
+ def ensure_event_invariants!(post_ids, opts)
+ return unless SiteSetting.discourse_post_event_enabled
+ return unless opts[:destination_topic_id]
+
+ destination = Topic.find_by(id: opts[:destination_topic_id])
+ return unless destination
+
+ destination_op = destination.first_post
+ destination_has_event = destination_op&.event.present?
+ incoming_event_post = Post.where(id: post_ids).joins(:event).order(:created_at).first
+
+ return unless destination_has_event || incoming_event_post
+
+ raise_event_move_error! if destination_has_event && incoming_event_post
+
+ chronological = !!opts[:chronological_order]
+
+ if destination_has_event && chronological
+ oldest_incoming = Post.where(id: post_ids).order(:created_at).first
+ if oldest_incoming && oldest_incoming.created_at < destination_op.created_at
+ raise_event_move_error!
+ end
+ end
+
+ if incoming_event_post && !destination_has_event
+ becomes_new_op =
+ chronological &&
+ (destination_op.nil? || incoming_event_post.created_at < destination_op.created_at)
+ raise_event_move_error! unless becomes_new_op
+ end
+ end
+
+ def raise_event_move_error!
+ raise ActiveRecord::RecordNotSaved.new(
+ I18n.t("discourse_post_event.errors.models.event.must_be_in_first_post"),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/validator.rb b/plugins/discourse-events/lib/discourse_events/events/validator.rb
new file mode 100644
index 00000000000..5db7e1a2e10
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/validator.rb
@@ -0,0 +1,185 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class Validator
+ VALID_RECURRENCES = %w[
+ every_month
+ every_week
+ every_two_weeks
+ every_four_weeks
+ every_day
+ every_weekday
+ ]
+
+ def initialize(post)
+ @post = post
+ end
+
+ def validate_event
+ extracted_events = DiscourseEvents::Events::Parser.extract_events(@post)
+
+ return false if extracted_events.count == 0
+
+ if extracted_events.count > 1
+ @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.only_one_event"))
+ return false
+ end
+
+ if [email protected]_first_post?
+ @post.errors.add(
+ :base,
+ I18n.t("discourse_post_event.errors.models.event.must_be_in_first_post"),
+ )
+ return false
+ end
+
+ extracted_event = extracted_events.first
+
+ return false unless can_invite_groups?(extracted_event)
+
+ if @post.acting_user && @post.event
+ if [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
+ end
+ else
+ if [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
+ end
+ end
+
+ 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
+ end
+
+ 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
+ end
+
+ 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
+ end
+
+ 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
+ end
+
+ 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"),
+ )
+ end
+ end
+
+ 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],
+ ),
+ )
+ end
+ end
+
+ if !Parser.valid_url?(extracted_event[:url])
+ @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.invalid_url"))
+ end
+
+ true
+ end
+
+ private
+
+ def can_invite_groups?(event)
+ return true unless event[:"allowed-groups"]
+
+ 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
+ end
+
+ 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
+ end
+
+ true
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/web_hook_extension.rb b/plugins/discourse-events/lib/discourse_events/events/web_hook_extension.rb
new file mode 100644
index 00000000000..9f41eb6f28a
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/web_hook_extension.rb
@@ -0,0 +1,93 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ module WebHookExtension
+ extend ActiveSupport::Concern
+
+ class_methods do
+ def enqueue_calendar_event_hooks(event_name, calendar_event, payload = nil)
+ if active_web_hooks(event_name).exists? && calendar_event.present?
+ payload ||= WebHook.build_calendar_event_payload(calendar_event)
+
+ WebHook.enqueue_hooks(
+ :calendar_event,
+ event_name,
+ id: calendar_event.id,
+ category_id: calendar_event.post&.topic&.category_id,
+ tag_ids: calendar_event.post&.topic&.tags&.pluck(:id),
+ payload: payload,
+ )
+ end
+ end
+
+ def build_calendar_event_payload(calendar_event)
+ post = calendar_event.post
+ topic = post&.topic
+
+ parsed_starts_at =
+ (
+ if calendar_event.all_day
+ calendar_event.starts_at&.utc&.strftime("%Y-%m-%d")
+ else
+ calendar_event.starts_at
+ end
+ )
+ parsed_ends_at =
+ (
+ if calendar_event.all_day
+ calendar_event.ends_at&.utc&.strftime("%Y-%m-%d")
+ else
+ calendar_event.ends_at
+ end
+ )
+
+ event_image =
+ if calendar_event.image_upload.present?
+ {
+ id: calendar_event.image_upload.id,
+ url: UrlHelper.absolute(calendar_event.image_upload.url),
+ width: calendar_event.image_upload.width,
+ height: calendar_event.image_upload.height,
+ }
+ end
+
+ {
+ event: {
+ id: calendar_event.id,
+ name: calendar_event.name,
+ description: calendar_event.description,
+ location: calendar_event.location,
+ url: calendar_event.url,
+ status: DiscourseEvents::Events::Event.statuses[calendar_event.status]&.to_s,
+ starts_at: parsed_starts_at,
+ ends_at: parsed_ends_at,
+ all_day: calendar_event.all_day,
+ recurrence: calendar_event.recurrence,
+ recurrence_until: calendar_event.recurrence_until,
+ timezone: calendar_event.timezone,
+ custom_fields: calendar_event.custom_fields,
+ closed: calendar_event.closed,
+ max_attendees: calendar_event.max_attendees,
+ chat_enabled: calendar_event.chat_enabled,
+ allowed_groups: calendar_event.raw_invitees,
+ image: event_image,
+ },
+ post: {
+ id: post&.id,
+ post_number: post&.post_number,
+ url: post&.url,
+ },
+ topic: {
+ id: topic&.id,
+ title: topic&.title,
+ url: topic&.url,
+ category_id: topic&.category_id,
+ tags: topic&.tags&.pluck(:name),
+ },
+ }.to_json
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/group_timezones/extractor.rb b/plugins/discourse-events/lib/discourse_events/group_timezones/extractor.rb
new file mode 100644
index 00000000000..6d556977bc5
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/group_timezones/extractor.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module GroupTimezones
+ class Extractor
+ def self.update(post)
+ groups = []
+
+ Nokogiri
+ .HTML(post.cooked)
+ .css("div.group-timezones")
+ .map do |group_timezones|
+ group_timezones.attributes.values.each do |attribute|
+ if attribute.name == "data-group"
+ group_name = CGI.escapeHTML(attribute.value || "")
+ groups << group_name if group_name.present?
+ end
+ end
+ end
+
+ post.group_timezones = groups.present? ? { groups: groups } : nil
+ post.save_custom_fields
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/holidays/finder.rb b/plugins/discourse-events/lib/discourse_events/holidays/finder.rb
new file mode 100644
index 00000000000..6eaf625be6a
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/holidays/finder.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+require "holidays"
+
+module DiscourseEvents
+ module Holidays
+ class Finder
+ def self.find_holidays_for(
+ region_code:,
+ start_date: Date.current.beginning_of_year,
+ end_date: Date.current.end_of_year,
+ show_holiday_observed_on_dates: false
+ )
+ holidays =
+ ::Holidays.between(
+ start_date,
+ end_date,
+ [region_code],
+ show_holiday_observed_on_dates ? :observed : [],
+ )
+
+ holidays.map do |holiday|
+ holiday[:disabled] = DiscourseEvents::Holidays::DisabledHoliday.where(
+ region_code: region_code,
+ ).exists?(holiday_name: holiday[:name])
+ end
+
+ holidays
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/holidays/status.rb b/plugins/discourse-events/lib/discourse_events/holidays/status.rb
new file mode 100644
index 00000000000..10e205848f6
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/holidays/status.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Holidays
+ class Status
+ def self.set!(user, ends_at)
+ status = user.user_status
+ if status.blank? || status.expired? ||
+ (is_holiday_status?(status) && status.ends_at != ends_at)
+ user.set_status!(
+ I18n.t("discourse_calendar.holiday_status.description"),
+ emoji_name,
+ ends_at,
+ )
+ end
+ end
+
+ def self.clear!(user)
+ user.clear_status! if user&.user_status && is_holiday_status?(user.user_status)
+ end
+
+ private
+
+ def self.is_holiday_status?(status)
+ status.emoji == emoji_name &&
+ status.description == I18n.t("discourse_calendar.holiday_status.description")
+ end
+
+ def self.emoji_name
+ SiteSetting.holiday_status_emoji.presence || "date"
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/holidays/users_on_holiday.rb b/plugins/discourse-events/lib/discourse_events/holidays/users_on_holiday.rb
new file mode 100644
index 00000000000..4978f8805dd
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/holidays/users_on_holiday.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Holidays
+ class UsersOnHoliday
+ def self.from(calendar_events)
+ calendar_events
+ .filter { |e| e.user_id.present? && e.username.present? }
+ .filter { |e| e.underway? || e.in_future? }
+ .group_by(&:user_id)
+ .map { |_, events| current_holiday(events) }
+ .compact
+ .to_h
+ end
+
+ private
+
+ def self.current_holiday(user_events)
+ ends_at = holiday_ends_at(user_events)
+ return nil unless ends_at
+
+ [user_events[0].user_id, { username: user_events[0].username, ends_at: ends_at }]
+ end
+
+ # If a user has several holidays one after another
+ # we want to show the farthest end date.
+ #
+ # Let's say today is Monday and I am sick,
+ # and I also have days off from Tuesday to Friday:
+ #
+ # sick ▭
+ # days off ▭▭▭▭
+ #
+ # We want to show Friday as an end date of my holiday.
+ #
+ # This algorithm also works in case the holidays intersect,
+ # like this:
+ #
+ # event_1 ▭▭▭▭
+ # event_2 ▭▭▭▭
+ # event_3 ▭▭▭▭
+ #
+ # or like this:
+ #
+ # event_1 ▭▭▭▭
+ # event_2 ▭▭▭▭▭▭▭▭
+ # event_3 ▭▭▭▭▭▭▭▭▭▭
+ #
+ # or like this:
+ #
+ # event_1 ▭▭▭▭▭▭▭▭▭▭
+ # event_2 ▭
+ #
+ def self.holiday_ends_at(events)
+ sorted_events = events.sort_by(&:start_date)
+ return nil if sorted_events.first.in_future?
+ return sorted_events.first.ends_at if events.count == 1
+
+ result = sorted_events.first.ends_at
+ sorted_events.each_cons(2) do |pair|
+ if pair[0].ends_at < pair[1].start_date
+ return result
+ elsif pair[1].ends_at > result
+ result = pair[1].ends_at
+ end
+ end
+
+ result
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_calendar/livestream/allowed_hosts.rb b/plugins/discourse-events/lib/discourse_events/livestream/allowed_hosts.rb
similarity index 98%
rename from plugins/discourse-events/lib/discourse_calendar/livestream/allowed_hosts.rb
rename to plugins/discourse-events/lib/discourse_events/livestream/allowed_hosts.rb
index 1501cf8d622..cd7821cef5f 100644
--- a/plugins/discourse-events/lib/discourse_calendar/livestream/allowed_hosts.rb
+++ b/plugins/discourse-events/lib/discourse_events/livestream/allowed_hosts.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Livestream
# Server-side counterpart of `isLivestreamUrl` in raw-event-helper.js: both
# accept a host listed in `livestream_allowed_hosts` and any of its
diff --git a/plugins/discourse-events/lib/discourse_calendar/livestream/allowed_hosts_validator.rb b/plugins/discourse-events/lib/discourse_events/livestream/allowed_hosts_validator.rb
similarity index 96%
rename from plugins/discourse-events/lib/discourse_calendar/livestream/allowed_hosts_validator.rb
rename to plugins/discourse-events/lib/discourse_events/livestream/allowed_hosts_validator.rb
index 45b14770bf7..2445a1b0dfe 100644
--- a/plugins/discourse-events/lib/discourse_calendar/livestream/allowed_hosts_validator.rb
+++ b/plugins/discourse-events/lib/discourse_events/livestream/allowed_hosts_validator.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Livestream
# Replaces the default `host_list` validator, which only rejects wildcards.
class AllowedHostsValidator
diff --git a/plugins/discourse-events/lib/discourse_calendar/livestream/chat_channel_extension.rb b/plugins/discourse-events/lib/discourse_events/livestream/chat_channel_extension.rb
similarity index 74%
rename from plugins/discourse-events/lib/discourse_calendar/livestream/chat_channel_extension.rb
rename to plugins/discourse-events/lib/discourse_events/livestream/chat_channel_extension.rb
index aee67d01445..fb6e78ba194 100644
--- a/plugins/discourse-events/lib/discourse_calendar/livestream/chat_channel_extension.rb
+++ b/plugins/discourse-events/lib/discourse_events/livestream/chat_channel_extension.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Livestream
module ChatChannelExtension
extend ActiveSupport::Concern
prepended do
has_one :livestream_topic_chat_channel,
- class_name: "DiscourseCalendar::Livestream::TopicChatChannel",
+ class_name: "DiscourseEvents::Livestream::TopicChatChannel",
dependent: :destroy,
foreign_key: :chat_channel_id
end
diff --git a/plugins/discourse-events/lib/discourse_calendar/livestream/topic_extension.rb b/plugins/discourse-events/lib/discourse_events/livestream/topic_extension.rb
similarity index 82%
rename from plugins/discourse-events/lib/discourse_calendar/livestream/topic_extension.rb
rename to plugins/discourse-events/lib/discourse_events/livestream/topic_extension.rb
index 82a83e9b5d1..bff0c7057e4 100644
--- a/plugins/discourse-events/lib/discourse_calendar/livestream/topic_extension.rb
+++ b/plugins/discourse-events/lib/discourse_events/livestream/topic_extension.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Livestream
module TopicExtension
extend ActiveSupport::Concern
prepended do
has_one :topic_chat_channel,
- class_name: "DiscourseCalendar::Livestream::TopicChatChannel",
+ class_name: "DiscourseEvents::Livestream::TopicChatChannel",
dependent: :destroy
after_update do
diff --git a/plugins/discourse-events/lib/discourse_calendar/livestream/zoom_url_parser.rb b/plugins/discourse-events/lib/discourse_events/livestream/zoom_url_parser.rb
similarity index 98%
rename from plugins/discourse-events/lib/discourse_calendar/livestream/zoom_url_parser.rb
rename to plugins/discourse-events/lib/discourse_events/livestream/zoom_url_parser.rb
index 432364ff0f7..d1350c31c9a 100644
--- a/plugins/discourse-events/lib/discourse_calendar/livestream/zoom_url_parser.rb
+++ b/plugins/discourse-events/lib/discourse_events/livestream/zoom_url_parser.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
module Livestream
module ZoomUrlParser
# Matches zoom.us and its vanity subdomains (us06web.zoom.us), but not
diff --git a/plugins/discourse-events/lib/discourse_post_event/email_renderer.rb b/plugins/discourse-events/lib/discourse_post_event/email_renderer.rb
deleted file mode 100644
index 44ac40f595b..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/email_renderer.rb
+++ /dev/null
@@ -1,220 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EmailRenderer
- RECURRENCE_ORDINALS = %w[first second third fourth]
-
- def self.render(event_node, post)
- new(event_node, post).to_html
- end
-
- def initialize(event_node, post)
- @event_node = event_node
- @post = post
- @event = DiscoursePostEvent::Event.includes(:image_upload, :event_dates).find_by(id: post.id)
- @starts_at = event_node["data-start"]
- @timezone = event_node["data-timezone"] || "UTC"
- @all_day = event_node["data-all-day"] == "true"
- end
-
- def to_html
- rows = [
- image_row,
- name_row,
- status_and_creator_row,
- dates_row,
- recurrence_row,
- location_row,
- url_row,
- invitees_row,
- description_row,
- ].join
-
- <<~HTML
- <table cellspacing="0" cellpadding="0" border="0" style="border: 1px solid #dedede; margin-bottom: 10px; width: 100%;">
- #{rows}
- </table>
- HTML
- end
-
- private
-
- attr_reader :event_node, :post, :starts_at, :timezone
-
- def image_row
- return "" if @event&.image_upload_id.blank?
-
- image_url = UrlHelper.absolute(@event.image_upload.url)
- <<~HTML
- <tr>
- <td style="padding: 0;">
- <img src="#{CGI.escape_html(image_url)}" style="width: 100%; max-height: 400px; object-fit: cover; display: block;" />
- </td>
- </tr>
- HTML
- end
-
- def name_row
- name = event_node["data-name"] || post.topic.title
- name = CGI.escape_html(Emoji.gsub_emoji_to_unicode(name))
- <<~HTML
- <tr>
- <td style="padding: 12px;">
- <a href="#{post.full_url}" style="font-weight: bold; font-size: 1.1em;">#{name}</a>
- </td>
- </tr>
- HTML
- end
-
- def muted_row(content)
- return "" if content.blank?
-
- <<~HTML
- <tr>
- <td style="padding: 0 12px 12px; color: #666;">#{content}</td>
- </tr>
- HTML
- end
-
- def status_and_creator_row
- muted_row([status_label, creator_label].compact.join(" · "))
- end
-
- def dates_row
- muted_row(CGI.escape_html(dates))
- end
-
- def recurrence_row
- label = recurrence_label
- muted_row(label && CGI.escape_html(label))
- end
-
- def cooked_location
- @cooked_location ||= EventParser.cook_location(event_node["data-location"], post:)
- end
-
- def location_row
- return "" if event_node["data-location"].blank?
-
- muted_row(cooked_location)
- end
-
- def url_row
- url = event_node["data-url"].to_s.strip
- location = event_node["data-location"]
- return "" if url.blank?
- if location.present? && EventParser.url_restates_location?(url, location, cooked_location:)
- return ""
- end
-
- href = EventParser.linkable_url?(url) ? url : "https://#{url}"
- <<~HTML
- <tr>
- <td style="padding: 0 12px 12px;"><a href="#{CGI.escape_html(href)}">#{CGI.escape_html(EventParser.display_link(url))}</a></td>
- </tr>
- HTML
- end
-
- def invitees_row
- return "" if @event.nil? || @event.standalone? || @event.minimal
-
- muted_row(
- CGI.escape_html(card_t("models.invitee.status.going_count", count: @event.going_count)),
- )
- end
-
- def description_row
- return "" if @event&.description.blank?
-
- muted_row(EventParser.cook_inline(@event.description, post:))
- end
-
- def dates
- return "-" if @event&.expired? && @event.recurring?
-
- suffix = timezone_suffix
- formatted = "#{format_date(starts_at)}#{suffix}"
-
- ends_at = event_node["data-end"]
- formatted = "#{formatted} → #{format_date(ends_at)}#{suffix}" if ends_at
-
- formatted
- end
-
- def format_date(value)
- format = all_day? ? "%B %-d, %Y" : "%B %-d, %Y %-I:%M %p"
- DateTime.parse(value).strftime(format)
- rescue StandardError
- value
- end
-
- def timezone_suffix
- all_day? ? "" : " (#{timezone})"
- end
-
- def status_label
- return nil if @event.nil?
- return card_t("models.event.expired") if @event.expired?
- return card_t("models.event.closed") if @event.closed
-
- key =
- if @event.standalone?
- "standalone"
- elsif @event.private?
- "private"
- else
- "public"
- end
- card_t("models.event.status.#{key}.title")
- end
-
- def creator_label
- user = post.user
- return nil if user.nil?
-
- name = SiteSetting.enable_names? ? user.display_name : user.username
- "#{card_t("created_by")} #{CGI.escape_html(name)}"
- end
-
- def recurrence_label
- recurrence = @event&.recurrence
- return nil if recurrence.blank? || EventValidator::VALID_RECURRENCES.exclude?(recurrence)
-
- card_t("builder_modal.recurrence.#{recurrence}", **recurrence_context)
- rescue StandardError
- nil
- end
-
- def recurrence_context
- ref = recurrence_ref
- return {} if ref.nil?
-
- { weekday: ref.strftime("%A"), ordinal: recurrence_ordinal(ref) }
- end
-
- def recurrence_ref
- return Date.parse(starts_at) if all_day?
-
- zone = ActiveSupport::TimeZone[timezone] || ActiveSupport::TimeZone["UTC"]
- zone.parse(starts_at)
- rescue StandardError
- nil
- end
-
- def recurrence_ordinal(ref)
- # Mirrors RRuleConfigurator: a fifth occurrence is expressed as "last",
- # since not every month has one.
- nth = (ref.mday / 7.0).ceil
- key = nth == 5 ? "last" : RECURRENCE_ORDINALS[nth - 1]
- card_t("builder_modal.recurrence.ordinals.#{key}")
- end
-
- def card_t(key, **options)
- I18n.t("js.discourse_post_event.#{key}", **options)
- end
-
- def all_day?
- @all_day
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/engine.rb b/plugins/discourse-events/lib/discourse_post_event/engine.rb
deleted file mode 100644
index 1fb8cc92a95..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/engine.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class Engine < ::Rails::Engine
- engine_name PLUGIN_NAME
- isolate_namespace DiscoursePostEvent
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/event_excerpt.rb b/plugins/discourse-events/lib/discourse_post_event/event_excerpt.rb
deleted file mode 100644
index 29dd9bd85d3..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/event_excerpt.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- # Replaces each event node in an excerpt fragment (see PrettyText.excerpt)
- # with a short plain-text summary — "📅 name · dates · location"
- class EventExcerpt
- def self.call(fragment, post: nil)
- new(fragment, post: post).call
- end
-
- def initialize(fragment, post: nil)
- @fragment = fragment
- @topic_title = post&.topic&.title
- end
-
- def call
- @fragment
- .css(".discourse-post-event")
- .each { |event_node| event_node.replace(CGI.escape_html(summary(event_node))) }
- end
-
- private
-
- def summary(event_node)
- event_name = event_node["data-name"].presence
- location = event_node["data-location"].presence
- location = EventParser.inline_text(location) if location
-
- parts = []
- # only repeat the name when it differs from the topic title, which is
- # already shown alongside the excerpt (e.g. in the topic onebox)
- parts << event_name if event_name && event_name != @topic_title
- parts << dates(event_node)
- parts << location
-
- summary = parts.compact.join(t("separator"))
- summary.present? ? t("summary", summary: summary) : ""
- end
-
- def dates(event_node)
- starts_at = event_node["data-start"]
- return if starts_at.blank?
-
- all_day = event_node["data-all-day"] == "true"
- ends_at = event_node["data-end"]
- timezone = event_node["data-timezone"] || "UTC"
-
- dates = format_date(starts_at, all_day)
- dates = t("date_range", from: dates, to: format_date(ends_at, all_day)) if ends_at.present?
- dates = t("date_with_timezone", date: dates, timezone: timezone) unless all_day
- dates
- end
-
- def format_date(value, all_day)
- I18n.l(DateTime.parse(value), format: t(all_day ? "date_format" : "datetime_format"))
- rescue StandardError
- value
- end
-
- def t(key, **args)
- I18n.t("discourse_post_event.event_excerpt.#{key}", **args)
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/event_finder.rb b/plugins/discourse-events/lib/discourse_post_event/event_finder.rb
deleted file mode 100644
index f786ed45414..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/event_finder.rb
+++ /dev/null
@@ -1,210 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EventFinder
- def self.search(user, params = {})
- guardian = Guardian.new(user)
-
- build_base_query(guardian, user, params)
- .then { |query| filter_by_post_id(query, params) }
- .then { |query| filter_by_topic_id(query, params) }
- .then { |query| filter_by_attending_user(query, params, guardian, user) }
- .then { |query| filter_by_dates(query, params) }
- .then { |query| filter_by_category(query, params) }
- .then { |query| apply_ordering(query, params) }
- .then { |query| apply_limit(query, params) }
- end
-
- private
-
- def self.build_base_query(guardian, user, params)
- topics = listable_topics(guardian)
- pms = private_messages(user)
-
- scope = DiscoursePostEvent::Event.visible
- scope = scope.open if params[:include_closed].blank?
-
- scope
- .joins(post: :topic)
- .merge(Post.secured(guardian))
- .merge(topics.or(pms))
- .joins(latest_event_date_join)
- .select(
- "discourse_post_event_events.*, latest_event_dates.starts_at, latest_event_dates.ends_at, latest_event_dates.finished_at",
- )
- .where(
- "(discourse_post_event_events.recurrence IS NOT NULL) OR (latest_event_dates.starts_at IS NOT NULL) OR (discourse_post_event_events.original_starts_at IS NOT NULL)",
- )
- .group(
- "discourse_post_event_events.id, latest_event_dates.starts_at, latest_event_dates.ends_at, latest_event_dates.finished_at",
- )
- end
-
- def self.latest_event_date_join
- <<~SQL
- LEFT JOIN (
- SELECT DISTINCT ON (event_id)
- event_id,
- starts_at,
- ends_at,
- finished_at
- FROM discourse_calendar_post_event_dates
- ORDER BY event_id, #{DiscoursePostEvent::EventDate.current_ordering_sql}
- ) latest_event_dates ON latest_event_dates.event_id = discourse_post_event_events.id
- SQL
- end
-
- def self.filter_by_post_id(events, params)
- return events if params[:post_id].blank?
- events.where(id: params[:post_id])
- end
-
- def self.filter_by_topic_id(events, params)
- return events if params[:topic_id].blank?
- events.where(topics: { id: params[:topic_id] })
- end
-
- def self.filter_by_attending_user(events, params, guardian, user)
- return events if params[:attending_user].blank?
-
- attending_user = User.find_by(username_lower: params[:attending_user].downcase)
- return events.none if !attending_user
-
- statuses = [DiscoursePostEvent::Invitee.statuses[:going]]
- if params[:include_interested].present? &&
- can_include_interested?(guardian, user, attending_user)
- statuses << DiscoursePostEvent::Invitee.statuses[:interested]
- end
-
- events =
- events.joins(:invitees).where(
- discourse_post_event_invitees: {
- user_id: attending_user.id,
- status: statuses,
- },
- )
-
- guardian.is_admin? ? events : apply_privacy_restrictions(events, user)
- end
-
- def self.can_include_interested?(guardian, user, attending_user)
- guardian.is_admin? || user&.id == attending_user.id
- end
-
- def self.apply_privacy_restrictions(events, user)
- private_status = DiscoursePostEvent::Event.statuses[:private]
-
- # If no user, can only see non-private events
- return events.where.not(status: private_status) if user.nil?
-
- # User can see private events if they still belong to an invited group.
- events.where(<<~SQL, private_status, private_status, user.id)
- discourse_post_event_events.status != ?
- OR (
- discourse_post_event_events.status = ?
- AND EXISTS (
- SELECT 1
- FROM group_users
- INNER JOIN groups ON groups.id = group_users.group_id
- WHERE group_users.user_id = ?
- AND groups.name = ANY(discourse_post_event_events.raw_invitees)
- )
- )
- SQL
- end
-
- def self.filter_by_dates(events, params)
- return events if params[:before].blank? && params[:after].blank?
-
- before_date = params[:before] == "now" ? Time.current : params[:before]&.to_datetime
- after_date = params[:after] == "now" ? Time.current : params[:after]&.to_datetime
- include_ongoing = params[:include_ongoing].present?
-
- recurring_scope = build_recurring_date_scope(after_date, before_date)
- non_recurring_scope =
- build_non_recurring_date_scope(after_date, before_date, include_ongoing:)
-
- # Apply the combined scope using OR logic
- events.merge(recurring_scope.or(non_recurring_scope))
- end
-
- private
-
- def self.build_recurring_date_scope(after_date, before_date)
- scope = DiscoursePostEvent::Event.where.not(recurrence: nil)
-
- if after_date
- # For recurring events: original start date OR recurrence_until should be >= after_date
- scope =
- scope.where(
- "original_starts_at >= ? OR recurrence_until IS NULL OR recurrence_until >= ?",
- after_date,
- after_date,
- )
- end
-
- if before_date
- # For recurring events: original start date should be < before_date
- scope = scope.where("original_starts_at < ?", before_date)
- end
-
- scope
- end
-
- def self.build_non_recurring_date_scope(after_date, before_date, include_ongoing: false)
- scope = DiscoursePostEvent::Event.where(recurrence: nil)
- if after_date
- if include_ongoing
- scope =
- scope.where(
- "latest_event_dates.starts_at >= ? OR (latest_event_dates.ends_at IS NOT NULL AND latest_event_dates.ends_at >= ?)",
- after_date,
- after_date,
- )
- else
- scope = scope.where("latest_event_dates.starts_at >= ?", after_date)
- end
- end
- scope = scope.where("latest_event_dates.starts_at < ?", before_date) if before_date
- scope
- end
-
- def self.filter_by_category(events, params)
- return events if params[:category_id].blank?
-
- category_id = params[:category_id].to_i
- category_ids =
- (
- if params[:include_subcategories].present?
- Category.subcategory_ids(category_id)
- else
- [category_id]
- end
- )
-
- events.where(topics: { category_id: category_ids })
- end
-
- def self.apply_ordering(events, params)
- order_direction = params[:order] == "desc" ? "DESC" : "ASC"
- events.order(
- "latest_event_dates.starts_at #{order_direction}, discourse_post_event_events.id #{order_direction}",
- )
- end
-
- def self.apply_limit(events, params)
- limit = params[:limit]&.to_i || 200
- events.limit(limit.clamp(1, 200))
- end
-
- def self.listable_topics(guardian)
- topics = Topic.listable_topics.secured(guardian)
- topics = topics.visible unless guardian.can_see_unlisted_topics?
- topics
- end
-
- def self.private_messages(user)
- user ? Topic.private_messages_for_user(user) : Topic.none
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/event_onebox_data.rb b/plugins/discourse-events/lib/discourse_post_event/event_onebox_data.rb
deleted file mode 100644
index f2f1aa421f6..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/event_onebox_data.rb
+++ /dev/null
@@ -1,105 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- # Builds, per post, the data needed to render an interactive event card for the
- # internal topic oneboxes that point at an event topic. Mirrors
- # ContentLocalization::OneboxLocalizer: batched via TopicLink and surfaced on
- # the post serializer (see TopicView.on_preload + PostSerializer#event_oneboxes)
- # so the client renders the card from inline data instead of fetching each
- # event individually.
- #
- # Returns { source_post_id => { linked_topic_id => serialized_event } }. It's
- # keyed by topic id so the client can match each `aside.quote[data-topic]`
- # onebox to its event (mirrors how core's localized_oneboxes are matched).
- class EventOneboxData
- def self.build(posts:, guardian:)
- new(posts:, guardian:).build
- end
-
- def initialize(posts:, guardian:)
- @posts = posts
- @guardian = guardian
- end
-
- def build
- return {} if @posts.blank?
-
- # cross-topic internal links (indexed lookup, no cooked scan). TopicLink
- # does not record a topic that links itself, so same-topic oneboxes are
- # detected from cooked further down.
- links =
- TopicLink
- .where(post_id: @posts.map(&:id), internal: true, reflection: false)
- .where.not(link_topic_id: nil)
- .pluck(:post_id, :link_topic_id)
- .uniq
-
- # the topic being viewed, only when it's itself an event (cheap custom-field
- # check, so non-event topic views do no extra work)
- topic = @posts.first.topic
- own_topic_id = topic&.event_starts_at ? topic.id : nil
-
- topic_ids = links.map(&:last)
- topic_ids << own_topic_id if own_topic_id
- topic_ids.uniq!
- return {} if topic_ids.empty?
-
- first_post_ids = Post.where(topic_id: topic_ids, post_number: 1, deleted_at: nil).pluck(:id)
- return {} if first_post_ids.empty?
-
- events_by_topic =
- DiscoursePostEvent::Event
- .where(id: first_post_ids)
- .includes(:image_upload, post: [:user, { topic: :category }])
- .index_by { |event| event.post.topic_id }
- return {} if events_by_topic.empty?
-
- @serialized = {}
- result = {}
-
- links.each do |source_post_id, link_topic_id|
- event = events_by_topic[link_topic_id]
- next if event.nil? || [email protected]_see?(event.post)
- (result[source_post_id] ||= {})[link_topic_id] = serialize(event)
- end
-
- own_event = own_topic_id && events_by_topic[own_topic_id]
- if own_event && @guardian.can_see?(own_event.post)
- each_self_onebox_post(own_topic_id) do |post_id|
- (result[post_id] ||= {})[own_topic_id] = serialize(own_event)
- end
- end
-
- result
- end
-
- private
-
- def serialize(event)
- @serialized[event.id] ||= DiscoursePostEvent::EventSerializer.new(
- event,
- scope: @guardian,
- root: false,
- ).as_json
- end
-
- # yields the id of each post whose cooked oneboxes its own (event) topic. A
- # same-topic onebox is `aside.quote[data-post="1"]` without a data-username
- # (which would mark a manual quote); the cheap include? skips parsing posts
- # that don't reference the topic at all.
- def each_self_onebox_post(topic_id)
- marker = %{data-topic="#{topic_id}"}
- @posts.each do |post|
- next if post.cooked.blank? || !post.cooked.include?(marker)
-
- onebox =
- Nokogiri::HTML5
- .fragment(post.cooked)
- .css(%{aside.quote[data-topic="#{topic_id}"][data-post="1"]})
- .any? { |aside| aside["data-username"].blank? }
-
- yield(post.id) if onebox
- end
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/event_parser.rb b/plugins/discourse-events/lib/discourse_post_event/event_parser.rb
deleted file mode 100644
index 6308ccaf02d..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/event_parser.rb
+++ /dev/null
@@ -1,209 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EventParser
- VALID_OPTIONS = [
- :start,
- :end,
- :status,
- :"allowed-groups",
- :url,
- :location,
- :name,
- :reminders,
- :recurrence,
- :"recurrence-until",
- :timezone,
- :"show-local-time",
- :minimal,
- :closed,
- :"chat-enabled",
- :livestream,
- :"max-attendees",
- :"all-day",
- :image,
- ]
-
- LEGACY_ESCAPED_ATTRS = %w[data-location]
- SCHEME_PREFIX = /\A[a-z][a-z0-9+.\-]*:/i
-
- def self.extract_events(post)
- cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
- valid_options = valid_option_attributes
-
- valid_custom_fields =
- SiteSetting
- .discourse_post_event_allowed_custom_fields
- .split("|")
- .map do |setting|
- { original: "data-#{setting}", normalized: custom_field_data_attribute(setting) }
- end
-
- Nokogiri
- .HTML(cooked)
- .css("div.discourse-post-event")
- .map do |doc|
- event = nil
- doc.attributes.values.each do |attribute|
- name = attribute.name
- value = attribute.value
-
- if value && valid_options.include?(name)
- event ||= {}
- value = CGI.unescapeHTML(value) if LEGACY_ESCAPED_ATTRS.include?(name)
- event[name.sub("data-", "").to_sym] = case name
- when "data-name", "data-url", "data-image", "data-location"
- value
- else
- CGI.escapeHTML(value)
- end
- end
-
- valid_custom_fields.each do |valid_custom_field|
- if value && valid_custom_field[:normalized] == name
- event ||= {}
- event[valid_custom_field[:original].sub("data-", "").to_sym] = CGI.escapeHTML(value)
- end
- end
- end
- event[:description] = to_markdown(doc) if event
- event
- end
- .compact
- end
-
- def self.valid_option_attributes
- VALID_OPTIONS.map { |option| "data-#{option}" }
- end
-
- def self.custom_field_data_attribute(setting)
- camelized = setting.downcase.gsub(/[-.]/, "_").gsub(/_(.)/) { $1.upcase }
- dasherized = camelized.gsub(/[A-Z]/) { |char| "-#{char.downcase}" }.sub(/\A-/, "")
- "data-#{dasherized}"
- end
-
- INLINE_MARKDOWN_FEATURES = %w[emoji linkify]
- INLINE_MARKDOWN_IT_RULES = %w[link linkify entity escape newline]
- INLINE_CACHE_VERSION = 2
-
- def self.cook_inline(text, post: nil)
- text = text.to_s
- add_nofollow = post.nil? || post.add_nofollow?
-
- Discourse
- .cache
- .fetch(
- "post-event-inline:#{INLINE_CACHE_VERSION}:#{Digest::SHA1.hexdigest(text)}:#{add_nofollow}",
- expires_in: 1.week,
- ) do
- cooked =
- PrettyText.cook(
- text,
- features_override: INLINE_MARKDOWN_FEATURES,
- markdown_it_rules: INLINE_MARKDOWN_IT_RULES,
- omit_nofollow: !add_nofollow,
- )
- fragment = Nokogiri::HTML5.fragment(cooked)
- content = fragment.children.reject(&:blank?)
- if content.length == 1 && content.first.name == "p"
- content.first.inner_html
- else
- fragment.to_html
- end
- end
- end
-
- def self.cook_location(text, post: nil)
- text = text.to_s
- add_nofollow = post.nil? || post.add_nofollow?
-
- Discourse
- .cache
- .fetch(
- "post-event-location:#{INLINE_CACHE_VERSION}:#{Digest::SHA1.hexdigest(text)}:#{add_nofollow}",
- expires_in: 1.week,
- ) { normalize_links(cook_inline(text, post:)) }
- end
-
- def self.inline_text(text)
- cooked = cook_inline(text)
- PrettyText.excerpt(cooked, cooked.length, strip_links: true, text_entities: true)
- end
-
- def self.linkable_url?(url)
- url = url.to_s.downcase
- schemes = %w[http https mailto] | SiteSetting.allowed_href_schemes.split("|")
- schemes.any? { |scheme| url.start_with?("#{scheme}:") }
- end
-
- def self.valid_url?(value)
- value = value.to_s.strip
- return true if value.blank?
- # Rejected before encoding, which would otherwise make a CR/LF payload parse.
- return false if value.match?(/\s/)
-
- candidate = value.match?(SCHEME_PREFIX) ? value : "https://#{value}"
- uri = URI.parse(UrlHelper.encode(candidate))
- uri.scheme == "mailto" ? uri.opaque.present? : uri.host.present?
- rescue URI::Error, Addressable::URI::InvalidURIError
- false
- end
-
- def self.normalize_link(value)
- value.to_s.strip.downcase.sub(%r{\Ahttps?://}, "").sub(%r{/+\z}, "")
- end
-
- def self.display_link(value)
- value.to_s.strip.sub(%r{\Ahttps?://}i, "")
- end
-
- # A location is cooked, so its links arrive as anchors. Present them the same
- # way the url row is presented: no scheme on screen, https when the author
- # did not write one. Anchors carrying custom text are left alone.
- def self.normalize_links(html)
- fragment = Nokogiri::HTML5.fragment(html.to_s)
- anchors =
- fragment.css("a[href]").select { |a| [a.text, "http://#{a.text}"].include?(a["href"]) }
- return html if anchors.empty?
-
- anchors.each do |anchor|
- text = anchor.text
- if anchor["href"] == text
- anchor.content = display_link(text)
- else
- anchor["href"] = "https://#{text}"
- end
- end
-
- fragment.to_html
- end
-
- def self.url_restates_location?(url, location, cooked_location: nil)
- return false if url.blank? || location.blank?
-
- target = normalize_link(url)
- return true if normalize_link(location) == target
-
- Nokogiri::HTML5
- .fragment(cooked_location || cook_location(location))
- .css("a[href]")
- .any? { |anchor| normalize_link(anchor["href"]) == target }
- end
-
- def self.to_markdown(node)
- fragment = node.dup
- fragment
- .css("img.emoji")
- .each { |img| img.replace(img.document.create_text_node(img["alt"].to_s)) }
- fragment
- .css("a[href]")
- .each do |a|
- href = a["href"].to_s
- next if !linkable_url?(href)
- markdown = a.text == href ? href : "[#{a.text}](#{href})"
- a.replace(a.document.create_text_node(markdown))
- end
- fragment.text.strip
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/event_validator.rb b/plugins/discourse-events/lib/discourse_post_event/event_validator.rb
deleted file mode 100644
index d0bf325a384..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/event_validator.rb
+++ /dev/null
@@ -1,181 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- class EventValidator
- VALID_RECURRENCES = %w[
- every_month
- every_week
- every_two_weeks
- every_four_weeks
- every_day
- every_weekday
- ]
-
- def initialize(post)
- @post = post
- end
-
- def validate_event
- extracted_events = DiscoursePostEvent::EventParser.extract_events(@post)
-
- return false if extracted_events.count == 0
-
- if extracted_events.count > 1
- @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.only_one_event"))
- return false
- end
-
- if [email protected]_first_post?
- @post.errors.add(
- :base,
- I18n.t("discourse_post_event.errors.models.event.must_be_in_first_post"),
- )
- return false
- end
-
- extracted_event = extracted_events.first
-
- return false unless can_invite_groups?(extracted_event)
-
- if @post.acting_user && @post.event
- if [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
- end
- else
- if [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
- end
- end
-
- 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
- end
-
- 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
- end
-
- 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
- end
-
- 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
- end
-
- 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"),
- )
- end
- end
-
- 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],
- ),
- )
- end
- end
-
- if !EventParser.valid_url?(extracted_event[:url])
- @post.errors.add(:base, I18n.t("discourse_post_event.errors.models.event.invalid_url"))
- end
-
- true
- end
-
- private
-
- def can_invite_groups?(event)
- return true unless event[:"allowed-groups"]
-
- 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
- end
-
- 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
- end
-
- true
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/export_csv_controller_extension.rb b/plugins/discourse-events/lib/discourse_post_event/export_csv_controller_extension.rb
deleted file mode 100644
index 0a18302c540..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/export_csv_controller_extension.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- module ExportCsvControllerExtension
- def export_entity
- if post_event_export? && ensure_can_export_post_event
- Jobs.enqueue(
- :export_csv_file,
- entity: export_params[:entity],
- user_id: current_user.id,
- args: export_params[:args],
- )
- StaffActionLogger.new(current_user).log_entity_export(export_params[:entity])
- render json: success_json
- else
- super
- end
- end
-
- private
-
- def export_params
- if post_event_export?
- @_export_params ||=
- begin
- params.require(:entity)
- params.permit(:entity, args: %i[id]).to_h
- end
- else
- super
- end
- end
-
- def post_event_export?
- params[:entity] === "post_event"
- end
-
- def ensure_can_export_post_event
- return if !SiteSetting.discourse_post_event_enabled
-
- post_event = DiscoursePostEvent::Event.find(export_params[:args][:id])
- post_event && guardian.can_act_on_discourse_post_event?(post_event)
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/export_csv_file_extension.rb b/plugins/discourse-events/lib/discourse_post_event/export_csv_file_extension.rb
deleted file mode 100644
index 41c7cbf8db9..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/export_csv_file_extension.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- module ExportPostEventCsvReportExtension
- def post_event_export(&block)
- return enum_for(:post_event_export) unless block_given?
-
- guardian = Guardian.new(current_user)
-
- event = DiscoursePostEvent::Event.includes(invitees: :user).find(@extra[:id])
-
- guardian.ensure_can_act_on_discourse_post_event!(event)
-
- event
- .invitees
- .order(:id)
- .each do |invitee|
- yield(
- [
- invitee.user.username,
- DiscoursePostEvent::Invitee.statuses[invitee.status],
- invitee.created_at,
- invitee.updated_at,
- ]
- )
- end
- end
-
- def get_header(entity)
- if SiteSetting.discourse_post_event_enabled && entity === "post_event"
- %w[username status first_answered_at last_updated_at]
- else
- super
- end
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/guardian_extensions.rb b/plugins/discourse-events/lib/discourse_post_event/guardian_extensions.rb
deleted file mode 100644
index 9aa7c1a69ab..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/guardian_extensions.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- module GuardianExtensions
- def can_act_on_invitee?(invitee)
- return false if anonymous?
- user.id == invitee.user_id || can_act_on_discourse_post_event?(invitee.event)
- end
-
- def can_create_discourse_post_event?
- return false if anonymous?
- @can_create_discourse_post_event ||=
- user.in_any_groups?(SiteSetting.discourse_post_event_allowed_on_groups_map)
- end
-
- def can_act_on_discourse_post_event?(event)
- return false if anonymous?
- can_create_discourse_post_event? && can_edit_post?(event.post)
- end
-
- def can_display_invitee_details?(event)
- return true if !event.private? || can_act_on_discourse_post_event?(event)
-
- raw_invitees = Array(event.raw_invitees).uniq
-
- return true if user && event.user_in_invited_group?(user)
- return false if raw_invitees.blank?
-
- Group
- .visible_groups(user)
- .members_visible_groups(user)
- .where(name: raw_invitees)
- .distinct
- .count == raw_invitees.length
- end
-
- def can_export_entity?(entity, entity_id = nil, args = nil)
- if entity == "post_event"
- return false if !SiteSetting.discourse_post_event_enabled
-
- event_id = args&.[](:id) || args&.[]("id")
- event = DiscoursePostEvent::Event.find_by(id: event_id)
-
- return event.present? && can_act_on_discourse_post_event?(event)
- end
-
- super
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/post_extension.rb b/plugins/discourse-events/lib/discourse_post_event/post_extension.rb
deleted file mode 100644
index 6ae0be0676b..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/post_extension.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- module PostExtension
- extend ActiveSupport::Concern
-
- prepended do
- has_one :event, dependent: :destroy, class_name: "DiscoursePostEvent::Event", foreign_key: :id
-
- validate :valid_event
- end
-
- def valid_event
- return unless raw_changed?
-
- validator = DiscoursePostEvent::EventValidator.new(self)
- validator.validate_event
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/rrule_configurator.rb b/plugins/discourse-events/lib/discourse_post_event/rrule_configurator.rb
deleted file mode 100644
index c6c79a07b13..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/rrule_configurator.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-# frozen_string_literal: true
-
-class RRuleConfigurator
- def self.rule(recurrence:, starts_at:, recurrence_until: nil)
- rule =
- case recurrence
- when "every_day"
- "FREQ=DAILY"
- when "every_month"
- weekday = starts_at.strftime("%A")
- nth = ((starts_at.day - 1) / 7) + 1
-
- # Every month has at least four of each weekday, so the first four
- # positions are safe. A fifth only exists in some months, so anchor it
- # to -1 ("last") instead, otherwise the rule would skip months.
- byday_count = nth == 5 ? -1 : nth
-
- "FREQ=MONTHLY;BYDAY=#{byday_count}#{weekday.upcase[0, 2]}"
- when "every_weekday"
- "FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"
- when "every_two_weeks"
- "FREQ=WEEKLY;INTERVAL=2"
- when "every_four_weeks"
- "FREQ=WEEKLY;INTERVAL=4"
- else
- byday = starts_at.strftime("%A").upcase[0, 2]
- "FREQ=WEEKLY;BYDAY=#{byday}"
- end
-
- rule += ";UNTIL=#{recurrence_until.strftime("%Y%m%dT%H%M%S")}" if recurrence_until
- rule
- end
-
- def self.how_many_recurring_events(recurrence:, max_years: nil)
- return 1 if !max_years
- per_year =
- case recurrence
- when "every_month"
- 12
- when "every_four_weeks"
- 13
- when "every_two_weeks"
- 26
- when "every_weekday"
- 260
- when "every_week"
- 52
- when "every_day"
- 365
- end
- per_year * max_years
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/rrule_generator.rb b/plugins/discourse-events/lib/discourse_post_event/rrule_generator.rb
deleted file mode 100644
index a26a333a92b..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/rrule_generator.rb
+++ /dev/null
@@ -1,66 +0,0 @@
-# frozen_string_literal: true
-
-require "rrule"
-
-class RRuleGenerator
- def self.generate(
- starts_at:,
- timezone: "UTC",
- max_years: nil,
- recurrence: "every_week",
- recurrence_until: nil,
- dtstart: nil
- )
- rrule = generate_hash(RRuleConfigurator.rule(recurrence_until:, recurrence:, starts_at:))
- rrule = set_mandatory_options(rrule, starts_at)
-
- ::RRule::Rule
- .new(stringify(rrule), dtstart: starts_at, tzid: timezone)
- .between(Time.current, 14.months.from_now)
- .first(RRuleConfigurator.how_many_recurring_events(recurrence:, max_years:))
- end
-
- def self.generate_string(
- starts_at:,
- recurrence: "every_week",
- recurrence_until: nil,
- dtstart: nil,
- show_local_time: false
- )
- rrule = generate_hash(RRuleConfigurator.rule(recurrence_until:, recurrence:, starts_at:))
- rrule = set_mandatory_options(rrule, starts_at)
- rrule_line = "RRULE:#{stringify(rrule)}"
-
- if dtstart
- if show_local_time
- dtstart_line = "DTSTART:#{dtstart.strftime("%Y%m%dT%H%M%S")}"
- else
- dtstart_line = "DTSTART:#{dtstart.utc.strftime("%Y%m%dT%H%M%SZ")}"
- end
- "#{dtstart_line}\n#{rrule_line}"
- else
- rrule_line
- end
- end
-
- private
-
- def self.stringify(rrule)
- rrule.map { |k, v| "#{k}=#{v}" }.join(";")
- end
-
- def self.generate_hash(rrule)
- rrule
- .split(";")
- .each_with_object({}) do |rr, h|
- key, value = rr.split("=")
- h[key] = value
- end
- end
-
- def self.set_mandatory_options(rrule, time)
- rrule["INTERVAL"] ||= 1
- rrule["WKST"] = "MO" # considers Monday as the first day of the week
- rrule
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/topic_extension.rb b/plugins/discourse-events/lib/discourse_post_event/topic_extension.rb
deleted file mode 100644
index 5bfe595a9e4..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/topic_extension.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- module TopicExtension
- def move_posts(moved_by, post_ids, opts)
- ensure_event_invariants!(post_ids, opts)
- super
- end
-
- private
-
- def ensure_event_invariants!(post_ids, opts)
- return unless SiteSetting.discourse_post_event_enabled
- return unless opts[:destination_topic_id]
-
- destination = Topic.find_by(id: opts[:destination_topic_id])
- return unless destination
-
- destination_op = destination.first_post
- destination_has_event = destination_op&.event.present?
- incoming_event_post = Post.where(id: post_ids).joins(:event).order(:created_at).first
-
- return unless destination_has_event || incoming_event_post
-
- raise_event_move_error! if destination_has_event && incoming_event_post
-
- chronological = !!opts[:chronological_order]
-
- if destination_has_event && chronological
- oldest_incoming = Post.where(id: post_ids).order(:created_at).first
- if oldest_incoming && oldest_incoming.created_at < destination_op.created_at
- raise_event_move_error!
- end
- end
-
- if incoming_event_post && !destination_has_event
- becomes_new_op =
- chronological &&
- (destination_op.nil? || incoming_event_post.created_at < destination_op.created_at)
- raise_event_move_error! unless becomes_new_op
- end
- end
-
- def raise_event_move_error!
- raise ActiveRecord::RecordNotSaved.new(
- I18n.t("discourse_post_event.errors.models.event.must_be_in_first_post"),
- )
- end
- end
-end
diff --git a/plugins/discourse-events/lib/discourse_post_event/web_hook_extension.rb b/plugins/discourse-events/lib/discourse_post_event/web_hook_extension.rb
deleted file mode 100644
index 77711737a9d..00000000000
--- a/plugins/discourse-events/lib/discourse_post_event/web_hook_extension.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-# frozen_string_literal: true
-
-module DiscoursePostEvent
- module WebHookExtension
- extend ActiveSupport::Concern
-
- class_methods do
- def enqueue_calendar_event_hooks(event_name, calendar_event, payload = nil)
- if active_web_hooks(event_name).exists? && calendar_event.present?
- payload ||= WebHook.build_calendar_event_payload(calendar_event)
-
- WebHook.enqueue_hooks(
- :calendar_event,
- event_name,
- id: calendar_event.id,
- category_id: calendar_event.post&.topic&.category_id,
- tag_ids: calendar_event.post&.topic&.tags&.pluck(:id),
- payload: payload,
- )
- end
- end
-
- def build_calendar_event_payload(calendar_event)
- post = calendar_event.post
- topic = post&.topic
-
- parsed_starts_at =
- (
- if calendar_event.all_day
- calendar_event.starts_at&.utc&.strftime("%Y-%m-%d")
- else
- calendar_event.starts_at
- end
- )
- parsed_ends_at =
- (
- if calendar_event.all_day
- calendar_event.ends_at&.utc&.strftime("%Y-%m-%d")
- else
- calendar_event.ends_at
- end
- )
-
- event_image =
- if calendar_event.image_upload.present?
- {
- id: calendar_event.image_upload.id,
- url: UrlHelper.absolute(calendar_event.image_upload.url),
- width: calendar_event.image_upload.width,
- height: calendar_event.image_upload.height,
- }
- end
-
- {
- event: {
- id: calendar_event.id,
- name: calendar_event.name,
- description: calendar_event.description,
- location: calendar_event.location,
- url: calendar_event.url,
- status: DiscoursePostEvent::Event.statuses[calendar_event.status]&.to_s,
- starts_at: parsed_starts_at,
- ends_at: parsed_ends_at,
- all_day: calendar_event.all_day,
- recurrence: calendar_event.recurrence,
- recurrence_until: calendar_event.recurrence_until,
- timezone: calendar_event.timezone,
- custom_fields: calendar_event.custom_fields,
- closed: calendar_event.closed,
- max_attendees: calendar_event.max_attendees,
- chat_enabled: calendar_event.chat_enabled,
- allowed_groups: calendar_event.raw_invitees,
- image: event_image,
- },
- post: {
- id: post&.id,
- post_number: post&.post_number,
- url: post&.url,
- },
- topic: {
- id: topic&.id,
- title: topic&.title,
- url: topic&.url,
- category_id: topic&.category_id,
- tags: topic&.tags&.pluck(:name),
- },
- }.to_json
- end
- end
- end
-end
diff --git a/plugins/discourse-events/lib/event_validator.rb b/plugins/discourse-events/lib/event_validator.rb
deleted file mode 100644
index 832bcf5a0d8..00000000000
--- a/plugins/discourse-events/lib/event_validator.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseCalendar
- class EventValidator
- def initialize(post)
- @post = post
- @first_post = post.topic.first_post
- end
-
- def validate_event
- dates_count = count_dates(@post)
- calendar_type = @first_post.custom_fields[DiscourseCalendar::CALENDAR_CUSTOM_FIELD]
-
- if @post.whisper? && dates_count > 0
- @post.errors.add(:base, I18n.t("discourse_calendar.whisper_not_allowed"))
- return false
- end
-
- if calendar_type == "dynamic" && dates_count > 2
- @post.errors.add(:base, I18n.t("discourse_calendar.more_than_two_dates"))
- return false
- end
-
- return false if calendar_type == "static" && dates_count > 0
-
- dates_count > 0
- end
-
- private
-
- def count_dates(post)
- cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
- Nokogiri.HTML(cooked).css("span.discourse-local-date").count
- end
- end
-end
diff --git a/plugins/discourse-events/lib/group_timezones.rb b/plugins/discourse-events/lib/group_timezones.rb
deleted file mode 100644
index 449a14777e7..00000000000
--- a/plugins/discourse-events/lib/group_timezones.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseCalendar
- class GroupTimezones
- def self.update(post)
- groups = []
-
- Nokogiri
- .HTML(post.cooked)
- .css("div.group-timezones")
- .map do |group_timezones|
- group_timezones.attributes.values.each do |attribute|
- if attribute.name == "data-group"
- group_name = CGI.escapeHTML(attribute.value || "")
- groups << group_name if group_name.present?
- end
- end
- end
-
- post.group_timezones = groups.present? ? { groups: groups } : nil
- post.save_custom_fields
- end
- end
-end
diff --git a/plugins/discourse-events/lib/holiday_status.rb b/plugins/discourse-events/lib/holiday_status.rb
deleted file mode 100644
index 7f9da028eeb..00000000000
--- a/plugins/discourse-events/lib/holiday_status.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseCalendar
- class HolidayStatus
- def self.set!(user, ends_at)
- status = user.user_status
- if status.blank? || status.expired? ||
- (is_holiday_status?(status) && status.ends_at != ends_at)
- user.set_status!(
- I18n.t("discourse_calendar.holiday_status.description"),
- emoji_name,
- ends_at,
- )
- end
- end
-
- def self.clear!(user)
- user.clear_status! if user&.user_status && is_holiday_status?(user.user_status)
- end
-
- private
-
- def self.is_holiday_status?(status)
- status.emoji == emoji_name &&
- status.description == I18n.t("discourse_calendar.holiday_status.description")
- end
-
- def self.emoji_name
- SiteSetting.holiday_status_emoji.presence || "date"
- end
- end
-end
diff --git a/plugins/discourse-events/lib/time_sniffer.rb b/plugins/discourse-events/lib/time_sniffer.rb
deleted file mode 100644
index 1e186f6838b..00000000000
--- a/plugins/discourse-events/lib/time_sniffer.rb
+++ /dev/null
@@ -1,320 +0,0 @@
-# frozen_string_literal: true
-
-class TimeSniffer
- Interval = Struct.new(:from, :to)
- Event = Struct.new(:at)
-
- Context = Struct.new(:at, :timezone, :date_order)
-
- class SniffedTime
- attr_reader :year
- attr_reader :month
- attr_reader :day
- attr_reader :hours
- attr_reader :minutes
- attr_reader :seconds
- attr_reader :zone
-
- def initialize(year:, month:, day:, hours: 0, minutes: 0, seconds: 0, zone:)
- @year = year
- @month = month
- @day = day
- @hours = hours
- @minutes = minutes
- @seconds = seconds
- @zone = zone
- end
-
- def self.from_datetime(obj, zone)
- new(
- year: obj.year,
- month: obj.month,
- day: obj.day,
- hours: obj.hour,
- minutes: obj.minute,
- seconds: obj.second,
- zone: zone,
- )
- end
-
- def to_time
- Time.use_zone(zone) do
- Time.zone.parse("#{year}-#{month}-#{day} #{hours}:#{minutes}:#{seconds}")
- end
- end
-
- def with(**args)
- SniffedTime.new(**to_hash.merge(args))
- end
-
- def to_hash
- {
- year: year,
- month: month,
- day: day,
- hours: hours,
- minutes: minutes,
- seconds: seconds,
- zone: zone,
- }
- end
-
- def ==(other)
- return false unless other.kind_of?(SniffedTime)
- return false if @year != other.year
- return false if @month != other.month
- return false if @day != other.day
- return false if @hours != other.hours
- return false if @minutes != other.minutes
- return false if @seconds != other.seconds
- return false if @zone != other.zone
- true
- end
- end
-
- class << self
- def matchers
- @matchers ||= {}
- end
-
- def matcher(name, regex, &blk)
- matchers[name] = { regex: regex, blk: blk }
- end
- end
-
- class Parser
- UTC_REGEX = / ?(Z|UTC)/
-
- def initialize(input, context)
- @input = input
- @context = context
- @offset = 0
- end
-
- def parse_timezone
- m = input_from_offset.match(UTC_REGEX)
- if m && m.offset(0)[0] == 0
- self.offset += m.offset(0)[1]
- "UTC"
- end
- end
-
- def parse_space
- if input[offset] == " "
- self.offset += 1
- true
- else
- false
- end
- end
-
- def parse_time(relative_to, immediate:)
- time, start_offset, stop_offset = peek_time(relative_to)
- if time && (!immediate || start_offset == 0)
- self.offset += stop_offset
- time
- end
- end
-
- def parse_date
- date_match = DATE_REGEX.match(input_from_offset)
- if date_match
- day, month =
- case @context.date_order
- when :us
- [date_match[2], date_match[1]]
- when :sane
- [date_match[1], date_match[2]]
- end
-
- year = date_match[3]
- year =
- case year.size
- when 2
- century = @context.at.year - (@context.at.year % 100)
- last_century = century - 100
-
- choices = [century + year.to_i, last_century + year.to_i]
-
- choices.sort_by { |x| (@context.at.year - x).abs }[0]
- when 4
- year.to_i
- end
-
- result =
- SniffedTime.new(year: year, month: month.to_i, day: day.to_i, zone: @context.timezone)
-
- self.offset += date_match.offset(0)[1]
- result
- end
- end
-
- def parse_time_with_timezone(relative_to, immediate:)
- result = parse_time(relative_to, immediate: immediate)
- if result
- zone = parse_timezone
-
- result = result.with(zone: zone) if zone
-
- result
- end
- end
-
- def parse_date_time(relative_to)
- date = parse_date
- if date
- if parse_space
- datetime = parse_time_with_timezone(date, immediate: true)
- datetime ? [false, datetime] : [true, date]
- else
- [true, date]
- end
- elsif relative_to
- datetime = parse_time_with_timezone(relative_to, immediate: false)
- datetime ? [false, datetime] : [true, nil]
- end
- end
-
- def parse_range
- if x = parse_date_time(nil)
- from_is_date, from = x
- to_is_date, to = parse_date_time(from)
-
- if to
- if to_is_date
- Interval.new(from.to_time, to.to_time + 1.day)
- else
- Interval.new(from.to_time, to.to_time)
- end
- else
- from_is_date ? Interval.new(from.to_time, from.to_time + 1.day) : Event.new(from.to_time)
- end
- end
- end
-
- def input_from_offset
- input[self.offset..-1]
- end
-
- def peek_time(relative_to)
- m = input_from_offset.match(TIME_REGEX)
- if m
- parsed =
- relative_to.with(
- hours: m[1].to_i,
- minutes: m[2].to_i,
- seconds: 0,
- zone: @context.timezone,
- )
-
- [parsed, *m.offset(0)]
- end
- end
-
- attr_reader :input
- attr_accessor :offset
- end
-
- matcher(:yesterday, /yesterday/) do |m|
- today = at.to_date
- yesterday = today - 1
-
- Interval.new(
- SniffedTime.from_datetime(yesterday.to_datetime, timezone).to_time,
- SniffedTime.from_datetime(today.to_datetime, timezone).to_time,
- )
- end
-
- matcher(:tomorrow, /tomorrow/i) do |_|
- tomorrow = at.to_date + 1
- the_day_after_tomorrow = tomorrow + 1
-
- Interval.new(
- SniffedTime.from_datetime(tomorrow.to_datetime, timezone).to_time,
- SniffedTime.from_datetime(the_day_after_tomorrow.to_datetime, timezone).to_time,
- )
- end
-
- TIME_REGEX = /(\d{1,2}):(\d{2})/
-
- matcher(:time, TIME_REGEX) do |m|
- times = input.scan(TIME_REGEX).to_a
- from, to = times[0..2]
- if to
- Interval.new(
- SniffedTime.new(
- year: at.year,
- month: at.month,
- day: at.day,
- hours: from[0].to_i,
- minutes: from[1].to_i,
- seconds: 0,
- zone: timezone,
- ).to_time,
- SniffedTime.new(
- year: at.year,
- month: at.month,
- day: at.day,
- hours: to[0].to_i,
- minutes: to[1].to_i,
- seconds: 0,
- zone: timezone,
- ).to_time,
- )
- else
- Event.new(
- SniffedTime.new(
- year: at.year,
- month: at.month,
- day: at.day,
- hours: from[0].to_i,
- minutes: from[1].to_i,
- seconds: 0,
- zone: timezone,
- ).to_time,
- )
- end
- end
-
- DATE_SEPARATOR = %r{[-/]}
- DATE_REGEX = /((?:^|\s)\d{1,2})#{DATE_SEPARATOR}(\d{1,2})#{DATE_SEPARATOR}(\d{2,4})/
-
- matcher(:date, DATE_REGEX) { |m| Parser.new(input, @context).parse_range }
-
- def initialize(input, at: DateTime.now, timezone:, date_order:, matchers:, raise_errors: false)
- @input = input
- @at = at
- @timezone = timezone
- @date_order = date_order
- @context = Context.new(@at, @timezone, @date_order)
- @matchers = matchers
- @raise_errors = raise_errors
- end
-
- def sniff
- @matchers.each do |matcher_name|
- matcher = self.class.matchers[matcher_name]
- regex, blk = matcher.values_at(:regex, :blk)
-
- match = regex.match(@input)
- if match
- begin
- result = instance_exec(match, &blk)
- rescue Exception
- raise if @raise_errors
- else
- return result if result
- end
- end
- end
-
- nil
- end
-
- private
-
- attr_reader :input
- attr_reader :at
- attr_reader :timezone
- attr_reader :date_order
-end
diff --git a/plugins/discourse-events/lib/users_on_holiday.rb b/plugins/discourse-events/lib/users_on_holiday.rb
deleted file mode 100644
index 8221e94d49e..00000000000
--- a/plugins/discourse-events/lib/users_on_holiday.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseCalendar
- class UsersOnHoliday
- def self.from(calendar_events)
- calendar_events
- .filter { |e| e.user_id.present? && e.username.present? }
- .filter { |e| e.underway? || e.in_future? }
- .group_by(&:user_id)
- .map { |_, events| current_holiday(events) }
- .compact
- .to_h
- end
-
- private
-
- def self.current_holiday(user_events)
- ends_at = holiday_ends_at(user_events)
- return nil unless ends_at
-
- [user_events[0].user_id, { username: user_events[0].username, ends_at: ends_at }]
- end
-
- # If a user has several holidays one after another
- # we want to show the farthest end date.
- #
- # Let's say today is Monday and I am sick,
- # and I also have days off from Tuesday to Friday:
- #
- # sick ▭
- # days off ▭▭▭▭
- #
- # We want to show Friday as an end date of my holiday.
- #
- # This algorithm also works in case the holidays intersect,
- # like this:
- #
- # event_1 ▭▭▭▭
- # event_2 ▭▭▭▭
- # event_3 ▭▭▭▭
- #
- # or like this:
- #
- # event_1 ▭▭▭▭
- # event_2 ▭▭▭▭▭▭▭▭
- # event_3 ▭▭▭▭▭▭▭▭▭▭
- #
- # or like this:
- #
- # event_1 ▭▭▭▭▭▭▭▭▭▭
- # event_2 ▭
- #
- def self.holiday_ends_at(events)
- sorted_events = events.sort_by(&:start_date)
- return nil if sorted_events.first.in_future?
- return sorted_events.first.ends_at if events.count == 1
-
- result = sorted_events.first.ends_at
- sorted_events.each_cons(2) do |pair|
- if pair[0].ends_at < pair[1].start_date
- return result
- elsif pair[1].ends_at > result
- result = pair[1].ends_at
- end
- end
-
- result
- end
- end
-end
diff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rb
index f43cbb1ef31..3bf5b95c342 100644
--- a/plugins/discourse-events/plugin.rb
+++ b/plugins/discourse-events/plugin.rb
@@ -10,10 +10,10 @@
libdir = File.join(File.dirname(__FILE__), "vendor/holidays/lib")
$LOAD_PATH.unshift(libdir) if $LOAD_PATH.exclude?(libdir)
-require_relative "lib/calendar_settings_validator"
-require_relative "lib/calendar_custom_fields_validator"
-require_relative "lib/calendar_first_day_of_week"
-require_relative "lib/calendar_upcoming_events_default_view"
+require_relative "lib/discourse_events/configuration/time_of_day_validator"
+require_relative "lib/discourse_events/configuration/event_custom_fields_validator"
+require_relative "lib/discourse_events/configuration/first_day_of_week"
+require_relative "lib/discourse_events/configuration/upcoming_events_default_view"
enabled_site_setting :discourse_events_enabled
@@ -46,7 +46,7 @@ register_svg_icon "location-pin"
register_svg_icon "arrows-up-to-line"
extend_content_security_policy(worker_src: %w[https://source.zoom.us blob:])
-module ::DiscourseCalendar
+module ::DiscourseEvents
# The plugin's identity slug — matches the `name:` metadata above. Used by
# requires_plugin, engine_name, settings attribution, and the admin UI.
PLUGIN_NAME = "discourse-events"
@@ -79,7 +79,7 @@ module ::DiscourseCalendar
def self.handle_topic_chat_channel_creation(topic)
return if topic.category.blank?
- return if DiscourseCalendar::Livestream::TopicChatChannel.exists?(topic_id: topic.id)
+ return if DiscourseEvents::Livestream::TopicChatChannel.exists?(topic_id: topic.id)
return unless topic.first_post&.event&.livestream?
channel =
@@ -93,7 +93,7 @@ module ::DiscourseCalendar
allow_channel_wide_mentions: true,
)
- DiscourseCalendar::Livestream::TopicChatChannel.create!(topic: topic, chat_channel: channel)
+ DiscourseEvents::Livestream::TopicChatChannel.create!(topic: topic, chat_channel: channel)
channel.user_chat_channel_memberships.create!(user: topic.user, following: false)
pin_topic_reference_message(topic, channel)
end
@@ -127,7 +127,7 @@ module ::DiscourseCalendar
return if message.blank?
- DiscourseCalendar::Livestream::TopicChatChannel.where(chat_channel_id: channel.id).update_all(
+ DiscourseEvents::Livestream::TopicChatChannel.where(chat_channel_id: channel.id).update_all(
reference_message_id: message.id,
)
@@ -173,7 +173,7 @@ module ::DiscourseCalendar
return {} if @user.nil?
@invitees_by_post_id ||=
- DiscoursePostEvent::Invitee.where(user_id: @user.id).index_by(&:post_id)
+ DiscourseEvents::Events::Invitee.where(user_id: @user.id).index_by(&:post_id)
end
def group_names
@@ -189,7 +189,7 @@ module ::DiscourseCalendar
def livestream_serialization_context
@livestream_serialization_context ||=
@options[:livestream_context] ||
- DiscourseCalendar::Livestream::ChannelSerializationContext.new(scope.user)
+ DiscourseEvents::Livestream::ChannelSerializationContext.new(scope.user)
end
def livestream_invitees_by_post_id
@@ -211,29 +211,29 @@ module ::DiscourseCalendar
end
end
-module ::DiscoursePostEvent
- PLUGIN_NAME = "discourse-post-event"
-
- # Topic where op has a post event custom field
- TOPIC_POST_EVENT_STARTS_AT = "TopicEventStartsAt"
- TOPIC_POST_EVENT_ENDS_AT = "TopicEventEndsAt"
- TOPIC_POST_EVENT_ALL_DAY = "TopicEventAllDay"
+module ::DiscourseEvents
+ module Events
+ # Topic where op has a post event custom field
+ TOPIC_POST_EVENT_STARTS_AT = "TopicEventStartsAt"
+ TOPIC_POST_EVENT_ENDS_AT = "TopicEventEndsAt"
+ TOPIC_POST_EVENT_ALL_DAY = "TopicEventAllDay"
+ end
end
-require_relative "lib/discourse_calendar/engine"
-require_relative "lib/discourse_calendar/livestream/allowed_hosts"
-require_relative "lib/discourse_calendar/livestream/allowed_hosts_validator"
-require_relative "lib/discourse_calendar/livestream/topic_extension"
-require_relative "lib/discourse_calendar/livestream/chat_channel_extension"
-require_relative "lib/discourse_calendar/livestream/zoom_url_parser"
+require_relative "lib/discourse_events/engine"
+require_relative "lib/discourse_events/livestream/allowed_hosts"
+require_relative "lib/discourse_events/livestream/allowed_hosts_validator"
+require_relative "lib/discourse_events/livestream/topic_extension"
+require_relative "lib/discourse_events/livestream/chat_channel_extension"
+require_relative "lib/discourse_events/livestream/zoom_url_parser"
Dir
- .glob(File.expand_path("../lib/discourse_calendar/site_settings/*.rb", __FILE__))
+ .glob(File.expand_path("../lib/discourse_events/configuration/*.rb", __FILE__))
.each { |f| require(f) }
after_initialize do
reloadable_patch do
- register_category_type(DiscourseCalendar::Categories::Types::Events)
+ register_category_type(DiscourseEvents::Categories::Types::Events)
Category.register_custom_field_type("sort_topics_by_event_start_date", :boolean)
Category.register_custom_field_type("disable_topic_resorting", :boolean)
register_preloaded_category_custom_fields("sort_topics_by_event_start_date")
@@ -263,7 +263,7 @@ after_initialize do
results =
results.joins(
"LEFT JOIN topic_custom_fields AS custom_fields on custom_fields.topic_id = topics.id
- AND custom_fields.name = '#{DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT}'
+ AND custom_fields.name = '#{DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT}'
",
).reorder(reorder_sql)
end
@@ -282,29 +282,25 @@ after_initialize do
require_relative "jobs/regular/discourse_post_event/bump_topic"
require_relative "jobs/regular/discourse_post_event/send_reminder"
require_relative "jobs/regular/discourse_post_event/warm_livestream_onebox"
- require_relative "lib/discourse_post_event/email_renderer"
- require_relative "lib/discourse_post_event/engine"
- require_relative "lib/discourse_post_event/event_excerpt"
- require_relative "lib/discourse_post_event/event_finder"
- require_relative "lib/discourse_post_event/event_onebox_data"
- require_relative "lib/discourse_post_event/event_parser"
- require_relative "lib/discourse_post_event/event_validator"
- require_relative "lib/discourse_post_event/export_csv_controller_extension"
- require_relative "lib/discourse_post_event/export_csv_file_extension"
- require_relative "lib/discourse_post_event/guardian_extensions"
- require_relative "lib/discourse_post_event/post_extension"
- require_relative "lib/discourse_post_event/topic_extension"
- require_relative "lib/discourse_post_event/rrule_generator"
- require_relative "lib/discourse_post_event/rrule_configurator"
- require_relative "lib/discourse_post_event/web_hook_extension"
+ require_relative "lib/discourse_events/events/chat_channel_sync"
+ require_relative "lib/discourse_events/events/email_renderer"
+ require_relative "lib/discourse_events/events/excerpt"
+ require_relative "lib/discourse_events/events/finder"
+ require_relative "lib/discourse_events/events/onebox_data"
+ require_relative "lib/discourse_events/events/parser"
+ require_relative "lib/discourse_events/events/validator"
+ require_relative "lib/discourse_events/events/export_csv_controller_extension"
+ require_relative "lib/discourse_events/events/export_csv_report_extension"
+ require_relative "lib/discourse_events/events/guardian_extensions"
+ require_relative "lib/discourse_events/events/post_extension"
+ require_relative "lib/discourse_events/events/topic_extension"
+ require_relative "lib/discourse_events/events/rrule_generator"
+ require_relative "lib/discourse_events/events/rrule_configurator"
+ require_relative "lib/discourse_events/events/web_hook_extension"
::ActionController::Base.prepend_view_path File.expand_path("../app/views", __FILE__)
- add_api_parameter_route(
- methods: :get,
- actions: "discourse_post_event/events#index",
- formats: :ics,
- )
+ add_api_parameter_route(methods: :get, actions: "discourse_events/events#index", formats: :ics)
# Register the calendar-feed scope explicitly under its frozen name (see
# EVENTS_CALENDAR_SCOPE). We can't use `add_user_api_key_scope` here: it derives
@@ -312,12 +308,8 @@ after_initialize do
# no longer match the value persisted in existing subscription keys.
DiscoursePluginRegistry.register_user_api_key_scope_mapping(
{
- DiscourseCalendar::EVENTS_CALENDAR_SCOPE.to_sym => [
- RouteMatcher.new(
- methods: :get,
- actions: "discourse_post_event/events#index",
- formats: :ics,
- ),
+ DiscourseEvents::EVENTS_CALENDAR_SCOPE.to_sym => [
+ RouteMatcher.new(methods: :get, actions: "discourse_events/events#index", formats: :ics),
],
},
self,
@@ -325,7 +317,7 @@ after_initialize do
register_calendar_subscription_feed(
name: "all_events",
- scope: DiscourseCalendar::EVENTS_CALENDAR_SCOPE,
+ scope: DiscourseEvents::EVENTS_CALENDAR_SCOPE,
description_key: "discourse_calendar.preferences.all_events_description",
url: ->(base_url, _user, key) do
"#{base_url}/discourse-post-event/events.ics?user_api_key=#{key}"
@@ -334,7 +326,7 @@ after_initialize do
register_calendar_subscription_feed(
name: "my_events",
- scope: DiscourseCalendar::EVENTS_CALENDAR_SCOPE,
+ scope: DiscourseEvents::EVENTS_CALENDAR_SCOPE,
description_key: "discourse_calendar.preferences.my_events_description",
url: ->(base_url, user, key) do
"#{base_url}/discourse-post-event/events.ics?attending_user=#{user.username_lower}&include_interested=true&user_api_key=#{key}"
@@ -342,14 +334,14 @@ after_initialize do
)
reloadable_patch do
- ExportCsvController.prepend(DiscoursePostEvent::ExportCsvControllerExtension)
- Jobs::ExportCsvFile.prepend(DiscoursePostEvent::ExportPostEventCsvReportExtension)
- Guardian.prepend(DiscoursePostEvent::GuardianExtensions)
- Post.prepend(DiscoursePostEvent::PostExtension)
- ::WebHook.prepend(DiscoursePostEvent::WebHookExtension)
- Topic.prepend(DiscoursePostEvent::TopicExtension)
- Topic.prepend(DiscourseCalendar::Livestream::TopicExtension)
- Chat::Channel.prepend(DiscourseCalendar::Livestream::ChatChannelExtension)
+ ExportCsvController.prepend(DiscourseEvents::Events::ExportCsvControllerExtension)
+ Jobs::ExportCsvFile.prepend(DiscourseEvents::Events::ExportCsvReportExtension)
+ Guardian.prepend(DiscourseEvents::Events::GuardianExtensions)
+ Post.prepend(DiscourseEvents::Events::PostExtension)
+ ::WebHook.prepend(DiscourseEvents::Events::WebHookExtension)
+ Topic.prepend(DiscourseEvents::Events::TopicExtension)
+ Topic.prepend(DiscourseEvents::Livestream::TopicExtension)
+ Chat::Channel.prepend(DiscourseEvents::Livestream::ChatChannelExtension)
end
add_to_serializer(:current_user, :can_create_discourse_post_event) do
@@ -372,14 +364,14 @@ after_initialize do
include_condition: -> do
SiteSetting.discourse_post_event_enabled && !object.nil? && !object.deleted_at.present?
end,
- ) { DiscoursePostEvent::EventSerializer.new(object.event, scope: scope, root: false) }
+ ) { DiscourseEvents::Events::EventSerializer.new(object.event, scope: scope, root: false) }
TopicView.on_preload do |topic_view|
if SiteSetting.discourse_post_event_enabled
# always set the store (even when empty) and avoid a per-post query for every post in the topic
topic_view.set_preloaded_post_data(
:event_oneboxes,
- DiscoursePostEvent::EventOneboxData.build(
+ DiscourseEvents::Events::OneboxData.build(
posts: topic_view.posts,
guardian: topic_view.guardian,
),
@@ -400,7 +392,7 @@ after_initialize do
if preloaded
preloaded[object.id] || {}
elsif object.cooked&.include?("data-topic")
- DiscoursePostEvent::EventOneboxData.build(posts: [object], guardian: scope)[object.id] ||
+ DiscourseEvents::Events::OneboxData.build(posts: [object], guardian: scope)[object.id] ||
{}
else
{}
@@ -409,7 +401,7 @@ after_initialize do
end
on(:post_created) do |post|
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.association(:event).reload
if SiteSetting.discourse_post_event_enabled && post.event
WebHook.enqueue_calendar_event_hooks(:calendar_event_created, post.event)
@@ -419,7 +411,7 @@ after_initialize do
on(:post_edited) do |post|
event_before = post.event
had_image_before = event_before&.image_upload_id.present?
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.association(:event).reload
if SiteSetting.discourse_post_event_enabled
@@ -428,7 +420,7 @@ after_initialize do
elsif had_image_before
post.trigger_post_process
end
- DiscoursePostEvent::Event.handle_post_event_webhooks(post, event_before)
+ DiscourseEvents::Events::Event.handle_post_event_webhooks(post, event_before)
end
end
@@ -447,7 +439,7 @@ after_initialize do
end
end
- add_preloaded_topic_list_custom_field DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT
+ add_preloaded_topic_list_custom_field DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT
add_to_serializer(
:topic_view,
@@ -455,14 +447,16 @@ after_initialize do
include_condition: -> do
SiteSetting.discourse_post_event_enabled &&
SiteSetting.display_post_event_date_on_topic_title &&
- object.topic.custom_fields.keys.include?(DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT)
+ object.topic.custom_fields.keys.include?(
+ DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT,
+ )
end,
) { object.topic.event_starts_at }
add_to_class(:topic, :event_starts_at) do
@event_starts_at ||=
begin
- value = custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT].to_s
+ value = custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT].to_s
Time.find_zone("UTC").parse(value) if value.present?
end
end
@@ -476,7 +470,7 @@ after_initialize do
end,
) { object.event_starts_at }
- add_preloaded_topic_list_custom_field DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT
+ add_preloaded_topic_list_custom_field DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT
add_to_serializer(
:topic_view,
@@ -484,14 +478,14 @@ after_initialize do
include_condition: -> do
SiteSetting.discourse_post_event_enabled &&
SiteSetting.display_post_event_date_on_topic_title &&
- object.topic.custom_fields.keys.include?(DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT)
+ object.topic.custom_fields.keys.include?(DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT)
end,
) { object.topic.event_ends_at }
add_to_class(:topic, :event_ends_at) do
@event_ends_at ||=
begin
- value = custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT].to_s
+ value = custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT].to_s
Time.find_zone("UTC").parse(value) if value.present?
end
end
@@ -505,7 +499,7 @@ after_initialize do
end,
) { object.event_ends_at }
- add_preloaded_topic_list_custom_field DiscoursePostEvent::TOPIC_POST_EVENT_ALL_DAY
+ add_preloaded_topic_list_custom_field DiscourseEvents::Events::TOPIC_POST_EVENT_ALL_DAY
add_to_serializer(
:topic_view,
@@ -520,7 +514,7 @@ after_initialize do
return @event_all_day if defined?(@event_all_day)
@event_all_day =
begin
- value = custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_ALL_DAY].to_s
+ value = custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_ALL_DAY].to_s
ActiveModel::Type::Boolean.new.cast(value)
end
end
@@ -560,59 +554,59 @@ after_initialize do
require_relative "jobs/scheduled/delete_expired_event_posts"
require_relative "jobs/scheduled/monitor_event_dates"
require_relative "jobs/scheduled/update_holiday_usernames"
- require_relative "lib/calendar_validator"
- require_relative "lib/calendar"
- require_relative "lib/event_validator"
- require_relative "lib/group_timezones"
- require_relative "lib/holiday_status"
- require_relative "lib/time_sniffer"
- require_relative "lib/users_on_holiday"
+ require_relative "lib/discourse_events/calendar/extractor"
+ require_relative "lib/discourse_events/calendar/validator"
+ require_relative "lib/discourse_events/calendar/event_validator"
+ require_relative "lib/discourse_events/group_timezones/extractor"
+ require_relative "lib/discourse_events/holidays/finder"
+ require_relative "lib/discourse_events/holidays/status"
+ require_relative "lib/discourse_events/holidays/users_on_holiday"
- register_post_custom_field_type(DiscourseCalendar::CALENDAR_CUSTOM_FIELD, :string)
- register_post_custom_field_type(DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD, :json)
- TopicView.default_post_custom_fields << DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD
+ register_post_custom_field_type(DiscourseEvents::CALENDAR_CUSTOM_FIELD, :string)
+ register_post_custom_field_type(DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD, :json)
+ TopicView.default_post_custom_fields << DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD
- register_user_custom_field_type(DiscourseCalendar::HOLIDAY_CUSTOM_FIELD, :boolean)
+ register_user_custom_field_type(DiscourseEvents::HOLIDAY_CUSTOM_FIELD, :boolean)
- allow_staff_user_custom_field(DiscourseCalendar::HOLIDAY_CUSTOM_FIELD)
- DiscoursePluginRegistry.serialized_current_user_fields << DiscourseCalendar::REGION_CUSTOM_FIELD
- register_editable_user_custom_field(DiscourseCalendar::REGION_CUSTOM_FIELD)
- register_user_custom_field_type(DiscourseCalendar::REGION_CUSTOM_FIELD, :string, max_length: 40)
+ allow_staff_user_custom_field(DiscourseEvents::HOLIDAY_CUSTOM_FIELD)
+ DiscoursePluginRegistry.serialized_current_user_fields << DiscourseEvents::REGION_CUSTOM_FIELD
+ register_editable_user_custom_field(DiscourseEvents::REGION_CUSTOM_FIELD)
+ register_user_custom_field_type(DiscourseEvents::REGION_CUSTOM_FIELD, :string, max_length: 40)
on(:site_setting_changed) do |name, old_value, new_value|
next if %i[all_day_event_start_time all_day_event_end_time].exclude? name
Post
- .where(id: CalendarEvent.select(:post_id).distinct)
- .each { |post| CalendarEvent.update(post) }
+ .where(id: DiscourseEvents::Calendar::Event.select(:post_id).distinct)
+ .each { |post| DiscourseEvents::Calendar::Event.update(post) }
end
on(:post_process_cooked) do |doc, post|
- DiscourseCalendar::Calendar.update(post)
- DiscourseCalendar::GroupTimezones.update(post)
- CalendarEvent.update(post)
+ DiscourseEvents::Calendar::Extractor.update(post)
+ DiscourseEvents::GroupTimezones::Extractor.update(post)
+ DiscourseEvents::Calendar::Event.update(post)
if SiteSetting.discourse_post_event_enabled
- event = DiscoursePostEvent::Event.find_by(id: post.id)
+ event = DiscourseEvents::Events::Event.find_by(id: post.id)
event&.sync_image_to_post_and_topic(generate_thumbnails: true) if event&.image_upload_id
end
end
on(:post_recovered) do |post, _, _|
- DiscourseCalendar::Calendar.update(post)
- DiscourseCalendar::GroupTimezones.update(post)
- CalendarEvent.update(post)
+ DiscourseEvents::Calendar::Extractor.update(post)
+ DiscourseEvents::GroupTimezones::Extractor.update(post)
+ DiscourseEvents::Calendar::Event.update(post)
end
on(:post_destroyed) do |post, _, _|
- DiscourseCalendar::Calendar.destroy(post)
- CalendarEvent.where(post_id: post.id).destroy_all
+ DiscourseEvents::Calendar::Extractor.destroy(post)
+ DiscourseEvents::Calendar::Event.where(post_id: post.id).destroy_all
end
validate(:post, :validate_calendar) do |force = nil|
return unless raw_changed? || force
- validator = DiscourseCalendar::CalendarValidator.new(self)
+ validator = DiscourseEvents::Calendar::Validator.new(self)
validator.validate_calendar
end
@@ -621,25 +615,25 @@ after_initialize do
return if is_first_post?
# Skip if not a calendar topic
- return if !topic&.first_post&.custom_fields&.[](DiscourseCalendar::CALENDAR_CUSTOM_FIELD)
+ return if !topic&.first_post&.custom_fields&.[](DiscourseEvents::CALENDAR_CUSTOM_FIELD)
- validator = DiscourseCalendar::EventValidator.new(self)
+ validator = DiscourseEvents::Calendar::EventValidator.new(self)
validator.validate_event
end
add_to_class(:post, :has_group_timezones?) do
- custom_fields[DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD].present?
+ custom_fields[DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD].present?
end
add_to_class(:post, :group_timezones) do
- custom_fields[DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD] || {}
+ custom_fields[DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD] || {}
end
add_to_class(:post, :group_timezones=) do |val|
if val.present?
- custom_fields[DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD] = val
+ custom_fields[DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD] = val
else
- custom_fields.delete(DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD)
+ custom_fields.delete(DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD)
end
end
@@ -675,7 +669,7 @@ after_initialize do
UserOption
.where(
user_id:
- CalendarEvent.where(
+ DiscourseEvents::Calendar::Event.where(
topic_id: object.topic_id,
post_id: nil,
start_date: start_date..,
@@ -728,11 +722,11 @@ after_initialize do
:post,
:group_timezones,
include_condition: -> do
- post_custom_fields[DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD].present?
+ post_custom_fields[DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD].present?
end,
) do
result = {}
- group_timezones = post_custom_fields[DiscourseCalendar::GROUP_TIMEZONES_CUSTOM_FIELD] || {}
+ group_timezones = post_custom_fields[DiscourseEvents::GROUP_TIMEZONES_CUSTOM_FIELD] || {}
group_names = group_timezones["groups"] || []
if group_names.present?
@@ -750,11 +744,11 @@ after_initialize do
.where(groups: { id: visible_group_ids })
.select("users.*", "groups.name AS group_name", "user_options.timezone")
- usernames_on_holiday = DiscourseCalendar.users_on_holiday
+ usernames_on_holiday = DiscourseEvents.users_on_holiday
users.each do |u|
result[u.group_name] ||= []
- result[u.group_name] << UserTimezoneSerializer.new(
+ result[u.group_name] << DiscourseEvents::GroupTimezones::UserSerializer.new(
u,
root: false,
on_holiday: usernames_on_holiday&.include?(u.username),
@@ -766,7 +760,7 @@ after_initialize do
end
add_to_serializer(:site, :users_on_holiday, include_condition: -> { scope.is_staff? }) do
- DiscourseCalendar.users_on_holiday
+ DiscourseEvents.users_on_holiday
end
on(:reduce_cooked) do |fragment, post|
@@ -774,7 +768,7 @@ after_initialize do
fragment
.css(".discourse-post-event")
.each do |event_node|
- event_node.replace(DiscoursePostEvent::EmailRenderer.render(event_node, post))
+ event_node.replace(DiscourseEvents::Events::EmailRenderer.render(event_node, post))
rescue => e
Discourse.warn_exception(
e,
@@ -786,16 +780,18 @@ after_initialize do
on(:reduce_excerpt) do |fragment, options|
if SiteSetting.discourse_post_event_enabled
- DiscoursePostEvent::EventExcerpt.call(fragment, post: options[:post])
+ DiscourseEvents::Events::Excerpt.call(fragment, post: options[:post])
end
end
- on(:user_destroyed) { |user| DiscoursePostEvent::Invitee.where(user_id: user.id).destroy_all }
+ on(:user_destroyed) do |user|
+ DiscourseEvents::Events::Invitee.where(user_id: user.id).destroy_all
+ end
on(:user_removed_from_group) do |user, group|
- DiscoursePostEvent::Event
- .where(id: DiscoursePostEvent::Invitee.unscoped.where(user_id: user.id).select(:post_id))
- .where(status: DiscoursePostEvent::Event.statuses[:private])
+ DiscourseEvents::Events::Event
+ .where(id: DiscourseEvents::Events::Invitee.unscoped.where(user_id: user.id).select(:post_id))
+ .where(status: DiscourseEvents::Events::Event.statuses[:private])
.where("? = ANY(discourse_post_event_events.raw_invitees)", group.name)
.find_each(&:enforce_private_invitees!)
end
@@ -826,7 +822,7 @@ after_initialize do
next if removed_fields.empty?
- DiscoursePostEvent::Event.all.find_each do |event|
+ DiscourseEvents::Events::Event.all.find_each do |event|
removed_fields.each { |field| event.custom_fields.delete(field) }
event.save
end
@@ -895,7 +891,7 @@ after_initialize do
]
group_usernames = group.users.pluck(:username)
- on_holiday_usernames = DiscourseCalendar.users_on_holiday
+ on_holiday_usernames = DiscourseEvents.users_on_holiday
report.data = (group_usernames & on_holiday_usernames).map { |username| { username: username } }
report.total = report.data.count
end
@@ -903,10 +899,10 @@ after_initialize do
register_anonymous_action("rsvp_event") do |user, params|
event_id = params["event_id"]
recurring = ActiveModel::Type::Boolean.new.cast(params["recurring"])
- existing_invitee = DiscoursePostEvent::Invitee.find_by(post_id: event_id, user_id: user.id)
+ existing_invitee = DiscourseEvents::Events::Invitee.find_by(post_id: event_id, user_id: user.id)
if existing_invitee
- DiscoursePostEvent::UpdateInvitee.call(
+ DiscourseEvents::Events::UpdateInvitee.call(
params: {
event_id: event_id,
invitee_id: existing_invitee.id,
@@ -916,7 +912,7 @@ after_initialize do
guardian: user.guardian,
)
else
- DiscoursePostEvent::CreateInvitee.call(
+ DiscourseEvents::Events::CreateInvitee.call(
params: {
event_id: event_id,
status: params["status"],
@@ -948,16 +944,16 @@ after_initialize do
include_condition: -> { scope.user.present? && object.topic.first_post&.event.present? },
) do
invitee =
- DiscoursePostEvent::Invitee.find_by(
+ DiscourseEvents::Events::Invitee.find_by(
post_id: object.topic.first_post.event.id,
user_id: scope.user.id,
)
- DiscoursePostEvent::Invitee.statuses[invitee.status] if invitee
+ DiscourseEvents::Events::Invitee.statuses[invitee.status] if invitee
end
reloadable_patch do
- Chat::ChannelSerializer.include(DiscourseCalendar::Livestream::ChannelSerializerExtension)
+ Chat::ChannelSerializer.include(DiscourseEvents::Livestream::ChannelSerializerExtension)
end
register_modifier(:chat_channel_fetcher_public_includes) do |includes|
@@ -967,7 +963,7 @@ after_initialize do
register_modifier(:chat_channel_serializer_public_options) do |serializer_options, guardian|
serializer_options.merge(
livestream_context:
- DiscourseCalendar::Livestream::ChannelSerializationContext.new(guardian.user),
+ DiscourseEvents::Livestream::ChannelSerializationContext.new(guardian.user),
)
end
@@ -1006,13 +1002,13 @@ after_initialize do
reference_message_id: object.livestream_topic_chat_channel.reference_message_id,
can_update_attendance: can_update_attendance,
watching_invitee_status:
- watching_invitee && DiscoursePostEvent::Invitee.statuses[watching_invitee.status],
+ watching_invitee && DiscourseEvents::Events::Invitee.statuses[watching_invitee.status],
}
end
on(:chat_channel_trashed) do |channel, user|
# If the chat channel is deleted, delete the related TopicChatChannel record
- DiscourseCalendar::Livestream::TopicChatChannel.where(chat_channel_id: channel.id).destroy_all
+ DiscourseEvents::Livestream::TopicChatChannel.where(chat_channel_id: channel.id).destroy_all
end
on(:discourse_calendar_post_event_invitee_status_changed) do |invitee|
@@ -1028,14 +1024,12 @@ after_initialize do
# Attendance is the chat gate: anyone going is auto-followed into the
# livestream channel, anyone else is unfollowed.
membership =
- if invitee.status == DiscoursePostEvent::Invitee.statuses[:going]
+ if invitee.status == DiscourseEvents::Events::Invitee.statuses[:going]
manager.follow(user)
else
manager.unfollow(user)
end
- if membership
- DiscourseCalendar::Livestream.publish_livestream_chat_status(membership, user: user)
- end
+ DiscourseEvents::Livestream.publish_livestream_chat_status(membership, user: user) if membership
end
end
diff --git a/plugins/discourse-events/spec/fabricators/calendar_event_fabricator.rb b/plugins/discourse-events/spec/fabricators/calendar_event_fabricator.rb
index 0d84694c95b..1a31df0b2de 100644
--- a/plugins/discourse-events/spec/fabricators/calendar_event_fabricator.rb
+++ b/plugins/discourse-events/spec/fabricators/calendar_event_fabricator.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-Fabricator(:calendar_event) do
+Fabricator(:calendar_event, from: "DiscourseEvents::Calendar::Event") do
user
username { |attrs| attrs[:user].username }
diff --git a/plugins/discourse-events/spec/fabricators/event_fabricator.rb b/plugins/discourse-events/spec/fabricators/event_fabricator.rb
index a6da5c5117f..378f0229064 100644
--- a/plugins/discourse-events/spec/fabricators/event_fabricator.rb
+++ b/plugins/discourse-events/spec/fabricators/event_fabricator.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-Fabricator(:event, from: "DiscoursePostEvent::Event") do
+Fabricator(:event, from: "DiscourseEvents::Events::Event") do
transient :user
post do |attrs|
@@ -17,9 +17,9 @@ Fabricator(:event, from: "DiscoursePostEvent::Event") do
status do |attrs|
if attrs[:status]
- DiscoursePostEvent::Event.statuses[attrs[:status]]
+ DiscourseEvents::Events::Event.statuses[attrs[:status]]
else
- DiscoursePostEvent::Event.statuses[:public]
+ DiscourseEvents::Events::Event.statuses[:public]
end
end
original_starts_at { |attrs| attrs[:original_starts_at] || 1.day.from_now.iso8601 }
@@ -38,7 +38,7 @@ Fabricator(:private_event, from: :event) do
end
end
-Fabricator(:event_date, from: "DiscoursePostEvent::EventDate") do
+Fabricator(:event_date, from: "DiscourseEvents::Events::EventDate") do
event
starts_at { |attrs| attrs[:starts_at] || 1.day.from_now.iso8601 }
diff --git a/plugins/discourse-events/spec/fabricators/invitee_fabricator.rb b/plugins/discourse-events/spec/fabricators/invitee_fabricator.rb
index a9da22690d2..28b99e49fc6 100644
--- a/plugins/discourse-events/spec/fabricators/invitee_fabricator.rb
+++ b/plugins/discourse-events/spec/fabricators/invitee_fabricator.rb
@@ -1,3 +1,3 @@
# frozen_string_literal: true
-Fabricator(:invitee, from: "DiscoursePostEvent::Invitee") {}
+Fabricator(:invitee, from: "DiscourseEvents::Events::Invitee") {}
diff --git a/plugins/discourse-events/spec/fabricators/post_event_invitee_fabricator.rb b/plugins/discourse-events/spec/fabricators/post_event_invitee_fabricator.rb
index 97c9a9999a6..34e16bce6eb 100644
--- a/plugins/discourse-events/spec/fabricators/post_event_invitee_fabricator.rb
+++ b/plugins/discourse-events/spec/fabricators/post_event_invitee_fabricator.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-Fabricator(:post_event_invitee, from: "DiscoursePostEvent::Invitee") do
+Fabricator(:post_event_invitee, from: "DiscourseEvents::Events::Invitee") do
event
user
status { |attrs| attrs[:status] || nil }
diff --git a/plugins/discourse-events/spec/fabricators/topic_chat_channel_fabricator.rb b/plugins/discourse-events/spec/fabricators/topic_chat_channel_fabricator.rb
index f930776e375..bf5c0c2977d 100644
--- a/plugins/discourse-events/spec/fabricators/topic_chat_channel_fabricator.rb
+++ b/plugins/discourse-events/spec/fabricators/topic_chat_channel_fabricator.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-Fabricator(:topic_chat_channel, from: "DiscourseCalendar::Livestream::TopicChatChannel") do
+Fabricator(:topic_chat_channel, from: "DiscourseEvents::Livestream::TopicChatChannel") do
topic
chat_channel
end
diff --git a/plugins/discourse-events/spec/integration/curently_away_report_spec.rb b/plugins/discourse-events/spec/integration/curently_away_report_spec.rb
index b7e5d14282a..3fc83ad0116 100644
--- a/plugins/discourse-events/spec/integration/curently_away_report_spec.rb
+++ b/plugins/discourse-events/spec/integration/curently_away_report_spec.rb
@@ -17,7 +17,7 @@ describe "currently_away report" do
end
context "when users_on_holiday is set" do
- before { DiscourseCalendar.users_on_holiday = [user_1.username] }
+ before { DiscourseEvents.users_on_holiday = [user_1.username] }
it "generates a correct report" do
report = Report.find("currently_away", filters: { group: group_1.id })
diff --git a/plugins/discourse-events/spec/integration/invitee_spec.rb b/plugins/discourse-events/spec/integration/invitee_spec.rb
index 967cd1196eb..ca28aed1ce4 100644
--- a/plugins/discourse-events/spec/integration/invitee_spec.rb
+++ b/plugins/discourse-events/spec/integration/invitee_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::Invitee do
+describe DiscourseEvents::Events::Invitee do
before do
freeze_time
Jobs.run_immediately!
@@ -108,10 +108,10 @@ describe DiscoursePostEvent::Invitee do
before do
post_event.create_invitees(
[
- { user_id: regular_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] },
- { user_id: suspended_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] },
- { user_id: silenced_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] },
- { user_id: staged_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] },
+ { user_id: regular_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] },
+ { user_id: suspended_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] },
+ { user_id: silenced_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] },
+ { user_id: staged_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] },
],
)
end
diff --git a/plugins/discourse-events/spec/integration/post_spec.rb b/plugins/discourse-events/spec/integration/post_spec.rb
index 9f9a550cb40..5f49f1109f1 100644
--- a/plugins/discourse-events/spec/integration/post_spec.rb
+++ b/plugins/discourse-events/spec/integration/post_spec.rb
@@ -52,8 +52,8 @@ describe Post do
end
it "sends a post revision to going invitees" do
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, post_1.id, :going)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(going_user.id, post_1.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(
interested_user.id,
post_1.id,
:interested,
@@ -76,8 +76,8 @@ describe Post do
before { event_1.event_dates.first.update_columns(starts_at: 5.hours.ago) }
it "doesn’t send a post revision to anyone" do
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, post_1.id, :going)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(going_user.id, post_1.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(
interested_user.id,
event_1.id,
:interested,
@@ -106,8 +106,8 @@ describe Post do
original_ends_at: nil,
)
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, event_1.id, :going)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(going_user.id, event_1.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(
interested_user.id,
event_1.id,
:interested,
@@ -130,10 +130,12 @@ describe Post do
it "clears status from invitees not marked as recurring" do
going_invitee =
- event_1.invitees.find_by(status: DiscoursePostEvent::Invitee.statuses[:going])
+ event_1.invitees.find_by(
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
+ )
interested_invitee =
event_1.invitees.find_by(
- status: DiscoursePostEvent::Invitee.statuses[:interested],
+ status: DiscourseEvents::Events::Invitee.statuses[:interested],
)
event_1.update_with_params!(original_ends_at: Time.now)
@@ -169,12 +171,12 @@ describe Post do
context "when updating status to private" do
it "changes the status and force invitees" do
expect(event_1.raw_invitees).to eq(["trust_level_0"])
- expect(event_1.status).to eq(DiscoursePostEvent::Event.statuses[:public])
+ expect(event_1.status).to eq(DiscourseEvents::Events::Event.statuses[:public])
- event_1.update_with_params!(status: DiscoursePostEvent::Event.statuses[:private])
+ event_1.update_with_params!(status: DiscourseEvents::Events::Event.statuses[:private])
expect(event_1.raw_invitees).to eq([])
- expect(event_1.status).to eq(DiscoursePostEvent::Event.statuses[:private])
+ expect(event_1.status).to eq(DiscourseEvents::Events::Event.statuses[:private])
end
end
end
@@ -213,7 +215,7 @@ describe Post do
it "works with status attribute" do
post = create_post_with_event(user, 'status="private"').reload
- expect(post.event.status).to eq(DiscoursePostEvent::Event.statuses[:private])
+ expect(post.event.status).to eq(DiscourseEvents::Events::Event.statuses[:private])
end
it "works with allowedGroups attribute" do
@@ -445,7 +447,7 @@ describe Post do
Fabricate(
:event,
post: post_1,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [group_1.name],
original_starts_at: 3.hours.ago,
original_ends_at: nil,
@@ -457,7 +459,7 @@ describe Post do
Fabricate(
:event,
post: post_1,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [group_1.name],
recurrence: "FREQ=WEEKLY;BYDAY=MO",
original_starts_at: 2.hours.from_now,
@@ -499,12 +501,12 @@ describe Post do
context "when updating status to public" do
it "changes the status and force invitees" do
expect(event_1.raw_invitees).to eq([group_1.name])
- expect(event_1.status).to eq(DiscoursePostEvent::Event.statuses[:private])
+ expect(event_1.status).to eq(DiscourseEvents::Events::Event.statuses[:private])
- event_1.update_with_params!(status: DiscoursePostEvent::Event.statuses[:public])
+ event_1.update_with_params!(status: DiscourseEvents::Events::Event.statuses[:public])
expect(event_1.raw_invitees).to eq(["trust_level_0"])
- expect(event_1.status).to eq(DiscoursePostEvent::Event.statuses[:public])
+ expect(event_1.status).to eq(DiscourseEvents::Events::Event.statuses[:public])
end
end
@@ -814,7 +816,7 @@ describe Post do
expect(post.event.original_starts_at).to eq_time(expected_datetime)
serializer =
- DiscoursePostEvent::BasicEventSerializer.new(post.event, scope: Guardian.new(user))
+ DiscourseEvents::Events::BasicEventSerializer.new(post.event, scope: Guardian.new(user))
serialized = serializer.as_json
# Should return floating time (no timezone info)
diff --git a/plugins/discourse-events/spec/integration/recurrence_spec.rb b/plugins/discourse-events/spec/integration/recurrence_spec.rb
index 8a6732a6a32..ae6d72c5c29 100644
--- a/plugins/discourse-events/spec/integration/recurrence_spec.rb
+++ b/plugins/discourse-events/spec/integration/recurrence_spec.rb
@@ -23,7 +23,7 @@ describe "discourse_post_event_recurrence" do
it "delete previous notifications before creating a new one for invites" do
going_user = Fabricate(:user)
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, post_event_1.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(going_user.id, post_event_1.id, :going)
post_event_1.update!(original_starts_at: starts_at + 10.minutes)
post_event_1.set_next_date
@@ -126,8 +126,12 @@ describe "discourse_post_event_recurrence" do
before { post_event_1.update!(recurrence: "every_week") }
it "clears non-recurring going invitees and keeps recurring ones" do
- DiscoursePostEvent::Invitee.create_attendance!(going_once_user.id, post_event_1.id, :going)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
+ going_once_user.id,
+ post_event_1.id,
+ :going,
+ )
+ DiscourseEvents::Events::Invitee.create_attendance!(
going_recurring_user.id,
post_event_1.id,
:going,
@@ -140,7 +144,7 @@ describe "discourse_post_event_recurrence" do
recurring = post_event_1.invitees.find_by(user_id: going_recurring_user.id)
expect(once.status).to be_nil
- expect(recurring.status).to eq(DiscoursePostEvent::Invitee.statuses[:going])
+ expect(recurring.status).to eq(DiscourseEvents::Events::Invitee.statuses[:going])
expect(recurring.recurring).to eq(true)
end
end
diff --git a/plugins/discourse-events/spec/integration/topic_spec.rb b/plugins/discourse-events/spec/integration/topic_spec.rb
index 2d9468f2dd5..a76a60e37e3 100644
--- a/plugins/discourse-events/spec/integration/topic_spec.rb
+++ b/plugins/discourse-events/spec/integration/topic_spec.rb
@@ -20,7 +20,7 @@ describe Topic do
raw: "The boat market is quite active lately.",
)
- expect(DiscoursePostEvent::Event).to_not exist(id: post_with_date.id)
+ expect(DiscourseEvents::Events::Event).to_not exist(id: post_with_date.id)
end
end
end
diff --git a/plugins/discourse-events/spec/jobs/regular/discourse_post_event/bulk_invite_spec.rb b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/bulk_invite_spec.rb
index 963dd8174b3..bf222d62550 100644
--- a/plugins/discourse-events/spec/jobs/regular/discourse_post_event/bulk_invite_spec.rb
+++ b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/bulk_invite_spec.rb
@@ -103,7 +103,7 @@ describe Jobs::DiscoursePostEventBulkInvite do
Jobs::DiscoursePostEventBulkInvite.new.execute(valid_params)
- invitee_klass = DiscoursePostEvent::Invitee
+ invitee_klass = DiscourseEvents::Events::Invitee
expect(invitee_klass.count).to eq(2)
expect(invitee_klass.find_by(user_id: invitee_1.id).status).to eq(
@@ -123,7 +123,7 @@ describe Jobs::DiscoursePostEventBulkInvite do
processed: 1,
)
- invitee_klass = DiscoursePostEvent::Invitee
+ invitee_klass = DiscourseEvents::Events::Invitee
Jobs::DiscoursePostEventBulkInvite.new.execute(
event_id: post_event_1.id,
@@ -165,7 +165,7 @@ describe Jobs::DiscoursePostEventBulkInvite do
current_user_id: moderator.id,
)
- expect(DiscoursePostEvent::Invitee.where(post_id: mod_post.id)).to be_empty
+ expect(DiscourseEvents::Events::Invitee.where(post_id: mod_post.id)).to be_empty
end
end
@@ -189,7 +189,7 @@ describe Jobs::DiscoursePostEventBulkInvite do
Jobs::DiscoursePostEventBulkInvite.new.execute(valid_params)
- invitee_klass = DiscoursePostEvent::Invitee
+ invitee_klass = DiscourseEvents::Events::Invitee
expect(invitee_klass.count).to eq(2)
expect(invitee_klass.find_by(user_id: invitee_1)).to eq(nil)
@@ -203,7 +203,7 @@ describe Jobs::DiscoursePostEventBulkInvite do
end
it "skips an unrecognized attendance instead of corrupting the invitee" do
- invitee_klass = DiscoursePostEvent::Invitee
+ invitee_klass = DiscourseEvents::Events::Invitee
Jobs::DiscoursePostEventBulkInvite.new.execute(
event_id: post_event_1.id,
diff --git a/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rb b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rb
index c9b8514efc8..17b51b9c04c 100644
--- a/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rb
+++ b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rb
@@ -12,20 +12,20 @@ describe Jobs::DiscoursePostEventSendReminder do
let(:reminders) { "notification.5.minutes" }
def init_invitees
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, event_1.id, :going)
- DiscoursePostEvent::Invitee.create_attendance!(interested_user.id, event_1.id, :interested)
- DiscoursePostEvent::Invitee.create_attendance!(not_going_user.id, event_1.id, :not_going)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(going_user.id, event_1.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(interested_user.id, event_1.id, :interested)
+ DiscourseEvents::Events::Invitee.create_attendance!(not_going_user.id, event_1.id, :not_going)
+ DiscourseEvents::Events::Invitee.create_attendance!(
going_user_unread_notification.id,
event_1.id,
:going,
)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
going_user_read_notification.id,
event_1.id,
:going,
)
- DiscoursePostEvent::Invitee.create_attendance!(visited_going_user.id, event_1.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(visited_going_user.id, event_1.id, :going)
[
going_user,
@@ -308,35 +308,35 @@ describe Jobs::DiscoursePostEventSendReminder do
end
def setup_recurring_event_invitees
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
going_user.id,
recurring_event.id,
:going,
recurring: true,
)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
interested_user.id,
recurring_event.id,
:interested,
)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
not_going_user.id,
recurring_event.id,
:not_going,
)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
going_user_unread_notification.id,
recurring_event.id,
:going,
recurring: true,
)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
going_user_read_notification.id,
recurring_event.id,
:going,
recurring: true,
)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
visited_going_user.id,
recurring_event.id,
:going,
@@ -424,7 +424,11 @@ describe Jobs::DiscoursePostEventSendReminder do
timezone: tokyo_timezone,
)
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, timezone_event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(
+ going_user.id,
+ timezone_event.id,
+ :going,
+ )
going_user.notifications.delete_all
expect { send_reminder(timezone_event) }.to change {
@@ -451,7 +455,7 @@ describe Jobs::DiscoursePostEventSendReminder do
timezone: la_timezone,
)
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, ongoing_event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(going_user.id, ongoing_event.id, :going)
going_user.notifications.delete_all
expect { send_reminder(ongoing_event) }.to change {
@@ -472,7 +476,7 @@ describe Jobs::DiscoursePostEventSendReminder do
end
it "handles expired recurring events" do
- DiscoursePostEvent::Invitee.create_attendance!(going_user.id, expired_event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(going_user.id, expired_event.id, :going)
expect(expired_event.starts_at).to be_nil
@@ -499,7 +503,7 @@ describe Jobs::DiscoursePostEventSendReminder do
recurrence: "every_week",
)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(
dst_user.id,
dst_event.id,
:going,
diff --git a/plugins/discourse-events/spec/jobs/scheduled/create_holiday_events_spec.rb b/plugins/discourse-events/spec/jobs/scheduled/create_holiday_events_spec.rb
index b01bccae19c..e33183dcfeb 100644
--- a/plugins/discourse-events/spec/jobs/scheduled/create_holiday_events_spec.rb
+++ b/plugins/discourse-events/spec/jobs/scheduled/create_holiday_events_spec.rb
@@ -6,11 +6,9 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
let(:calendar_post) { create_post(raw: "[calendar]\n[/calendar]") }
let(:frenchy) do
- Fabricate(:user, custom_fields: { DiscourseCalendar::REGION_CUSTOM_FIELD => "fr" })
- end
- let(:aussie) do
- Fabricate(:user, custom_fields: { DiscourseCalendar::REGION_CUSTOM_FIELD => "au" })
+ Fabricate(:user, custom_fields: { DiscourseEvents::REGION_CUSTOM_FIELD => "fr" })
end
+ let(:aussie) { Fabricate(:user, custom_fields: { DiscourseEvents::REGION_CUSTOM_FIELD => "au" }) }
before do
Jobs.run_immediately!
@@ -25,7 +23,7 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 8, 1)
job.execute(nil)
- expect(CalendarEvent.where(user_id: frenchy.id).count).to eq(0)
+ expect(DiscourseEvents::Calendar::Event.where(user_id: frenchy.id).count).to eq(0)
end
it "adds all holidays in the next 6 months" do
@@ -33,7 +31,9 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 8, 1)
job.execute(nil)
- expect(CalendarEvent.pluck(:region, :description, :start_date, :user_id)).to match_array(
+ expect(
+ DiscourseEvents::Calendar::Event.pluck(:region, :description, :start_date, :user_id),
+ ).to match_array(
[
["fr", "Assomption", Date.parse("2019-08-15"), frenchy.id],
["fr", "Toussaint", Date.parse("2019-11-01"), frenchy.id],
@@ -50,7 +50,9 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
job.execute(nil)
# The "Australia Day" is always observed on a Monday
- expect(CalendarEvent.pluck(:region, :description, :start_date, :user_id)).to match_array(
+ expect(
+ DiscourseEvents::Calendar::Event.pluck(:region, :description, :start_date, :user_id),
+ ).to match_array(
[
["au", "Australia Day", Date.parse("2020-01-27"), aussie.id],
["au", "Good Friday", Date.parse("2020-04-10"), aussie.id],
@@ -65,7 +67,9 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
job.execute(nil)
# The "Fête Nationale" is on July 14th but it's on a Sunday in 2019
- expect(CalendarEvent.pluck(:region, :description, :start_date, :user_id)).to match_array(
+ expect(
+ DiscourseEvents::Calendar::Event.pluck(:region, :description, :start_date, :user_id),
+ ).to match_array(
[
["fr", "Assomption", Date.parse("2019-08-15"), frenchy.id],
["fr", "Toussaint", Date.parse("2019-11-01"), frenchy.id],
@@ -80,13 +84,13 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 8, 1)
robot =
- Fabricate(:user, id: -100, custom_fields: { DiscourseCalendar::REGION_CUSTOM_FIELD => "fr" })
+ Fabricate(:user, id: -100, custom_fields: { DiscourseEvents::REGION_CUSTOM_FIELD => "fr" })
inactive =
Fabricate(
:user,
active: false,
custom_fields: {
- DiscourseCalendar::REGION_CUSTOM_FIELD => "fr",
+ DiscourseEvents::REGION_CUSTOM_FIELD => "fr",
},
)
suspended =
@@ -94,7 +98,7 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
:user,
suspended_till: 1.year.from_now,
custom_fields: {
- DiscourseCalendar::REGION_CUSTOM_FIELD => "fr",
+ DiscourseEvents::REGION_CUSTOM_FIELD => "fr",
},
)
silenced =
@@ -102,34 +106,36 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
:user,
silenced_till: 1.year.from_now,
custom_fields: {
- DiscourseCalendar::REGION_CUSTOM_FIELD => "fr",
+ DiscourseEvents::REGION_CUSTOM_FIELD => "fr",
},
)
job.execute(nil)
- expect(CalendarEvent.pluck(:region, :description, :start_date, :user_id)).to eq([])
+ expect(
+ DiscourseEvents::Calendar::Event.pluck(:region, :description, :start_date, :user_id),
+ ).to eq([])
end
it "does not create duplicates when username is changed" do
frenchy
job.execute(nil)
- created_event = CalendarEvent.last
+ created_event = DiscourseEvents::Calendar::Event.last
expect(created_event.username).to eq(frenchy.username)
frenchy.update!(username: "new_username")
- expect { job.execute(nil) }.not_to change { CalendarEvent.count }
+ expect { job.execute(nil) }.not_to change { DiscourseEvents::Calendar::Event.count }
expect(created_event.reload.username).to eq("new_username")
end
it "does not create duplicates when timezone is changed" do
frenchy
job.execute(nil)
- created_event = CalendarEvent.last
+ created_event = DiscourseEvents::Calendar::Event.last
expect(created_event.timezone).to eq(frenchy.user_option.timezone)
frenchy.user_option.update!(timezone: "Asia/Taipei")
- expect { job.execute(nil) }.not_to change { CalendarEvent.count }
+ expect { job.execute(nil) }.not_to change { DiscourseEvents::Calendar::Event.count }
expect(created_event.reload.timezone).to eq("Asia/Taipei")
end
@@ -138,14 +144,14 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 8, 1)
job.execute(nil)
- expect(CalendarEvent.exists?(user_id: frenchy.id)).to eq(true)
+ expect(DiscourseEvents::Calendar::Event.exists?(user_id: frenchy.id)).to eq(true)
frenchy.active = false
frenchy.save!
job.execute(nil)
- expect(CalendarEvent.exists?(user_id: frenchy.id)).to eq(false)
+ expect(DiscourseEvents::Calendar::Event.exists?(user_id: frenchy.id)).to eq(false)
end
it "cleans up holidays from users who changed their region" do
@@ -153,9 +159,9 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 8, 1)
job.execute(nil)
- expect(CalendarEvent.exists?(user_id: frenchy.id)).to eq(true)
+ expect(DiscourseEvents::Calendar::Event.exists?(user_id: frenchy.id)).to eq(true)
- frenchy.custom_fields[DiscourseCalendar::REGION_CUSTOM_FIELD] = "au"
+ frenchy.custom_fields[DiscourseEvents::REGION_CUSTOM_FIELD] = "au"
frenchy.save!
freeze_time Time.zone.local(2020, 1, 1)
@@ -164,7 +170,7 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
# Past 'fr' holidays should not be removed
expect(
- CalendarEvent
+ DiscourseEvents::Calendar::Event
.where(user: frenchy)
.where(region: "fr")
.where("start_date <= ?", Date.today)
@@ -173,7 +179,7 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
# Future 'fr' holidays should be removed
expect(
- CalendarEvent
+ DiscourseEvents::Calendar::Event
.where(user: frenchy)
.where(region: "fr")
.where("start_date > ?", Date.today)
@@ -182,7 +188,7 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
# Future 'au' holidays should be added
expect(
- CalendarEvent
+ DiscourseEvents::Calendar::Event
.where(user: frenchy)
.where(region: "au")
.where("start_date > ?", Date.today)
@@ -195,8 +201,8 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
let(:france_toussaint) { { holiday_name: "Toussaint", region_code: "fr" } }
before do
- DiscourseCalendar::DisabledHoliday.create!(france_assomption)
- DiscourseCalendar::DisabledHoliday.create!(france_toussaint)
+ DiscourseEvents::Holidays::DisabledHoliday.create!(france_assomption)
+ DiscourseEvents::Holidays::DisabledHoliday.create!(france_toussaint)
end
it "only adds enabled holidays to the calendar" do
@@ -204,7 +210,9 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 7, 1)
job.execute(nil)
- expect(CalendarEvent.pluck(:region, :description, :start_date, :user_id)).to match_array(
+ expect(
+ DiscourseEvents::Calendar::Event.pluck(:region, :description, :start_date, :user_id),
+ ).to match_array(
[
["fr", "Armistice 1918", Date.parse("2019-11-11"), frenchy.id],
["fr", "Noël", Date.parse("2019-12-25"), frenchy.id],
@@ -218,8 +226,12 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 7, 1)
job.execute(nil)
- expect(CalendarEvent.pluck(:description)).not_to include(france_assomption[:holiday_name])
- expect(CalendarEvent.pluck(:description)).not_to include(france_toussaint[:holiday_name])
+ expect(DiscourseEvents::Calendar::Event.pluck(:description)).not_to include(
+ france_assomption[:holiday_name],
+ )
+ expect(DiscourseEvents::Calendar::Event.pluck(:description)).not_to include(
+ france_toussaint[:holiday_name],
+ )
end
end
@@ -229,7 +241,7 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 8, 1)
job.execute(nil)
- calendar_event = CalendarEvent.first
+ calendar_event = DiscourseEvents::Calendar::Event.first
expect(calendar_event.region).to eq("fr")
expect(calendar_event.description).to eq("Assomption")
expect(calendar_event.start_date).to eq("2019-08-15T00:00:00+02:00")
@@ -248,7 +260,7 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
freeze_time Time.zone.local(2019, 8, 1)
job.execute(nil)
- calendar_event = CalendarEvent.first
+ calendar_event = DiscourseEvents::Calendar::Event.first
expect(calendar_event.region).to eq("fr")
expect(calendar_event.description).to eq("Assomption")
expect(calendar_event.start_date).to eq("2019-08-15T06:00:00+02:00")
@@ -261,13 +273,13 @@ describe Jobs::DiscourseCalendar::CreateHolidayEvents do
it "skips invalid regions and continues processing valid ones" do
frenchy
invalid_region_user =
- Fabricate(:user, custom_fields: { DiscourseCalendar::REGION_CUSTOM_FIELD => "invalid_xx" })
+ Fabricate(:user, custom_fields: { DiscourseEvents::REGION_CUSTOM_FIELD => "invalid_xx" })
freeze_time Time.zone.local(2019, 8, 1)
expect { job.execute(nil) }.not_to raise_error
- expect(CalendarEvent.where(user_id: frenchy.id).count).to be > 0
- expect(CalendarEvent.where(user_id: invalid_region_user.id).count).to eq(0)
+ expect(DiscourseEvents::Calendar::Event.where(user_id: frenchy.id).count).to be > 0
+ expect(DiscourseEvents::Calendar::Event.where(user_id: invalid_region_user.id).count).to eq(0)
end
end
diff --git a/plugins/discourse-events/spec/jobs/scheduled/delete_expired_event_posts_spec.rb b/plugins/discourse-events/spec/jobs/scheduled/delete_expired_event_posts_spec.rb
index 404be4ce577..5ae475e3e08 100644
--- a/plugins/discourse-events/spec/jobs/scheduled/delete_expired_event_posts_spec.rb
+++ b/plugins/discourse-events/spec/jobs/scheduled/delete_expired_event_posts_spec.rb
@@ -34,10 +34,10 @@ describe Jobs::DiscourseCalendar::DeleteExpiredEventPosts do
expect(Post.exists?(post_with_a_date_range.id)).to eq(false)
expect(Post.exists?(post_in_the_future.id)).to eq(true)
- expect(CalendarEvent.exists?(post: post_with_one_date)).to eq(false)
- expect(CalendarEvent.exists?(post: post_with_two_dates)).to eq(false)
- expect(CalendarEvent.exists?(post: post_with_a_date_range)).to eq(false)
- expect(CalendarEvent.exists?(post: post_in_the_future)).to eq(true)
+ expect(DiscourseEvents::Calendar::Event.exists?(post: post_with_one_date)).to eq(false)
+ expect(DiscourseEvents::Calendar::Event.exists?(post: post_with_two_dates)).to eq(false)
+ expect(DiscourseEvents::Calendar::Event.exists?(post: post_with_a_date_range)).to eq(false)
+ expect(DiscourseEvents::Calendar::Event.exists?(post: post_in_the_future)).to eq(true)
expect(UserHistory.find_by(post_id: post_with_one_date.id).context).to eq(
I18n.t("discourse_calendar.event_expired"),
@@ -46,7 +46,7 @@ describe Jobs::DiscourseCalendar::DeleteExpiredEventPosts do
it "does not delete holiday events" do
matariki =
- CalendarEvent.create!(
+ DiscourseEvents::Calendar::Event.create!(
topic: calendar_topic,
start_date: Date.new(2022, 6, 24),
region: "nz",
@@ -55,12 +55,16 @@ describe Jobs::DiscourseCalendar::DeleteExpiredEventPosts do
job.execute(nil)
- expect(CalendarEvent.exists?(matariki.id)).to eq(true)
+ expect(DiscourseEvents::Calendar::Event.exists?(matariki.id)).to eq(true)
end
it "does not delete event posts outside calendar topics" do
post = create_post(raw: "Discourse 💬 Launch 🚀 on [date=2013-02-05]")
- CalendarEvent.create!(topic: post.topic, post: post, start_date: Date.new(2013, 2, 5))
+ DiscourseEvents::Calendar::Event.create!(
+ topic: post.topic,
+ post: post,
+ start_date: Date.new(2013, 2, 5),
+ )
job.execute(nil)
diff --git a/plugins/discourse-events/spec/jobs/scheduled/update_holiday_usernames_spec.rb b/plugins/discourse-events/spec/jobs/scheduled/update_holiday_usernames_spec.rb
index cffa7a49a4d..b96bffa6b46 100644
--- a/plugins/discourse-events/spec/jobs/scheduled/update_holiday_usernames_spec.rb
+++ b/plugins/discourse-events/spec/jobs/scheduled/update_holiday_usernames_spec.rb
@@ -19,12 +19,12 @@ describe Jobs::DiscourseCalendar::UpdateHolidayUsernames do
job.execute(nil)
- expect(DiscourseCalendar.users_on_holiday).to eq([post.user.username])
+ expect(DiscourseEvents.users_on_holiday).to eq([post.user.username])
freeze_time Time.utc(2018, 6, 7, 18, 40)
job.execute(nil)
- expect(DiscourseCalendar.users_on_holiday).to eq([])
+ expect(DiscourseEvents.users_on_holiday).to eq([])
end
it "adds custom field to users on holiday" do
@@ -38,46 +38,28 @@ describe Jobs::DiscourseCalendar::UpdateHolidayUsernames do
job.execute(nil)
expect(
- UserCustomField.exists?(
- name: DiscourseCalendar::HOLIDAY_CUSTOM_FIELD,
- user_id: post1.user.id,
- ),
+ UserCustomField.exists?(name: DiscourseEvents::HOLIDAY_CUSTOM_FIELD, user_id: post1.user.id),
).to be_truthy
expect(
- UserCustomField.exists?(
- name: DiscourseCalendar::HOLIDAY_CUSTOM_FIELD,
- user_id: post2.user.id,
- ),
+ UserCustomField.exists?(name: DiscourseEvents::HOLIDAY_CUSTOM_FIELD, user_id: post2.user.id),
).to be_truthy
freeze_time Time.utc(2018, 6, 6, 10, 00)
job.execute(nil)
expect(
- UserCustomField.exists?(
- name: DiscourseCalendar::HOLIDAY_CUSTOM_FIELD,
- user_id: post1.user.id,
- ),
+ UserCustomField.exists?(name: DiscourseEvents::HOLIDAY_CUSTOM_FIELD, user_id: post1.user.id),
).to be_truthy
expect(
- UserCustomField.exists?(
- name: DiscourseCalendar::HOLIDAY_CUSTOM_FIELD,
- user_id: post2.user.id,
- ),
+ UserCustomField.exists?(name: DiscourseEvents::HOLIDAY_CUSTOM_FIELD, user_id: post2.user.id),
).to be_falsey
freeze_time Time.utc(2018, 6, 7, 10, 00)
job.execute(nil)
expect(
- UserCustomField.exists?(
- name: DiscourseCalendar::HOLIDAY_CUSTOM_FIELD,
- user_id: post1.user.id,
- ),
+ UserCustomField.exists?(name: DiscourseEvents::HOLIDAY_CUSTOM_FIELD, user_id: post1.user.id),
).to be_falsey
expect(
- UserCustomField.exists?(
- name: DiscourseCalendar::HOLIDAY_CUSTOM_FIELD,
- user_id: post2.user.id,
- ),
+ UserCustomField.exists?(name: DiscourseEvents::HOLIDAY_CUSTOM_FIELD, user_id: post2.user.id),
).to be_falsey
end
diff --git a/plugins/discourse-events/spec/lib/calendar_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/calendar/extractor_spec.rb
similarity index 86%
rename from plugins/discourse-events/spec/lib/calendar_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/calendar/extractor_spec.rb
index 71691a54824..806a64eb673 100644
--- a/plugins/discourse-events/spec/lib/calendar_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/calendar/extractor_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscourseCalendar::Calendar do
+describe DiscourseEvents::Calendar::Extractor do
before do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
@@ -10,7 +10,7 @@ describe DiscourseCalendar::Calendar do
let(:calendar_post) { create_post(raw: raw) }
it "defaults to dynamic" do
- expect(calendar_post.reload.custom_fields[DiscourseCalendar::CALENDAR_CUSTOM_FIELD]).to eq(
+ expect(calendar_post.reload.custom_fields[DiscourseEvents::CALENDAR_CUSTOM_FIELD]).to eq(
"dynamic",
)
end
@@ -22,7 +22,7 @@ describe DiscourseCalendar::Calendar do
raw: 'Rome [date="2018-06-05" timezone="Europe/Paris"]',
)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.description).to eq("Rome")
expect(calendar_event.start_date).to eq("2018-06-05T00:00:00+02:00")
expect(calendar_event.end_date).to eq(nil)
@@ -32,7 +32,7 @@ describe DiscourseCalendar::Calendar do
it "adds an entry with a single date/time event" do
post = create_post(topic: calendar_post.topic, raw: 'Rome [date="2018-06-05" time="12:34:56"]')
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.description).to eq("Rome")
expect(calendar_event.start_date).to eq("2018-06-05T12:34:56Z")
expect(calendar_event.end_date).to eq("2018-06-05T13:34:56Z")
@@ -47,7 +47,7 @@ describe DiscourseCalendar::Calendar do
'Rome [date="2018-06-05" timezone="Europe/Paris"] → [date="2018-06-08" timezone="Europe/Paris"]',
)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.description).to eq("Rome")
expect(calendar_event.start_date).to eq("2018-06-05T00:00:00+02:00")
expect(calendar_event.end_date).to eq("2018-06-08T00:00:00+02:00")
@@ -90,7 +90,7 @@ describe DiscourseCalendar::Calendar do
raw: 'Rome [date="2018-06-05" timezone="Europe/Paris"]',
)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.description).to eq("Rome")
expect(calendar_event.start_date).to eq("2018-06-05T07:00:00+02:00")
expect(calendar_event.end_date).to eq("2018-06-05T18:00:00+02:00")
@@ -101,7 +101,7 @@ describe DiscourseCalendar::Calendar do
post =
create_post(topic: calendar_post.topic, raw: 'Rome [date="2018-06-05" time="12:34:56"]')
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.description).to eq("Rome")
expect(calendar_event.start_date).to eq("2018-06-05T12:34:56Z")
expect(calendar_event.end_date).to eq("2018-06-05T13:34:56Z")
@@ -116,7 +116,7 @@ describe DiscourseCalendar::Calendar do
'Rome [date="2018-06-05" timezone="Europe/Paris"] → [date="2018-06-08" timezone="Europe/Paris"]',
)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.description).to eq("Rome")
expect(calendar_event.start_date).to eq("2018-06-05T07:00:00+02:00")
expect(calendar_event.end_date).to eq("2018-06-08T18:00:00+02:00")
diff --git a/plugins/discourse-events/spec/lib/calendar_custom_fields_validator_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/configuration/event_custom_fields_validator_spec.rb
similarity index 95%
rename from plugins/discourse-events/spec/lib/calendar_custom_fields_validator_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/configuration/event_custom_fields_validator_spec.rb
index ede9827475a..82b5694eda6 100644
--- a/plugins/discourse-events/spec/lib/calendar_custom_fields_validator_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/configuration/event_custom_fields_validator_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe CalendarCustomFieldsValidator do
+describe DiscourseEvents::Configuration::EventCustomFieldsValidator do
def expect_invalid(val)
expect(subject.valid_value?(val)).to eq(false)
expect(subject.error_message).to be_present
diff --git a/plugins/discourse-events/spec/lib/calendar_first_day_of_week_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/configuration/first_day_of_week_spec.rb
similarity index 100%
rename from plugins/discourse-events/spec/lib/calendar_first_day_of_week_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/configuration/first_day_of_week_spec.rb
diff --git a/plugins/discourse-events/spec/lib/calendar_settings_validator_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/configuration/time_of_day_validator_spec.rb
similarity index 89%
rename from plugins/discourse-events/spec/lib/calendar_settings_validator_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/configuration/time_of_day_validator_spec.rb
index 01ade405095..db09d787fb3 100644
--- a/plugins/discourse-events/spec/lib/calendar_settings_validator_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/configuration/time_of_day_validator_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe CalendarSettingsValidator do
+describe DiscourseEvents::Configuration::TimeOfDayValidator do
def expect_invalid(val)
expect(subject.valid_value?(val)).to eq(false)
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/chat_channel_sync_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/chat_channel_sync_spec.rb
similarity index 82%
rename from plugins/discourse-events/spec/services/discourse_post_event/chat_channel_sync_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/chat_channel_sync_spec.rb
index f75ecc35123..a93d590c78f 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/chat_channel_sync_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/chat_channel_sync_spec.rb
@@ -2,7 +2,7 @@
return if !defined?(Chat)
-describe DiscoursePostEvent::ChatChannelSync do
+describe DiscourseEvents::Events::ChatChannelSync do
fab!(:user)
fab!(:admin)
fab!(:admin_post) { Fabricate(:post, user: admin) }
@@ -15,7 +15,9 @@ describe DiscoursePostEvent::ChatChannelSync do
expect(event.chat_channel.user_chat_channel_memberships.count).to eq(1)
expect(event.chat_channel.user_chat_channel_memberships.first.user_id).to eq(admin.id)
- event.create_invitees([user_id: user.id, status: DiscoursePostEvent::Invitee.statuses[:going]])
+ event.create_invitees(
+ [user_id: user.id, status: DiscourseEvents::Events::Invitee.statuses[:going]],
+ )
event.save!
expect(event.chat_channel.user_chat_channel_memberships.count).to eq(2)
@@ -43,7 +45,7 @@ describe DiscoursePostEvent::ChatChannelSync do
it "does not add suspended users to the chat channel" do
event = Fabricate(:event, chat_enabled: true, post: admin_post, name: "Test Event")
event.create_invitees(
- [user_id: suspended_user.id, status: DiscoursePostEvent::Invitee.statuses[:going]],
+ [user_id: suspended_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going]],
)
event.save!
@@ -55,7 +57,7 @@ describe DiscoursePostEvent::ChatChannelSync do
it "does not add silenced users to the chat channel" do
event = Fabricate(:event, chat_enabled: true, post: admin_post, name: "Test Event")
event.create_invitees(
- [user_id: silenced_user.id, status: DiscoursePostEvent::Invitee.statuses[:going]],
+ [user_id: silenced_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going]],
)
event.save!
@@ -67,7 +69,7 @@ describe DiscoursePostEvent::ChatChannelSync do
it "does not add staged users to the chat channel" do
event = Fabricate(:event, chat_enabled: true, post: admin_post, name: "Test Event")
event.create_invitees(
- [user_id: staged_user.id, status: DiscoursePostEvent::Invitee.statuses[:going]],
+ [user_id: staged_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going]],
)
event.save!
@@ -79,7 +81,7 @@ describe DiscoursePostEvent::ChatChannelSync do
it "adds regular users to the chat channel" do
event = Fabricate(:event, chat_enabled: true, post: admin_post, name: "Test Event")
event.create_invitees(
- [user_id: regular_user.id, status: DiscoursePostEvent::Invitee.statuses[:going]],
+ [user_id: regular_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going]],
)
event.save!
@@ -92,7 +94,7 @@ describe DiscoursePostEvent::ChatChannelSync do
formerly_suspended = Fabricate(:user, suspended_till: 1.day.ago)
event = Fabricate(:event, chat_enabled: true, post: admin_post, name: "Test Event")
event.create_invitees(
- [user_id: formerly_suspended.id, status: DiscoursePostEvent::Invitee.statuses[:going]],
+ [user_id: formerly_suspended.id, status: DiscourseEvents::Events::Invitee.statuses[:going]],
)
event.save!
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/event_excerpt_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/excerpt_spec.rb
similarity index 98%
rename from plugins/discourse-events/spec/lib/discourse_post_event/event_excerpt_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/excerpt_spec.rb
index a82817a174b..4a77286b241 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/event_excerpt_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/excerpt_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::EventExcerpt do
+describe DiscourseEvents::Events::Excerpt do
def excerpt(post: nil, **attributes)
fragment = Nokogiri::HTML5.fragment(<<~HTML)
<p>intro</p>
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/event_finder_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/finder_spec.rb
similarity index 93%
rename from plugins/discourse-events/spec/lib/discourse_post_event/event_finder_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/finder_spec.rb
index 7c448b21613..d26211dcf61 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/event_finder_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/finder_spec.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::EventFinder do
+describe DiscourseEvents::Events::Finder do
fab!(:current_user, :user)
fab!(:user)
- subject(:finder) { DiscoursePostEvent::EventFinder }
+ subject(:finder) { DiscourseEvents::Events::Finder }
before do
Jobs.run_immediately!
@@ -15,37 +15,41 @@ describe DiscoursePostEvent::EventFinder do
describe "by attending user" do
fab!(:attending_user, :user)
fab!(:invited_group) { Fabricate(:group, users: [attending_user]) }
- fab!(:public_event) { Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public]) }
+ fab!(:public_event) do
+ Fabricate(:event, status: DiscourseEvents::Events::Event.statuses[:public])
+ end
fab!(:private_event) do
Fabricate(
:event,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [invited_group.name],
)
end
- fab!(:another_event) { Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public]) }
+ fab!(:another_event) do
+ Fabricate(:event, status: DiscourseEvents::Events::Event.statuses[:public])
+ end
fab!(:attending_public_event) do
- DiscoursePostEvent::Invitee.create!(
+ DiscourseEvents::Events::Invitee.create!(
user: attending_user,
event: public_event,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
)
end
fab!(:attending_private_event) do
- DiscoursePostEvent::Invitee.create!(
+ DiscourseEvents::Events::Invitee.create!(
user: attending_user,
event: private_event,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
)
end
fab!(:not_attending_event) do
- DiscoursePostEvent::Invitee.create!(
+ DiscourseEvents::Events::Invitee.create!(
user: attending_user,
event: another_event,
- status: DiscoursePostEvent::Invitee.statuses[:not_going],
+ status: DiscourseEvents::Events::Invitee.statuses[:not_going],
)
end
@@ -428,8 +432,8 @@ describe DiscoursePostEvent::EventFinder do
end
describe "by topic id" do
- fab!(:event_one) { Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public]) }
- fab!(:event_two) { Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public]) }
+ fab!(:event_one) { Fabricate(:event, status: DiscourseEvents::Events::Event.statuses[:public]) }
+ fab!(:event_two) { Fabricate(:event, status: DiscourseEvents::Events::Event.statuses[:public]) }
it "returns only the event in the given topic" do
expect(finder.search(current_user, { topic_id: event_one.post.topic_id })).to match_array(
@@ -443,7 +447,7 @@ describe DiscoursePostEvent::EventFinder do
context "with a closed event" do
fab!(:closed_event) do
- Fabricate(:event, status: DiscoursePostEvent::Event.statuses[:public], closed: true)
+ Fabricate(:event, status: DiscourseEvents::Events::Event.statuses[:public], closed: true)
end
it "excludes the closed event by default" do
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/guardian_extensions_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/guardian_extensions_spec.rb
similarity index 91%
rename from plugins/discourse-events/spec/lib/discourse_post_event/guardian_extensions_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/guardian_extensions_spec.rb
index 8351f4733e2..98be2f85ed8 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/guardian_extensions_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/guardian_extensions_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscoursePostEvent::GuardianExtensions do
+RSpec.describe DiscourseEvents::Events::GuardianExtensions do
fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
fab!(:other_user, :user)
fab!(:allowed_group) do
@@ -81,7 +81,7 @@ RSpec.describe DiscoursePostEvent::GuardianExtensions do
:invitee,
event: other_event,
user:,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
)
expect(guardian.can_act_on_invitee?(invitee)).to eq(true)
@@ -93,7 +93,7 @@ RSpec.describe DiscoursePostEvent::GuardianExtensions do
:invitee,
event: own_event,
user: other_user,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
)
expect(guardian.can_act_on_invitee?(invitee)).to eq(true)
@@ -107,7 +107,7 @@ RSpec.describe DiscoursePostEvent::GuardianExtensions do
end
it "allows an event manager to see invitee details for a private event" do
- own_event.update!(status: DiscoursePostEvent::Event.statuses[:private])
+ own_event.update!(status: DiscourseEvents::Events::Event.statuses[:private])
expect(guardian.can_display_invitee_details?(own_event)).to eq(true)
end
@@ -121,7 +121,7 @@ RSpec.describe DiscoursePostEvent::GuardianExtensions do
)
hidden_group.add(user)
other_event.update!(
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [hidden_group.name],
)
@@ -136,7 +136,7 @@ RSpec.describe DiscoursePostEvent::GuardianExtensions do
members_visibility_level: Group.visibility_levels[:public],
)
other_event.update!(
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [visible_group.name],
)
@@ -151,7 +151,7 @@ RSpec.describe DiscoursePostEvent::GuardianExtensions do
members_visibility_level: Group.visibility_levels[:owners],
)
other_event.update!(
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [hidden_group.name],
)
@@ -159,7 +159,10 @@ RSpec.describe DiscoursePostEvent::GuardianExtensions do
end
it "denies a user when a private event has no invited groups" do
- other_event.update!(status: DiscoursePostEvent::Event.statuses[:private], raw_invitees: [])
+ other_event.update!(
+ status: DiscourseEvents::Events::Event.statuses[:private],
+ raw_invitees: [],
+ )
expect(guardian.can_display_invitee_details?(other_event)).to eq(false)
end
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/event_onebox_data_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/onebox_data_spec.rb
similarity index 99%
rename from plugins/discourse-events/spec/lib/discourse_post_event/event_onebox_data_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/onebox_data_spec.rb
index fe116ee16de..ab927a2cfc8 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/event_onebox_data_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/onebox_data_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::EventOneboxData do
+describe DiscourseEvents::Events::OneboxData do
fab!(:author, :user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }
fab!(:reader, :user)
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/event_parser_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/parser_spec.rb
similarity index 99%
rename from plugins/discourse-events/spec/lib/discourse_post_event/event_parser_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/parser_spec.rb
index 629f76431c1..b552261b045 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/event_parser_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/parser_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::EventParser do
- subject(:parser) { DiscoursePostEvent::EventParser }
+describe DiscourseEvents::Events::Parser do
+ subject(:parser) { DiscourseEvents::Events::Parser }
let(:user) { Fabricate(:user) }
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/pretty_text_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/pretty_text_spec.rb
similarity index 98%
rename from plugins/discourse-events/spec/lib/discourse_post_event/pretty_text_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/pretty_text_spec.rb
index 19a33ac3cb7..656bab1adb4 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/pretty_text_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/pretty_text_spec.rb
@@ -298,10 +298,10 @@ describe PrettyText do
let(:post_1) { create_post_with_event(user_1, 'status="public"') }
it "displays the going count" do
- DiscoursePostEvent::Invitee.create!(
+ DiscourseEvents::Events::Invitee.create!(
post_id: post_1.id,
user_id: Fabricate(:user).id,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
)
cooked = PrettyText.cook(post_1.raw)
@@ -353,7 +353,7 @@ describe PrettyText do
it "does not abort the rest of the email rendering" do
cooked = PrettyText.cook(post_1.raw)
- DiscoursePostEvent::EmailRenderer.stubs(:render).raises(StandardError.new("boom"))
+ DiscourseEvents::Events::EmailRenderer.stubs(:render).raises(StandardError.new("boom"))
expect { PrettyText.format_for_email(cooked, post_1) }.not_to raise_error
end
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/rrule_configurator_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/rrule_configurator_spec.rb
similarity index 54%
rename from plugins/discourse-events/spec/lib/discourse_post_event/rrule_configurator_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/rrule_configurator_spec.rb
index b69602af22d..d4eff6983b6 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/rrule_configurator_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/rrule_configurator_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe RRuleConfigurator do
+describe DiscourseEvents::Events::RRuleConfigurator do
let(:time) { Time.now }
before { freeze_time Time.utc(2020, 8, 12, 16, 32) }
@@ -8,7 +8,8 @@ describe RRuleConfigurator do
describe ".rule" do
context "with every_day recurrence" do
it "generates the correct rule" do
- rule = RRuleConfigurator.rule(recurrence: "every_day", starts_at: time)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(recurrence: "every_day", starts_at: time)
expect(rule).to eq("FREQ=DAILY")
end
end
@@ -16,40 +17,64 @@ describe RRuleConfigurator do
context "with every_month recurrence" do
it "generates the correct rule for the second Wednesday of the month" do
# August 12, 2020 was the second Wednesday of the month
- rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: time)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_month",
+ starts_at: time,
+ )
expect(rule).to eq("FREQ=MONTHLY;BYDAY=2WE")
end
it "generates the correct rule for the first Monday of the month" do
first_monday = Time.utc(2020, 8, 3, 16, 32) # First Monday of August 2020
- rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: first_monday)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_month",
+ starts_at: first_monday,
+ )
expect(rule).to eq("FREQ=MONTHLY;BYDAY=1MO")
end
it "uses BYDAY=-1 when the start is the fifth (and final) Monday of the month" do
last_day = Time.utc(2020, 8, 31, 16, 32) # 5th and last Monday of August 2020
- rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: last_day)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_month",
+ starts_at: last_day,
+ )
expect(rule).to eq("FREQ=MONTHLY;BYDAY=-1MO")
end
it "uses BYDAY=4 when the fourth occurrence is also the last in the month" do
# February 2026 has only 4 Mondays (2, 9, 16, 23)
last_monday = Time.utc(2026, 2, 23, 12, 0)
- rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: last_monday)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_month",
+ starts_at: last_monday,
+ )
expect(rule).to eq("FREQ=MONTHLY;BYDAY=4MO")
end
it "uses BYDAY=4 when there is also a fifth occurrence in the month" do
# March 2027: 1, 8, 15, 22, 29 — 5 Mondays. The 4th Monday is Mar 22.
fourth_monday = Time.utc(2027, 3, 22, 12, 0)
- rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: fourth_monday)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_month",
+ starts_at: fourth_monday,
+ )
expect(rule).to eq("FREQ=MONTHLY;BYDAY=4MO")
end
it "keeps a fourth-weekday series on the fourth weekday in months with five" do
# Feb 26 2026 is both the 4th and the last Thursday of the month
fourth_thursday = Time.utc(2026, 2, 26, 17, 0)
- rule = RRuleConfigurator.rule(recurrence: "every_month", starts_at: fourth_thursday)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_month",
+ starts_at: fourth_thursday,
+ )
occurrences = RRule::Rule.new(rule, dtstart: fourth_thursday).all(limit: 3).map(&:to_date)
@@ -61,41 +86,62 @@ describe RRuleConfigurator do
context "with every_weekday recurrence" do
it "generates the correct rule" do
- rule = RRuleConfigurator.rule(recurrence: "every_weekday", starts_at: time)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_weekday",
+ starts_at: time,
+ )
expect(rule).to eq("FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR")
end
end
context "with every_two_weeks recurrence" do
it "generates the correct rule" do
- rule = RRuleConfigurator.rule(recurrence: "every_two_weeks", starts_at: time)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_two_weeks",
+ starts_at: time,
+ )
expect(rule).to eq("FREQ=WEEKLY;INTERVAL=2")
end
end
context "with every_four_weeks recurrence" do
it "generates the correct rule" do
- rule = RRuleConfigurator.rule(recurrence: "every_four_weeks", starts_at: time)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_four_weeks",
+ starts_at: time,
+ )
expect(rule).to eq("FREQ=WEEKLY;INTERVAL=4")
end
end
context "with every_week recurrence (default)" do
it "generates the correct rule" do
- rule = RRuleConfigurator.rule(recurrence: "every_week", starts_at: time)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(recurrence: "every_week", starts_at: time)
expect(rule).to eq("FREQ=WEEKLY;BYDAY=WE")
end
it "uses the day of the week from starts_at" do
monday = Time.utc(2020, 8, 10, 16, 32) # A Monday
- rule = RRuleConfigurator.rule(recurrence: "every_week", starts_at: monday)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_week",
+ starts_at: monday,
+ )
expect(rule).to eq("FREQ=WEEKLY;BYDAY=MO")
end
end
context "with an unknown recurrence" do
it "defaults to every_week" do
- rule = RRuleConfigurator.rule(recurrence: "invalid_recurrence", starts_at: time)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "invalid_recurrence",
+ starts_at: time,
+ )
expect(rule).to eq("FREQ=WEEKLY;BYDAY=WE")
end
end
@@ -103,7 +149,12 @@ describe RRuleConfigurator do
context "with a recurrence_until date" do
it "adds the UNTIL parameter to the rule" do
recurrence_until = Time.utc(2021, 8, 12, 16, 32)
- rule = RRuleConfigurator.rule(recurrence: "every_day", starts_at: time, recurrence_until:)
+ rule =
+ DiscourseEvents::Events::RRuleConfigurator.rule(
+ recurrence: "every_day",
+ starts_at: time,
+ recurrence_until:,
+ )
expect(rule).to eq("FREQ=DAILY;UNTIL=20210812T163200")
end
end
@@ -112,44 +163,66 @@ describe RRuleConfigurator do
describe ".how_many_recurring_events" do
context "when max_years is nil" do
it "returns 1" do
- expect(RRuleConfigurator.how_many_recurring_events(recurrence: "every_day")).to eq(1)
+ expect(
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence: "every_day",
+ ),
+ ).to eq(1)
end
end
context "when max_years is provided" do
it "returns the correct number for every_month" do
expect(
- RRuleConfigurator.how_many_recurring_events(recurrence: "every_month", max_years: 2),
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence: "every_month",
+ max_years: 2,
+ ),
).to eq(24)
end
it "returns the correct number for every_four_weeks" do
expect(
- RRuleConfigurator.how_many_recurring_events(recurrence: "every_four_weeks", max_years: 2),
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence: "every_four_weeks",
+ max_years: 2,
+ ),
).to eq(26)
end
it "returns the correct number for every_two_weeks" do
expect(
- RRuleConfigurator.how_many_recurring_events(recurrence: "every_two_weeks", max_years: 2),
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence: "every_two_weeks",
+ max_years: 2,
+ ),
).to eq(52)
end
it "returns the correct number for every_weekday" do
expect(
- RRuleConfigurator.how_many_recurring_events(recurrence: "every_weekday", max_years: 2),
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence: "every_weekday",
+ max_years: 2,
+ ),
).to eq(520)
end
it "returns the correct number for every_week" do
expect(
- RRuleConfigurator.how_many_recurring_events(recurrence: "every_week", max_years: 2),
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence: "every_week",
+ max_years: 2,
+ ),
).to eq(104)
end
it "returns the correct number for every_day" do
expect(
- RRuleConfigurator.how_many_recurring_events(recurrence: "every_day", max_years: 2),
+ DiscourseEvents::Events::RRuleConfigurator.how_many_recurring_events(
+ recurrence: "every_day",
+ max_years: 2,
+ ),
).to eq(730)
end
end
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/rrule_generator_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/rrule_generator_spec.rb
similarity index 68%
rename from plugins/discourse-events/spec/lib/discourse_post_event/rrule_generator_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/rrule_generator_spec.rb
index 9718899135b..4935be244d4 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/rrule_generator_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/rrule_generator_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe RRuleGenerator do
+describe DiscourseEvents::Events::RRuleGenerator do
let(:time) { Time.now }
before { freeze_time Time.utc(2020, 8, 12, 16, 32) }
@@ -10,7 +10,11 @@ describe RRuleGenerator do
let(:time) { Time.utc(2020, 8, 10, 16, 32) }
it "generates the rule" do
- rrule = RRuleGenerator.generate(starts_at: time, recurrence: "every_week").first
+ rrule =
+ DiscourseEvents::Events::RRuleGenerator.generate(
+ starts_at: time,
+ recurrence: "every_week",
+ ).first
expect(rrule.to_s).to eq("2020-08-17 16:32:00 UTC")
end
end
@@ -23,12 +27,17 @@ describe RRuleGenerator do
freeze_time DateTime.parse("2020-02-25 15:36")
- rrule = RRuleGenerator.generate(starts_at: time, timezone:, recurrence: "every_week").first
+ rrule =
+ DiscourseEvents::Events::RRuleGenerator.generate(
+ starts_at: time,
+ timezone:,
+ recurrence: "every_week",
+ ).first
expect(rrule.to_s).to eq("2020-02-29 16:36:00 +0100")
freeze_time DateTime.parse("2020-09-25 15:36")
- rrule = RRuleGenerator.generate(starts_at: time, timezone:).first
+ rrule = DiscourseEvents::Events::RRuleGenerator.generate(starts_at: time, timezone:).first
expect(rrule.to_s).to eq("2020-09-26 16:36:00 +0200")
end
end
@@ -38,7 +47,7 @@ describe RRuleGenerator do
time = Time.utc(2020, 1, 25, 15, 36)
rrule_string =
- RRuleGenerator.generate_string(
+ DiscourseEvents::Events::RRuleGenerator.generate_string(
starts_at: time,
recurrence: "every_week",
dtstart: time,
@@ -54,7 +63,7 @@ describe RRuleGenerator do
time = Time.utc(2020, 1, 25, 15, 36)
rrule_string =
- RRuleGenerator.generate_string(
+ DiscourseEvents::Events::RRuleGenerator.generate_string(
starts_at: time,
recurrence: "every_week",
dtstart: time,
@@ -70,7 +79,14 @@ describe RRuleGenerator do
describe "every day" do
context "when a rule and time are given" do
it "generates the rule" do
- rrule = RRuleGenerator.generate(starts_at: time, recurrence: "every_day", max_years: 1)[1]
+ rrule =
+ DiscourseEvents::Events::RRuleGenerator.generate(
+ starts_at: time,
+ recurrence: "every_day",
+ max_years: 1,
+ )[
+ 1
+ ]
expect(rrule.to_s).to eq("2020-08-13 16:32:00 UTC")
end
@@ -78,7 +94,11 @@ describe RRuleGenerator do
let(:time) { Time.utc(2020, 8, 10, 16, 32) }
it "returns the next valid after given time and in the future" do
- rrule = RRuleGenerator.generate(starts_at: time, recurrence: "every_day").first
+ rrule =
+ DiscourseEvents::Events::RRuleGenerator.generate(
+ starts_at: time,
+ recurrence: "every_day",
+ ).first
expect(rrule.to_s).to eq("2020-08-12 16:32:00 UTC")
end
end
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/topic_extension_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/topic_extension_spec.rb
similarity index 99%
rename from plugins/discourse-events/spec/lib/discourse_post_event/topic_extension_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/events/topic_extension_spec.rb
index 19141cfaf78..a4f084e75de 100644
--- a/plugins/discourse-events/spec/lib/discourse_post_event/topic_extension_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/events/topic_extension_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::TopicExtension do
+describe DiscourseEvents::Events::TopicExtension do
before do
freeze_time
Jobs.run_immediately!
diff --git a/plugins/discourse-events/spec/lib/group_timezones_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/group_timezones/extractor_spec.rb
similarity index 92%
rename from plugins/discourse-events/spec/lib/group_timezones_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/group_timezones/extractor_spec.rb
index 0a3cf874f29..d8adb2ae674 100644
--- a/plugins/discourse-events/spec/lib/group_timezones_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/group_timezones/extractor_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscourseCalendar::GroupTimezones do
+describe DiscourseEvents::GroupTimezones::Extractor do
before do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
diff --git a/plugins/discourse-events/spec/lib/discourse_events/holidays/finder_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/holidays/finder_spec.rb
new file mode 100644
index 00000000000..b412b278a51
--- /dev/null
+++ b/plugins/discourse-events/spec/lib/discourse_events/holidays/finder_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Holidays
+ describe Finder do
+ describe ".find_holidays_for" do
+ before { DisabledHoliday.create!(holiday_name: "Saudi National Day", region_code: "sa") }
+
+ let(:holidays) do
+ Finder.find_holidays_for(
+ region_code: "sa",
+ start_date: "2023-02-21",
+ end_date: "2023-09-23",
+ )
+ end
+
+ it "returns a list of holidays indicating whether a holiday is disabled or not" do
+ expect(holidays).to include(
+ a_hash_including({ name: "Saudi National Day", regions: [:sa], disabled: true }),
+ )
+
+ expect(holidays).to include(
+ a_hash_including({ name: "Foundation Day", regions: [:sa], disabled: false }),
+ )
+ end
+
+ describe "dates holidays are observed on" do
+ let(:holidays) do
+ Finder.find_holidays_for(
+ region_code: "sg",
+ start_date: "2021-12-31",
+ end_date: "2022-05-31",
+ show_holiday_observed_on_dates: show_holiday_observed_on_dates,
+ )
+ end
+
+ context "when `show_holiday_observed_on_dates` is set to true" do
+ let(:show_holiday_observed_on_dates) { true }
+
+ it "returns the holidays with the date the holidays are observed on" do
+ expect(holidays).to include(
+ a_hash_including(
+ { name: "New Year's Day", date: Date.new(2021, 12, 31), regions: [:sg] },
+ ),
+ )
+
+ expect(holidays).to include(
+ a_hash_including(
+ { name: "Labour Day", date: Date.new(2022, 5, 2), regions: [:sg] },
+ ),
+ )
+ end
+ end
+
+ context "when `show_holiday_observed_on_dates` is set to false" do
+ let(:show_holiday_observed_on_dates) { false }
+
+ it "returns the holidays with the actual holiday dates" do
+ expect(holidays).to include(
+ a_hash_including(
+ { name: "New Year's Day", date: Date.new(2022, 1, 1), regions: [:sg] },
+ ),
+ )
+
+ expect(holidays).to include(
+ a_hash_including(
+ { name: "Labour Day", date: Date.new(2022, 5, 1), regions: [:sg] },
+ ),
+ )
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/spec/lib/users_on_holiday_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/holidays/users_on_holiday_spec.rb
similarity index 86%
rename from plugins/discourse-events/spec/lib/users_on_holiday_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/holidays/users_on_holiday_spec.rb
index 6b69e1a3cdd..58d044a59d1 100644
--- a/plugins/discourse-events/spec/lib/users_on_holiday_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/holidays/users_on_holiday_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscourseCalendar::UsersOnHoliday do
+describe DiscourseEvents::Holidays::UsersOnHoliday do
it "returns users on holiday" do
event1 = Fabricate(:calendar_event, start_date: "2000-01-01")
event2 = Fabricate(:calendar_event, start_date: "2000-01-01")
@@ -8,7 +8,8 @@ describe DiscourseCalendar::UsersOnHoliday do
event4 = Fabricate(:calendar_event, start_date: "2000-01-02")
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2, event3, event4])
+ users_on_holiday =
+ DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2, event3, event4])
usernames = users_on_holiday.values.map { |u| u[:username] }
expect(usernames).to contain_exactly(event1.username, event2.username, event3.username)
@@ -21,7 +22,8 @@ describe DiscourseCalendar::UsersOnHoliday do
event4 = Fabricate(:calendar_event, start_date: "2000-01-05")
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2, event3, event4])
+ users_on_holiday =
+ DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2, event3, event4])
expect(users_on_holiday).to be_empty
end
@@ -32,7 +34,7 @@ describe DiscourseCalendar::UsersOnHoliday do
event3 = Fabricate(:calendar_event, start_date: "2000-01-01", username: nil)
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2, event3])
+ users_on_holiday = DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2, event3])
usernames = users_on_holiday.values.map { |u| u[:username] }
expect(usernames).to contain_exactly(event1.username, event2.username)
@@ -45,7 +47,8 @@ describe DiscourseCalendar::UsersOnHoliday do
event4 = Fabricate(:calendar_event, start_date: "2000-01-05")
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2, event3, event4])
+ users_on_holiday =
+ DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2, event3, event4])
expect(users_on_holiday).to be_empty
end
@@ -67,7 +70,7 @@ describe DiscourseCalendar::UsersOnHoliday do
Fabricate(:calendar_event, user: user, start_date: "2000-01-01", end_date: biggest_end_date)
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2, event3])
+ users_on_holiday = DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2, event3])
expect(users_on_holiday.length).to be(1)
expect(users_on_holiday.values[0][:ends_at]).to eq(biggest_end_date)
@@ -86,7 +89,7 @@ describe DiscourseCalendar::UsersOnHoliday do
Fabricate(:calendar_event, user: user, start_date: "2000-01-04", end_date: "2000-01-05")
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2])
+ users_on_holiday = DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2])
expect(users_on_holiday.length).to be(1)
expect(users_on_holiday.values[0][:ends_at]).to eq(biggest_end_date)
@@ -117,7 +120,8 @@ describe DiscourseCalendar::UsersOnHoliday do
Fabricate(:calendar_event, user: user, start_date: "2000-01-08", end_date: "2000-01-10")
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2, event3, event4])
+ users_on_holiday =
+ DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2, event3, event4])
expect(users_on_holiday.length).to be(1)
expect(users_on_holiday.values[0][:ends_at]).to eq(farthest_end_date)
@@ -158,7 +162,8 @@ describe DiscourseCalendar::UsersOnHoliday do
Fabricate(:calendar_event, user: user, start_date: "2000-01-08", end_date: "2000-01-10")
freeze_time Time.utc(2000, 1, 1, 8, 0)
- users_on_holiday = DiscourseCalendar::UsersOnHoliday.from([event1, event2, event3, event4])
+ users_on_holiday =
+ DiscourseEvents::Holidays::UsersOnHoliday.from([event1, event2, event3, event4])
expect(users_on_holiday.length).to be(1)
expect(users_on_holiday.values[0][:ends_at]).to eq(farthest_end_date)
diff --git a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/allowed_hosts_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/livestream/allowed_hosts_spec.rb
similarity index 98%
rename from plugins/discourse-events/spec/lib/discourse_calendar/livestream/allowed_hosts_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/livestream/allowed_hosts_spec.rb
index 638d6884e9a..368389835d5 100644
--- a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/allowed_hosts_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/livestream/allowed_hosts_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseCalendar::Livestream::AllowedHosts do
+RSpec.describe DiscourseEvents::Livestream::AllowedHosts do
describe ".allows_url?" do
it "accepts a host on the default list and its subdomains" do
expect(described_class.allows_url?("https://www.youtube.com/watch?v=abc")).to eq(true)
diff --git a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/allowed_hosts_validator_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/livestream/allowed_hosts_validator_spec.rb
similarity index 95%
rename from plugins/discourse-events/spec/lib/discourse_calendar/livestream/allowed_hosts_validator_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/livestream/allowed_hosts_validator_spec.rb
index a4c8d3c5a02..43e846e3c40 100644
--- a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/allowed_hosts_validator_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/livestream/allowed_hosts_validator_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseCalendar::Livestream::AllowedHostsValidator do
+RSpec.describe DiscourseEvents::Livestream::AllowedHostsValidator do
subject(:validator) { described_class.new }
it "accepts bare hosts" do
diff --git a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/handle_topic_chat_channel_creation_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/livestream/handle_topic_chat_channel_creation_spec.rb
similarity index 86%
rename from plugins/discourse-events/spec/lib/discourse_calendar/livestream/handle_topic_chat_channel_creation_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/livestream/handle_topic_chat_channel_creation_spec.rb
index d48a4b42b77..5175a910889 100644
--- a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/handle_topic_chat_channel_creation_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/livestream/handle_topic_chat_channel_creation_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseCalendar::Livestream do
+RSpec.describe DiscourseEvents::Livestream do
describe ".handle_topic_chat_channel_creation" do
let(:topic) { Fabricate(:topic) }
@@ -55,8 +55,8 @@ RSpec.describe DiscourseCalendar::Livestream do
it "creates a topic chat channel" do
described_class.handle_topic_chat_channel_creation(topic)
- expect(DiscourseCalendar::Livestream::TopicChatChannel.count).to eq(1)
- expect(DiscourseCalendar::Livestream::TopicChatChannel.first.topic).to eq(topic)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.count).to eq(1)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.first.topic).to eq(topic)
end
it "creates a user chat channel membership for the topic creator" do
@@ -73,22 +73,22 @@ RSpec.describe DiscourseCalendar::Livestream do
topic.destroy!
expect(Chat::Channel.count).to eq(0)
- expect(DiscourseCalendar::Livestream::TopicChatChannel.count).to eq(0)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.count).to eq(0)
end
it "deletes the topic chat channel when the chat channel is destroyed" do
described_class.handle_topic_chat_channel_creation(topic)
- expect(DiscourseCalendar::Livestream::TopicChatChannel.count).to eq(1)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.count).to eq(1)
Chat::Channel.first.destroy!
- expect(DiscourseCalendar::Livestream::TopicChatChannel.count).to eq(0)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.count).to eq(0)
end
it "deletes the topic chat channel when the chat channel is soft deleted" do
described_class.handle_topic_chat_channel_creation(topic)
- expect(DiscourseCalendar::Livestream::TopicChatChannel.count).to eq(1)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.count).to eq(1)
expect(Chat::Channel.count).to eq(1)
chat_channel = Chat::Channel.first
@@ -99,15 +99,15 @@ RSpec.describe DiscourseCalendar::Livestream do
},
)
expect(chat_channel.reload).to be_trashed
- expect(DiscourseCalendar::Livestream::TopicChatChannel.count).to eq(0)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.count).to eq(0)
end
it "deletes the chat channel when topic chat channel is destroyed" do
described_class.handle_topic_chat_channel_creation(topic)
- expect(DiscourseCalendar::Livestream::TopicChatChannel.count).to eq(1)
+ expect(DiscourseEvents::Livestream::TopicChatChannel.count).to eq(1)
- DiscourseCalendar::Livestream::TopicChatChannel.first.destroy!
+ DiscourseEvents::Livestream::TopicChatChannel.first.destroy!
expect(Chat::Channel.count).to eq(0)
end
@@ -120,7 +120,7 @@ RSpec.describe DiscourseCalendar::Livestream do
expect(message.message).to include(topic.title)
expect(message.message).to include(topic.relative_url)
expect(Chat::PinnedMessage.where(chat_message: message, chat_channel: channel)).to exist
- expect(DiscourseCalendar::Livestream::TopicChatChannel.first.reference_message_id).to eq(
+ expect(DiscourseEvents::Livestream::TopicChatChannel.first.reference_message_id).to eq(
message.id,
)
end
diff --git a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/zoom_url_parser_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/livestream/zoom_url_parser_spec.rb
similarity index 97%
rename from plugins/discourse-events/spec/lib/discourse_calendar/livestream/zoom_url_parser_spec.rb
rename to plugins/discourse-events/spec/lib/discourse_events/livestream/zoom_url_parser_spec.rb
index 6c0d9dd8208..a2400c7d8c2 100644
--- a/plugins/discourse-events/spec/lib/discourse_calendar/livestream/zoom_url_parser_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/livestream/zoom_url_parser_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseCalendar::Livestream::ZoomUrlParser do
+RSpec.describe DiscourseEvents::Livestream::ZoomUrlParser do
describe ".parse" do
it "parses a standard Zoom meeting URL" do
result = described_class.parse("https://us06web.zoom.us/j/123456789?pwd=secret")
diff --git a/plugins/discourse-events/spec/lib/discourse_post_event/time_sniffer_spec.rb b/plugins/discourse-events/spec/lib/discourse_post_event/time_sniffer_spec.rb
deleted file mode 100644
index 376e929cc4f..00000000000
--- a/plugins/discourse-events/spec/lib/discourse_post_event/time_sniffer_spec.rb
+++ /dev/null
@@ -1,180 +0,0 @@
-# frozen_string_literal: true
-
-describe TimeSniffer do
- before { freeze_time DateTime.parse("2020-04-24 14:10") }
-
- let(:default_context) do
- {
- at: DateTime.parse("2020-1-20 00:00:00"),
- timezone: "EST",
- date_order: :sane,
- matchers: %i[tomorrow date time],
- raise_errors: true,
- }
- end
-
- define_method(:expect_parsed_as_interval) do |str, from:, to:, context: default_context|
- Time.use_zone(context[:timezone]) do
- expect(TimeSniffer.new(str, **context).sniff).to(
- eq(TimeSniffer::Interval.new(Time.zone.parse(from), Time.zone.parse(to))),
- )
- end
- end
-
- define_method(:expect_parsed_as_event) do |str, at, context: default_context|
- Time.use_zone(context[:timezone]) do
- expect(TimeSniffer.new(str, **context).sniff).to(
- eq(TimeSniffer::Event.new(Time.zone.parse(at))),
- )
- end
- end
-
- define_method(:expect_parsed_as_nil) do |str, context: default_context|
- expect(TimeSniffer.new(str, **context).sniff).to(eq(nil))
- end
-
- it "should support tomorrow with a timezone" do
- expect_parsed_as_interval("tomorrow", from: "2020-1-21 EST", to: "2020-1-22 EST")
- end
-
- it "should support Tomorrow" do
- expect_parsed_as_interval("Tomorrow", from: "2020-1-21", to: "2020-1-22")
- end
-
- it "should support 14:00" do
- expect_parsed_as_event("14:00", "2020-1-20 14:00 EST")
- end
-
- it "should support 14:24" do
- expect_parsed_as_event("14:24", "2020-1-20 14:24 EST")
- end
-
- it "should support 15:00 with emojis" do
- expect_parsed_as_event("😊😊😊😊15:00😊😊😊😊", "2020-1-20 15:00 EST")
- end
-
- it "should support 14:00 - 15:00" do
- expect_parsed_as_interval(
- "14:00 - 15:00",
- from: "2020-1-20 14:00 EST",
- to: "2020-1-20 15:00 EST",
- )
- end
-
- it "should support too many times" do
- expect_parsed_as_interval(
- "14:00 - 15:00 asotuhosthu 16:00",
- from: "2020-1-20 14:00 EST",
- to: "2020-1-20 15:00 EST",
- )
- end
-
- it "should support too many times" do
- expect_parsed_as_interval(
- "14:00 - 15:00 asotuhosthu 16:00",
- from: "2020-1-20 14:00 EST",
- to: "2020-1-20 15:00 EST",
- )
- end
-
- it "should support a date" do
- expect_parsed_as_interval("31/3/25", from: "2025-3-31 00:00 EST", to: "2025-4-1 00:00 EST")
- end
-
- it "should support a date in the past century" do
- expect_parsed_as_interval("31/3/75", from: "1975-3-31 00:00 EST", to: "1975-4-1 00:00 EST")
- end
-
- it "should support a date with a year with 4 digits" do
- expect_parsed_as_interval("31/3/2021", from: "2021-3-31 00:00 EST", to: "2021-4-1 00:00 EST")
- end
-
- it "should support a date with hyphens" do
- expect_parsed_as_interval("31-3-25", from: "2025-3-31 00:00 EST", to: "2025-4-1 00:00 EST")
- end
-
- it "should support a date with a time" do
- expect_parsed_as_event("31-3-25 08:00", "2025-3-31 08:00 EST")
- end
-
- it "should support a date with a time with non-zero minutes" do
- expect_parsed_as_event("31-3-25 08:45", "2025-3-31 08:45 EST")
- end
-
- it "should support a date with a time and a timezone" do
- expect_parsed_as_event(
- "31-3-25 08:00 UTC",
- "2025-3-31 08:00:00 UTC",
- context: default_context.merge(timezone: "EST"),
- )
- end
-
- it "should support a date with a time and a timezone" do
- expect_parsed_as_event(
- "31-3-25 08:00UTC",
- "2025-3-31 08:00:00 UTC",
- context: default_context.merge(timezone: "EST"),
- )
- end
-
- it "should support a date with a time and a timezone" do
- expect_parsed_as_event(
- "31-3-25 08:00Z",
- "2025-3-31 08:00:00 UTC",
- context: default_context.merge(timezone: "EST"),
- )
- end
-
- it "should support a date range" do
- expect_parsed_as_interval(
- "25/2/21 - 10/3/22",
- from: "2021-2-25 00:00 EST",
- to: "2022-3-11 00:00 EST",
- )
- end
-
- it "should support a date range" do
- expect_parsed_as_interval(
- "25/2/21 - 10/3/22 14:00",
- from: "2021-2-25 00:00 EST",
- to: "2022-3-10 14:00 EST",
- )
- end
-
- it "should support a date range with two times" do
- expect_parsed_as_interval(
- "25/2/21 9:00 - 10/3/22 14:00",
- from: "2021-2-25 09:00 EST",
- to: "2022-3-10 14:00 EST",
- )
- end
-
- it "should support a date range with two times where the second is relative to the first" do
- expect_parsed_as_interval(
- "25/2/21 9:00 - 14:00",
- from: "2021-2-25 09:00 EST",
- to: "2021-2-25 14:00 EST",
- )
- end
-
- it "should correctly handle timezones in future" do
- expect_parsed_as_event(
- "24/06/2020 14:23",
- "2020-06-24 14:23 CEST",
- context: default_context.merge(timezone: "Europe/Paris"),
- )
- end
-
- it "should not find a time in a random number" do
- expect_parsed_as_nil("1500")
- end
-
- it "should not find a time in random numbers and an emoji" do
- expect_parsed_as_nil("15😊00")
- end
-
- it "shouldn't match a date starting with the year" do
- expect_parsed_as_nil("2020-03-27")
- expect_parsed_as_nil("foo 2020-03-27")
- end
-end
diff --git a/plugins/discourse-events/spec/migrations/update_upload_reference_target_type_for_events_spec.rb b/plugins/discourse-events/spec/migrations/update_upload_reference_target_type_for_events_spec.rb
new file mode 100644
index 00000000000..c3c86ae8763
--- /dev/null
+++ b/plugins/discourse-events/spec/migrations/update_upload_reference_target_type_for_events_spec.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+require Rails.root.join(
+ "plugins/discourse-events/db/post_migrate/20260819131113_update_upload_reference_target_type_for_events.rb",
+ )
+
+RSpec.describe UpdateUploadReferenceTargetTypeForEvents do
+ subject(:migrate) { described_class.new.up }
+
+ fab!(:upload)
+ fab!(:other_upload, :upload)
+ fab!(:event) { Fabricate(:event, post: Fabricate(:post)) }
+
+ before do
+ @original_verbose = ActiveRecord::Migration.verbose
+ ActiveRecord::Migration.verbose = false
+ UploadReference.delete_all
+ end
+
+ after { ActiveRecord::Migration.verbose = @original_verbose }
+
+ def reference(upload_id:, target_type:, target_id:)
+ UploadReference.insert_all(
+ [
+ {
+ upload_id:,
+ target_type:,
+ target_id:,
+ created_at: Time.zone.now,
+ updated_at: Time.zone.now,
+ },
+ ],
+ )
+ end
+
+ def target_types_for(upload_id)
+ UploadReference.where(upload_id:).pluck(:target_type)
+ end
+
+ it "moves references onto the renamed model" do
+ reference(upload_id: upload.id, target_type: "DiscoursePostEvent::Event", target_id: event.id)
+
+ migrate
+
+ expect(target_types_for(upload.id)).to eq(["DiscourseEvents::Events::Event"])
+ end
+
+ it "leaves references belonging to other models alone" do
+ reference(upload_id: upload.id, target_type: "Post", target_id: event.id)
+
+ migrate
+
+ expect(target_types_for(upload.id)).to eq(["Post"])
+ end
+
+ it "keeps a stale row that has no renamed counterpart for that upload" do
+ reference(upload_id: upload.id, target_type: "DiscoursePostEvent::Event", target_id: event.id)
+ reference(
+ upload_id: other_upload.id,
+ target_type: "DiscourseEvents::Events::Event",
+ target_id: event.id,
+ )
+
+ migrate
+
+ expect(target_types_for(upload.id)).to eq(["DiscourseEvents::Events::Event"])
+ expect(target_types_for(other_upload.id)).to eq(["DiscourseEvents::Events::Event"])
+ end
+
+ it "reconnects the association the model reads" do
+ reference(upload_id: upload.id, target_type: "DiscoursePostEvent::Event", target_id: event.id)
+
+ expect(event.reload.upload_references).to be_empty
+
+ migrate
+
+ expect(event.reload.upload_references.pluck(:upload_id)).to eq([upload.id])
+ end
+end
diff --git a/plugins/discourse-events/spec/models/calendar_event_spec.rb b/plugins/discourse-events/spec/models/discourse_events/calendar/event_spec.rb
similarity index 84%
rename from plugins/discourse-events/spec/models/calendar_event_spec.rb
rename to plugins/discourse-events/spec/models/discourse_events/calendar/event_spec.rb
index 4ebf95265b6..f0766adb2ab 100644
--- a/plugins/discourse-events/spec/models/calendar_event_spec.rb
+++ b/plugins/discourse-events/spec/models/discourse_events/calendar/event_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe CalendarEvent do
+describe DiscourseEvents::Calendar::Event do
let(:calendar_post) { create_post(raw: "[calendar]\n[/calendar]") }
before do
@@ -14,7 +14,7 @@ describe CalendarEvent do
raw = %{Rome [date="2018-06-05" time="10:20:00"]}
post = create_post(raw: raw, topic: calendar_post.topic)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.topic_id).to eq(calendar_post.topic_id)
expect(calendar_event.description).to eq("Rome")
expect(calendar_event.start_date).to eq("2018-06-05T10:20:00Z")
@@ -26,19 +26,19 @@ describe CalendarEvent do
raw = %{Rome [date="2018-06-05" time="10:20:00"]}
post = create_post(raw: raw, topic: calendar_post.topic)
- expect(CalendarEvent.find_by(post_id: post.id)).to be_present
+ expect(DiscourseEvents::Calendar::Event.find_by(post_id: post.id)).to be_present
post.update(raw: "Not sure about the dates anymore")
CookedPostProcessor.new(post).post_process
- expect(CalendarEvent.find_by(post_id: post.id)).not_to be_present
+ expect(DiscourseEvents::Calendar::Event.find_by(post_id: post.id)).not_to be_present
end
it "works with no time date" do
raw = %{Rome [date="2018-06-05"] [date="2018-06-11"]}
post = create_post(raw: raw, topic: calendar_post.topic)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.start_date).to eq("2018-06-05T00:00:00Z")
expect(calendar_event.end_date).to eq("2018-06-11T00:00:00Z")
end
@@ -48,7 +48,7 @@ describe CalendarEvent do
%{Rome [date="2018-06-05" timezone="Europe/Paris"] [date="2018-06-11" time="13:45:33" timezone="America/Los_Angeles"]}
post = create_post(raw: raw, topic: calendar_post.topic)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.start_date).to eq("2018-06-05T00:00:00+02:00")
expect(calendar_event.end_date).to eq("2018-06-11T13:45:33-07:00")
end
@@ -76,7 +76,7 @@ describe CalendarEvent do
)
}.to raise_error(StandardError, /Whispers can.t be used to create calendar events/)
- expect(CalendarEvent.where(topic_id: calendar_post.topic_id)).to be_empty
+ expect(DiscourseEvents::Calendar::Event.where(topic_id: calendar_post.topic_id)).to be_empty
end
it "does not allow whispers to be edited into calendar events" do
@@ -97,7 +97,7 @@ describe CalendarEvent do
/Whispers can.t be used to create calendar events/,
)
- expect(CalendarEvent.where(topic_id: calendar_post.topic_id)).to be_empty
+ expect(DiscourseEvents::Calendar::Event.where(topic_id: calendar_post.topic_id)).to be_empty
end
it "does not work if topic was deleted" do
@@ -113,13 +113,13 @@ describe CalendarEvent do
it "recreates calendar event for all posts" do
post = create_post(raw: 'Rome [date="2018-06-05" time="10:20:00"]', topic: calendar_post.topic)
- expect(CalendarEvent.count).to eq(1)
+ expect(DiscourseEvents::Calendar::Event.count).to eq(1)
PostDestroyer.new(Discourse.system_user, calendar_post.reload, context: "spec").destroy
- expect(CalendarEvent.count).to eq(0)
+ expect(DiscourseEvents::Calendar::Event.count).to eq(0)
PostDestroyer.new(Discourse.system_user, calendar_post.reload, context: "spec").recover
- expect(CalendarEvent.count).to eq(1)
+ expect(DiscourseEvents::Calendar::Event.count).to eq(1)
end
describe "all day event site settings" do
@@ -132,7 +132,7 @@ describe CalendarEvent do
raw = %{Rome [date="2018-06-05"] [date="2018-06-11"]}
post = create_post(raw: raw, topic: calendar_post.topic)
- calendar_event = CalendarEvent.find_by(post_id: post.id)
+ calendar_event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(calendar_event.start_date).to eq("2018-06-05T06:30:00Z")
expect(calendar_event.end_date).to eq("2018-06-11T18:00:00Z")
end
@@ -142,7 +142,7 @@ describe CalendarEvent do
%{Rome [date="2018-06-05" timezone="Europe/Paris"] [date="2018-06-11" time="13:45:33" timezone="America/Los_Angeles"]}
post = create_post(raw: raw, topic: calendar_post.topic)
- event = CalendarEvent.find_by(post_id: post.id)
+ event = DiscourseEvents::Calendar::Event.find_by(post_id: post.id)
expect(event.start_date).to eq("2018-06-05T06:30:00+02:00")
expect(event.end_date).to eq("2018-06-11T13:45:33-07:00")
end
@@ -185,11 +185,11 @@ describe CalendarEvent do
it "removes event when a post is deleted" do
post = create_post(raw: %{Some Event [date="2019-09-10"]}, topic: calendar_post.topic)
- expect(CalendarEvent.find_by(post_id: post.id)).to be_present
+ expect(DiscourseEvents::Calendar::Event.find_by(post_id: post.id)).to be_present
PostDestroyer.new(Discourse.system_user, post, context: "spec").destroy
- expect(CalendarEvent.find_by(post_id: post.id)).to_not be_present
+ expect(DiscourseEvents::Calendar::Event.find_by(post_id: post.id)).to_not be_present
end
it "works for events belonging to deleted users" do
@@ -200,7 +200,7 @@ describe CalendarEvent do
# Holiday events are not associated with a user post
event =
- CalendarEvent.create!(
+ DiscourseEvents::Calendar::Event.create!(
topic_id: topic.id,
user_id: user.id,
start_date: 1.day.ago,
diff --git a/plugins/discourse-events/spec/models/discourse_post_event/event_date_spec.rb b/plugins/discourse-events/spec/models/discourse_events/events/event_date_spec.rb
similarity index 92%
rename from plugins/discourse-events/spec/models/discourse_post_event/event_date_spec.rb
rename to plugins/discourse-events/spec/models/discourse_events/events/event_date_spec.rb
index 3a04a15afee..cb1badab4b4 100644
--- a/plugins/discourse-events/spec/models/discourse_post_event/event_date_spec.rb
+++ b/plugins/discourse-events/spec/models/discourse_events/events/event_date_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::EventDate do
+describe DiscourseEvents::Events::EventDate do
let(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }
let(:topic) { Fabricate(:topic, user: user) }
let!(:first_post) { Fabricate(:post, topic: topic) }
@@ -50,7 +50,7 @@ describe DiscoursePostEvent::EventDate do
custom_field =
TopicCustomField.find_by(
topic_id: all_day_post.topic_id,
- name: DiscoursePostEvent::TOPIC_POST_EVENT_ALL_DAY,
+ name: DiscourseEvents::Events::TOPIC_POST_EVENT_ALL_DAY,
)
expect(custom_field).to be_present
@@ -61,7 +61,7 @@ describe DiscoursePostEvent::EventDate do
custom_field =
TopicCustomField.find_by(
topic_id: first_post.topic_id,
- name: DiscoursePostEvent::TOPIC_POST_EVENT_ALL_DAY,
+ name: DiscourseEvents::Events::TOPIC_POST_EVENT_ALL_DAY,
)
expect(custom_field).to be_present
diff --git a/plugins/discourse-events/spec/models/discourse_post_event/event_spec.rb b/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb
similarity index 88%
rename from plugins/discourse-events/spec/models/discourse_post_event/event_spec.rb
rename to plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb
index 37670201f77..0cfcecc8b92 100644
--- a/plugins/discourse-events/spec/models/discourse_post_event/event_spec.rb
+++ b/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::Event do
+describe DiscourseEvents::Events::Event do
before do
freeze_time DateTime.parse("2020-04-24 14:10")
Jobs.run_immediately!
@@ -10,14 +10,14 @@ describe DiscoursePostEvent::Event do
it do
is_expected.to validate_length_of(:description).is_at_most(
- DiscoursePostEvent::Event::MAX_DESCRIPTION_LENGTH,
+ DiscourseEvents::Events::Event::MAX_DESCRIPTION_LENGTH,
)
end
it do
is_expected.to validate_length_of(:name).is_at_least(
- DiscoursePostEvent::Event::MIN_NAME_LENGTH,
- ).is_at_most(DiscoursePostEvent::Event::MAX_NAME_LENGTH)
+ DiscourseEvents::Events::Event::MIN_NAME_LENGTH,
+ ).is_at_most(DiscourseEvents::Events::Event::MAX_NAME_LENGTH)
end
describe "#warm_livestream_onebox" do
@@ -179,7 +179,7 @@ describe DiscoursePostEvent::Event do
livestream: true,
location: "https://www.youtube.com/live/abc123",
)
- }.to change(DiscourseCalendar::Livestream::TopicChatChannel, :count).by(1)
+ }.to change(DiscourseEvents::Livestream::TopicChatChannel, :count).by(1)
expect(post.topic.topic_chat_channel.chat_channel.chatable).to eq(category)
end
@@ -194,7 +194,7 @@ describe DiscoursePostEvent::Event do
livestream: true,
location: "https://www.youtube.com/live/abc123",
)
- }.not_to change(DiscourseCalendar::Livestream::TopicChatChannel, :count)
+ }.not_to change(DiscourseEvents::Livestream::TopicChatChannel, :count)
end
it "does not create a chat channel for a livestream event on a reply" do
@@ -207,7 +207,7 @@ describe DiscoursePostEvent::Event do
livestream: true,
location: "https://www.youtube.com/live/abc123",
)
- }.not_to change(DiscourseCalendar::Livestream::TopicChatChannel, :count)
+ }.not_to change(DiscourseEvents::Livestream::TopicChatChannel, :count)
end
end
@@ -351,15 +351,15 @@ describe DiscoursePostEvent::Event do
it "is valid when an invitee is a group whose name collides with a username" do
Fabricate(:user).update_columns(
- username: DiscoursePostEvent::Event::PUBLIC_GROUP,
- username_lower: DiscoursePostEvent::Event::PUBLIC_GROUP,
+ username: DiscourseEvents::Events::Event::PUBLIC_GROUP,
+ username_lower: DiscourseEvents::Events::Event::PUBLIC_GROUP,
)
event =
Fabricate.build(
:event,
post: post,
original_starts_at: Time.now,
- raw_invitees: [DiscoursePostEvent::Event::PUBLIC_GROUP],
+ raw_invitees: [DiscourseEvents::Events::Event::PUBLIC_GROUP],
)
expect(event).to be_valid
@@ -377,14 +377,14 @@ describe DiscoursePostEvent::Event do
let!(:alt_starts_at) { Time.zone.parse("2020-04-24 14:14:25") }
let!(:alt_ends_at) { Time.zone.parse("2020-04-24 19:15:25") }
let(:event) do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: Time.now + 1.hour,
original_ends_at: Time.now + 2.hours,
)
end
let(:late_event) do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: Time.now - 10.hours,
original_ends_at: Time.now - 8.hours,
@@ -392,11 +392,13 @@ describe DiscoursePostEvent::Event do
end
let(:first_post_starts_at) do
Time.zone.parse(
- first_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT],
+ first_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT],
)
end
let(:first_post_ends_at) do
- Time.zone.parse(first_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT])
+ Time.zone.parse(
+ first_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT],
+ )
end
describe "#after_commit[:create, :update]" do
@@ -407,18 +409,18 @@ describe DiscoursePostEvent::Event do
expect(first_post.topic.custom_fields).to be_blank
expect {
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: starts_at,
original_ends_at: ends_at,
)
- }.to change { DiscoursePostEvent::EventDate.count }
+ }.to change { DiscourseEvents::Events::EventDate.count }
first_post.topic.reload
expect(first_post_starts_at).to eq_time(starts_at)
expect(first_post_ends_at).to eq_time(ends_at)
- expect(DiscoursePostEvent::EventDate.last.starts_at).to eq_time(starts_at)
- expect(DiscoursePostEvent::EventDate.last.ends_at).to eq_time(ends_at)
+ expect(DiscourseEvents::Events::EventDate.last.starts_at).to eq_time(starts_at)
+ expect(DiscourseEvents::Events::EventDate.last.ends_at).to eq_time(ends_at)
end
end
@@ -428,8 +430,11 @@ describe DiscoursePostEvent::Event do
expect(second_post.topic.custom_fields).to be_blank
expect {
- DiscoursePostEvent::Event.create!(id: second_post.id, original_starts_at: starts_at)
- }.to change { DiscoursePostEvent::EventDate.count }
+ DiscourseEvents::Events::Event.create!(
+ id: second_post.id,
+ original_starts_at: starts_at,
+ )
+ }.to change { DiscourseEvents::Events::EventDate.count }
second_post.topic.reload
expect(second_post.topic.custom_fields).to be_blank
@@ -511,12 +516,12 @@ describe DiscoursePostEvent::Event do
expect(
Time.zone.parse(
- first_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT],
+ first_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT],
),
).to eq(alt_starts_at)
expect(
Time.zone.parse(
- first_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT],
+ first_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT],
),
).to eq(alt_ends_at)
@@ -535,14 +540,14 @@ describe DiscoursePostEvent::Event do
it "doesn’t set the topic custom field" do
expect(second_post.is_first_post?).to be(false)
expect(
- second_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT],
+ second_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT],
).to be_blank
post_event.update_with_params!(original_starts_at: alt_starts_at)
second_post.topic.reload
expect(
- second_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT],
+ second_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT],
).to be_blank
second_event_date = post_event.event_dates.last
@@ -575,10 +580,10 @@ describe DiscoursePostEvent::Event do
first_post.topic.reload
expect(
- first_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT],
+ first_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT],
).to be_blank
expect(
- first_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT],
+ first_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT],
).to be_blank
end
end
@@ -607,12 +612,14 @@ describe DiscoursePostEvent::Event do
expect(first_post.is_first_post?).to be(true)
expect(
Time.zone.parse(
- second_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT],
+ second_post.topic.custom_fields[
+ DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT
+ ],
),
).to eq(starts_at)
expect(
Time.zone.parse(
- second_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT],
+ second_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT],
),
).to eq(ends_at)
expect(second_post.is_first_post?).to be(false)
@@ -622,12 +629,14 @@ describe DiscoursePostEvent::Event do
expect(
Time.zone.parse(
- second_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT],
+ second_post.topic.custom_fields[
+ DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT
+ ],
),
).to eq(starts_at)
expect(
Time.zone.parse(
- second_post.topic.custom_fields[DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT],
+ second_post.topic.custom_fields[DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT],
),
).to eq(ends_at)
end
@@ -646,7 +655,7 @@ describe DiscoursePostEvent::Event do
context "with ends_at < current date" do
it "is ongoing" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: 2.hours.ago,
original_ends_at: 1.hour.ago,
post: first_post,
@@ -659,7 +668,7 @@ describe DiscoursePostEvent::Event do
context "with ends_at > current date" do
it "is not ongoing" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: 2.hours.ago,
original_ends_at: 3.hours.from_now,
post: first_post,
@@ -674,7 +683,7 @@ describe DiscoursePostEvent::Event do
context "when ends_at > current date" do
it "is not ongoing" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
post: first_post,
@@ -690,7 +699,10 @@ describe DiscoursePostEvent::Event do
context "when starts_at < current date" do
it "is ongoing" do
post_event =
- DiscoursePostEvent::Event.create!(original_starts_at: 2.hours.ago, post: first_post)
+ DiscourseEvents::Events::Event.create!(
+ original_starts_at: 2.hours.ago,
+ post: first_post,
+ )
expect(post_event.ongoing?).to be(true)
end
@@ -699,7 +711,7 @@ describe DiscoursePostEvent::Event do
context "when starts_at == current date" do
it "is ongoing" do
post_event =
- DiscoursePostEvent::Event.create!(original_starts_at: Time.now, post: first_post)
+ DiscourseEvents::Events::Event.create!(original_starts_at: Time.now, post: first_post)
expect(post_event.ongoing?).to be(true)
end
@@ -708,7 +720,10 @@ describe DiscoursePostEvent::Event do
context "when starts_at > current date" do
it "is not ongoing" do
post_event =
- DiscoursePostEvent::Event.create!(original_starts_at: 1.hour.from_now, post: first_post)
+ DiscourseEvents::Events::Event.create!(
+ original_starts_at: 1.hour.from_now,
+ post: first_post,
+ )
expect(post_event.ongoing?).to be(false)
end
@@ -722,7 +737,7 @@ describe DiscoursePostEvent::Event do
let!(:first_post) { Fabricate(:post, topic: topic) }
def event_with(starts_at:, ends_at: nil, all_day: false)
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: starts_at,
original_ends_at: ends_at,
all_day:,
@@ -815,7 +830,7 @@ describe DiscoursePostEvent::Event do
context "when ends_at < current date" do
it "is expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-22 14:05"),
original_ends_at: DateTime.parse("2020-04-23 14:05"),
post: first_post,
@@ -828,7 +843,7 @@ describe DiscoursePostEvent::Event do
context "when ends_at > current date" do
it "is not expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-24 14:15"),
original_ends_at: DateTime.parse("2020-04-25 11:05"),
post: first_post,
@@ -842,7 +857,7 @@ describe DiscoursePostEvent::Event do
context "when starts_at > current date" do
it "is not expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-25 14:05"),
original_ends_at: DateTime.parse("2020-04-26 14:05"),
post: first_post,
@@ -857,7 +872,7 @@ describe DiscoursePostEvent::Event do
context "when starts_at < current date" do
it "is expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-24 14:05"),
post: first_post,
)
@@ -869,7 +884,7 @@ describe DiscoursePostEvent::Event do
context "when starts_at == current date" do
it "is expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-24 14:10"),
post: first_post,
)
@@ -881,7 +896,7 @@ describe DiscoursePostEvent::Event do
context "when starts_at > current date" do
it "is not expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-24 14:15"),
post: first_post,
)
@@ -896,7 +911,7 @@ describe DiscoursePostEvent::Event do
context "when current date is before recurrence_until" do
it "is not expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-22 14:05"),
original_ends_at: DateTime.parse("2020-04-22 15:05"),
recurrence: "FREQ=WEEKLY",
@@ -911,7 +926,7 @@ describe DiscoursePostEvent::Event do
context "when current date is after recurrence_until" do
it "is expired" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-22 14:05"),
original_ends_at: DateTime.parse("2020-04-22 15:05"),
recurrence: "FREQ=WEEKLY",
@@ -927,7 +942,7 @@ describe DiscoursePostEvent::Event do
it "is not expired" do
current_time = DateTime.parse("2020-04-24 14:10")
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-22 14:05"),
original_ends_at: DateTime.parse("2020-04-22 15:05"),
recurrence: "FREQ=WEEKLY",
@@ -943,7 +958,7 @@ describe DiscoursePostEvent::Event do
context "without recurrence_until set" do
it "never expires" do
post_event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
original_starts_at: DateTime.parse("2020-04-22 14:05"),
original_ends_at: DateTime.parse("2020-04-22 15:05"),
recurrence: "FREQ=WEEKLY",
@@ -963,7 +978,7 @@ describe DiscoursePostEvent::Event do
context "when event has both starts_at and ends_at" do
it "returns duration in HH:MM:SS format" do
event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post_1.id,
original_starts_at: "2022-01-15 10:00:00 UTC",
original_ends_at: "2022-01-15 11:30:00 UTC",
@@ -976,7 +991,7 @@ describe DiscoursePostEvent::Event do
context "when event only has starts_at" do
it "returns default duration of 1 hour" do
event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post_1.id,
original_starts_at: "2022-01-15 10:00:00 UTC",
)
@@ -988,7 +1003,7 @@ describe DiscoursePostEvent::Event do
context "when event spans multiple days" do
it "returns correct duration" do
event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post_1.id,
original_starts_at: "2022-01-15 10:00:00 UTC",
original_ends_at: "2022-01-16 12:30:00 UTC",
@@ -1016,7 +1031,7 @@ describe DiscoursePostEvent::Event do
Fabricate(
:event,
post: post_1,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [group_1.name],
)
end
@@ -1120,12 +1135,12 @@ describe DiscoursePostEvent::Event do
Fabricate(
:event,
post: post_1,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [group_1.name, group_2.name],
)
end
- before { DiscoursePostEvent::Invitee.create_attendance!(user_3.id, post_1.id, :going) }
+ before { DiscourseEvents::Events::Invitee.create_attendance!(user_3.id, post_1.id, :going) }
it "doesn't return already attending user" do
expect(event_1.missing_users.pluck(:id)).to_not include(user_3.id)
@@ -1140,7 +1155,7 @@ describe DiscoursePostEvent::Event do
Fabricate(
:event,
post: Fabricate(:post),
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [],
)
end
@@ -1201,7 +1216,7 @@ describe DiscoursePostEvent::Event do
it "serializer handles nil starts_at correctly" do
serializer =
- DiscoursePostEvent::EventSerializer.new(
+ DiscourseEvents::Events::EventSerializer.new(
expired_recurring_event,
scope: Guardian.new,
root: false,
@@ -1214,7 +1229,7 @@ describe DiscoursePostEvent::Event do
it "basic serializer handles expired recurring events correctly" do
serializer =
- DiscoursePostEvent::BasicEventSerializer.new(
+ DiscourseEvents::Events::BasicEventSerializer.new(
expired_recurring_event,
root: false,
scope: Guardian.new,
@@ -1280,7 +1295,7 @@ describe DiscoursePostEvent::Event do
"[event start=\"2020-04-24 14:15\" livestream=\"true\" location=\"https://www.youtube.com/live/abc123\"]\n[/event]",
)
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
expect(post.event.livestream).to eq(true)
@@ -1289,7 +1304,7 @@ describe DiscoursePostEvent::Event do
it "defaults livestream to false when the attribute is absent" do
post.update!(raw: "[event start=\"2020-04-24 14:15\"]\n[/event]")
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
expect(post.event.livestream).to eq(false)
@@ -1300,7 +1315,7 @@ describe DiscoursePostEvent::Event do
raw: "[event start=\"2020-04-24 14:15\" livestream=\"true\" location=\"Room 5\"]\n[/event]",
)
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
expect(post.event.livestream).to eq(false)
@@ -1312,7 +1327,7 @@ describe DiscoursePostEvent::Event do
raw: "[event start=\"2020-04-24 14:15\" image=\"#{upload.short_url}\"]\n[/event]",
)
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
end
@@ -1324,7 +1339,7 @@ describe DiscoursePostEvent::Event do
it "clears image_upload_id when image is removed" do
post.update!(raw: "[event start=\"2020-04-24 14:15\"]\n[/event]")
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
expect(post.event.image_upload_id).to be_nil
@@ -1344,7 +1359,7 @@ describe DiscoursePostEvent::Event do
raw: "[event start=\"2020-04-24 14:15\" image=\"#{upload.short_url}\"]\n[/event]",
)
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
CookedPostProcessor.new(post).post_process
@@ -1358,7 +1373,7 @@ describe DiscoursePostEvent::Event do
raw: "[event start=\"2020-04-24 14:15\" image=\"#{upload.short_url}\"]\n[/event]",
)
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
CookedPostProcessor.new(post).post_process
@@ -1377,7 +1392,7 @@ describe DiscoursePostEvent::Event do
raw: "[event start=\"2020-04-24 14:15\"]\n[/event]\n![image](#{other_upload.url})",
)
post.rebake!
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
CookedPostProcessor.new(post).post_process
@@ -1416,7 +1431,7 @@ describe DiscoursePostEvent::Event do
end
it "does not associate the upload" do
- DiscoursePostEvent::Event::SyncFromPost.call(params: { post_id: post.id })
+ DiscourseEvents::Events::Event::SyncFromPost.call(params: { post_id: post.id })
post.reload
expect(post.event.image_upload_id).to be_nil
@@ -1466,7 +1481,7 @@ describe DiscoursePostEvent::Event do
end
end
-describe DiscoursePostEvent::Event, "#most_likely_going" do
+describe DiscourseEvents::Events::Event, "#most_likely_going" do
before do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
@@ -1485,14 +1500,14 @@ describe DiscoursePostEvent::Event, "#most_likely_going" do
:post_event_invitee,
event:,
user: late_rsvp,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
created_at: 2.hours.ago,
)
Fabricate(
:post_event_invitee,
event:,
user: early_rsvp,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
created_at: 1.hour.ago,
)
@@ -1507,14 +1522,14 @@ describe DiscoursePostEvent::Event, "#most_likely_going" do
:post_event_invitee,
event:,
user: interested,
- status: DiscoursePostEvent::Invitee.statuses[:interested],
+ status: DiscourseEvents::Events::Invitee.statuses[:interested],
created_at: 2.hours.ago,
)
Fabricate(
:post_event_invitee,
event:,
user: going,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
created_at: 1.hour.ago,
)
@@ -1522,7 +1537,7 @@ describe DiscoursePostEvent::Event, "#most_likely_going" do
end
end
-describe DiscoursePostEvent::Event, "#capacity" do
+describe DiscourseEvents::Events::Event, "#capacity" do
before do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
@@ -1535,13 +1550,13 @@ describe DiscoursePostEvent::Event, "#capacity" do
post = Fabricate(:post, user: creator, topic: topic)
event = Fabricate(:event, post: post, max_attendees: 1)
event.create_invitees(
- [{ user_id: creator.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: creator.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
expect(event.at_capacity?).to eq(true)
end
end
-describe DiscoursePostEvent::Event, "#url" do
+describe DiscourseEvents::Events::Event, "#url" do
fab!(:post)
before { SiteSetting.discourse_post_event_enabled = true }
diff --git a/plugins/discourse-events/spec/models/topic_query_spec.rb b/plugins/discourse-events/spec/models/topic_query_spec.rb
index c7cfe229cf7..63b20ec38f1 100644
--- a/plugins/discourse-events/spec/models/topic_query_spec.rb
+++ b/plugins/discourse-events/spec/models/topic_query_spec.rb
@@ -14,28 +14,28 @@ describe TopicQuery do
fab!(:post_4) { Fabricate(:post, topic: topic_4) }
fab!(:future_event_1) do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post_1.id,
original_starts_at: Time.now + 5.hours,
original_ends_at: Time.now + 7.hours,
)
end
fab!(:future_event_2) do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post_2.id,
original_starts_at: Time.now + 1.hour,
original_ends_at: Time.now + 2.hours,
)
end
fab!(:past_event_1) do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post_3.id,
original_starts_at: Time.now - 10.hours,
original_ends_at: Time.now - 8.hours,
)
end
fab!(:past_event_2) do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post_4.id,
original_starts_at: Time.now - 7.hours,
original_ends_at: Time.now - 5.hours,
diff --git a/plugins/discourse-events/spec/requests/admin/admin_holidays_controller_spec.rb b/plugins/discourse-events/spec/requests/admin/holidays_controller_spec.rb
similarity index 91%
rename from plugins/discourse-events/spec/requests/admin/admin_holidays_controller_spec.rb
rename to plugins/discourse-events/spec/requests/admin/holidays_controller_spec.rb
index 6e92ac12963..28b7fb0a5bd 100644
--- a/plugins/discourse-events/spec/requests/admin/admin_holidays_controller_spec.rb
+++ b/plugins/discourse-events/spec/requests/admin/holidays_controller_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-module Admin::DiscourseCalendar
- describe AdminHolidaysController do
+module Admin::DiscourseEvents
+ describe HolidaysController do
fab!(:admin) { Fabricate(:user, admin: true, refresh_auto_groups: true) }
fab!(:member, :user)
@@ -88,7 +88,7 @@ module Admin::DiscourseCalendar
disabled_holiday: dia_de_la_independencia,
}
- disabled_holiday = DiscourseCalendar::DisabledHoliday.last
+ disabled_holiday = DiscourseEvents::Holidays::DisabledHoliday.last
expect(disabled_holiday.holiday_name).to eq(dia_de_la_independencia[:holiday_name])
expect(disabled_holiday.region_code).to eq(dia_de_la_independencia[:region_code])
@@ -112,14 +112,14 @@ module Admin::DiscourseCalendar
end
before do
- CalendarEvent.create!(
+ DiscourseEvents::Calendar::Event.create!(
topic_id: calendar_post.topic_id,
description: australia_new_years_day[:holiday_name],
start_date: australia_new_years_day[:date],
region: australia_new_years_day[:region_code],
)
- CalendarEvent.create!(
+ DiscourseEvents::Calendar::Event.create!(
topic_id: calendar_post.topic_id,
description: australia_day[:holiday_name],
start_date: australia_day[:date],
@@ -137,14 +137,14 @@ module Admin::DiscourseCalendar
}
expect(
- CalendarEvent.where(
+ DiscourseEvents::Calendar::Event.where(
description: australia_new_years_day[:holiday_name],
region: australia_new_years_day[:region_code],
).count,
).to eq(0)
expect(
- CalendarEvent.where(
+ DiscourseEvents::Calendar::Event.where(
description: australia_day[:holiday_name],
region: australia_day[:region_code],
).count,
@@ -165,17 +165,17 @@ module Admin::DiscourseCalendar
context "when there is a disabled holiday" do
let(:hong_kong_labour_day) { { holiday_name: "Labour Day", region_code: "hk" } }
- before { DiscourseCalendar::DisabledHoliday.create!(hong_kong_labour_day) }
+ before { DiscourseEvents::Holidays::DisabledHoliday.create!(hong_kong_labour_day) }
it "enables a holiday (by deleting its 'disabled' record) and returns a 200 status code" do
- expect(DiscourseCalendar::DisabledHoliday.count).to eq(1)
+ expect(DiscourseEvents::Holidays::DisabledHoliday.count).to eq(1)
delete "/admin/discourse-calendar/holidays/enable.json",
params: {
disabled_holiday: hong_kong_labour_day,
}
- expect(DiscourseCalendar::DisabledHoliday.count).to eq(0)
+ expect(DiscourseEvents::Holidays::DisabledHoliday.count).to eq(0)
expect(response.status).to eq(200)
end
end
diff --git a/plugins/discourse-events/spec/requests/categories_controller_spec.rb b/plugins/discourse-events/spec/requests/categories_controller_spec.rb
index 42bc35d592d..7d6a974ab70 100644
--- a/plugins/discourse-events/spec/requests/categories_controller_spec.rb
+++ b/plugins/discourse-events/spec/requests/categories_controller_spec.rb
@@ -7,7 +7,7 @@ describe CategoriesController do
before do
SiteSetting.discourse_events_enabled = true
SiteSetting.discourse_post_event_enabled = true
- DiscourseCalendar::Categories::Types::Events.configure_category(
+ DiscourseEvents::Categories::Types::Events.configure_category(
category,
guardian: admin.guardian,
)
@@ -40,7 +40,7 @@ describe CategoriesController do
end
it "preserves unspecified category_type_settings when only one key is sent" do
- DiscourseCalendar::Categories::Types::Events.configure_category(
+ DiscourseEvents::Categories::Types::Events.configure_category(
category,
guardian: admin.guardian,
configuration_values: {
diff --git a/plugins/discourse-events/spec/requests/chat/livestream_channels_spec.rb b/plugins/discourse-events/spec/requests/chat/livestream_channels_spec.rb
index 6a68f539fc5..c9883f4f3c0 100644
--- a/plugins/discourse-events/spec/requests/chat/livestream_channels_spec.rb
+++ b/plugins/discourse-events/spec/requests/chat/livestream_channels_spec.rb
@@ -18,12 +18,12 @@ RSpec.describe "Livestream channel list serialization" do
def create_livestream_channel
topic = Fabricate(:topic, category:)
post = Fabricate(:post, topic:)
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
location: "https://www.youtube.com/live/abc123",
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [group.name],
livestream: true,
)
@@ -60,13 +60,13 @@ RSpec.describe "Livestream channel list serialization" do
channel = create_livestream_channel
event = channel.livestream_topic_chat_channel.topic.first_post.event
event.create_invitees(
- [{ user_id: user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
group.remove(user)
- DiscoursePostEvent::Invitee
+ DiscourseEvents::Events::Invitee
.unscoped
.find_or_create_by!(post_id: event.id, user_id: user.id) do |invitee|
- invitee.status = DiscoursePostEvent::Invitee.statuses[:going]
+ invitee.status = DiscourseEvents::Events::Invitee.statuses[:going]
end
get "/chat/api/channels.json", params: { filter: "" }
diff --git a/plugins/discourse-events/spec/requests/events_controller_spec.rb b/plugins/discourse-events/spec/requests/events_controller_spec.rb
index 5ce7a24b79a..e013f55c5f7 100644
--- a/plugins/discourse-events/spec/requests/events_controller_spec.rb
+++ b/plugins/discourse-events/spec/requests/events_controller_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-module DiscoursePostEvent
- describe EventsController do
+module DiscourseEvents::Events
+ describe DiscourseEvents::EventsController do
before do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
@@ -691,7 +691,7 @@ module DiscoursePostEvent
Fabricate(
:event,
post: private_event_post,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [restricted_group.name],
)
end
diff --git a/plugins/discourse-events/spec/requests/invitees_controller_spec.rb b/plugins/discourse-events/spec/requests/invitees_controller_spec.rb
index c2a3a5cf089..9cf6da2f0c5 100644
--- a/plugins/discourse-events/spec/requests/invitees_controller_spec.rb
+++ b/plugins/discourse-events/spec/requests/invitees_controller_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-module DiscoursePostEvent
- describe InviteesController do
+module DiscourseEvents::Events
+ describe DiscourseEvents::InviteesController do
before do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
@@ -57,7 +57,7 @@ module DiscoursePostEvent
Fabricate(
:event,
post: public_post,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [restricted_group.name],
)
end
@@ -417,10 +417,10 @@ module DiscoursePostEvent
fab!(:event) { Fabricate(:event, post: post_1) }
fab!(:invitee_user, :user)
fab!(:invitee) do
- DiscoursePostEvent::Invitee.create!(
+ DiscourseEvents::Events::Invitee.create!(
post_id: post_1.id,
user_id: invitee_user.id,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
)
end
@@ -462,14 +462,14 @@ module DiscoursePostEvent
Fabricate(
:event,
post: private_event_post,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [restricted_group.name],
)
end
before do
private_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
end
diff --git a/plugins/discourse-events/spec/requests/livestream_controller_spec.rb b/plugins/discourse-events/spec/requests/livestream_controller_spec.rb
index 87150045e43..da9fbbbe072 100644
--- a/plugins/discourse-events/spec/requests/livestream_controller_spec.rb
+++ b/plugins/discourse-events/spec/requests/livestream_controller_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscourseCalendar
+module DiscourseEvents
describe LivestreamController do
fab!(:current_user, :user)
fab!(:tag) { Fabricate(:tag, name: "livestream") }
diff --git a/plugins/discourse-events/spec/requests/private_event_group_invitees_spec.rb b/plugins/discourse-events/spec/requests/private_event_group_invitees_spec.rb
index 90ca98d7b91..4630373f55d 100644
--- a/plugins/discourse-events/spec/requests/private_event_group_invitees_spec.rb
+++ b/plugins/discourse-events/spec/requests/private_event_group_invitees_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-module DiscoursePostEvent
+module DiscourseEvents::Events
describe "private event group invitees" do
fab!(:event_owner, :admin)
fab!(:invitee_user) { Fabricate(:user, refresh_auto_groups: true) }
@@ -17,7 +17,7 @@ module DiscoursePostEvent
Fabricate(
:event,
post:,
- status: DiscoursePostEvent::Event.statuses[:private],
+ status: DiscourseEvents::Events::Event.statuses[:private],
raw_invitees: [invited_group.name],
)
end
@@ -31,7 +31,7 @@ module DiscoursePostEvent
def create_invitee
event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
event.invitees.find_by(user_id: invitee_user.id)
end
@@ -40,7 +40,7 @@ module DiscoursePostEvent
invitee = create_invitee
expect { invited_group.remove(invitee_user) }.to change {
- DiscoursePostEvent::Invitee.unscoped.exists?(id: invitee.id)
+ DiscourseEvents::Events::Invitee.unscoped.exists?(id: invitee.id)
}.from(true).to(false)
end
@@ -48,10 +48,10 @@ module DiscoursePostEvent
stale_invitee = create_invitee
invited_group.remove(invitee_user)
stale_invitee =
- DiscoursePostEvent::Invitee
+ DiscourseEvents::Events::Invitee
.unscoped
.find_or_create_by!(post_id: event.id, user_id: invitee_user.id) do |invitee|
- invitee.status = DiscoursePostEvent::Invitee.statuses[:going]
+ invitee.status = DiscourseEvents::Events::Invitee.statuses[:going]
end
sign_in(invitee_user)
@@ -92,7 +92,7 @@ module DiscoursePostEvent
expect(response.status).to eq(403)
expect(response.parsed_body).not_to have_key("success")
- expect(stale_invitee.reload.status).to eq(DiscoursePostEvent::Invitee.statuses[:going])
+ expect(stale_invitee.reload.status).to eq(DiscourseEvents::Events::Invitee.statuses[:going])
end
end
end
diff --git a/plugins/discourse-events/spec/requests/site_spec.rb b/plugins/discourse-events/spec/requests/site_spec.rb
index d294bbbf2a9..2adda41184c 100644
--- a/plugins/discourse-events/spec/requests/site_spec.rb
+++ b/plugins/discourse-events/spec/requests/site_spec.rb
@@ -6,7 +6,7 @@ describe "calendar site additions" do
before do
SiteSetting.discourse_events_enabled = true
- DiscourseCalendar.users_on_holiday = [user.username]
+ DiscourseEvents.users_on_holiday = [user.username]
end
it "includes users_on_holiday for staff only" do
diff --git a/plugins/discourse-events/spec/serializers/chat_channel_serializer_spec.rb b/plugins/discourse-events/spec/serializers/chat_channel_serializer_spec.rb
index a322fbe2f34..4f8fd81e32e 100644
--- a/plugins/discourse-events/spec/serializers/chat_channel_serializer_spec.rb
+++ b/plugins/discourse-events/spec/serializers/chat_channel_serializer_spec.rb
@@ -16,12 +16,12 @@ RSpec.describe Chat::ChannelSerializer do
end
def create_event(livestream: true, status: :public, raw_invitees: nil)
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
location: "https://www.youtube.com/live/abc123",
- status: DiscoursePostEvent::Event.statuses[status],
+ status: DiscourseEvents::Events::Event.statuses[status],
raw_invitees:,
livestream:,
)
diff --git a/plugins/discourse-events/spec/serializers/discourse_post_event/basic_event_serializer_spec.rb b/plugins/discourse-events/spec/serializers/discourse_events/events/basic_event_serializer_spec.rb
similarity index 95%
rename from plugins/discourse-events/spec/serializers/discourse_post_event/basic_event_serializer_spec.rb
rename to plugins/discourse-events/spec/serializers/discourse_events/events/basic_event_serializer_spec.rb
index 1ff8bedea52..5889c4ce712 100644
--- a/plugins/discourse-events/spec/serializers/discourse_post_event/basic_event_serializer_spec.rb
+++ b/plugins/discourse-events/spec/serializers/discourse_events/events/basic_event_serializer_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::BasicEventSerializer do
+describe DiscourseEvents::Events::BasicEventSerializer do
before do
SiteSetting.discourse_events_enabled = true
SiteSetting.discourse_post_event_enabled = true
diff --git a/plugins/discourse-events/spec/serializers/discourse_post_event/event_serializer_spec.rb b/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb
similarity index 77%
rename from plugins/discourse-events/spec/serializers/discourse_post_event/event_serializer_spec.rb
rename to plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb
index 603746c88ec..d122cdd9e3a 100644
--- a/plugins/discourse-events/spec/serializers/discourse_post_event/event_serializer_spec.rb
+++ b/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscoursePostEvent::EventSerializer do
+describe DiscourseEvents::Events::EventSerializer do
before do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
@@ -15,17 +15,17 @@ describe DiscoursePostEvent::EventSerializer do
fab!(:event) { Fabricate(:event, post: post, location: "[RSVP](https://zoom.example.com)") }
it "serializes location_html with rendered links" do
- json = DiscoursePostEvent::EventSerializer.new(event, scope: Guardian.new).as_json
+ json = DiscourseEvents::Events::EventSerializer.new(event, scope: Guardian.new).as_json
expect(json[:event][:location_html]).to eq(
- DiscoursePostEvent::EventParser.cook_inline(event.location, post: event.post),
+ DiscourseEvents::Events::Parser.cook_inline(event.location, post: event.post),
)
expect(json[:event][:location_html]).to include('href="https://zoom.example.com"')
end
it "omits location_html without a location" do
event.update_columns(location: nil)
- json = DiscoursePostEvent::EventSerializer.new(event, scope: Guardian.new).as_json
+ json = DiscourseEvents::Events::EventSerializer.new(event, scope: Guardian.new).as_json
expect(json[:event]).not_to have_key(:location_html)
end
@@ -33,7 +33,7 @@ describe DiscoursePostEvent::EventSerializer do
context "with a private event" do
fab!(:private_event) do
- Fabricate(:event, post: post, status: DiscoursePostEvent::Event.statuses[:private])
+ Fabricate(:event, post: post, status: DiscourseEvents::Events::Event.statuses[:private])
end
fab!(:invitee_1, :user)
@@ -49,12 +49,13 @@ describe DiscoursePostEvent::EventSerializer do
context "when some invited users have not rsvp-ed yet" do
before do
private_event.update_with_params!(raw_invitees: [group_1.name])
- DiscoursePostEvent::Invitee.create_attendance!(invitee_1.id, private_event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(invitee_1.id, private_event.id, :going)
private_event.reload
end
it "returns the correct stats" do
- json = DiscoursePostEvent::EventSerializer.new(private_event, scope: Guardian.new).as_json
+ json =
+ DiscourseEvents::Events::EventSerializer.new(private_event, scope: Guardian.new).as_json
expect(json[:event][:stats]).to eq(
going: 1,
going_recurring: 0,
@@ -69,8 +70,8 @@ describe DiscoursePostEvent::EventSerializer do
context "with recurring 'going' invitees" do
before do
private_event.update_with_params!(raw_invitees: [group_1.name])
- DiscoursePostEvent::Invitee.create_attendance!(invitee_1.id, private_event.id, :going)
- DiscoursePostEvent::Invitee.create_attendance!(
+ DiscourseEvents::Events::Invitee.create_attendance!(invitee_1.id, private_event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(
invitee_2.id,
private_event.id,
:going,
@@ -80,7 +81,8 @@ describe DiscoursePostEvent::EventSerializer do
end
it "counts only recurring 'going' invitees in going_recurring" do
- json = DiscoursePostEvent::EventSerializer.new(private_event, scope: Guardian.new).as_json
+ json =
+ DiscourseEvents::Events::EventSerializer.new(private_event, scope: Guardian.new).as_json
expect(json[:event][:stats]).to eq(
going: 2,
going_recurring: 1,
@@ -97,12 +99,12 @@ describe DiscoursePostEvent::EventSerializer do
fab!(:event) { Fabricate(:event, post: post) }
it "returns the event category's id" do
- json = DiscoursePostEvent::EventSerializer.new(event, scope: Guardian.new).as_json
+ json = DiscourseEvents::Events::EventSerializer.new(event, scope: Guardian.new).as_json
expect(json[:event][:category_id]).to eq(category.id)
end
it "includes image_upload key as nil when not set" do
- json = DiscoursePostEvent::EventSerializer.new(event, scope: Guardian.new).as_json
+ json = DiscourseEvents::Events::EventSerializer.new(event, scope: Guardian.new).as_json
expect(json[:event]).to have_key(:image_upload)
expect(json[:event][:image_upload]).to be_nil
end
@@ -115,7 +117,10 @@ describe DiscoursePostEvent::EventSerializer do
it "includes image_upload in serialized output" do
json =
- DiscoursePostEvent::EventSerializer.new(event_with_image, scope: Guardian.new).as_json
+ DiscourseEvents::Events::EventSerializer.new(
+ event_with_image,
+ scope: Guardian.new,
+ ).as_json
expect(json[:event][:image_upload][:id]).to eq(upload.id)
expect(json[:event][:image_upload][:url]).to include(upload.url)
end
@@ -138,7 +143,10 @@ describe DiscoursePostEvent::EventSerializer do
expect_not_enqueued_with(job: :warm_livestream_onebox) do
json =
- DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+ DiscourseEvents::Events::EventSerializer.new(
+ livestream_event,
+ scope: Guardian.new,
+ ).as_json
expect(json[:event][:livestream_onebox]).to be_nil
end
@@ -148,7 +156,7 @@ describe DiscoursePostEvent::EventSerializer do
livestream_event
Oneboxer.expects(:onebox).never
- DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+ DiscourseEvents::Events::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
end
it "serves the onebox from the cache when it has been warmed" do
@@ -159,7 +167,10 @@ describe DiscoursePostEvent::EventSerializer do
)
json =
- DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+ DiscourseEvents::Events::EventSerializer.new(
+ livestream_event,
+ scope: Guardian.new,
+ ).as_json
expect(json[:event][:livestream_onebox]).to eq("<aside>cached</aside>")
end
@@ -168,7 +179,10 @@ describe DiscoursePostEvent::EventSerializer do
livestream_event
json =
- DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+ DiscourseEvents::Events::EventSerializer.new(
+ livestream_event,
+ scope: Guardian.new,
+ ).as_json
expect(json[:event][:livestream_url]).to eq(livestream_url)
expect(json[:event].key?(:livestream_chat_channel_id)).to eq(true)
@@ -178,7 +192,10 @@ describe DiscoursePostEvent::EventSerializer do
livestream_event
json =
- DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+ DiscourseEvents::Events::EventSerializer.new(
+ livestream_event,
+ scope: Guardian.new,
+ ).as_json
expect(json[:event][:is_zoom_livestream]).to eq(false)
end
@@ -189,7 +206,8 @@ describe DiscoursePostEvent::EventSerializer do
fab!(:plain_event) { Fabricate(:event, post: plain_post, location: "Room 5") }
it "omits the livestream attributes" do
- json = DiscoursePostEvent::EventSerializer.new(plain_event, scope: Guardian.new).as_json
+ json =
+ DiscourseEvents::Events::EventSerializer.new(plain_event, scope: Guardian.new).as_json
expect(json[:event].key?(:livestream_url)).to eq(false)
expect(json[:event].key?(:livestream_onebox)).to eq(false)
@@ -209,7 +227,7 @@ describe DiscoursePostEvent::EventSerializer do
end
it "flags the event as a Zoom livestream" do
- json = DiscoursePostEvent::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
+ json = DiscourseEvents::Events::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
expect(json[:event][:is_zoom_livestream]).to eq(true)
expect(json[:event][:livestream_url]).to eq(zoom_url)
@@ -221,7 +239,7 @@ describe DiscoursePostEvent::EventSerializer do
{ onebox: "<aside>cached</aside>" },
)
- json = DiscoursePostEvent::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
+ json = DiscourseEvents::Events::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
expect(json[:event].key?(:livestream_onebox)).to eq(false)
end
@@ -229,7 +247,7 @@ describe DiscoursePostEvent::EventSerializer do
it "falls back to the onebox when Zoom is disabled" do
SiteSetting.livestream_zoom_enabled = false
- json = DiscoursePostEvent::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
+ json = DiscourseEvents::Events::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
expect(json[:event][:is_zoom_livestream]).to eq(false)
expect(json[:event].key?(:livestream_onebox)).to eq(true)
@@ -249,7 +267,10 @@ describe DiscoursePostEvent::EventSerializer do
it "includes duration in serialized output" do
json =
- DiscoursePostEvent::EventSerializer.new(event_with_duration, scope: Guardian.new).as_json
+ DiscourseEvents::Events::EventSerializer.new(
+ event_with_duration,
+ scope: Guardian.new,
+ ).as_json
expect(json[:event][:duration]).to eq("01:30:00")
end
end
@@ -266,7 +287,8 @@ describe DiscoursePostEvent::EventSerializer do
end
it "includes default 1-hour duration in serialized output" do
- json = DiscoursePostEvent::EventSerializer.new(event_no_end, scope: Guardian.new).as_json
+ json =
+ DiscourseEvents::Events::EventSerializer.new(event_no_end, scope: Guardian.new).as_json
expect(json[:event]).to have_key(:duration)
expect(json[:event][:duration]).to eq("01:00:00")
end
@@ -290,7 +312,7 @@ describe DiscoursePostEvent::EventSerializer do
it "serializes starts_at using the next occurrence" do
json =
- DiscoursePostEvent::EventSerializer.new(
+ DiscourseEvents::Events::EventSerializer.new(
recurring_event.reload,
scope: Guardian.new,
).as_json
@@ -300,7 +322,7 @@ describe DiscoursePostEvent::EventSerializer do
it "serializes ends_at using the next occurrence" do
json =
- DiscoursePostEvent::EventSerializer.new(
+ DiscourseEvents::Events::EventSerializer.new(
recurring_event.reload,
scope: Guardian.new,
).as_json
@@ -322,17 +344,20 @@ describe DiscoursePostEvent::EventSerializer do
end
it "serializes starts_at as date-only string" do
- json = DiscoursePostEvent::EventSerializer.new(all_day_event, scope: Guardian.new).as_json
+ json =
+ DiscourseEvents::Events::EventSerializer.new(all_day_event, scope: Guardian.new).as_json
expect(json[:event][:starts_at]).to eq("2026-03-12")
end
it "serializes ends_at as date-only string" do
- json = DiscoursePostEvent::EventSerializer.new(all_day_event, scope: Guardian.new).as_json
+ json =
+ DiscourseEvents::Events::EventSerializer.new(all_day_event, scope: Guardian.new).as_json
expect(json[:event][:ends_at]).to eq("2026-03-14")
end
it "serializes all_day as true" do
- json = DiscoursePostEvent::EventSerializer.new(all_day_event, scope: Guardian.new).as_json
+ json =
+ DiscourseEvents::Events::EventSerializer.new(all_day_event, scope: Guardian.new).as_json
expect(json[:event][:all_day]).to eq(true)
end
end
diff --git a/plugins/discourse-events/spec/serializers/discourse_post_event/post_serializer_spec.rb b/plugins/discourse-events/spec/serializers/discourse_events/events/post_serializer_spec.rb
similarity index 100%
rename from plugins/discourse-events/spec/serializers/discourse_post_event/post_serializer_spec.rb
rename to plugins/discourse-events/spec/serializers/discourse_events/events/post_serializer_spec.rb
diff --git a/plugins/discourse-events/spec/serializers/post_serializer_spec.rb b/plugins/discourse-events/spec/serializers/post_serializer_spec.rb
index b11bd7eee51..01b9cda5965 100644
--- a/plugins/discourse-events/spec/serializers/post_serializer_spec.rb
+++ b/plugins/discourse-events/spec/serializers/post_serializer_spec.rb
@@ -45,11 +45,11 @@ describe PostSerializer do
it "groups calendar events correctly" do
user = Fabricate(:user)
- user.upsert_custom_fields(DiscourseCalendar::REGION_CUSTOM_FIELD => "ar")
+ user.upsert_custom_fields(DiscourseEvents::REGION_CUSTOM_FIELD => "ar")
user.user_option.update!(timezone: "America/Buenos_Aires")
user2 = Fabricate(:user)
- user2.upsert_custom_fields(DiscourseCalendar::REGION_CUSTOM_FIELD => "ar")
+ user2.upsert_custom_fields(DiscourseEvents::REGION_CUSTOM_FIELD => "ar")
user2.user_option.update!(timezone: "America/Buenos_Aires")
post = create_post(raw: "[calendar]\n[/calendar]")
diff --git a/plugins/discourse-events/spec/serializers/topic_list_item_serializer_spec.rb b/plugins/discourse-events/spec/serializers/topic_list_item_serializer_spec.rb
index 61c0e25c6fd..3ec6ee3edae 100644
--- a/plugins/discourse-events/spec/serializers/topic_list_item_serializer_spec.rb
+++ b/plugins/discourse-events/spec/serializers/topic_list_item_serializer_spec.rb
@@ -12,7 +12,7 @@ RSpec.describe TopicListItemSerializer do
Jobs.run_immediately!
SiteSetting.discourse_events_enabled = true
SiteSetting.discourse_post_event_enabled = true
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
@@ -53,7 +53,7 @@ RSpec.describe TopicListItemSerializer do
all_day_topic = Fabricate(:topic)
all_day_post = Fabricate(:post, topic: all_day_topic)
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: all_day_post.id,
original_starts_at: Time.utc(2020, 4, 25),
original_ends_at: Time.utc(2020, 4, 27),
diff --git a/plugins/discourse-events/spec/serializers/topic_view_serializer_spec.rb b/plugins/discourse-events/spec/serializers/topic_view_serializer_spec.rb
index 939f58b11de..ba6a78e3fe7 100644
--- a/plugins/discourse-events/spec/serializers/topic_view_serializer_spec.rb
+++ b/plugins/discourse-events/spec/serializers/topic_view_serializer_spec.rb
@@ -18,7 +18,7 @@ RSpec.describe TopicViewSerializer do
context "without timezone" do
before do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
@@ -52,7 +52,7 @@ RSpec.describe TopicViewSerializer do
context "with timezone and show_local_time true" do
before do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
@@ -76,7 +76,7 @@ RSpec.describe TopicViewSerializer do
context "with timezone and show_local_time false" do
before do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
@@ -101,7 +101,7 @@ RSpec.describe TopicViewSerializer do
context "with all-day event" do
before do
SiteSetting.display_post_event_date_on_topic_title = true
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: Time.utc(2020, 4, 25),
original_ends_at: Time.utc(2020, 4, 27),
@@ -118,7 +118,7 @@ RSpec.describe TopicViewSerializer do
context "without all-day event" do
before do
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
@@ -142,7 +142,7 @@ RSpec.describe TopicViewSerializer do
end
def create_event
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
@@ -151,7 +151,7 @@ RSpec.describe TopicViewSerializer do
it "returns the status the current user answered with" do
event = create_event
- DiscoursePostEvent::Invitee.create_attendance!(viewer.id, event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(viewer.id, event.id, :going)
expect(parsed_json_for(viewer)["event_watching_invitee_status"]).to eq("going")
end
@@ -176,7 +176,7 @@ RSpec.describe TopicViewSerializer do
it "is not affected by other users' answers" do
event = create_event
- DiscoursePostEvent::Invitee.create_attendance!(Fabricate(:user).id, event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(Fabricate(:user).id, event.id, :going)
expect(parsed_json_for(viewer)["event_watching_invitee_status"]).to be_nil
end
@@ -195,12 +195,12 @@ RSpec.describe TopicViewSerializer do
end
def create_event(livestream:, status: :public, raw_invitees: nil)
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.hour.from_now,
original_ends_at: 2.hours.from_now,
location: "https://www.youtube.com/live/abc123",
- status: DiscoursePostEvent::Event.statuses[status],
+ status: DiscourseEvents::Events::Event.statuses[status],
raw_invitees:,
livestream:,
)
diff --git a/plugins/discourse-events/spec/serializers/user_serializer_spec.rb b/plugins/discourse-events/spec/serializers/user_serializer_spec.rb
index 9fff3b17777..0b4d22024bf 100644
--- a/plugins/discourse-events/spec/serializers/user_serializer_spec.rb
+++ b/plugins/discourse-events/spec/serializers/user_serializer_spec.rb
@@ -7,7 +7,7 @@ describe UserSerializer do
before do
SiteSetting.discourse_events_enabled = true
- user.upsert_custom_fields(DiscourseCalendar::REGION_CUSTOM_FIELD => "uk")
+ user.upsert_custom_fields(DiscourseEvents::REGION_CUSTOM_FIELD => "uk")
end
context "as another user" do
@@ -22,7 +22,7 @@ describe UserSerializer do
let(:guardian) { user.guardian }
it "returns user region" do
- expect(json[:user][:custom_fields]).to eq(DiscourseCalendar::REGION_CUSTOM_FIELD => "uk")
+ expect(json[:user][:custom_fields]).to eq(DiscourseEvents::REGION_CUSTOM_FIELD => "uk")
end
end
@@ -30,7 +30,7 @@ describe UserSerializer do
let(:guardian) { Fabricate(:admin).guardian }
it "returns user region" do
- expect(json[:user][:custom_fields]).to eq(DiscourseCalendar::REGION_CUSTOM_FIELD => "uk")
+ expect(json[:user][:custom_fields]).to eq(DiscourseEvents::REGION_CUSTOM_FIELD => "uk")
end
end
end
diff --git a/plugins/discourse-events/spec/services/discourse_calendar/categories/types/events_spec.rb b/plugins/discourse-events/spec/services/discourse_events/categories/types/events_spec.rb
similarity index 99%
rename from plugins/discourse-events/spec/services/discourse_calendar/categories/types/events_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/categories/types/events_spec.rb
index bdef245084a..62389ea4a42 100644
--- a/plugins/discourse-events/spec/services/discourse_calendar/categories/types/events_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/categories/types/events_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseCalendar::Categories::Types::Events do
+RSpec.describe DiscourseEvents::Categories::Types::Events do
fab!(:admin)
fab!(:category)
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/action/expand_occurrences_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/action/expand_occurrences_spec.rb
similarity index 92%
rename from plugins/discourse-events/spec/services/discourse_post_event/action/expand_occurrences_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/action/expand_occurrences_spec.rb
index f820d165642..36e0bb6ee06 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/action/expand_occurrences_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/action/expand_occurrences_spec.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-RSpec.describe DiscoursePostEvent::Action::ExpandOccurrences do
+RSpec.describe DiscourseEvents::Events::Action::ExpandOccurrences do
describe ".call" do
subject(:action) { described_class.call(event:, after:, before:, limit:) }
let(:after) { Time.zone.parse("2030-01-01 00:00:00 UTC") }
let(:before) { nil }
let(:limit) { described_class::MAX_LIMIT + 1 }
- let(:event) { instance_double(DiscoursePostEvent::Event, recurring?: true) }
+ let(:event) { instance_double(DiscourseEvents::Events::Event, recurring?: true) }
before do
next_occurrence_starts_at = Time.zone.parse("2030-01-01 09:00:00 UTC")
@@ -33,7 +33,7 @@ RSpec.describe DiscoursePostEvent::Action::ExpandOccurrences do
let(:current_ends_at) { Time.zone.parse("2030-01-05 10:00:00 UTC") }
let(:event) do
instance_double(
- DiscoursePostEvent::Event,
+ DiscourseEvents::Events::Event,
recurring?: true,
starts_at: current_starts_at,
ends_at: current_ends_at,
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/action/parse_invitees_csv_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/action/parse_invitees_csv_spec.rb
similarity index 95%
rename from plugins/discourse-events/spec/services/discourse_post_event/action/parse_invitees_csv_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/action/parse_invitees_csv_spec.rb
index a7c837d1f64..bc49d1334a6 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/action/parse_invitees_csv_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/action/parse_invitees_csv_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::Action::ParseInviteesCsv) do
+RSpec.describe(DiscourseEvents::Events::Action::ParseInviteesCsv) do
subject(:result) { described_class.call(file: file) }
def csv_file(content)
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/bulk_invite_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/bulk_invite_spec.rb
similarity index 98%
rename from plugins/discourse-events/spec/services/discourse_post_event/bulk_invite_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/bulk_invite_spec.rb
index f6c2fd96f4f..f49d16d00ac 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/bulk_invite_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/bulk_invite_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::BulkInvite) do
+RSpec.describe(DiscourseEvents::Events::BulkInvite) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:event_id) }
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/create_invitee_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/create_invitee_spec.rb
similarity index 87%
rename from plugins/discourse-events/spec/services/discourse_post_event/create_invitee_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/create_invitee_spec.rb
index 0ffaa045265..6c03a222841 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/create_invitee_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/create_invitee_spec.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::CreateInvitee) do
+RSpec.describe(DiscourseEvents::Events::CreateInvitee) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:event_id) }
it do
is_expected.to validate_inclusion_of(:status).in_array(
- DiscoursePostEvent::Invitee.statuses.keys.map(&:to_s),
+ DiscourseEvents::Events::Invitee.statuses.keys.map(&:to_s),
)
end
end
@@ -86,7 +86,7 @@ RSpec.describe(DiscoursePostEvent::CreateInvitee) do
before do
full_event.create_invitees(
- [{ user_id: other_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: other_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
end
@@ -99,11 +99,11 @@ RSpec.describe(DiscoursePostEvent::CreateInvitee) do
it { is_expected.to run_successfully }
it "creates the invitee" do
- expect { result }.to change { DiscoursePostEvent::Invitee.count }.by(1)
+ expect { result }.to change { DiscourseEvents::Events::Invitee.count }.by(1)
expect(result[:invitee]).to have_attributes(
user_id: current_user.id,
post_id: event.id,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
)
end
end
@@ -118,10 +118,10 @@ RSpec.describe(DiscoursePostEvent::CreateInvitee) do
it { is_expected.to run_successfully }
it "creates the invitee for the other user" do
- expect { result }.to change { DiscoursePostEvent::Invitee.count }.by(1)
+ expect { result }.to change { DiscourseEvents::Events::Invitee.count }.by(1)
expect(result[:invitee]).to have_attributes(
user_id: other_user.id,
- status: DiscoursePostEvent::Invitee.statuses[:interested],
+ status: DiscourseEvents::Events::Invitee.statuses[:interested],
)
end
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/csv_bulk_invite_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/csv_bulk_invite_spec.rb
similarity index 98%
rename from plugins/discourse-events/spec/services/discourse_post_event/csv_bulk_invite_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/csv_bulk_invite_spec.rb
index eaa117503a3..784c26863f8 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/csv_bulk_invite_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/csv_bulk_invite_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::CsvBulkInvite) do
+RSpec.describe(DiscourseEvents::Events::CsvBulkInvite) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:event_id) }
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/destroy_event_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/destroy_event_spec.rb
similarity index 89%
rename from plugins/discourse-events/spec/services/discourse_post_event/destroy_event_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/destroy_event_spec.rb
index ecbb6a64e30..6ae34d18040 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/destroy_event_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/destroy_event_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::DestroyEvent) do
+RSpec.describe(DiscourseEvents::Events::DestroyEvent) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:event_id) }
end
@@ -47,8 +47,8 @@ RSpec.describe(DiscoursePostEvent::DestroyEvent) do
it { is_expected.to run_successfully }
it "destroys the event" do
- expect { result }.to change { DiscoursePostEvent::Event.count }.by(-1)
- expect(DiscoursePostEvent::Event.exists?(event.id)).to eq(false)
+ expect { result }.to change { DiscourseEvents::Events::Event.count }.by(-1)
+ expect(DiscourseEvents::Events::Event.exists?(event.id)).to eq(false)
end
it "publishes an event update" do
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/destroy_invitee_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/destroy_invitee_spec.rb
similarity index 84%
rename from plugins/discourse-events/spec/services/discourse_post_event/destroy_invitee_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/destroy_invitee_spec.rb
index 4511195d1a0..ca10b15e88d 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/destroy_invitee_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/destroy_invitee_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
+RSpec.describe(DiscourseEvents::Events::DestroyInvitee) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:post_id) }
it { is_expected.to validate_presence_of(:id) }
@@ -16,7 +16,7 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
fab!(:invitee_user) { Fabricate(:user, refresh_auto_groups: true) }
fab!(:invitee) do
event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
event.invitees.find_by(user_id: invitee_user.id)
end
@@ -59,7 +59,7 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
fab!(:private_event)
fab!(:private_invitee) do
private_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
private_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -74,7 +74,7 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
fab!(:closed_event) { Fabricate(:event, post: closed_post, closed: true) }
fab!(:closed_invitee) do
closed_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
closed_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -96,7 +96,7 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
end
fab!(:expired_invitee) do
expired_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
expired_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -110,8 +110,8 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
it { is_expected.to run_successfully }
it "destroys the invitee" do
- expect { result }.to change { DiscoursePostEvent::Invitee.count }.by(-1)
- expect(DiscoursePostEvent::Invitee.exists?(invitee.id)).to eq(false)
+ expect { result }.to change { DiscourseEvents::Events::Invitee.count }.by(-1)
+ expect(DiscourseEvents::Events::Invitee.exists?(invitee.id)).to eq(false)
end
it "resets the invitee's topic tracking to regular" do
@@ -131,7 +131,7 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
it { is_expected.to run_successfully }
it "destroys the invitee" do
- expect { result }.to change { DiscoursePostEvent::Invitee.count }.by(-1)
+ expect { result }.to change { DiscourseEvents::Events::Invitee.count }.by(-1)
end
end
@@ -142,7 +142,7 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
fab!(:creator_event) { Fabricate(:event, post: creator_post) }
fab!(:creator_event_invitee) do
creator_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
creator_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -157,7 +157,7 @@ RSpec.describe(DiscoursePostEvent::DestroyInvitee) do
it { is_expected.to run_successfully }
it "destroys the invitee" do
- expect { result }.to change { DiscoursePostEvent::Invitee.count }.by(-1)
+ expect { result }.to change { DiscourseEvents::Events::Invitee.count }.by(-1)
end
end
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/event/action/attributes_from_raw_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/event/action/attributes_from_raw_spec.rb
similarity index 93%
rename from plugins/discourse-events/spec/services/discourse_post_event/event/action/attributes_from_raw_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/event/action/attributes_from_raw_spec.rb
index 925bc65737a..8a22ca925d7 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/event/action/attributes_from_raw_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/event/action/attributes_from_raw_spec.rb
@@ -1,9 +1,9 @@
# frozen_string_literal: true
-RSpec.describe DiscoursePostEvent::Event::Action::AttributesFromRaw do
+RSpec.describe DiscourseEvents::Events::Event::Action::AttributesFromRaw do
subject(:attributes) { described_class.call(raw_event:, current_status:) }
- let(:current_status) { DiscoursePostEvent::Event.statuses[:public] }
+ let(:current_status) { DiscourseEvents::Events::Event.statuses[:public] }
let(:raw_event) { { name: "My event", start: "2030-04-24 14:15", timezone: "Europe/Paris" } }
before do
@@ -50,7 +50,7 @@ RSpec.describe DiscoursePostEvent::Event::Action::AttributesFromRaw do
it "falls back to the default timezone when none is provided" do
raw_event.merge!(start: "2030-04-24 14:15", timezone: nil)
- utc = ActiveSupport::TimeZone[DiscoursePostEvent::Event::DEFAULT_TIMEZONE]
+ utc = ActiveSupport::TimeZone[DiscourseEvents::Events::Event::DEFAULT_TIMEZONE]
expect(attributes[:original_starts_at]).to eq(utc.parse("2030-04-24 14:15"))
end
@@ -95,7 +95,7 @@ RSpec.describe DiscoursePostEvent::Event::Action::AttributesFromRaw do
it "resolves a known raw status to its enum value" do
raw_event[:status] = "private"
- expect(attributes[:status]).to eq(DiscoursePostEvent::Event.statuses[:private])
+ expect(attributes[:status]).to eq(DiscourseEvents::Events::Event.statuses[:private])
end
it "falls back to the current status when the raw status is missing" do
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/event/action/resolve_image_upload_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/event/action/resolve_image_upload_spec.rb
similarity index 96%
rename from plugins/discourse-events/spec/services/discourse_post_event/event/action/resolve_image_upload_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/event/action/resolve_image_upload_spec.rb
index 4b598fd61f7..80c8dfd7ece 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/event/action/resolve_image_upload_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/event/action/resolve_image_upload_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscoursePostEvent::Event::Action::ResolveImageUpload do
+RSpec.describe DiscourseEvents::Events::Event::Action::ResolveImageUpload do
subject(:resolved) { described_class.call(image:, post:) }
fab!(:author, :user)
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/event/sync_from_post_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/event/sync_from_post_spec.rb
similarity index 78%
rename from plugins/discourse-events/spec/services/discourse_post_event/event/sync_from_post_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/event/sync_from_post_spec.rb
index 68e9a4ce04f..4a22e02e9dd 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/event/sync_from_post_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/event/sync_from_post_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscoursePostEvent::Event::SyncFromPost do
+RSpec.describe DiscourseEvents::Events::Event::SyncFromPost do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:post_id) }
end
@@ -24,7 +24,7 @@ RSpec.describe DiscoursePostEvent::Event::SyncFromPost do
SiteSetting.discourse_post_event_enabled = true
Jobs.run_immediately!
- DiscoursePostEvent::EventParser.stubs(:extract_events).returns([raw_event])
+ DiscourseEvents::Events::Parser.stubs(:extract_events).returns([raw_event])
end
context "when the contract is invalid" do
@@ -43,17 +43,17 @@ RSpec.describe DiscoursePostEvent::Event::SyncFromPost do
it { is_expected.to run_successfully }
it "creates the event from the raw" do
- expect { result }.to change { DiscoursePostEvent::Event.count }.by(1)
+ expect { result }.to change { DiscourseEvents::Events::Event.count }.by(1)
event = post.reload.event
expect(event.original_starts_at).to eq_time(Time.utc(2030, 4, 24, 14, 15))
- expect(event.status).to eq(DiscoursePostEvent::Event.statuses[:public])
+ expect(event.status).to eq(DiscourseEvents::Events::Event.statuses[:public])
expect(event.name).to eq("My event")
end
it "reconciles invitees through update_with_params! (public status)" do
result
- expect(post.reload.event.raw_invitees).to eq([DiscoursePostEvent::Event::PUBLIC_GROUP])
+ expect(post.reload.event.raw_invitees).to eq([DiscourseEvents::Events::Event::PUBLIC_GROUP])
end
it "publishes the event update" do
@@ -76,7 +76,7 @@ RSpec.describe DiscoursePostEvent::Event::SyncFromPost do
context "when the synced event is standalone" do
fab!(:event) do
- Fabricate(:event, post:, status: DiscoursePostEvent::Event.statuses[:standalone])
+ Fabricate(:event, post:, status: DiscourseEvents::Events::Event.statuses[:standalone])
end
fab!(:invitee) { Fabricate(:post_event_invitee, event:, user: Fabricate(:user)) }
@@ -85,30 +85,30 @@ RSpec.describe DiscoursePostEvent::Event::SyncFromPost do
it { is_expected.to run_successfully }
it "destroys the event's invitees" do
- expect { result }.to change { DiscoursePostEvent::Invitee.count }.by(-1)
+ expect { result }.to change { DiscourseEvents::Events::Invitee.count }.by(-1)
end
end
context "when the raw has no event but the post has one" do
fab!(:event) { Fabricate(:event, post:) }
- before { DiscoursePostEvent::EventParser.stubs(:extract_events).returns([]) }
+ before { DiscourseEvents::Events::Parser.stubs(:extract_events).returns([]) }
it { is_expected.to run_successfully }
it "removes the event" do
- expect { result }.to change { DiscoursePostEvent::Event.count }.by(-1)
+ expect { result }.to change { DiscourseEvents::Events::Event.count }.by(-1)
expect(post.reload.event).to be_nil
end
end
context "when the raw has no event and the post has none" do
- before { DiscoursePostEvent::EventParser.stubs(:extract_events).returns([]) }
+ before { DiscourseEvents::Events::Parser.stubs(:extract_events).returns([]) }
it { is_expected.to run_successfully }
it "does not create an event" do
- expect { result }.not_to change { DiscoursePostEvent::Event.count }
+ expect { result }.not_to change { DiscourseEvents::Events::Event.count }
end
end
@@ -126,7 +126,7 @@ RSpec.describe DiscoursePostEvent::Event::SyncFromPost do
it { is_expected.to be_a_failure }
it "does not persist the event" do
- expect { result }.not_to change { DiscoursePostEvent::Event.count }
+ expect { result }.not_to change { DiscourseEvents::Events::Event.count }
end
end
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/invite_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/invite_spec.rb
similarity index 97%
rename from plugins/discourse-events/spec/services/discourse_post_event/invite_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/invite_spec.rb
index dfb64429810..3f4925a121f 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/invite_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/invite_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::Invite) do
+RSpec.describe(DiscourseEvents::Events::Invite) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:event_id) }
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/list_invitees_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/list_invitees_spec.rb
similarity index 91%
rename from plugins/discourse-events/spec/services/discourse_post_event/list_invitees_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/list_invitees_spec.rb
index 72b527b834b..b1402933479 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/list_invitees_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/list_invitees_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::ListInvitees) do
+RSpec.describe(DiscourseEvents::Events::ListInvitees) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:post_id) }
end
@@ -26,10 +26,10 @@ RSpec.describe(DiscoursePostEvent::ListInvitees) do
event.create_invitees(
[
- { user_id: francis.id, status: DiscoursePostEvent::Invitee.statuses[:going] },
- { user_id: francisco.id, status: DiscoursePostEvent::Invitee.statuses[:interested] },
- { user_id: frank.id, status: DiscoursePostEvent::Invitee.statuses[:not_going] },
- { user_id: franchesca.id, status: DiscoursePostEvent::Invitee.statuses[:going] },
+ { user_id: francis.id, status: DiscourseEvents::Events::Invitee.statuses[:going] },
+ { user_id: francisco.id, status: DiscourseEvents::Events::Invitee.statuses[:interested] },
+ { user_id: frank.id, status: DiscourseEvents::Events::Invitee.statuses[:not_going] },
+ { user_id: franchesca.id, status: DiscourseEvents::Events::Invitee.statuses[:going] },
],
)
end
diff --git a/plugins/discourse-events/spec/services/discourse_post_event/update_invitee_spec.rb b/plugins/discourse-events/spec/services/discourse_events/events/update_invitee_spec.rb
similarity index 81%
rename from plugins/discourse-events/spec/services/discourse_post_event/update_invitee_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/events/update_invitee_spec.rb
index 8583a8d1489..f96adc8b1ec 100644
--- a/plugins/discourse-events/spec/services/discourse_post_event/update_invitee_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/events/update_invitee_spec.rb
@@ -1,12 +1,12 @@
# frozen_string_literal: true
-RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
+RSpec.describe(DiscourseEvents::Events::UpdateInvitee) do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:event_id) }
it { is_expected.to validate_presence_of(:invitee_id) }
it do
is_expected.to validate_inclusion_of(:status).in_array(
- DiscoursePostEvent::Invitee.statuses.keys.map(&:to_s),
+ DiscourseEvents::Events::Invitee.statuses.keys.map(&:to_s),
)
end
end
@@ -21,7 +21,7 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
fab!(:invitee_user) { Fabricate(:user, refresh_auto_groups: true) }
fab!(:invitee) do
event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
event.invitees.find_by(user_id: invitee_user.id)
end
@@ -58,7 +58,7 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
fab!(:private_event)
fab!(:private_invitee) do
private_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
private_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -75,7 +75,7 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
fab!(:closed_event) { Fabricate(:event, post: closed_post, closed: true) }
fab!(:closed_invitee) do
closed_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
closed_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -99,7 +99,7 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
end
fab!(:expired_invitee) do
expired_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
expired_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -117,13 +117,18 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
fab!(:full_event) { Fabricate(:event, post: full_post, max_attendees: 1) }
fab!(:going_invitee) do
full_event.create_invitees(
- [{ user_id: other_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: other_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
full_event.invitees.find_by(user_id: other_user.id)
end
fab!(:interested_invitee) do
full_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:interested] }],
+ [
+ {
+ user_id: invitee_user.id,
+ status: DiscourseEvents::Events::Invitee.statuses[:interested],
+ },
+ ],
)
full_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -142,7 +147,7 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
fab!(:creator_event) { Fabricate(:event, post: creator_post) }
fab!(:creator_event_invitee) do
creator_event.create_invitees(
- [{ user_id: invitee_user.id, status: DiscoursePostEvent::Invitee.statuses[:going] }],
+ [{ user_id: invitee_user.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
)
creator_event.invitees.find_by(user_id: invitee_user.id)
end
@@ -160,8 +165,8 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
it "updates the invitee status" do
expect { result }.to change { creator_event_invitee.reload.status }.from(
- DiscoursePostEvent::Invitee.statuses[:going],
- ).to(DiscoursePostEvent::Invitee.statuses[:not_going])
+ DiscourseEvents::Events::Invitee.statuses[:going],
+ ).to(DiscourseEvents::Events::Invitee.statuses[:not_going])
end
end
@@ -170,8 +175,8 @@ RSpec.describe(DiscoursePostEvent::UpdateInvitee) do
it "updates the invitee status" do
expect { result }.to change { invitee.reload.status }.from(
- DiscoursePostEvent::Invitee.statuses[:going],
- ).to(DiscoursePostEvent::Invitee.statuses[:interested])
+ DiscourseEvents::Events::Invitee.statuses[:going],
+ ).to(DiscourseEvents::Events::Invitee.statuses[:interested])
end
end
end
diff --git a/plugins/discourse-events/spec/services/discourse_calendar/livestream/prepare_zoom_join_spec.rb b/plugins/discourse-events/spec/services/discourse_events/livestream/prepare_zoom_join_spec.rb
similarity index 98%
rename from plugins/discourse-events/spec/services/discourse_calendar/livestream/prepare_zoom_join_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/livestream/prepare_zoom_join_spec.rb
index 4ab1c226b5e..96f11b51755 100644
--- a/plugins/discourse-events/spec/services/discourse_calendar/livestream/prepare_zoom_join_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/livestream/prepare_zoom_join_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseCalendar::Livestream::PrepareZoomJoin do
+RSpec.describe DiscourseEvents::Livestream::PrepareZoomJoin do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:topic_id) }
end
diff --git a/plugins/discourse-events/spec/services/discourse_calendar/livestream/zoom_payload_builder_spec.rb b/plugins/discourse-events/spec/services/discourse_events/livestream/zoom_payload_builder_spec.rb
similarity index 97%
rename from plugins/discourse-events/spec/services/discourse_calendar/livestream/zoom_payload_builder_spec.rb
rename to plugins/discourse-events/spec/services/discourse_events/livestream/zoom_payload_builder_spec.rb
index f3fe22c2cdb..14ad6a2f30d 100644
--- a/plugins/discourse-events/spec/services/discourse_calendar/livestream/zoom_payload_builder_spec.rb
+++ b/plugins/discourse-events/spec/services/discourse_events/livestream/zoom_payload_builder_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseCalendar::Livestream::ZoomPayloadBuilder do
+RSpec.describe DiscourseEvents::Livestream::ZoomPayloadBuilder do
subject(:payload) { described_class.call(topic:, user:, zoom_join_data:) }
fab!(:user)
diff --git a/plugins/discourse-events/spec/services/discouse-calendar/holiday_spec.rb b/plugins/discourse-events/spec/services/discouse-calendar/holiday_spec.rb
deleted file mode 100644
index e853116a44a..00000000000
--- a/plugins/discourse-events/spec/services/discouse-calendar/holiday_spec.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseCalendar
- describe Holiday do
- describe ".find_holidays_for" do
- before { DisabledHoliday.create!(holiday_name: "Saudi National Day", region_code: "sa") }
-
- let(:holidays) do
- Holiday.find_holidays_for(
- region_code: "sa",
- start_date: "2023-02-21",
- end_date: "2023-09-23",
- )
- end
-
- it "returns a list of holidays indicating whether a holiday is disabled or not" do
- expect(holidays).to include(
- a_hash_including({ name: "Saudi National Day", regions: [:sa], disabled: true }),
- )
-
- expect(holidays).to include(
- a_hash_including({ name: "Foundation Day", regions: [:sa], disabled: false }),
- )
- end
-
- describe "dates holidays are observed on" do
- let(:holidays) do
- Holiday.find_holidays_for(
- region_code: "sg",
- start_date: "2021-12-31",
- end_date: "2022-05-31",
- show_holiday_observed_on_dates: show_holiday_observed_on_dates,
- )
- end
-
- context "when `show_holiday_observed_on_dates` is set to true" do
- let(:show_holiday_observed_on_dates) { true }
-
- it "returns the holidays with the date the holidays are observed on" do
- expect(holidays).to include(
- a_hash_including(
- { name: "New Year's Day", date: Date.new(2021, 12, 31), regions: [:sg] },
- ),
- )
-
- expect(holidays).to include(
- a_hash_including({ name: "Labour Day", date: Date.new(2022, 5, 2), regions: [:sg] }),
- )
- end
- end
-
- context "when `show_holiday_observed_on_dates` is set to false" do
- let(:show_holiday_observed_on_dates) { false }
-
- it "returns the holidays with the actual holiday dates" do
- expect(holidays).to include(
- a_hash_including(
- { name: "New Year's Day", date: Date.new(2022, 1, 1), regions: [:sg] },
- ),
- )
-
- expect(holidays).to include(
- a_hash_including({ name: "Labour Day", date: Date.new(2022, 5, 1), regions: [:sg] }),
- )
- end
- end
- end
- end
- end
-end
diff --git a/plugins/discourse-events/spec/system/anonymous_user_rsvp_event_spec.rb b/plugins/discourse-events/spec/system/anonymous_user_rsvp_event_spec.rb
index 2101f1294aa..eddea2f3f4d 100644
--- a/plugins/discourse-events/spec/system/anonymous_user_rsvp_event_spec.rb
+++ b/plugins/discourse-events/spec/system/anonymous_user_rsvp_event_spec.rb
@@ -5,7 +5,7 @@ describe "Anonymous user RSVPing to an event" do
fab!(:user) { Fabricate(:user, username: "testuser", password: "supersecurepassword") }
fab!(:topic) { Fabricate(:topic, user: admin) }
- let(:post_event_page) { PageObjects::Pages::DiscourseCalendar::PostEvent.new }
+ let(:post_event_page) { PageObjects::Pages::DiscourseEvents::PostEvent.new }
let(:login_page) { PageObjects::Pages::Login.new }
before do
@@ -36,8 +36,8 @@ describe "Anonymous user RSVPing to an event" do
end
it "overwrites an existing RSVP when an anon clicks a different status and logs in" do
- event = DiscoursePostEvent::Event.find(topic.first_post.id)
- DiscoursePostEvent::Invitee.create_attendance!(user.id, event.id, :not_going)
+ event = DiscourseEvents::Events::Event.find(topic.first_post.id)
+ DiscourseEvents::Events::Invitee.create_attendance!(user.id, event.id, :not_going)
visit(topic.url)
post_event_page.going
@@ -48,8 +48,8 @@ describe "Anonymous user RSVPing to an event" do
expect(page).to have_current_path(%r{/t/#{topic.slug}/#{topic.id}})
expect(post_event_page).to have_going_status
- invitee = DiscoursePostEvent::Invitee.find_by(user_id: user.id, post_id: event.id)
- expect(invitee.status).to eq(DiscoursePostEvent::Invitee.statuses[:going])
+ invitee = DiscourseEvents::Events::Invitee.find_by(user_id: user.id, post_id: event.id)
+ expect(invitee.status).to eq(DiscourseEvents::Events::Invitee.statuses[:going])
end
context "when the site is invite-only without login required" do
diff --git a/plugins/discourse-events/spec/system/calendar_first_day_of_week_spec.rb b/plugins/discourse-events/spec/system/calendar_first_day_of_week_spec.rb
index d3cf6000401..0c8296da3ac 100644
--- a/plugins/discourse-events/spec/system/calendar_first_day_of_week_spec.rb
+++ b/plugins/discourse-events/spec/system/calendar_first_day_of_week_spec.rb
@@ -3,7 +3,7 @@
describe "Calendar first day of week" do
fab!(:admin)
- let(:upcoming_events) { PageObjects::Pages::DiscourseCalendar::UpcomingEvents.new }
+ let(:upcoming_events) { PageObjects::Pages::DiscourseEvents::UpcomingEvents.new }
before do
SiteSetting.discourse_events_enabled = true
diff --git a/plugins/discourse-events/spec/system/composer/create_event_action_spec.rb b/plugins/discourse-events/spec/system/composer/create_event_action_spec.rb
index 72bf5d157be..a4dd06372bb 100644
--- a/plugins/discourse-events/spec/system/composer/create_event_action_spec.rb
+++ b/plugins/discourse-events/spec/system/composer/create_event_action_spec.rb
@@ -10,7 +10,7 @@ describe "Composer - Create event action" do
before do
SiteSetting.discourse_events_enabled = true
SiteSetting.discourse_post_event_enabled = true
- DiscourseCalendar::Categories::Types::Events.configure_category(
+ DiscourseEvents::Categories::Types::Events.configure_category(
events_category,
guardian: admin.guardian,
)
@@ -39,9 +39,9 @@ describe "Composer - Create event action" do
expect(page).to have_current_path(%r{/t/team-offsite-kickoff/})
topic = Topic.find_by(title: "Team offsite kickoff")
expect(topic).to be_present
- event = DiscoursePostEvent::Event.find_by(id: topic.first_post.id)
+ event = DiscourseEvents::Events::Event.find_by(id: topic.first_post.id)
expect(event).to be_present
- expect(event.status).to eq(DiscoursePostEvent::Event.statuses[:public])
+ expect(event.status).to eq(DiscourseEvents::Events::Event.statuses[:public])
expect(event.starts_at).to be_present
end
diff --git a/plugins/discourse-events/spec/system/composer/event_location_spec.rb b/plugins/discourse-events/spec/system/composer/event_location_spec.rb
index 742f0b43070..e8451e6b76b 100644
--- a/plugins/discourse-events/spec/system/composer/event_location_spec.rb
+++ b/plugins/discourse-events/spec/system/composer/event_location_spec.rb
@@ -39,7 +39,9 @@ describe "Composer - Event location" do
composer.create
expect(page).to have_css(".event-location a", text: "RSVP")
- expect(DiscoursePostEvent::Event.find(topic.first_post.id).location).to eq(markdown_location)
+ expect(DiscourseEvents::Events::Event.find(topic.first_post.id).location).to eq(
+ markdown_location,
+ )
end
it "shows the link affordance for scheme-less urls, matching what the card links" do
diff --git a/plugins/discourse-events/spec/system/event_card_spec.rb b/plugins/discourse-events/spec/system/event_card_spec.rb
index d9f18450b78..b422c7eafa0 100644
--- a/plugins/discourse-events/spec/system/event_card_spec.rb
+++ b/plugins/discourse-events/spec/system/event_card_spec.rb
@@ -23,7 +23,7 @@ describe "Event card" do
raw:
"[event start=\"#{2.hours.from_now.iso8601}\" end=\"#{3.hours.from_now.iso8601}\"]\n[/event]",
)
- DiscoursePostEvent::Event.find(post.id).update!(image_upload: upload)
+ DiscourseEvents::Events::Event.find(post.id).update!(image_upload: upload)
category_page.visit(category)
diff --git a/plugins/discourse-events/spec/system/events_category_type_setup_spec.rb b/plugins/discourse-events/spec/system/events_category_type_setup_spec.rb
index c2f7c14090c..85a6a470e42 100644
--- a/plugins/discourse-events/spec/system/events_category_type_setup_spec.rb
+++ b/plugins/discourse-events/spec/system/events_category_type_setup_spec.rb
@@ -48,7 +48,7 @@ RSpec.describe "Events Category Type Setup" do
fab!(:category)
before do
- DiscourseCalendar::Categories::Types::Events.configure_category(
+ DiscourseEvents::Categories::Types::Events.configure_category(
category,
guardian: admin.guardian,
)
@@ -82,7 +82,7 @@ RSpec.describe "Events Category Type Setup" do
end
it "preloads stored category_settings values onto the edit form" do
- DiscourseCalendar::Categories::Types::Events.configure_category(
+ DiscourseEvents::Categories::Types::Events.configure_category(
category,
guardian: admin.guardian,
configuration_values: {
diff --git a/plugins/discourse-events/spec/system/livestream_calendar_event_spec.rb b/plugins/discourse-events/spec/system/livestream_calendar_event_spec.rb
index 24c726bd628..d22b20a3ff8 100644
--- a/plugins/discourse-events/spec/system/livestream_calendar_event_spec.rb
+++ b/plugins/discourse-events/spec/system/livestream_calendar_event_spec.rb
@@ -32,14 +32,14 @@ describe "Discourse Livestream - Topic Livestream with events - Authenticated" d
topic = Fabricate(:topic, category:)
first_post = Fabricate(:post, topic:)
event =
- DiscoursePostEvent::Event.create!(
+ DiscourseEvents::Events::Event.create!(
id: first_post.id,
original_starts_at: 1.day.from_now,
original_ends_at: 2.days.from_now,
livestream: true,
location: PageObjects::Pages::TopicLivestream::LIVESTREAM_URL,
)
- DiscoursePostEvent::Invitee.create_attendance!(current_user.id, event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(current_user.id, event.id, :going)
25.times { Fabricate(:post, topic:) }
visit "/t/#{topic.slug}/#{topic.id}/26"
diff --git a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/bulk_invite_modal.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/bulk_invite_modal.rb
similarity index 98%
rename from plugins/discourse-events/spec/system/page_objects/discourse_calendar/bulk_invite_modal.rb
rename to plugins/discourse-events/spec/system/page_objects/discourse_events/bulk_invite_modal.rb
index 387483bfca0..4eb900e0f24 100644
--- a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/bulk_invite_modal.rb
+++ b/plugins/discourse-events/spec/system/page_objects/discourse_events/bulk_invite_modal.rb
@@ -2,7 +2,7 @@
module PageObjects
module Pages
- module DiscourseCalendar
+ module DiscourseEvents
class BulkInviteModal < PageObjects::Pages::Base
def set_invitee_at_row(name, status, row_number)
dropdown =
diff --git a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/livestream/topic_livestream.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/livestream/topic_livestream.rb
similarity index 100%
rename from plugins/discourse-events/spec/system/page_objects/discourse_calendar/livestream/topic_livestream.rb
rename to plugins/discourse-events/spec/system/page_objects/discourse_events/livestream/topic_livestream.rb
diff --git a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/post_event.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb
similarity index 99%
rename from plugins/discourse-events/spec/system/page_objects/discourse_calendar/post_event.rb
rename to plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb
index 74f3d3f7ebf..8fcc7b5e1bc 100644
--- a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/post_event.rb
+++ b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb
@@ -2,7 +2,7 @@
module PageObjects
module Pages
- module DiscourseCalendar
+ module DiscourseEvents
class PostEvent < PageObjects::Pages::Base
TRIGGER_MENU_SELECTOR = ".discourse-post-event-more-menu-trigger"
diff --git a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/post_event_form.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event_form.rb
similarity index 97%
rename from plugins/discourse-events/spec/system/page_objects/discourse_calendar/post_event_form.rb
rename to plugins/discourse-events/spec/system/page_objects/discourse_events/post_event_form.rb
index 483da5cfe8d..a42872bd284 100644
--- a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/post_event_form.rb
+++ b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event_form.rb
@@ -2,7 +2,7 @@
module PageObjects
module Pages
- module DiscourseCalendar
+ module DiscourseEvents
class PostEventForm < PageObjects::Pages::Base
MODAL_SELECTOR = ".post-event-builder-modal"
diff --git a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/upcoming_events.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/upcoming_events.rb
similarity index 99%
rename from plugins/discourse-events/spec/system/page_objects/discourse_calendar/upcoming_events.rb
rename to plugins/discourse-events/spec/system/page_objects/discourse_events/upcoming_events.rb
index 45d805d3cfb..a2475698d89 100644
--- a/plugins/discourse-events/spec/system/page_objects/discourse_calendar/upcoming_events.rb
+++ b/plugins/discourse-events/spec/system/page_objects/discourse_events/upcoming_events.rb
@@ -2,7 +2,7 @@
module PageObjects
module Pages
- module DiscourseCalendar
+ module DiscourseEvents
class UpcomingEvents < PageObjects::Pages::Base
def visit(prefix = "")
super("#{prefix}/upcoming-events")
diff --git a/plugins/discourse-events/spec/system/post_event_spec.rb b/plugins/discourse-events/spec/system/post_event_spec.rb
index dc74e1f081e..cf6ddf6cd4d 100644
--- a/plugins/discourse-events/spec/system/post_event_spec.rb
+++ b/plugins/discourse-events/spec/system/post_event_spec.rb
@@ -6,9 +6,9 @@ describe "Post event" do
fab!(:group)
let(:composer) { PageObjects::Components::Composer.new }
- let(:post_event_page) { PageObjects::Pages::DiscourseCalendar::PostEvent.new }
- let(:post_event_form_page) { PageObjects::Pages::DiscourseCalendar::PostEventForm.new }
- let(:bulk_invite_modal_page) { PageObjects::Pages::DiscourseCalendar::BulkInviteModal.new }
+ let(:post_event_page) { PageObjects::Pages::DiscourseEvents::PostEvent.new }
+ let(:post_event_form_page) { PageObjects::Pages::DiscourseEvents::PostEventForm.new }
+ let(:bulk_invite_modal_page) { PageObjects::Pages::DiscourseEvents::BulkInviteModal.new }
before do
SiteSetting.discourse_events_enabled = true
@@ -292,8 +292,8 @@ describe "Post event" do
expect(post_event_page).to have_going_status
expect(post_event_page).to have_selected_status(:going)
- invitee = DiscoursePostEvent::Invitee.find_by(user_id: rsvp_user.id, post_id: post.id)
- expect(invitee.status).to eq(DiscoursePostEvent::Invitee.statuses[:going])
+ invitee = DiscourseEvents::Events::Invitee.find_by(user_id: rsvp_user.id, post_id: post.id)
+ expect(invitee.status).to eq(DiscourseEvents::Events::Invitee.statuses[:going])
expect(invitee.recurring).to eq(true)
end
@@ -306,8 +306,8 @@ describe "Post event" do
expect(post_event_page).to have_going_status
expect(post_event_page).to have_selected_status(:going)
- invitee = DiscoursePostEvent::Invitee.find_by(user_id: rsvp_user.id, post_id: post.id)
- expect(invitee.status).to eq(DiscoursePostEvent::Invitee.statuses[:going])
+ invitee = DiscourseEvents::Events::Invitee.find_by(user_id: rsvp_user.id, post_id: post.id)
+ expect(invitee.status).to eq(DiscourseEvents::Events::Invitee.statuses[:going])
expect(invitee.recurring).to eq(false)
end
@@ -393,7 +393,7 @@ describe "Post event" do
MD
post = PostCreator.create!(admin, title:, raw:)
- event = DiscoursePostEvent::Event.find_by(post:)
+ event = DiscourseEvents::Events::Event.find_by(post:)
event.set_next_date
sign_in(viewer)
diff --git a/plugins/discourse-events/spec/system/upcoming_events_spec.rb b/plugins/discourse-events/spec/system/upcoming_events_spec.rb
index 5efb54d836b..1da58ea866b 100644
--- a/plugins/discourse-events/spec/system/upcoming_events_spec.rb
+++ b/plugins/discourse-events/spec/system/upcoming_events_spec.rb
@@ -7,7 +7,7 @@ describe "Upcoming Events" do
let(:composer) { PageObjects::Components::Composer.new }
let(:topic_page) { PageObjects::Pages::Topic.new }
- let(:upcoming_events) { PageObjects::Pages::DiscourseCalendar::UpcomingEvents.new }
+ let(:upcoming_events) { PageObjects::Pages::DiscourseEvents::UpcomingEvents.new }
before do
SiteSetting.discourse_events_enabled = true
@@ -35,7 +35,7 @@ describe "Upcoming Events" do
describe "popup invitees on recurring events" do
fab!(:going_recurring_user, :user)
fab!(:going_once_user, :user)
- let(:post_event_page) { PageObjects::Pages::DiscourseCalendar::PostEvent.new }
+ let(:post_event_page) { PageObjects::Pages::DiscourseEvents::PostEvent.new }
it "filters non-recurring goings out of future occurrences",
time: Time.utc(2026, 5, 12, 12, 0) do
@@ -48,14 +48,14 @@ describe "Upcoming Events" do
title: "Weekly stand-up event",
raw: "[event status='public' start='2026-05-14 14:00' recurrence='every_week']\n[/event]",
)
- event = DiscoursePostEvent::Event.find(post.id)
- DiscoursePostEvent::Invitee.create_attendance!(
+ event = DiscourseEvents::Events::Event.find(post.id)
+ DiscourseEvents::Events::Invitee.create_attendance!(
going_recurring_user.id,
event.id,
:going,
recurring: true,
)
- DiscoursePostEvent::Invitee.create_attendance!(going_once_user.id, event.id, :going)
+ DiscourseEvents::Events::Invitee.create_attendance!(going_once_user.id, event.id, :going)
upcoming_events.visit("/discuss")
upcoming_events.click_event_on("2026-05-14")
@@ -85,9 +85,14 @@ describe "Upcoming Events" do
raw:
"[event status='public' start='2026-06-11 18:00' end='2026-06-11 18:30' recurrence='every_day']\n[/event]",
)
- event = DiscoursePostEvent::Event.find(post.id)
+ event = DiscourseEvents::Events::Event.find(post.id)
- DiscoursePostEvent::Invitee.create_attendance!(admin.id, event.id, :going, recurring: false)
+ DiscourseEvents::Events::Invitee.create_attendance!(
+ admin.id,
+ event.id,
+ :going,
+ recurring: false,
+ )
visit("/upcoming-events/mine/month/2026/6/1")
@@ -98,7 +103,7 @@ describe "Upcoming Events" do
end
describe "event description in popup" do
- let(:post_event_page) { PageObjects::Pages::DiscourseCalendar::PostEvent.new }
+ let(:post_event_page) { PageObjects::Pages::DiscourseEvents::PostEvent.new }
it "shows clamped description with expand toggle", time: Time.utc(2025, 9, 10, 12, 0) do
long_description =
@@ -415,7 +420,7 @@ describe "Upcoming Events" do
title: "Non attending post event",
raw: "[event start=\"2025-06-12 08:05\"]\n[/event]",
)
- DiscoursePostEvent::Event.find(attending_event.id).create_invitees(
+ DiscourseEvents::Events::Event.find(attending_event.id).create_invitees(
[{ user_id: admin.id, status: 0 }],
)
diff --git a/script/bulk_import/generic_bulk.rb b/script/bulk_import/generic_bulk.rb
index 64305897585..9bf462eb148 100644
--- a/script/bulk_import/generic_bulk.rb
+++ b/script/bulk_import/generic_bulk.rb
@@ -1249,15 +1249,15 @@ class BulkImport::Generic < BulkImport::Base
end
def event_bbcode(event)
- return unless defined?(DiscoursePostEvent)
+ return unless defined?(DiscourseEvents::Events)
starts_at = to_datetime(event["starts_at"])
ends_at = to_datetime(event["ends_at"])
- status = DiscoursePostEvent::Event.statuses[event["status"]].to_s
+ status = DiscourseEvents::Events::Event.statuses[event["status"]].to_s
name =
if (name = event["name"].presence)
- name.ljust(DiscoursePostEvent::Event::MIN_NAME_LENGTH, ".").truncate(
- DiscoursePostEvent::Event::MAX_NAME_LENGTH,
+ name.ljust(DiscourseEvents::Events::Event::MIN_NAME_LENGTH, ".").truncate(
+ DiscourseEvents::Events::Event::MAX_NAME_LENGTH,
)
end
url = event["url"]
@@ -2673,7 +2673,7 @@ class BulkImport::Generic < BulkImport::Base
def import_post_events
puts "", "Importing events..."
- unless defined?(DiscoursePostEvent)
+ unless defined?(DiscourseEvents::Events)
puts " Skipping import of events because the plugin is not installed."
return
end
@@ -2686,10 +2686,10 @@ class BulkImport::Generic < BulkImport::Base
default_custom_fields = "{}"
timezone = "UTC"
- public_group_invitees = "{#{DiscoursePostEvent::Event::PUBLIC_GROUP}}"
+ public_group_invitees = "{#{DiscourseEvents::Events::Event::PUBLIC_GROUP}}"
standalone_invitees = "{}"
- existing_events = DiscoursePostEvent::Event.pluck(:id).to_set
+ existing_events = DiscourseEvents::Events::Event.pluck(:id).to_set
create_post_events(post_events) do |row|
post_id = post_id_from_imported_id(row["post_id"])
@@ -2706,7 +2706,7 @@ class BulkImport::Generic < BulkImport::Base
timezone: timezone,
raw_invitees:
(
- if row["status"] == DiscoursePostEvent::Event.statuses[:public]
+ if row["status"] == DiscourseEvents::Events::Event.statuses[:public]
public_group_invitees
else
standalone_invitees
@@ -2718,7 +2718,7 @@ class BulkImport::Generic < BulkImport::Base
puts "", "Importing event dates..."
post_events.reset
- existing_events = DiscoursePostEvent::EventDate.pluck(:event_id).to_set
+ existing_events = DiscourseEvents::Events::EventDate.pluck(:event_id).to_set
create_post_event_dates(post_events) do |row|
post_id = post_id_from_imported_id(row["post_id"])
@@ -2734,7 +2734,7 @@ class BulkImport::Generic < BulkImport::Base
puts "", "Importing topic event custom fields..."
post_events.reset
- field_name = DiscoursePostEvent::TOPIC_POST_EVENT_STARTS_AT
+ field_name = DiscourseEvents::Events::TOPIC_POST_EVENT_STARTS_AT
existing_fields = TopicCustomField.where(name: field_name).pluck(:topic_id).to_set
create_topic_custom_fields(post_events) do |row|
@@ -2748,7 +2748,7 @@ class BulkImport::Generic < BulkImport::Base
end
post_events.reset
- field_name = DiscoursePostEvent::TOPIC_POST_EVENT_ENDS_AT
+ field_name = DiscourseEvents::Events::TOPIC_POST_EVENT_ENDS_AT
existing_fields = TopicCustomField.where(name: field_name).pluck(:topic_id).to_set
create_topic_custom_fields(post_events) do |row|