Skip to content

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

FEATURE: Add event-specific topic filters for /filter (#45158)

Kris70330015b80d
diff --git a/plugins/discourse-events/config/locales/server.en.yml b/plugins/discourse-events/config/locales/server.en.yml
index f66bff8791f..f3107054bb9 100644
--- a/plugins/discourse-events/config/locales/server.en.yml
+++ b/plugins/discourse-events/config/locales/server.en.yml
@@ -174,6 +174,21 @@ en:
date_with_timezone: "%{date} (%{timezone})"
date_format: "%B %-d, %Y"
datetime_format: "%B %-d, %Y %-I:%M %p"
+ filter:
+ description:
+ event: "Show topics with an event"
+ event_any_of: "Show topics with an event in any of the specified states (comma-separated)"
+ exclude_event: "Exclude topics with an event in the specified state"
+ event_any: "Show topics with an event"
+ event_upcoming: "Show topics with an event that hasn't started yet"
+ event_ongoing: "Show topics with an event that is happening now"
+ event_past: "Show topics with an event that has ended"
+ event_after: "Show topics with an event starting on or after a date (YYYY-MM-DD)"
+ event_before: "Show topics with an event starting before a date (YYYY-MM-DD)"
+ event_attending: "Show topics with an event a user is going to"
+ event_attending_me: "Events you're going to"
+ order_event_start: "Sort by event start date (latest first)"
+ order_event_start_asc: "Sort by event start date (soonest first)"
notifications:
before_event_reminder: "%{title} is about to start."
after_event_reminder: "%{title} has ended."
diff --git a/plugins/discourse-events/lib/discourse_events/events/topics_filter.rb b/plugins/discourse-events/lib/discourse_events/events/topics_filter.rb
new file mode 100644
index 00000000000..87f0eb0470c
--- /dev/null
+++ b/plugins/discourse-events/lib/discourse_events/events/topics_filter.rb
@@ -0,0 +1,188 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class TopicsFilter
+ STATES = %w[any upcoming ongoing past].freeze
+ DATE_REGEXP = /\A[12]\d{3}-(0?[1-9]|1[0-2])-(0?[1-9]|[12]\d|3[01])\z/
+
+ STARTS_AT_SQL =
+ "COALESCE(current_event_dates.starts_at, discourse_post_event_events.original_starts_at)"
+ # Mirrors Event#ongoing?: an event without an end runs until the end of its start day.
+ ENDS_AT_SQL =
+ "COALESCE(current_event_dates.ends_at, date_trunc('day', #{STARTS_AT_SQL}) + INTERVAL '1 day')"
+
+ STATE_CONDITIONS = {
+ "upcoming" =>
+ "NOT discourse_post_event_events.closed AND current_event_dates.finished_at IS NULL AND #{STARTS_AT_SQL} > :now",
+ "ongoing" =>
+ "NOT discourse_post_event_events.closed AND current_event_dates.finished_at IS NULL AND #{STARTS_AT_SQL} <= :now AND #{ENDS_AT_SQL} > :now",
+ "past" =>
+ "discourse_post_event_events.closed OR current_event_dates.finished_at IS NOT NULL OR #{ENDS_AT_SQL} <= :now",
+ }.freeze
+
+ class << self
+ def register(plugin)
+ plugin.add_filter_custom_filter("event") do |scope, values, _guardian|
+ filter_by_state(scope, values) if enabled?
+ end
+
+ plugin.add_filter_custom_filter("event-after") do |scope, values, _guardian|
+ filter_by_start(scope, ">=", values) if enabled?
+ end
+
+ plugin.add_filter_custom_filter("event-before") do |scope, values, _guardian|
+ filter_by_start(scope, "<", values) if enabled?
+ end
+
+ plugin.add_filter_custom_filter("event-attending") do |scope, values, guardian|
+ filter_by_attendee(scope, values, guardian) if enabled?
+ end
+
+ plugin.add_filter_custom_filter("order:event-start") do |scope, direction, _guardian|
+ order_by_start(scope, direction) if enabled?
+ end
+
+ plugin.register_modifier(:topics_filter_options) do |results, _guardian|
+ results.concat(options) if enabled?
+ results
+ end
+ end
+
+ def filter_by_state(scope, values)
+ states = values.flat_map { |value| value.split(",") }.map(&:strip) & STATES
+ return if states.empty?
+ return scope.where(id: topic_events.select("posts.topic_id")) if states.include?("any")
+
+ condition = states.map { |state| "(#{STATE_CONDITIONS[state]})" }.join(" OR ")
+ scope.where(id: topic_events.where(condition, now: Time.current).select("posts.topic_id"))
+ end
+
+ def filter_by_start(scope, operator, values)
+ value = values.last.to_s
+ return if !value.match?(DATE_REGEXP)
+
+ date = Time.zone.parse(value)
+ return if date.nil?
+
+ scope.where(
+ id: topic_events.where("#{STARTS_AT_SQL} #{operator} ?", date).select("posts.topic_id"),
+ )
+ end
+
+ def filter_by_attendee(scope, values, guardian)
+ names =
+ values
+ .flat_map { |value| value.split(",") }
+ .map { |name| name.strip.delete_prefix("@").downcase }
+ .compact_blank
+ return if names.empty?
+
+ user_ids = User.where(username_lower: names - ["me"]).pluck(:id)
+ user_ids << guardian.user.id if names.include?("me") && guardian.authenticated?
+ return scope.none if user_ids.empty?
+
+ events =
+ Event
+ .visible
+ .joins(:invitees)
+ .where(
+ discourse_post_event_invitees: {
+ user_id: user_ids,
+ status: Invitee.statuses[:going],
+ },
+ )
+ events = Finder.apply_privacy_restrictions(events, guardian.user) if !guardian.is_admin?
+
+ scope.where(
+ id: events.joins(:post).where(posts: { post_number: 1 }).select("posts.topic_id"),
+ )
+ end
+
+ def order_by_start(scope, direction)
+ direction = direction == "ASC" ? "ASC" : "DESC"
+ starts =
+ topic_events.where("posts.topic_id = topics.id").select("#{STARTS_AT_SQL} AS starts_at")
+
+ scope.joins("LEFT JOIN LATERAL (#{starts.to_sql}) topic_event_starts ON true").order(
+ "topic_event_starts.starts_at #{direction} NULLS LAST",
+ )
+ end
+
+ def options
+ [
+ {
+ name: "event:",
+ description: I18n.t("discourse_post_event.filter.description.event"),
+ priority: 1,
+ delimiters: [
+ {
+ name: ",",
+ description: I18n.t("discourse_post_event.filter.description.event_any_of"),
+ },
+ ],
+ prefixes: [
+ {
+ name: "-",
+ description: I18n.t("discourse_post_event.filter.description.exclude_event"),
+ },
+ ],
+ },
+ *STATES.map do |state|
+ {
+ name: "event:#{state}",
+ description: I18n.t("discourse_post_event.filter.description.event_#{state}"),
+ }
+ end,
+ {
+ name: "event-after:",
+ description: I18n.t("discourse_post_event.filter.description.event_after"),
+ },
+ {
+ name: "event-before:",
+ description: I18n.t("discourse_post_event.filter.description.event_before"),
+ },
+ {
+ name: "event-attending:",
+ description: I18n.t("discourse_post_event.filter.description.event_attending"),
+ type: "username",
+ extra_entries: [
+ {
+ name: "me",
+ description: I18n.t("discourse_post_event.filter.description.event_attending_me"),
+ },
+ ],
+ },
+ {
+ name: "order:event-start",
+ description: I18n.t("discourse_post_event.filter.description.order_event_start"),
+ },
+ {
+ name: "order:event-start-asc",
+ description: I18n.t("discourse_post_event.filter.description.order_event_start_asc"),
+ },
+ ]
+ end
+
+ private
+
+ def enabled?
+ SiteSetting.discourse_post_event_enabled
+ end
+
+ # Events can only live in a topic's first post, so each matches at most one topic.
+ def topic_events
+ Event.visible.joins(:post).where(posts: { post_number: 1, deleted_at: nil }).joins(<<~SQL)
+ LEFT JOIN LATERAL (
+ SELECT starts_at, ends_at, finished_at
+ FROM discourse_calendar_post_event_dates
+ WHERE event_id = discourse_post_event_events.id
+ ORDER BY #{EventDate.current_ordering_sql}
+ LIMIT 1
+ ) current_event_dates ON true
+ SQL
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rb
index 7af5052103e..f6bb659a9b8 100644
--- a/plugins/discourse-events/plugin.rb
+++ b/plugins/discourse-events/plugin.rb
@@ -312,10 +312,13 @@ after_initialize do
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/topics_filter"
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"
+ DiscourseEvents::Events::TopicsFilter.register(self)
+
::ActionController::Base.prepend_view_path File.expand_path("../app/views", __FILE__)
add_api_parameter_route(methods: :get, actions: "discourse_events/events#index", formats: :ics)
diff --git a/plugins/discourse-events/spec/lib/topics_filter_spec.rb b/plugins/discourse-events/spec/lib/topics_filter_spec.rb
new file mode 100644
index 00000000000..eea466bb2cd
--- /dev/null
+++ b/plugins/discourse-events/spec/lib/topics_filter_spec.rb
@@ -0,0 +1,181 @@
+# frozen_string_literal: true
+
+RSpec.describe TopicsFilter do
+ fab!(:plain_topic, :topic)
+ fab!(:upcoming_event) do
+ Fabricate(
+ :event,
+ original_starts_at: 3.days.from_now,
+ original_ends_at: 3.days.from_now + 1.hour,
+ )
+ end
+ fab!(:ongoing_event) do
+ Fabricate(:event, original_starts_at: 1.hour.ago, original_ends_at: 1.hour.from_now)
+ end
+ fab!(:past_event) do
+ Fabricate(:event, original_starts_at: 3.days.ago, original_ends_at: 3.days.ago + 1.hour)
+ end
+
+ let(:upcoming_topic) { upcoming_event.post.topic }
+ let(:ongoing_topic) { ongoing_event.post.topic }
+ let(:past_topic) { past_event.post.topic }
+ let(:fixture_topic_ids) { [plain_topic.id, upcoming_topic.id, ongoing_topic.id, past_topic.id] }
+
+ before do
+ SiteSetting.discourse_events_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ end
+
+ def filtered_topic_ids(query_string, user: nil)
+ TopicsFilter
+ .new(guardian: Guardian.new(user))
+ .filter_from_query_string(query_string)
+ .pluck(:id) & fixture_topic_ids
+ end
+
+ describe "event:" do
+ it "matches topics by event state" do
+ expect(filtered_topic_ids("event:any")).to contain_exactly(
+ upcoming_topic.id,
+ ongoing_topic.id,
+ past_topic.id,
+ )
+ expect(filtered_topic_ids("event:upcoming")).to contain_exactly(upcoming_topic.id)
+ expect(filtered_topic_ids("event:ongoing")).to contain_exactly(ongoing_topic.id)
+ expect(filtered_topic_ids("event:past")).to contain_exactly(past_topic.id)
+ expect(filtered_topic_ids("event:upcoming,ongoing")).to contain_exactly(
+ upcoming_topic.id,
+ ongoing_topic.id,
+ )
+ end
+
+ it "excludes topics with events when negated" do
+ expect(filtered_topic_ids("-event:any")).to contain_exactly(plain_topic.id)
+ expect(filtered_topic_ids("-event:past")).to contain_exactly(
+ plain_topic.id,
+ upcoming_topic.id,
+ ongoing_topic.id,
+ )
+ end
+
+ it "treats closed events as past" do
+ upcoming_event.update_columns(closed: true)
+
+ expect(filtered_topic_ids("event:past")).to contain_exactly(upcoming_topic.id, past_topic.id)
+ end
+
+ it "ignores events that have been deleted" do
+ upcoming_event.update_columns(deleted_at: Time.current)
+
+ expect(filtered_topic_ids("event:any")).to contain_exactly(ongoing_topic.id, past_topic.id)
+ end
+
+ it "ignores unknown states" do
+ expect(filtered_topic_ids("event:someday")).to match_array(fixture_topic_ids)
+ end
+
+ it "does nothing when events are disabled" do
+ SiteSetting.discourse_post_event_enabled = false
+
+ expect(filtered_topic_ids("event:upcoming")).to match_array(fixture_topic_ids)
+ end
+ end
+
+ describe "event-after: and event-before:" do
+ it "matches topics by event start date" do
+ expect(filtered_topic_ids("event-after:#{1.day.from_now.to_date}")).to contain_exactly(
+ upcoming_topic.id,
+ )
+ expect(filtered_topic_ids("event-before:#{Date.current}")).to contain_exactly(past_topic.id)
+ expect(
+ filtered_topic_ids(
+ "event-after:#{2.days.ago.to_date} event-before:#{1.day.from_now.to_date}",
+ ),
+ ).to contain_exactly(ongoing_topic.id)
+ end
+
+ it "ignores values that are not dates" do
+ expect(filtered_topic_ids("event-after:7")).to match_array(fixture_topic_ids)
+ end
+ end
+
+ describe "event-attending:" do
+ fab!(:attendee, :user)
+ fab!(:viewer, :user)
+ fab!(:invited_group) { Fabricate(:group, users: [attendee]) }
+ fab!(:private_event) do
+ Fabricate(
+ :event,
+ status: DiscourseEvents::Events::Event.statuses[:private],
+ raw_invitees: [invited_group.name],
+ )
+ end
+
+ before do
+ Fabricate(
+ :post_event_invitee,
+ event: upcoming_event,
+ user: attendee,
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
+ )
+ Fabricate(
+ :post_event_invitee,
+ event: past_event,
+ user: attendee,
+ status: DiscourseEvents::Events::Invitee.statuses[:interested],
+ )
+ Fabricate(
+ :post_event_invitee,
+ event: private_event,
+ user: attendee,
+ status: DiscourseEvents::Events::Invitee.statuses[:going],
+ )
+ fixture_topic_ids << private_event.post.topic.id
+ end
+
+ it "matches events the user is going to" do
+ expect(
+ filtered_topic_ids("event-attending:#{attendee.username}", user: viewer),
+ ).to contain_exactly(upcoming_topic.id)
+ end
+
+ it "includes private events for members of an invited group" do
+ expect(filtered_topic_ids("event-attending:me", user: attendee)).to contain_exactly(
+ upcoming_topic.id,
+ private_event.post.topic.id,
+ )
+ end
+
+ it "matches nothing for anonymous users asking for their own events" do
+ expect(filtered_topic_ids("event-attending:me")).to be_empty
+ end
+ end
+
+ describe "order:event-start" do
+ it "sorts topics by event start date" do
+ ids = ->(query) { filtered_topic_ids(query) - [plain_topic.id] }
+
+ expect(ids.call("order:event-start")).to eq(
+ [upcoming_topic.id, ongoing_topic.id, past_topic.id],
+ )
+ expect(ids.call("order:event-start-asc")).to eq(
+ [past_topic.id, ongoing_topic.id, upcoming_topic.id],
+ )
+ end
+ end
+
+ describe ".option_info" do
+ it "includes the event filters" do
+ names = described_class.option_info(Guardian.new).map { |option| option[:name] }
+
+ expect(names).to include(
+ "event:",
+ "event:upcoming",
+ "event-after:",
+ "event-attending:",
+ "order:event-start",
+ "order:event-start-asc",
+ )
+ end
+ end
+end