Skip to content

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

FIX: Rework topic filter dispatch and fix negation, tags and ordering

Régis Hanolede8c7d173d0
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 8eeb90aef7c..47adc676da8 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -3319,8 +3319,6 @@ en:
tags_any: "Show topics with any of the specified tags (comma-separated)"
tags_all: "Show topics with all of the specified tags (plus-separated)"
exclude_tag: "Exclude topics with a specific tag"
- exclude_tags_any: "Exclude topics with any of the specified tags (comma-separated)"
- exclude_tags_all: "Exclude topics with all of the specified tags (plus-separated)"
tag_group: "Show topics with tags from a specific tag group"
exclude_tag_group: "Exclude topics with tags from a specific tag group"
activity_before: "Show topics with last activity before a date (YYYY-MM-DD or days ago)"
@@ -3330,7 +3328,6 @@ en:
created_before: "Show topics created before a date (YYYY-MM-DD or days ago)"
created_after: "Show topics created after a date (YYYY-MM-DD or days ago)"
created_by: "Show topics created by a specific user or group"
- created_by_user: "Show topics created by username or group (without @)"
created_by_multiple: "Show topics created by any of the specified users or groups (comma-separated)"
latest_post_before: "Show topics with last post before a date (YYYY-MM-DD or days ago)"
latest_post_after: "Show topics with last post after a date (YYYY-MM-DD or days ago)"
@@ -3353,6 +3350,7 @@ en:
status_public: "Show topics in public categories"
status_noreplies: "Show topics with no replies"
status_single_user: "Show topics with a single participant"
+ status_scheduled: "Show topics scheduled to publish to a category"
in_pinned: "Show pinned topics"
in_bookmarked: "Show topics you've bookmarked"
in_watching: "Show topics you're watching"
@@ -3364,6 +3362,7 @@ en:
in_new_replies: "Show topics with new replies"
in_new_topics: "Show new topics"
in_unseen: "Show topics you haven't seen"
+ in_untagged: "Show topics without any tags"
order_activity: "Sort by last activity (newest first)"
order_activity_asc: "Sort by last activity (oldest first)"
order_category: "Sort by category name (Z-A)"
@@ -3378,6 +3377,8 @@ en:
order_likes_op_asc: "Sort by likes on first post (least first)"
order_posters: "Sort by number of participants (most first)"
order_posters_asc: "Sort by number of participants (least first)"
+ order_posts: "Sort by number of replies (most first)"
+ order_posts_asc: "Sort by number of replies (least first)"
order_title: "Sort by title (Z-A)"
order_title_asc: "Sort by title (A-Z)"
order_views: "Sort by view count (most first)"
diff --git a/lib/topic_query.rb b/lib/topic_query.rb
index 1096ee60fea..da6da6caa8d 100644
--- a/lib/topic_query.rb
+++ b/lib/topic_query.rb
@@ -119,6 +119,7 @@ class TopicQuery
self.results_filter_callbacks = []
attr_accessor :options, :user, :guardian
+ attr_reader :invalid_filters
def self.add_custom_filter(key, &blk)
@custom_filters ||= {}
@@ -146,6 +147,7 @@ class TopicQuery
@options = options.dup
@user = user
@guardian = options[:guardian] || Guardian.new(@user)
+ @invalid_filters = []
end
def joined_topic_user(list = nil)
@@ -313,6 +315,7 @@ class TopicQuery
)
results = topics_filter.filter_from_query_string(@options[:q])
+ @invalid_filters = topics_filter.invalid_filters
if !topics_filter.topic_notification_levels.include?(NotificationLevels.all[:muted])
results = remove_muted_topics(results, @user)
diff --git a/lib/topics_filter.rb b/lib/topics_filter.rb
index c7a01c04554..3f3c321b64c 100644
--- a/lib/topics_filter.rb
+++ b/lib/topics_filter.rb
@@ -1,134 +1,105 @@
# frozen_string_literal: true
class TopicsFilter
- attr_reader :topic_ids, :topic_notification_levels
+ attr_reader :topic_ids, :topic_notification_levels, :invalid_filters
- def initialize(guardian:, scope: Topic.all, loaded_topic_users_reference: false)
+ def initialize(guardian:, scope: nil, loaded_topic_users_reference: false)
@loaded_topic_users_reference = loaded_topic_users_reference
@guardian = guardian || Guardian.new
- @scope = scope
+ @scope = scope || Topic.secured(@guardian)
@topic_notification_levels = Set.new
+ @invalid_filters = []
end
FILTER_ALIASES = {
"categories" => "category",
+ "tag-group" => "tag_group",
"tags" => "tag",
"groups" => "group",
"user" => "users",
- }
+ }.freeze
private_constant :FILTER_ALIASES
- # Shared pattern for matching quoted values (single or double quotes)
QUOTED_VALUE_PATTERN = '"[^"]*"|\'[^\']*\''
private_constant :QUOTED_VALUE_PATTERN
- # Pattern for extracting filter components: prefix, key, and value (supports quoted values)
FILTER_EXTRACTION_PATTERN =
/(?<key_prefix>(?:-|=|-=|=-))?(?<key>[\w-]+):(?<value>#{QUOTED_VALUE_PATTERN}|[^\s]+)/
private_constant :FILTER_EXTRACTION_PATTERN
- # Pattern for tokenizing query string while preserving quoted values and filter:value pairs
- # Note: wrap QUOTED_VALUE_PATTERN in non-capturing group to preserve alternation precedence
+ CATEGORY_SLUGS_PATTERN =
+ /\A(?<category_slugs>([\p{L}\p{N}\-:]+)(?<delimiter>[,])?([\p{L}\p{N}\-:]+)?(\k<delimiter>[\p{L}\p{N}\-:]+)*)\z/
+ private_constant :CATEGORY_SLUGS_PATTERN
+
+ TAG_NAMES_PATTERN =
+ /\A(?<tag_names>([\p{N}\p{L}\-_.]+)(?<delimiter>[,+])?([\p{N}\p{L}\-_.]+)?(\k<delimiter>[\p{N}\p{L}\-_.]+)*)\z/
+ private_constant :TAG_NAMES_PATTERN
+
TOKENIZER_PATTERN =
/[\w-]+:(?:#{QUOTED_VALUE_PATTERN})|[\w-]+:[^\s]+|(?:#{QUOTED_VALUE_PATTERN})|[^\s]+/
private_constant :TOKENIZER_PATTERN
+ IN_VALUES =
+ (
+ TopicUser.notification_levels.keys.map(&:to_s) +
+ %w[watching_first_post pinned bookmarked untagged new new-replies new-topics unseen]
+ ).freeze
+ private_constant :IN_VALUES
+
+ SELF_NEGATING_FILTERS = %w[category order].freeze
+ private_constant :SELF_NEGATING_FILTERS
+
+ RANGE_FILTERS = {
+ "activity-after" => %w[topics.bumped_at >=],
+ "activity-before" => %w[topics.bumped_at <=],
+ "created-after" => %w[topics.created_at >=],
+ "created-before" => %w[topics.created_at <=],
+ "latest-post-after" => %w[topics.last_posted_at >=],
+ "latest-post-before" => %w[topics.last_posted_at <=],
+ "likes-min" => %w[topics.like_count >=],
+ "likes-max" => %w[topics.like_count <=],
+ "likes-op-min" => %w[first_posts.like_count >=],
+ "likes-op-max" => %w[first_posts.like_count <=],
+ "posters-min" => %w[topics.participant_count >=],
+ "posters-max" => %w[topics.participant_count <=],
+ "posts-min" => %w[topics.posts_count >=],
+ "posts-max" => %w[topics.posts_count <=],
+ "views-min" => %w[topics.views >=],
+ "views-max" => %w[topics.views <=],
+ }.freeze
+ private_constant :RANGE_FILTERS
+
+ BOOKMARKED_FILTERS = { "bookmarked-before" => :lteq, "bookmarked-after" => :gteq }.freeze
+ private_constant :BOOKMARKED_FILTERS
+
def filter_from_query_string(query_string)
return @scope if query_string.blank?
- filters = {}
+ filters = Hash.new { |hash, key| hash[key] = [] }
query_string.scan(FILTER_EXTRACTION_PATTERN) do |key_prefix, key, value|
- key = FILTER_ALIASES[key] || key
-
- filters[key] ||= {}
- filters[key]["key_prefixes"] ||= []
- filters[key]["key_prefixes"] << key_prefix
- filters[key]["values"] ||= []
- filters[key]["values"] << value
+ filters[FILTER_ALIASES[key] || key] << [key_prefix, value]
end
- filters.each do |filter, hash|
- key_prefixes = hash["key_prefixes"]
- values = hash["values"]
-
- filter_values = extract_and_validate_value_for(filter, values)
- case filter
- when "activity-before"
- filter_by_activity(before: filter_values)
- when "activity-after"
- filter_by_activity(after: filter_values)
- when "bookmarked-after"
- filter_by_bookmarked(after: filter_values)
- when "bookmarked-before"
- filter_by_bookmarked(before: filter_values)
- when "category"
- filter_categories(values: key_prefixes.zip(filter_values))
- when "created-after"
- filter_by_created(after: filter_values)
- when "created-before"
- filter_by_created(before: filter_values)
- when "created-by"
- filter_created_by(names: filter_values.flat_map { |value| value.split(",") })
- when "in"
- filter_in(values: filter_values)
- when "latest-post-after"
- filter_by_latest_post(after: filter_values)
- when "latest-post-before"
- filter_by_latest_post(before: filter_values)
- when "likes-min"
- filter_by_number_of_likes(min: filter_values)
- when "likes-max"
- filter_by_number_of_likes(max: filter_values)
- when "likes-op-min"
- filter_by_number_of_likes_in_first_post(min: filter_values)
- when "likes-op-max"
- filter_by_number_of_likes_in_first_post(max: filter_values)
- when "order"
- order_by(values: filter_values)
- when "users"
- filter_users(values: key_prefixes.zip(filter_values))
- when "group"
- filter_groups(values: key_prefixes.zip(filter_values))
- when "posts-min"
- filter_by_number_of_posts(min: filter_values)
- when "posts-max"
- filter_by_number_of_posts(max: filter_values)
- when "posters-min"
- filter_by_number_of_posters(min: filter_values)
- when "posters-max"
- filter_by_number_of_posters(max: filter_values)
- when "status"
- filter_values.each { |status| @scope = filter_status(status: status) }
- when "tag_group"
- filter_tag_groups(values: key_prefixes.zip(filter_values))
- when "tag"
- filter_tags(values: key_prefixes.zip(filter_values))
- when "topic"
- filter_topics(values: filter_values)
- when "locale"
- filter_locale(values: key_prefixes.zip(filter_values))
- when "views-min"
- filter_by_number_of_views(min: filter_values)
- when "views-max"
- filter_by_number_of_views(max: filter_values)
+ filters.each do |filter, pairs|
+ if SELF_NEGATING_FILTERS.include?(filter)
+ positive, negated = pairs, []
else
- if custom_filter = DiscoursePluginRegistry.custom_filter_mappings.find { it.key?(filter) }
- @scope = custom_filter[filter].call(@scope, filter_values, @guardian) || @scope
- end
+ negated, positive = pairs.partition { |key_prefix, _| key_prefix&.include?("-") }
end
+
+ positive = positive.reject { |_, value| unusable_value?(filter, value) }
+ negated = negated.reject { |_, value| unusable_value?(filter, value) }
+
+ apply_filter(**filter_arguments(filter, positive)) if positive.present?
+
+ negated.each { |pair| apply_negated_filter(**filter_arguments(filter, [pair])) }
end
- # Tokenize while preserving quoted values, then extract keywords (non-filter terms)
- keywords =
- query_string
- .scan(TOKENIZER_PATTERN)
- .reject { |word| word.include?(":") }
- .map(&:strip)
- .reject(&:empty?)
+ keywords = query_string.scan(TOKENIZER_PATTERN).reject { |word| word.include?(":") }.join(" ")
- if keywords.present? && keywords.join(" ").length >= SiteSetting.min_search_term_length
- ts_query = Search.ts_query(term: keywords.join(" "))
+ if keywords.present? && keywords.length >= SiteSetting.min_search_term_length
+ ts_query = Search.ts_query(term: keywords)
@scope = @scope.where(<<~SQL)
topics.id IN (
SELECT topic_id
@@ -167,28 +138,47 @@ class TopicsFilter
if @guardian.can_see_deleted_topics?(category)
@scope = @scope.unscope(where: :deleted_at).where.not(topics: { deleted_at: nil })
+ else
+ @scope = @scope.none
end
when "public"
@scope = @scope.joins(:category).where("NOT categories.read_restricted")
when "noreplies"
@scope = @scope.where("topics.posts_count = 1")
- when "single_user"
+ when "single_user", "single-user"
@scope = @scope.where("topics.participant_count = 1")
+ when "scheduled"
+ @scope =
+ @scope.where(
+ id:
+ TopicTimer.where(status_type: TopicTimer.types[:publish_to_category]).select(
+ :timerable_id,
+ ),
+ )
else
- if custom_filter = TopicsFilter.custom_status_filters[status]
- @scope = custom_filter[:block].call(@scope) if custom_filter[:enabled].call
+ custom_filter = TopicsFilter.custom_status_filters[status]
+
+ if custom_filter&.fetch(:enabled)&.call
+ @scope = custom_filter[:block].call(@scope)
+ else
+ invalid_filter!("status:#{status}")
end
end
@scope
end
+ def self.option(name, **attributes)
+ key = name.delete_suffix(":").tr("-:", "__")
+ { name:, description: I18n.t("filter.description.#{key}"), **attributes }
+ end
+ private_class_method :option
+
def self.option_info(guardian)
results = [
- {
- name: "category:",
+ option(
+ "category:",
alias: "categories:",
- description: I18n.t("filter.description.category"),
priority: 1,
type: "category",
delimiters: [{ name: ",", description: I18n.t("filter.description.category_any") }],
@@ -200,43 +190,23 @@ class TopicsFilter
description: I18n.t("filter.description.exclude_category_without_subcategories"),
},
],
- },
- {
- name: "topic:",
- description: I18n.t("filter.description.topic"),
+ ),
+ option(
+ "topic:",
type: "text",
delimiters: [{ name: ",", description: I18n.t("filter.description.topic_any") }],
- },
- {
- name: "activity-before:",
- description: I18n.t("filter.description.activity_before"),
- type: "date",
- },
- {
- name: "activity-after:",
- description: I18n.t("filter.description.activity_after"),
- type: "date",
- },
- {
- name: "created-before:",
- description: I18n.t("filter.description.created_before"),
- type: "date",
- },
- {
- name: "created-after:",
- description: I18n.t("filter.description.created_after"),
- priority: 1,
- type: "date",
- },
- {
- name: "created-by:",
- description: I18n.t("filter.description.created_by"),
+ ),
+ option("activity-before:", type: "date"),
+ option("activity-after:", type: "date"),
+ option("created-before:", type: "date"),
+ option("created-after:", type: "date", priority: 1),
+ option(
+ "created-by:",
type: "username_group_list",
delimiters: [{ name: ",", description: I18n.t("filter.description.created_by_multiple") }],
- },
- {
- name: "users:",
- description: I18n.t("filter.description.users"),
+ ),
+ option(
+ "users:",
type: "username",
priority: 1,
prefixes: [{ name: "-", description: I18n.t("filter.description.exclude_users") }],
@@ -244,118 +214,59 @@ class TopicsFilter
{ name: ",", description: I18n.t("filter.description.users_any") },
{ name: "+", description: I18n.t("filter.description.users_all") },
],
- },
- {
- name: "latest-post-before:",
- description: I18n.t("filter.description.latest_post_before"),
- type: "date",
- },
- {
- name: "latest-post-after:",
- description: I18n.t("filter.description.latest_post_after"),
- type: "date",
- },
- { name: "likes-min:", description: I18n.t("filter.description.likes_min"), type: "number" },
- { name: "likes-max:", description: I18n.t("filter.description.likes_max"), type: "number" },
- {
- name: "likes-op-min:",
- description: I18n.t("filter.description.likes_op_min"),
- type: "number",
- },
- {
- name: "likes-op-max:",
- description: I18n.t("filter.description.likes_op_max"),
- type: "number",
- },
- { name: "posts-min:", description: I18n.t("filter.description.posts_min"), type: "number" },
- { name: "posts-max:", description: I18n.t("filter.description.posts_max"), type: "number" },
- {
- name: "posters-min:",
- description: I18n.t("filter.description.posters_min"),
- type: "number",
- },
- {
- name: "posters-max:",
- description: I18n.t("filter.description.posters_max"),
- type: "number",
- },
- { name: "views-min:", description: I18n.t("filter.description.views_min"), type: "number" },
- { name: "views-max:", description: I18n.t("filter.description.views_max"), type: "number" },
- { name: "status:", description: I18n.t("filter.description.status"), priority: 1 },
- { name: "status:open", description: I18n.t("filter.description.status_open") },
- { name: "status:closed", description: I18n.t("filter.description.status_closed") },
- { name: "status:archived", description: I18n.t("filter.description.status_archived") },
- { name: "status:listed", description: I18n.t("filter.description.status_listed") },
- { name: "status:unlisted", description: I18n.t("filter.description.status_unlisted") },
- { name: "status:deleted", description: I18n.t("filter.description.status_deleted") },
- { name: "status:public", description: I18n.t("filter.description.status_public") },
- { name: "status:noreplies", description: I18n.t("filter.description.status_noreplies") },
- { name: "status:single_user", description: I18n.t("filter.description.status_single_user") },
- { name: "order:", description: I18n.t("filter.description.order"), priority: 1 },
- { name: "order:activity", description: I18n.t("filter.description.order_activity") },
- { name: "order:activity-asc", description: I18n.t("filter.description.order_activity_asc") },
- { name: "order:category", description: I18n.t("filter.description.order_category") },
- { name: "order:category-asc", description: I18n.t("filter.description.order_category_asc") },
- { name: "order:created", description: I18n.t("filter.description.order_created") },
- { name: "order:created-asc", description: I18n.t("filter.description.order_created_asc") },
- { name: "order:latest-post", description: I18n.t("filter.description.order_latest_post") },
- {
- name: "order:latest-post-asc",
- description: I18n.t("filter.description.order_latest_post_asc"),
- },
- { name: "order:likes", description: I18n.t("filter.description.order_likes") },
- { name: "order:likes-asc", description: I18n.t("filter.description.order_likes_asc") },
- { name: "order:likes-op", description: I18n.t("filter.description.order_likes_op") },
- { name: "order:likes-op-asc", description: I18n.t("filter.description.order_likes_op_asc") },
- { name: "order:posters", description: I18n.t("filter.description.order_posters") },
- { name: "order:posters-asc", description: I18n.t("filter.description.order_posters_asc") },
- { name: "order:title", description: I18n.t("filter.description.order_title") },
- { name: "order:title-asc", description: I18n.t("filter.description.order_title_asc") },
- { name: "order:views", description: I18n.t("filter.description.order_views") },
- { name: "order:views-asc", description: I18n.t("filter.description.order_views_asc") },
- { name: "order:hot", description: I18n.t("filter.description.order_hot") },
- { name: "order:hot-asc", description: I18n.t("filter.description.order_hot_asc") },
- { name: "order:read", description: I18n.t("filter.description.order_read") },
- { name: "order:read-asc", description: I18n.t("filter.description.order_read_asc") },
+ ),
+ option("latest-post-before:", type: "date"),
+ option("latest-post-after:", type: "date"),
+ option("likes-min:", type: "number"),
+ option("likes-max:", type: "number"),
+ option("likes-op-min:", type: "number"),
+ option("likes-op-max:", type: "number"),
+ option("posts-min:", type: "number"),
+ option("posts-max:", type: "number"),
+ option("posters-min:", type: "number"),
+ option("posters-max:", type: "number"),
+ option("views-min:", type: "number"),
+ option("views-max:", type: "number"),
+ option("status:", priority: 1),
+ option("status:open"),
+ option("status:closed"),
+ option("status:archived"),
+ option("status:listed"),
+ option("status:unlisted"),
+ option("status:deleted"),
+ option("status:public"),
+ option("status:noreplies"),
+ option("status:single-user"),
+ option("status:scheduled"),
+ option("order:", priority: 1),
+ *ORDER_BY_MAPPINGS.keys.flat_map { |o| [option("order:#{o}"), option("order:#{o}-asc")] },
]
if guardian.authenticated?
results.concat(
[
- { name: "in:", description: I18n.t("filter.description.in"), priority: 1 },
- { name: "in:pinned", description: I18n.t("filter.description.in_pinned") },
- { name: "in:bookmarked", description: I18n.t("filter.description.in_bookmarked") },
- {
- name: "bookmarked-before:",
- description: I18n.t("filter.description.bookmarked_before"),
- type: "date",
- },
- {
- name: "bookmarked-after:",
- description: I18n.t("filter.description.bookmarked_after"),
- type: "date",
- },
- { name: "in:watching", description: I18n.t("filter.description.in_watching") },
- { name: "in:tracking", description: I18n.t("filter.description.in_tracking") },
- { name: "in:muted", description: I18n.t("filter.description.in_muted") },
- { name: "in:normal", description: I18n.t("filter.description.in_normal") },
- {
- name: "in:watching_first_post",
- description: I18n.t("filter.description.in_watching_first_post"),
- },
- { name: "in:new", description: I18n.t("filter.description.in_new") },
- { name: "in:new-replies", description: I18n.t("filter.description.in_new_replies") },
- { name: "in:new-topics", description: I18n.t("filter.description.in_new_topics") },
- { name: "in:unseen", description: I18n.t("filter.description.in_unseen") },
+ option("in:", priority: 1),
+ option("in:pinned"),
+ option("in:bookmarked"),
+ option("bookmarked-before:", type: "date"),
+ option("bookmarked-after:", type: "date"),
+ option("in:watching"),
+ option("in:tracking"),
+ option("in:muted"),
+ option("in:normal"),
+ option("in:watching-first-post"),
+ option("in:new"),
+ option("in:new-replies"),
+ option("in:new-topics"),
+ option("in:unseen"),
],
)
end
if SiteSetting.tagging_enabled?
results.push(
- {
- name: "tag:",
- description: I18n.t("filter.description.tag"),
+ option(
+ "tag:",
alias: "tags:",
priority: 1,
type: "tag",
@@ -364,24 +275,21 @@ class TopicsFilter
{ name: "+", description: I18n.t("filter.description.tags_all") },
],
prefixes: [{ name: "-", description: I18n.t("filter.description.exclude_tag") }],
- },
- )
- results.push(
- {
- name: "tag_group:",
- description: I18n.t("filter.description.tag_group"),
+ ),
+ option("in:untagged"),
+ option(
+ "tag-group:",
+ alias: "tag_group:",
type: "tag_group",
prefixes: [{ name: "-", description: I18n.t("filter.description.exclude_tag_group") }],
- },
+ ),
)
end
- # Group participation filter (any/all)
results.push(
- {
- name: "group:",
+ option(
+ "group:",
alias: "groups:",
- description: I18n.t("filter.description.group"),
type: "group",
priority: 1,
prefixes: [{ name: "-", description: I18n.t("filter.description.exclude_group") }],
@@ -389,26 +297,88 @@ class TopicsFilter
{ name: ",", description: I18n.t("filter.description.groups_any") },
{ name: "+", description: I18n.t("filter.description.groups_all") },
],
- },
- )
-
- # Locale filter
- results.push(
- {
- name: "locale:",
- description: I18n.t("filter.description.locale"),
+ ),
+ option(
+ "locale:",
type: "text",
delimiters: [{ name: ",", description: I18n.t("filter.description.locale_any") }],
prefixes: [{ name: "-", description: I18n.t("filter.description.exclude_locale") }],
- },
+ ),
)
- # this modifier allows custom plugins to add UI tips in the /filter route
- DiscoursePluginRegistry.apply_modifier(:topics_filter_options, results, guardian)
+ results = DiscoursePluginRegistry.apply_modifier(:topics_filter_options, results, guardian)
+
+ results.each { |option| option[:prefixes] = [] if option[:name].start_with?("order:") }
end
private
+ def apply_filter(filter:, filter_values:, key_prefixes:)
+ case filter
+ when *RANGE_FILTERS.keys
+ filter_by_range(filter:, value: filter_values)
+ when *BOOKMARKED_FILTERS.keys
+ filter_by_bookmarked(filter:, value: filter_values)
+ when "category"
+ filter_categories(values: key_prefixes.zip(filter_values))
+ when "created-by"
+ filter_created_by(names: filter_values.flat_map { |value| value.split(",") })
+ when "in"
+ filter_in(values: filter_values)
+ when "order"
+ order_by(values: filter_values)
+ when "users"
+ filter_participation(values: key_prefixes.zip(filter_values), by: :users)
+ when "group"
+ filter_participation(values: key_prefixes.zip(filter_values), by: :groups)
+ when "status"
+ filter_values.each { |status| filter_status(status:) }
+ when "tag_group"
+ filter_tag_groups(values: key_prefixes.zip(filter_values))
+ when "tag"
+ filter_tags(values: key_prefixes.zip(filter_values))
+ when "topic"
+ filter_topics(values: filter_values)
+ when "locale"
+ filter_locale(values: key_prefixes.zip(filter_values))
+ else
+ if custom_filter = DiscoursePluginRegistry.custom_filter_mappings.find { it.key?(filter) }
+ @scope = custom_filter[filter].call(@scope, filter_values, @guardian) || @scope
+ end
+ end
+ end
+
+ def apply_negated_filter(filter:, filter_values:, key_prefixes:)
+ scope_before_filter = @scope
+ loaded_topic_users_reference = @loaded_topic_users_reference
+ topic_notification_levels = @topic_notification_levels.dup
+ topic_ids = @topic_ids
+
+ apply_filter(filter:, filter_values:, key_prefixes:)
+
+ matched_topics = @scope.except(:order, :limit, :offset).reselect("topics.id")
+
+ filter_acted = [email protected]?(scope_before_filter)
+
+ @loaded_topic_users_reference = loaded_topic_users_reference
+ @topic_notification_levels = topic_notification_levels
+ @topic_ids = topic_ids
+
+ @scope = filter_acted ? scope_before_filter.where.not(id: matched_topics) : scope_before_filter
+ end
+
+ def invalid_filter!(token)
+ @invalid_filters << token
+ end
+
+ def unusable_value?(filter, value)
+ return false if !RANGE_FILTERS.key?(filter) && !BOOKMARKED_FILTERS.key?(filter)
+ return false if extract_and_validate_value_for(filter, [value]).present?
+
+ invalid_filter!("#{filter}:#{value}")
+ true
+ end
+
def filter_topics(values:)
@topic_ids =
values
@@ -424,6 +394,14 @@ class TopicsFilter
/\A(?<year>[12][0-9]{3})-(?<month>0?[1-9]|1[0-2])-(?<day>0?[1-9]|[12]\d|3[01])\z/
private_constant :YYYY_MM_DD_REGEXP
+ def filter_arguments(filter, pairs)
+ {
+ filter:,
+ filter_values: extract_and_validate_value_for(filter, pairs.map(&:last)),
+ key_prefixes: pairs.map(&:first),
+ }
+ end
+
def extract_and_validate_value_for(filter, values)
case filter
when "activity-before", "activity-after", "bookmarked-before", "bookmarked-after",
@@ -453,29 +431,20 @@ class TopicsFilter
end
end
- def filter_by_topic_range(column_name:, min: nil, max: nil, scope: nil)
- return @scope if min.nil? && max.nil?
+ def filter_by_range(filter:, value:)
+ return if value.nil?
- value = min || max
- operator = min ? ">=" : "<="
- @scope = (scope || @scope).where("#{column_name} #{operator} ?", value)
+ column, operator = RANGE_FILTERS[filter]
+ @scope = joins_first_posts(@scope) if column.start_with?("first_posts.")
+ @scope = @scope.where("#{column} #{operator} ?", value)
end
- def filter_by_activity(before: nil, after: nil)
- filter_by_topic_range(column_name: "topics.bumped_at", min: after, max: before)
- end
-
- def filter_by_created(before: nil, after: nil)
- filter_by_topic_range(column_name: "topics.created_at", min: after, max: before)
- end
-
- def filter_by_bookmarked(before: nil, after: nil)
+ def filter_by_bookmarked(filter:, value:)
return @scope = @scope.none if [email protected]?
- return @scope if before.nil? && after.nil?
+ return if value.nil?
user_id = @guardian.user.id.to_i
- value = before || after
- date_comparison = before ? :lteq : :gteq
+ date_comparison = BOOKMARKED_FILTERS[filter]
bookmarks_table = Bookmark.arel_table
topic_bookmarks =
@@ -496,259 +465,103 @@ class TopicsFilter
@scope = @scope.where(id: topic_bookmarks).or(@scope.where(id: post_bookmarks))
end
- def filter_by_latest_post(before: nil, after: nil)
- filter_by_topic_range(column_name: "topics.last_posted_at", min: after, max: before)
- end
-
- def filter_by_number_of_posts(min: nil, max: nil)
- filter_by_topic_range(column_name: "topics.posts_count", min:, max:)
- end
-
- def filter_by_number_of_posters(min: nil, max: nil)
- filter_by_topic_range(column_name: "topics.participant_count", min:, max:)
- end
-
- def filter_by_number_of_likes(min: nil, max: nil)
- filter_by_topic_range(column_name: "topics.like_count", min:, max:)
- end
-
- def filter_by_number_of_likes_in_first_post(min: nil, max: nil)
- filter_by_topic_range(
- column_name: "first_posts.like_count",
- min:,
- max:,
- scope: joins_first_posts(@scope),
- )
- end
-
- def filter_by_number_of_views(min: nil, max: nil)
- filter_by_topic_range(column_name: "topics.views", min:, max:)
- end
-
- def calculate_all_or_any(value)
- require_all = nil
- names = nil
-
- if value.include?("+")
- names = value.split("+")
- require_all = true
- if value.include?(",")
- # no mix and match
- return nil, []
- end
- else
- names = value.split(",")
- require_all = false
- if value.include?("+")
- # no mix and match
- return nil, []
- end
- end
-
- [require_all, names.map(&:downcase).reject(&:blank?)]
- end
-
# users:a,b => any of a or b participated in the topic
# users:a+b => both a and b participated in the topic
- # -users:a,b => neither a nor b participated in the topic
- # -users:a+b => at least one of a or b did not participate in the topic
- def filter_users(values:)
- values.each do |prefix, value|
- require_all, usernames = calculate_all_or_any(value)
+ # group: matches the same way, on group membership instead of the user.
+ def filter_participation(values:, by:)
+ values.each do |key_prefix, value|
+ require_all = value.include?("+")
+ names = value.split(require_all ? "+" : ",").map(&:downcase).reject(&:blank?)
+ names = [] if require_all && value.include?(",")
- if usernames.empty?
- @scope = @scope.none
+ if names.empty?
+ invalid_filter!("#{by == :users ? "users" : "group"}:#{value}")
+ @scope = @scope.none if !key_prefix&.include?("-")
next
end
- user_ids = User.not_staged.where("username_lower IN (?)", usernames).pluck(:id)
+ ids = participant_ids(by, names)
- if user_ids.empty?
+ if ids.empty? || (require_all && ids.length < names.length)
@scope = @scope.none
next
end
if require_all
- if user_ids.length < usernames.length
- @scope = @scope.none
- next
- end
-
- # A possible alternative is to select the topics with the users with the least posts
- # then expand to all of the rest of the users, this can limit the scanning
- if prefix == "-"
- @scope = @scope.where(<<~SQL, user_ids: user_ids, user_count: user_ids.length)
- topics.id NOT IN (
- SELECT p1.topic_id
- FROM posts p1
- WHERE p1.user_id IN (:user_ids) AND p1.deleted_at IS NULL #{whisper_condition("p1")}
- GROUP BY p1.topic_id
- HAVING COUNT(DISTINCT p1.user_id) = :user_count
- )
- SQL
- else
- user_ids.each_with_index { |uid, idx| @scope = @scope.where(<<~SQL) }
- EXISTS (
- SELECT 1
- FROM posts p#{idx}
- WHERE p#{idx}.topic_id = topics.id AND p#{idx}.user_id = #{uid} AND p#{idx}.deleted_at IS NULL #{whisper_condition("p#{idx}")}
- LIMIT 1
- )
- SQL
- end
+ ids.each { |id| @scope = @scope.where(participation_sql(by, [id])) }
else
- not_sql = prefix == "-" ? "NOT" : ""
- @scope = @scope.where(<<~SQL, user_ids: user_ids)
- topics.id #{not_sql} IN (
- SELECT DISTINCT p.topic_id
- FROM posts p
- WHERE p.user_id IN (:user_ids)
- AND p.deleted_at IS NULL
- #{whisper_condition("p")}
- )
- SQL
+ @scope = @scope.where(participation_sql(by, ids))
end
end
end
- # group:staff,moderators => any of the groups have participation
- # group:staff+moderators => both groups have participation
- # -group:staff,moderators => none of the groups have participation
- # -group:staff+moderators => at least one of the groups has no participation
- def filter_groups(values:)
- values.each do |prefix, value|
- require_all, group_names = calculate_all_or_any(value)
+ def participant_ids(by, names)
+ return User.not_staged.where(username_lower: names).pluck(:id) if by == :users
- if group_names.empty?
- @scope = @scope.none
- next
- end
-
- group_ids =
- Group
- .visible_groups(@guardian.user)
- .members_visible_groups(@guardian.user)
- .where("lower(name) IN (?)", group_names)
- .pluck(:id)
-
- if group_ids.empty?
- @scope = @scope.none if prefix != "-"
- next
- end
-
- if require_all
- if group_ids.length < group_names.length
- @scope = @scope.none if prefix != "-"
- next
- end
+ Group
+ .visible_groups(@guardian.user)
+ .members_visible_groups(@guardian.user)
+ .where("lower(name) IN (?)", names)
+ .pluck(:id)
+ end
- exists_clauses = group_ids.each_with_index.map { |gid, idx| <<~SQL }
- EXISTS (
- SELECT 1
- FROM posts pg#{idx}
- JOIN group_users gu#{idx} ON gu#{idx}.user_id = pg#{idx}.user_id
- WHERE pg#{idx}.topic_id = topics.id
- AND pg#{idx}.deleted_at IS NULL
- AND gu#{idx}.group_id = #{gid}
- #{whisper_condition("pg#{idx}")}
- )
- SQL
-
- if prefix == "-"
- @scope = @scope.where("NOT (#{exists_clauses.join(" AND ")})")
- else
- exists_clauses.each { |exists_clause| @scope = @scope.where(exists_clause) }
- end
- else
- not_sql = prefix == "-" ? "NOT" : ""
- @scope = @scope.where(<<~SQL, group_ids:)
- #{not_sql} EXISTS (
- SELECT 1
- FROM posts p
- JOIN group_users gu ON gu.user_id = p.user_id
- WHERE p.topic_id = topics.id
- AND gu.group_id IN (:group_ids)
- AND p.deleted_at IS NULL
- #{whisper_condition("p")}
- )
- SQL
- end
+ def participation_sql(by, ids)
+ if by == :groups
+ join = "JOIN group_users gu ON gu.user_id = p.user_id"
+ column = "gu.group_id"
+ else
+ join = nil
+ column = "p.user_id"
end
+
+ <<~SQL
+ EXISTS (
+ SELECT 1
+ FROM posts p
+ #{join}
+ WHERE p.topic_id = topics.id
+ AND #{column} IN (#{ids.join(",")})
+ AND p.deleted_at IS NULL
+ #{whisper_condition("p")}
+ )
+ SQL
end
def filter_categories(values:)
- category_slugs = {
- include: {
- with_subcategories: [],
- without_subcategories: [],
- },
- exclude: {
- with_subcategories: [],
- without_subcategories: [],
- },
- }
+ include_category_ids = []
+ exclude_category_ids = []
+ include_requested = false
values.each do |key_prefix, value|
exclude_categories = key_prefix&.include?("-")
exclude_subcategories = key_prefix&.include?("=")
- value
- .scan(
- /\A(?<category_slugs>([\p{L}\p{N}\-:]+)(?<delimiter>[,])?([\p{L}\p{N}\-:]+)?(\k<delimiter>[\p{L}\p{N}\-:]+)*)\z/,
- )
- .each do |category_slugs_match, delimiter|
- slugs = category_slugs_match.split(delimiter)
- type = exclude_categories ? :exclude : :include
- subcategory_type = exclude_subcategories ? :without_subcategories : :with_subcategories
- category_slugs[type][subcategory_type].concat(slugs)
- end
- end
+ match = value.match(CATEGORY_SLUGS_PATTERN)
- include_category_ids = []
+ if match.nil?
+ invalid_filter!("category:#{value}")
+ @scope = @scope.none if !exclude_categories
+ next
+ end
- if category_slugs[:include][:without_subcategories].present?
- include_category_ids =
- get_category_ids_from_slugs(
- category_slugs[:include][:without_subcategories],
- exclude_subcategories: true,
- )
- end
+ slugs = match[:category_slugs].split(match[:delimiter] || ",")
+ ids = category_ids_from_slugs(slugs, exclude_subcategories:)
- if category_slugs[:include][:with_subcategories].present?
- include_category_ids.concat(
- get_category_ids_from_slugs(
- category_slugs[:include][:with_subcategories],
- exclude_subcategories: false,
- ),
- )
+ if exclude_categories
+ exclude_category_ids.concat(ids)
+ else
+ include_requested = true
+ include_category_ids.concat(ids)
+ end
end
if include_category_ids.present?
@scope = @scope.where("topics.category_id IN (?)", include_category_ids)
- elsif category_slugs[:include].values.flatten.present?
+ elsif include_requested
@scope = @scope.none
return
end
- exclude_category_ids = []
-
- if category_slugs[:exclude][:without_subcategories].present?
- exclude_category_ids =
- get_category_ids_from_slugs(
- category_slugs[:exclude][:without_subcategories],
- exclude_subcategories: true,
- )
- end
-
- if category_slugs[:exclude][:with_subcategories].present?
- exclude_category_ids.concat(
- get_category_ids_from_slugs(
- category_slugs[:exclude][:with_subcategories],
- exclude_subcategories: false,
- ),
- )
- end
-
# Use `NOT EXISTS` instead of `NOT IN` to avoid performance issues with large arrays.
@scope = @scope.where(<<~SQL) if exclude_category_ids.present?
NOT EXISTS (
@@ -760,66 +573,54 @@ class TopicsFilter
end
def filter_created_by(names:)
- if names.include?("me") && @guardian.authenticated?
- names = names.map { |n| n == "me" ? @guardian.user.username_lower : n }
- end
+ names = names.map(&:downcase)
- if (user_ids = User.where("username_lower IN (?)", names.map(&:downcase)).pluck(:id)) &&
- user_ids.any?
- @scope = @scope.joins(:user).where(user_id: user_ids)
- return
+ if @guardian.authenticated?
+ names = names.map { |name| name == "me" ? @guardian.user.username_lower : name }
end
- if (
- group_ids =
- Group
- .visible_groups(@guardian.user)
- .members_visible_groups(@guardian.user)
- .where("lower(name) IN (?)", names.map(&:downcase))
- .pluck(:id)
- ) && group_ids.any?
- @scope =
- @scope
- .joins(:user)
- .joins("INNER JOIN group_users ON group_users.user_id = users.id")
- .where("group_users.group_id IN (?)", group_ids)
- .distinct(:id)
- return
+ user_ids = User.where(username_lower: names).pluck(:id)
+ return @scope = @scope.where(user_id: user_ids) if user_ids.any?
+
+ group_ids =
+ Group
+ .visible_groups(@guardian.user)
+ .members_visible_groups(@guardian.user)
+ .where("lower(name) IN (?)", names)
+ .pluck(:id)
+
+ if group_ids.any?
+ return @scope = @scope.where(user_id: GroupUser.where(group_id: group_ids).select(:user_id))
end
@scope = @scope.none
end
- def apply_custom_filter!(scope:, filter_name:, values:)
+ def apply_custom_in_filters!(values)
values.dup.each do |value|
- custom_key = "#{filter_name}:#{value}"
- if custom_match =
- DiscoursePluginRegistry.custom_filter_mappings.find { |hash| hash.key?(custom_key) }
- scope = custom_match[custom_key].call(scope, custom_key, @guardian) || scope
- values.delete(value)
- end
+ custom_key = "in:#{value}"
+ custom_match =
+ DiscoursePluginRegistry.custom_filter_mappings.find { |hash| hash.key?(custom_key) }
+ next if custom_match.nil?
+
+ @scope = custom_match[custom_key].call(@scope, custom_key, @guardian) || @scope
+ values.delete(value)
end
- scope
end
def ensure_topic_users_reference!
- if @guardian.authenticated?
- if !@loaded_topic_users_reference
- @scope =
- @scope.joins(
- "LEFT JOIN topic_users tu ON tu.topic_id = topics.id
- AND tu.user_id = #{@guardian.user.id.to_i}",
- )
- @loaded_topic_users_reference = true
- end
- end
+ return if [email protected]? || @loaded_topic_users_reference
+
+ @scope =
+ @scope.joins(
+ "LEFT JOIN topic_users tu ON tu.topic_id = topics.id
+ AND tu.user_id = #{@guardian.user.id.to_i}",
+ )
+ @loaded_topic_users_reference = true
end
- def topic_user_scope
- @scope.where(
- "tu.notification_level IN (:topic_notification_levels)",
- topic_notification_levels: @topic_notification_levels.to_a,
- )
+ def topic_user_scope(levels)
+ @scope.where("tu.notification_level IN (?)", levels)
end
def watching_first_post_scope
@@ -834,18 +635,24 @@ class TopicsFilter
def filter_in(values:)
values.uniq!
- # handle edge case of comma-separated values
values.map! { |value| value.split(",") }.flatten!
+ values.map! { |value| value == "watching-first-post" ? "watching_first_post" : value }
+
if values.delete("pinned")
@scope =
@scope.where(
- "topics.pinned_at IS NOT NULL AND topics.pinned_until > topics.pinned_at AND ? < topics.pinned_until",
+ "topics.pinned_at IS NOT NULL AND (topics.pinned_until IS NULL OR ? < topics.pinned_until)",
Time.zone.now,
)
end
- @scope = apply_custom_filter!(scope: @scope, filter_name: "in", values:)
+ if values.delete("untagged")
+ @scope =
+ @scope.where("NOT EXISTS (SELECT 1 FROM topic_tags WHERE topic_tags.topic_id = topics.id)")
+ end
+
+ apply_custom_in_filters!(values)
if @guardian.authenticated?
if values.delete("new-topics")
@@ -883,37 +690,30 @@ class TopicsFilter
@scope = @scope.where("tu.bookmarked")
end
- if values.present?
- values.each do |value|
- value
- .split(",")
- .each do |topic_notification_level|
- if level = TopicUser.notification_levels[topic_notification_level.to_sym]
- @topic_notification_levels << level
- end
- end
- end
- end
+ levels = values.filter_map { |value| TopicUser.notification_levels[value.to_sym] }
+ @topic_notification_levels.merge(levels)
- # watching_first_post is a category/tag-level notification, not a topic-level one
- # We need to handle it separately from regular notification levels and combine with OR
- has_watching_first_post = values.delete("watching_first_post")
+ watching_first_post = values.include?("watching_first_post")
- if has_watching_first_post && @topic_notification_levels.present?
+ if watching_first_post && levels.present?
ensure_topic_users_reference!
- @scope = combine_scopes_with_or(topic_user_scope, watching_first_post_scope)
- elsif has_watching_first_post
+ @scope = combine_scopes_with_or(topic_user_scope(levels), watching_first_post_scope)
+ elsif watching_first_post
@scope = @scope.merge(watching_first_post_scope)
- elsif @topic_notification_levels.present?
+ elsif levels.present?
ensure_topic_users_reference!
- @scope = @scope.merge(topic_user_scope)
+ @scope = @scope.merge(topic_user_scope(levels))
end
elsif values.present?
@scope = @scope.none
end
+
+ (values - IN_VALUES).each { |value| invalid_filter!("in:#{value}") }
end
- def get_category_ids_from_slugs(slugs, exclude_subcategories: false)
+ def category_ids_from_slugs(slugs, exclude_subcategories: false)
+ return [] if slugs.empty?
+
category_ids = Category.ids_from_slugs(slugs)
category_ids =
@@ -929,36 +729,13 @@ class TopicsFilter
category_ids
end
- # Accepts an array of tag names and returns an array of resolved tag IDs.
- # Synonym tags are resolved to their target tag ID.
- def tag_ids_from_tag_names(tag_names)
- DiscourseTagging
- .filter_visible(Tag, @guardian)
- .where_name(tag_names)
- .pluck(:id, :target_tag_id)
- .map { |id, target_id| target_id || id }
- .uniq
- end
-
def filter_tag_groups(values:)
- values.each do |key_prefix, tag_groups_value|
- tag_group_name = strip_quotes(tag_groups_value)
- tag_group_ids = TagGroup.visible(@guardian).where_name(tag_group_name).pluck(:id)
- exclude_clause = "NOT" if key_prefix == "-"
- filter =
- "tags.id #{exclude_clause} IN (SELECT tag_id FROM tag_group_memberships WHERE tag_group_id IN (?))"
-
- query =
- if exclude_clause.present?
- @scope
- .joins("LEFT JOIN topic_tags ON topic_tags.topic_id = topics.id")
- .joins("LEFT JOIN tags ON tags.id = topic_tags.tag_id")
- .where("tags.id IS NULL OR #{filter}", tag_group_ids)
- else
- @scope.joins(:tags).where(filter, tag_group_ids)
- end
+ values.each do |_, value|
+ tag_group_ids = TagGroup.visible(@guardian).where_name(strip_quotes(value)).pluck(:id)
+
+ tag_ids = TagGroupMembership.where(tag_group_id: tag_group_ids).select(:tag_id)
- @scope = query.distinct(:id)
+ @scope = @scope.where(id: TopicTag.where(tag_id: tag_ids).select(:topic_id))
end
end
@@ -970,64 +747,35 @@ class TopicsFilter
return if !SiteSetting.tagging_enabled?
values.each do |key_prefix, value|
- break if key_prefix && key_prefix != "-"
-
- value.scan(
- /\A(?<tag_names>([\p{N}\p{L}\-_.]+)(?<delimiter>[,+])?([\p{N}\p{L}\-_.]+)?(\k<delimiter>[\p{N}\p{L}\-_.]+)*)\z/,
- ) do |tag_names, delimiter|
- match_all = delimiter != ","
-
- tags = tag_names.split(delimiter)
- tag_ids = tag_ids_from_tag_names(tags)
-
- case [key_prefix, match_all]
- in ["-", false]
- exclude_topics_with_any_tags(tag_ids)
- in ["-", true]
- exclude_topics_with_all_tags(tag_ids)
- in [nil, false]
- include_topics_with_any_tags(tag_ids)
- in [nil, true]
- has_invalid_tags = tag_ids.length < tags.length
-
- if has_invalid_tags
- @scope = @scope.none
- else
- include_topics_with_all_tags(tag_ids)
- end
- end
+ if key_prefix && key_prefix != "-"
+ invalid_filter!("#{key_prefix}tag:#{value}")
+ next
end
- end
- end
-
- def topic_tags_alias
- @topic_tags_alias ||= 0
- "tt#{@topic_tags_alias += 1}"
- end
- def exclude_topics_with_all_tags(tag_ids)
- where_clause = []
+ match = value.match(TAG_NAMES_PATTERN)
- tag_ids.each do |tag_id|
- sql_alias = "tt#{topic_tags_alias}"
+ if match.nil?
+ invalid_filter!("tag:#{value}")
+ @scope = @scope.none if key_prefix != "-"
+ next
+ end
- @scope =
- @scope.joins(
- "LEFT JOIN topic_tags #{sql_alias} ON #{sql_alias}.topic_id = topics.id AND #{sql_alias}.tag_id = #{tag_id}",
- )
+ tags = match[:tag_names].split(match[:delimiter])
+ tag_ids = DiscourseTagging.visible_tag_ids_resolving_synonyms(tags, @guardian)
- where_clause << "#{sql_alias}.topic_id IS NULL"
+ if match[:delimiter] == ","
+ include_topics_with_any_tags(tag_ids)
+ elsif tag_ids.length < tags.length
+ @scope = @scope.none
+ else
+ include_topics_with_all_tags(tag_ids)
+ end
end
-
- @scope = @scope.where(where_clause.join(" OR "))
end
- def exclude_topics_with_any_tags(tag_ids)
- @scope =
- @scope.where(
- "topics.id NOT IN (SELECT DISTINCT topic_id FROM topic_tags WHERE topic_tags.tag_id IN (?))",
- tag_ids,
- )
+ def topic_tags_alias
+ @topic_tags_alias ||= 0
+ "tt#{@topic_tags_alias += 1}"
end
def include_topics_with_all_tags(tag_ids)
@@ -1041,35 +789,12 @@ class TopicsFilter
end
def include_topics_with_any_tags(tag_ids)
- sql_alias = topic_tags_alias
-
- @scope =
- @scope
- .joins("INNER JOIN topic_tags #{sql_alias} ON #{sql_alias}.topic_id = topics.id")
- .where("#{sql_alias}.tag_id IN (?)", tag_ids)
- .distinct(:id)
+ @scope = @scope.where(id: TopicTag.where(tag_id: tag_ids).select(:topic_id))
end
def filter_locale(values:)
- include_locales = []
- exclude_locales = []
-
- values.each do |key_prefix, value|
- locales = value.split(",").map(&:strip).reject(&:blank?)
- next if locales.empty?
-
- if key_prefix == "-"
- exclude_locales.concat(locales)
- else
- include_locales.concat(locales)
- end
- end
-
- @scope = @scope.where(locale: include_locales) if include_locales.present?
-
- if exclude_locales.present?
- @scope = @scope.where("topics.locale IS NULL OR topics.locale NOT IN (?)", exclude_locales)
- end
+ locales = values.flat_map { |_, value| value.split(",").map(&:strip) }.reject(&:blank?)
+ @scope = @scope.where(locale: locales) if locales.present?
end
ORDER_BY_MAPPINGS = {
@@ -1096,6 +821,9 @@ class TopicsFilter
"posters" => {
column: "topics.participant_count",
},
+ "posts" => {
+ column: "topics.posts_count",
+ },
"title" => {
column: "LOWER(topics.title)",
},
@@ -1128,13 +856,11 @@ class TopicsFilter
def order_by(values:)
values.each do |value|
- # If the order by value is not recognized, check if it is a custom filter.
match_data = value.match(ORDER_BY_REGEXP)
- if match_data && column_name = ORDER_BY_MAPPINGS.dig(match_data[:order_by], :column)
- if scope = ORDER_BY_MAPPINGS.dig(match_data[:order_by], :scope)
- @scope = instance_exec(&scope)
- end
- @scope = @scope.order("#{column_name} #{match_data[:asc] ? "ASC" : "DESC"}")
+ if match_data
+ mapping = ORDER_BY_MAPPINGS[match_data[:order_by]]
+ @scope = instance_exec(&mapping[:scope]) if mapping[:scope]
+ @scope = @scope.order("#{mapping[:column]} #{match_data[:asc] ? "ASC" : "DESC"}")
else
match_data = value.match(/^(?<column>.*?)(?:-(?<asc>asc))?$/)
key = "order:#{match_data[:column]}"
@@ -1142,6 +868,8 @@ class TopicsFilter
DiscoursePluginRegistry.custom_filter_mappings.find { |hash| hash.key?(key) }
dir = match_data[:asc] ? "ASC" : "DESC"
@scope = custom_match[key].call(@scope, dir, @guardian) || @scope
+ else
+ invalid_filter!("order:#{value}")
end
end
end
diff --git a/spec/lib/topic_query_spec.rb b/spec/lib/topic_query_spec.rb
index 61e546f147d..6f806fcc4e4 100644
--- a/spec/lib/topic_query_spec.rb
+++ b/spec/lib/topic_query_spec.rb
@@ -44,6 +44,15 @@ RSpec.describe TopicQuery do
)
end
+ describe "#list_filter" do
+ it "exposes the filter fragments it could not parse" do
+ topic_query = TopicQuery.new(nil, q: "status:nonsense")
+ topic_query.list_filter
+
+ expect(topic_query.invalid_filters).to eq(["status:nonsense"])
+ end
+ end
+
describe "secure category" do
it "filters categories out correctly" do
category = Fabricate(:category_with_definition)
diff --git a/spec/lib/topics_filter_spec.rb b/spec/lib/topics_filter_spec.rb
index 0f5ee85d8e4..0abb80f33f5 100644
--- a/spec/lib/topics_filter_spec.rb
+++ b/spec/lib/topics_filter_spec.rb
@@ -5,16 +5,25 @@ RSpec.describe TopicsFilter do
fab!(:admin)
fab!(:group)
+ def filtered(query, guardian = Guardian.new)
+ TopicsFilter.new(guardian:).filter_from_query_string(query).pluck(:id)
+ end
+
describe "#option_info" do
let(:options) { TopicsFilter.option_info(Guardian.new) }
it "returns name and description keys for every option" do
- expect(options).to be_an(Array)
- expect(options).to all(be_a(Hash))
+ expect(options).to be_present
expect(options).to all(include(:name, :description))
+ end
+
+ it "resolves a real translation for every option" do
+ untranslated =
+ options.select do |option|
+ option[:description].blank? || option[:description].to_s.match?(/translation missing/i)
+ end
- # 10 is arbitray, but better than just checking for 1
- expect(options.length).to be > 10
+ expect(untranslated.map { |option| option[:name] }).to eq([])
end
it "does not include tag options when tagging is disabled" do
@@ -55,7 +64,7 @@ RSpec.describe TopicsFilter do
in:tracking
in:muted
in:normal
- in:watching_first_post
+ in:watching-first-post
in:unseen
]
@@ -103,7 +112,100 @@ RSpec.describe TopicsFilter do
end
end
+ describe "#invalid_filters" do
+ fab!(:topic)
+
+ it "reports values a known keyword does not understand" do
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ filter.filter_from_query_string(
+ "status:nonsense order:nonsense in:nonsense views-min:abc created-after:2024-13-45",
+ )
+
+ expect(filter.invalid_filters).to contain_exactly(
+ "status:nonsense",
+ "order:nonsense",
+ "in:nonsense",
+ "views-min:abc",
+ "created-after:2024-13-45",
+ )
+ end
+
+ it "reports only the bad value when a keyword repeats with a good and a bad one" do
+ chatty = Fabricate(:topic, posts_count: 10)
+ quiet = Fabricate(:topic, posts_count: 1)
+
+ ["posts-min:10 -posts-min:abc", "-posts-min:abc posts-min:10"].each do |query|
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ ids = filter.filter_from_query_string(query).pluck(:id)
+
+ expect(filter.invalid_filters).to contain_exactly("posts-min:abc"), query
+ expect(ids).to include(chatty.id), query
+ expect(ids).not_to include(quiet.id), query
+ end
+ end
+
+ it "reports an invalid bookmark date" do
+ filter = TopicsFilter.new(guardian: user.guardian)
+ filter.filter_from_query_string("bookmarked-after:2024-13-45")
+
+ expect(filter.invalid_filters).to contain_exactly("bookmarked-after:2024-13-45")
+ end
+
+ it "reports invalid values on negated keywords" do
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ filter.filter_from_query_string("-status:nonsense -in:nonsense")
+
+ expect(filter.invalid_filters).to contain_exactly("status:nonsense", "in:nonsense")
+ end
+
+ it "does not report free text that happens to contain a colon" do
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ filter.filter_from_query_string("outage https://status.example.com standup at 12:30")
+
+ expect(filter.invalid_filters).to eq([])
+ end
+
+ it "does not report user-specific in: values for anonymous users" do
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ filter.filter_from_query_string("in:bookmarked")
+
+ expect(filter.invalid_filters).to eq([])
+ end
+
+ it "is empty for a query it fully understands" do
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ filter.filter_from_query_string("status:open order:created")
+
+ expect(filter.invalid_filters).to eq([])
+ end
+ end
+
+ describe "scope defaulting" do
+ it "does not expose topics in categories the guardian cannot see" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ hidden = Fabricate(:topic, category: private_category)
+ visible = Fabricate(:topic)
+
+ ids = filtered("")
+
+ expect(ids).to include(visible.id)
+ expect(ids).not_to include(hidden.id)
+ end
+ end
+
describe "#filter_from_query_string" do
+ it "preserves extra selected columns when negating a filter" do
+ open_topic = Fabricate(:topic)
+ Fabricate(:topic, closed: true)
+ scope = Topic.select("topics.*, topics.id AS custom_id")
+
+ topics =
+ TopicsFilter.new(guardian: user.guardian, scope:).filter_from_query_string("-status:closed")
+
+ expect(topics.map(&:id)).to contain_exactly(open_topic.id)
+ expect(topics.first.custom_id).to eq(open_topic.id)
+ end
+
describe "when filtering with the `users` and `group` filters" do
fab!(:u1) { Fabricate(:user, username: "alice") }
fab!(:u2) { Fabricate(:user, username: "bob") }
@@ -126,171 +228,99 @@ RSpec.describe TopicsFilter do
end
it "users:alice returns topics where alice participated" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("users:alice")
- .pluck(:id)
+ ids = filtered("users:alice")
expect(ids).to include(topic_by_u1.id, topic_by_u1_and_u2.id)
expect(ids).not_to include(topic_by_u2.id)
end
+ it "-users:alice excludes topics where alice participated" do
+ ids = filtered("-users:alice")
+ expect(ids).to include(topic_by_u2.id)
+ expect(ids).not_to include(topic_by_u1.id, topic_by_u1_and_u2.id)
+ end
+
it "users:alice,bob returns topics with either alice or bob" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("users:alice,bob")
- .pluck(:id)
+ ids = filtered("users:alice,bob")
expect(ids).to include(topic_by_u1.id, topic_by_u2.id, topic_by_u1_and_u2.id)
end
it "users:alice+bob returns only topics where both participated/allowed" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("users:alice+bob")
- .pluck(:id)
+ ids = filtered("users:alice+bob")
expect(ids).to contain_exactly(topic_by_u1_and_u2.id)
end
it "-users:alice,bob returns topics where neither alice nor bob participated" do
post = Fabricate(:post)
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-users:alice,bob")
- .pluck(:id)
+ ids = filtered("-users:alice,bob")
expect(ids).to contain_exactly(post.topic_id)
end
it "-users:alice+bob returns topics where bob and alice did not participate together" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-users:alice+bob")
- .pluck(:id)
+ ids = filtered("-users:alice+bob")
expect(ids).to contain_exactly(topic_by_u1.id, topic_by_u2.id)
end
it "-user:alice,bob (alias) returns topics where neither alice nor bob participated" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-user:alice,bob")
- .pluck(:id)
+ ids = filtered("-user:alice,bob")
expect(ids).to contain_exactly()
end
it "group:group1 returns topics with participants from the group or group-allowed PMs" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("group:group1")
- .pluck(:id)
+ ids = filtered("group:group1")
expect(ids).to include(topic_by_u1.id, topic_by_u1_and_u2.id)
end
it "groups:group1,group2 returns union of both groups" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("groups:group1,group2")
- .pluck(:id)
+ ids = filtered("groups:group1,group2")
expect(ids).to include(topic_by_u1.id, topic_by_u2.id, topic_by_u1_and_u2.id)
end
it "group:group1+group2 returns only topics with both groups represented" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("group:group1+group2")
- .pluck(:id)
+ ids = filtered("group:group1+group2")
expect(ids).to contain_exactly(topic_by_u1_and_u2.id)
end
it "-group:group1 returns topics without participants from the group" do
topic_by_u3 = Fabricate(:post, user: u3).topic
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-group:group1")
- .pluck(:id)
+ ids = filtered("-group:group1")
expect(ids).to contain_exactly(topic_by_u2.id, topic_by_u3.id)
end
it "-groups:group1,group2 returns topics with participants from neither group" do
topic_by_u3 = Fabricate(:post, user: u3).topic
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-groups:group1,group2")
- .pluck(:id)
+ ids = filtered("-groups:group1,group2")
expect(ids).to contain_exactly(topic_by_u3.id)
end
it "-group:group1+group2 returns topics where both groups are not represented together" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-group:group1+group2")
- .pluck(:id)
+ ids = filtered("-group:group1+group2")
expect(ids).to contain_exactly(topic_by_u1.id, topic_by_u2.id)
end
- it "-group:missing is a no-op when the group cannot be resolved" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-group:missing")
- .pluck(:id)
- expect(ids).to contain_exactly(topic_by_u1.id, topic_by_u2.id, topic_by_u1_and_u2.id)
- end
-
- it "-group:group1+missing is a no-op when any group cannot be resolved" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-group:group1+missing")
- .pluck(:id)
- expect(ids).to contain_exactly(topic_by_u1.id, topic_by_u2.id, topic_by_u1_and_u2.id)
- end
-
- it "-group:group1 returns topics where the only post from a group member is deleted" do
- topic = Fabricate(:topic)
- Fabricate(:post, topic:, user: u1).update_column(:deleted_at, Time.zone.now)
+ it "reports a negated value that mixes the + and , delimiters" do
+ %w[-users:alice+bob,cara -group:group1+group2,group2].each do |query|
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ filter.filter_from_query_string(query)
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-group:group1")
- .pluck(:id)
- expect(ids).to include(topic.id)
+ expect(filter.invalid_filters).to contain_exactly(query.delete_prefix("-")), query
+ end
end
- it "group:group1 should not return topics where the only post from a group member is deleted" do
- topic = Fabricate(:topic)
- post = Fabricate(:post, topic:, user: u1)
- post.update_column(:deleted_at, Time.zone.now)
+ it "is a no-op when a negated group cannot be resolved" do
+ all_ids = [topic_by_u1.id, topic_by_u2.id, topic_by_u1_and_u2.id]
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("group:group1")
- .pluck(:id)
- expect(ids).not_to include(topic.id)
+ expect(filtered("-group:missing")).to contain_exactly(*all_ids)
+ expect(filtered("-group:group1+missing")).to contain_exactly(*all_ids)
end
- it "group:group1+group2 should not return topics where a group member's only post is deleted" do
+ it "ignores deleted posts when matching group participation" do
topic = Fabricate(:topic)
Fabricate(:post, topic:, user: u1).update_column(:deleted_at, Time.zone.now)
Fabricate(:post, topic:, user: u2)
- ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("group:group1+group2")
- .pluck(:id)
- expect(ids).not_to include(topic.id)
+ expect(filtered("-group:group1")).to include(topic.id)
+ expect(filtered("group:group1")).not_to include(topic.id)
+ expect(filtered("group:group1+group2")).not_to include(topic.id)
end
context "with whispers" do
@@ -303,24 +333,13 @@ RSpec.describe TopicsFilter do
before { SiteSetting.whispers_allowed_groups = "#{whisperer_group.id}" }
- it "users:alice should not return topics where alice only whispered when viewed by non-whisperer" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new(regular_user))
- .filter_from_query_string("users:alice")
- .pluck(:id)
- expect(ids).not_to include(topic_with_whisper_only.id)
- expect(ids).to include(topic_by_u1.id, topic_by_u1_and_u2.id)
- end
+ it "hides whisper-only participation from non-whisperers" do
+ %w[users:alice group:group1].each do |query|
+ ids = filtered(query, Guardian.new(regular_user))
- it "group:group1 should not return topics where group members only whispered when viewed by non-whisperer" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new(regular_user))
- .filter_from_query_string("group:group1")
- .pluck(:id)
- expect(ids).not_to include(topic_with_whisper_only.id)
- expect(ids).to include(topic_by_u1.id, topic_by_u1_and_u2.id)
+ expect(ids).not_to include(topic_with_whisper_only.id), query
+ expect(ids).to include(topic_by_u1.id, topic_by_u1_and_u2.id), query
+ end
end
end
end
@@ -335,18 +354,11 @@ RSpec.describe TopicsFilter do
end
it "order:hot sorts by topic_hot_scores.score desc" do
- expect(
- TopicsFilter.new(guardian: Guardian.new).filter_from_query_string("order:hot").pluck(:id),
- ).to start_with(t2.id, t1.id)
+ expect(filtered("order:hot")).to start_with(t2.id, t1.id)
end
it "order:hot-asc sorts ascending" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:hot-asc")
- .pluck(:id),
- ).to start_with(t1.id, t2.id)
+ expect(filtered("order:hot-asc")).to start_with(t1.id, t2.id)
end
end
@@ -359,12 +371,10 @@ RSpec.describe TopicsFilter do
fab!(:closed_topic_with_tag2) { Fabricate(:topic, tags: [tag2], closed: true) }
it "returns matching topics for `status:closed tags:tag1,tag2`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:closed tags:tag1,tag2")
- .pluck(:id),
- ).to contain_exactly(closed_topic_with_tag.id, closed_topic_with_tag2.id)
+ expect(filtered("status:closed tags:tag1,tag2")).to contain_exactly(
+ closed_topic_with_tag.id,
+ closed_topic_with_tag2.id,
+ )
end
end
@@ -379,25 +389,32 @@ RSpec.describe TopicsFilter do
Fabricate(:topic, pinned_at: 2.hours.ago, pinned_until: 1.hour.ago)
end
+ describe "when query string is `in:untagged`" do
+ it "returns only topics without tags" do
+ SiteSetting.tagging_enabled = true
+ untagged = Fabricate(:topic)
+ tagged = Fabricate(:topic, tags: [Fabricate(:tag)])
+
+ ids = filtered("in:untagged")
+
+ expect(ids).to include(untagged.id)
+ expect(ids).not_to include(tagged.id)
+ end
+ end
+
describe "when query string is `in:pinned`" do
it "returns pinned topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("in:pinned")
- .pluck(:id),
- ).to contain_exactly(pinned_topic.id)
+ expect(filtered("in:pinned")).to contain_exactly(pinned_topic.id)
+ end
+
+ it "returns topics pinned without an expiry date" do
+ permanent = Fabricate(:topic, pinned_at: Time.zone.now, pinned_until: nil)
+
+ expect(filtered("in:pinned")).to include(permanent.id)
end
it "does not return expired pinned topics" do
- freeze_time(2.hours.from_now) do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("in:pinned")
- .pluck(:id),
- ).to eq([])
- end
+ freeze_time(2.hours.from_now) { expect(filtered("in:pinned")).to eq([]) }
end
end
@@ -421,11 +438,7 @@ RSpec.describe TopicsFilter do
before { user_for_new_filters.user_option.update!(new_topic_duration_minutes: 1.day.ago) }
it "in:new-topics returns only new topics" do
- ids =
- TopicsFilter
- .new(guardian: user_for_new_filters.guardian)
- .filter_from_query_string("in:new-topics")
- .pluck(:id)
+ ids = filtered("in:new-topics", user_for_new_filters.guardian)
expect(ids).to contain_exactly(new_topic.id)
end
@@ -464,9 +477,7 @@ RSpec.describe TopicsFilter do
end
it "anonymous user with in:new returns none" do
- ids =
- TopicsFilter.new(guardian: Guardian.new).filter_from_query_string("in:new").pluck(:id)
- expect(ids).to be_empty
+ expect(filtered("in:new")).to be_empty
end
end
@@ -486,79 +497,47 @@ RSpec.describe TopicsFilter do
end
it "returns no topics for an anonymous user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("in:bookmarked")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("in:bookmarked")).to eq([])
end
it "returns bookmarked topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:bookmarked")
- .pluck(:id),
- ).to contain_exactly(topic.id)
+ expect(filtered("in:bookmarked", Guardian.new(user))).to contain_exactly(topic.id)
end
end
describe "when query string is `in:bookmarked in:pinnned`" do
it "returns topics that are bookmarked and pinned" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:bookmarked in:pinned")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("in:bookmarked in:pinned", Guardian.new(user))).to eq([])
BookmarkManager.new(user).create_for(
bookmarkable_id: pinned_topic.id,
bookmarkable_type: "Topic",
)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:bookmarked in:pinned")
- .pluck(:id),
- ).to contain_exactly(pinned_topic.id)
+ expect(filtered("in:bookmarked in:pinned", Guardian.new(user))).to contain_exactly(
+ pinned_topic.id,
+ )
end
end
- TopicUser.notification_levels.keys.each do |notification_level|
- describe "when query string is `in:#{notification_level}`" do
- fab!(:"user_#{notification_level}_topic") do
- Fabricate(:topic).tap do |topic|
- TopicUser.change(
- user.id,
- topic.id,
- notification_level: TopicUser.notification_levels[notification_level],
- )
- end
- end
-
- it "returns no topics when the user is anonymous" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("in:#{notification_level}")
- .pluck(:id),
- ).to eq([])
+ it "returns topics matching each topic notification level" do
+ topics =
+ TopicUser.notification_levels.values.uniq.to_h do |value|
+ topic = Fabricate(:topic)
+ TopicUser.change(user.id, topic.id, notification_level: value)
+ [value, topic]
end
- it "returns topics set to the #{notification_level} notification level" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:#{notification_level}")
- .pluck(:id),
- ).to contain_exactly(public_send("user_#{notification_level}_topic").id)
- end
+ TopicUser.notification_levels.each do |level, value|
+ expect(filtered("in:#{level}", user.guardian)).to contain_exactly(topics[value].id),
+ "in:#{level}"
end
end
+ it "returns no topics for a notification level filter when the user is anonymous" do
+ expect(filtered("in:watching")).to eq([])
+ end
+
describe "when filtering by multiple topic notification levels" do
fab!(:user_muted_topic) do
Fabricate(:topic).tap do |topic|
@@ -592,34 +571,27 @@ RSpec.describe TopicsFilter do
describe "when query string is `in:muted,invalid`" do
it "ignores the invalid notification level" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:muted,invalid")
- .pluck(:id),
- ).to contain_exactly(user_muted_topic.id)
+ expect(filtered("in:muted,invalid", Guardian.new(user))).to contain_exactly(
+ user_muted_topic.id,
+ )
end
end
describe "when query string is `in:muted in:tracking`" do
it "returns topics that the user is tracking or has muted" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:muted in:tracking")
- .pluck(:id),
- ).to contain_exactly(user_muted_topic.id, user_tracking_topic.id)
+ expect(filtered("in:muted in:tracking", Guardian.new(user))).to contain_exactly(
+ user_muted_topic.id,
+ user_tracking_topic.id,
+ )
end
end
describe "when query string is `in:muted,tracking" do
it "returns tracked or muted topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:muted,tracking")
- .pluck(:id),
- ).to contain_exactly(user_muted_topic.id, user_tracking_topic.id)
+ expect(filtered("in:muted,tracking", Guardian.new(user))).to contain_exactly(
+ user_muted_topic.id,
+ user_tracking_topic.id,
+ )
end
end
end
@@ -654,36 +626,23 @@ RSpec.describe TopicsFilter do
end
it "returns no topics when the user is anonymous" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("in:watching_first_post")
- .pluck(:id),
- ).to be_empty
+ expect(filtered("in:watching_first_post")).to be_empty
end
it "returns the union of watched-category and watched-tag topics" do
- ids =
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:watching_first_post")
- .pluck(:id)
+ expected = [topic_in_watched_category.id, topic_with_watched_tag.id, topic_with_both.id]
- expect(ids).to contain_exactly(
- topic_in_watched_category.id,
- topic_with_watched_tag.id,
- topic_with_both.id,
- )
+ %w[in:watching_first_post in:watching-first-post].each do |query|
+ ids = filtered(query, Guardian.new(user))
+
+ expect(ids).to contain_exactly(*expected), query
+ end
end
it "combines with other filters" do
topic_in_watched_category.update!(closed: true)
- ids =
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:watching_first_post status:closed")
- .pluck(:id)
+ ids = filtered("in:watching_first_post status:closed", Guardian.new(user))
expect(ids).to contain_exactly(topic_in_watched_category.id)
end
@@ -698,11 +657,7 @@ RSpec.describe TopicsFilter do
)
end
- ids =
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:watching,watching_first_post")
- .pluck(:id)
+ ids = filtered("in:watching,watching_first_post", Guardian.new(user))
expect(ids).to contain_exactly(
user_watching_topic.id,
@@ -733,24 +688,19 @@ RSpec.describe TopicsFilter do
it "supports a custom filter" do
plugin.add_filter_custom_filter("word_count", &word_count_block)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("word_count:42")
- .pluck(:id),
- ).to contain_exactly(word_count_topic.id, word_count_topic_2.id)
+ expect(filtered("word_count:42")).to contain_exactly(
+ word_count_topic.id,
+ word_count_topic_2.id,
+ )
end
it "supports multiple custom filters" do
plugin.add_filter_custom_filter("word_count", &word_count_block)
plugin.add_filter_custom_filter("id", &id_block)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("word_count:42 id:#{word_count_topic.id}")
- .pluck(:id),
- ).to contain_exactly(word_count_topic.id)
+ expect(filtered("word_count:42 id:#{word_count_topic.id}")).to contain_exactly(
+ word_count_topic.id,
+ )
end
end
@@ -772,207 +722,112 @@ RSpec.describe TopicsFilter do
fab!(:topic_in_category2) { Fabricate(:topic, category: category2) }
fab!(:topic_in_category2_subcategory) { Fabricate(:topic, category: category2_subcategory) }
- describe "when query string is `category:category`" do
- it "returns topics from the specified category and its subcategories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category")
- .pluck(:id),
- ).to contain_exactly(topic_in_category.id, topic_in_category_subcategory.id)
- end
-
- it "returns topics from the specified category and all descendant categories" do
- SiteSetting.max_category_nesting = 3
+ it "returns no topics when the category value cannot be parsed" do
+ expect(filtered("category:category+category2")).to eq([])
+ end
- category_subcategory_subcategory =
- Fabricate(
- :category,
- parent_category: category_subcategory,
- name: "category subcategory subcategory",
- )
+ it "returns topics from the specified category and its subcategories" do
+ expect(filtered("category:category")).to contain_exactly(
+ topic_in_category.id,
+ topic_in_category_subcategory.id,
+ )
+ end
- topic_in_category_subcategory_subcategory =
- Fabricate(:topic, category: category_subcategory_subcategory)
+ it "returns topics from every descendant category" do
+ SiteSetting.max_category_nesting = 3
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category.id,
- topic_in_category_subcategory.id,
- topic_in_category_subcategory_subcategory.id,
+ category_subcategory_subcategory =
+ Fabricate(
+ :category,
+ parent_category: category_subcategory,
+ name: "category subcategory subcategory",
)
- end
- end
- describe "when query string is `category:category,category2`" do
- it "returns topics from any specified category and its subcategories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category,category2")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category.id,
- topic_in_category_subcategory.id,
- topic_in_category2.id,
- topic_in_category2_subcategory.id,
- )
- end
- end
+ topic_in_category_subcategory_subcategory =
+ Fabricate(:topic, category: category_subcategory_subcategory)
- describe "when query string is `category:category category:category2`" do
- it "returns topics from any specified category and its descendants" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category category:category2")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category.id,
- topic_in_category_subcategory.id,
- topic_in_category2.id,
- topic_in_category2_subcategory.id,
- )
- end
+ expect(filtered("category:category")).to contain_exactly(
+ topic_in_category.id,
+ topic_in_category_subcategory.id,
+ topic_in_category_subcategory_subcategory.id,
+ )
end
- describe "when query string is `category:category =category:category2`" do
- it "includes descendants only for categories marked with the subcategory option" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category =category:category2")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category.id,
- topic_in_category_subcategory.id,
- topic_in_category2.id,
- )
- end
- end
+ it "unions categories given as a comma list or as repeated keys" do
+ expected = [
+ topic_in_category.id,
+ topic_in_category_subcategory.id,
+ topic_in_category2.id,
+ topic_in_category2_subcategory.id,
+ ]
- describe "when query string is `-category:category`" do
- it "excludes topics from the specified category and its subcategories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-category:category")
- .pluck(:id),
- ).to contain_exactly(topic_in_category2.id, topic_in_category2_subcategory.id)
- end
+ expect(filtered("category:category,category2")).to contain_exactly(*expected)
+ expect(filtered("category:category category:category2")).to contain_exactly(*expected)
end
- describe "when query string is `-category:category2,category`" do
- it "excludes topics from either specified category and their subcategories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-category:category2,category")
- .pluck(:id),
- ).to eq([])
- end
+ it "includes descendants only for the categories without the = prefix" do
+ expect(filtered("category:category =category:category2")).to contain_exactly(
+ topic_in_category.id,
+ topic_in_category_subcategory.id,
+ topic_in_category2.id,
+ )
end
- describe "when query string is `-category:category -category:category2-subcategory`" do
- it "excludes topics from each specified category and its descendants" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-category:category -category:category2-subcategory")
- .pluck(:id),
- ).to contain_exactly(topic_in_category2.id)
- end
- end
+ it "excludes the specified categories and their subcategories" do
+ expect(filtered("-category:category")).to contain_exactly(
+ topic_in_category2.id,
+ topic_in_category2_subcategory.id,
+ )
- describe "when query string is `-=category:category`" do
- it "excludes topics only from the specified category" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-=category:category")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category_subcategory.id,
- topic_in_category2.id,
- topic_in_category2_subcategory.id,
- )
- end
- end
+ expect(filtered("-category:category2,category")).to eq([])
- describe "when query string is `-=category:category,category2`" do
- it "excludes topics only from the specified categories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-=category:category,category2")
- .pluck(:id),
- ).to contain_exactly(topic_in_category_subcategory.id, topic_in_category2_subcategory.id)
- end
+ expect(filtered("-category:category -category:category2-subcategory")).to contain_exactly(
+ topic_in_category2.id,
+ )
end
- describe "when query string is `=category:category`" do
- it "does not return topics from subcategories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("=category:category")
- .pluck(:id),
- ).to contain_exactly(topic_in_category.id)
- end
+ it "restricts to the category itself with the = prefix" do
+ expect(filtered("=category:category")).to contain_exactly(topic_in_category.id)
+
+ expect(filtered("=category:category,category2")).to contain_exactly(
+ topic_in_category.id,
+ topic_in_category2.id,
+ )
+
+ expect(filtered("-=category:category")).to contain_exactly(
+ topic_in_category_subcategory.id,
+ topic_in_category2.id,
+ topic_in_category2_subcategory.id,
+ )
+
+ expect(filtered("-=category:category,category2")).to contain_exactly(
+ topic_in_category_subcategory.id,
+ topic_in_category2_subcategory.id,
+ )
end
- describe "when query string is `=category:category,category2`" do
- it "excludes subcategory topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("=category:category,category2")
- .pluck(:id),
- ).to contain_exactly(topic_in_category.id, topic_in_category2.id)
- end
+ it "returns the descendants of a category except the one excluded with -=" do
+ expect(
+ filtered("category:category2 -=category:category2:category2-subcategory"),
+ ).to contain_exactly(topic_in_category2.id)
end
- describe "when query string is `category:category2 -=category:category2-subcategory`" do
- it "returns category2 descendants except the excluded subcategory" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "category:category2 -=category:category2:category2-subcategory",
- )
- .pluck(:id),
- ).to contain_exactly(topic_in_category2.id)
+ describe "when max category nesting is 3" do
+ fab!(:category2_subcategory_subcategory) do
+ SiteSetting.max_category_nesting = 3
+ Fabricate(:category, parent_category: category2_subcategory, name: "sub-subcategory")
end
- describe "when max category nesting is 3" do
- fab!(:category2_subcategory_subcategory) do
- SiteSetting.max_category_nesting = 3
- Fabricate(:category, parent_category: category2_subcategory, name: "sub-subcategory")
- end
-
- fab!(:topic_in_category2_subcategory_subcategory) do
- Fabricate(:topic, category: category2_subcategory_subcategory)
- end
+ fab!(:topic_in_category2_subcategory_subcategory) do
+ Fabricate(:topic, category: category2_subcategory_subcategory)
+ end
- before { SiteSetting.max_category_nesting = 3 }
+ before { SiteSetting.max_category_nesting = 3 }
- it "returns category2 descendants except topics directly in the excluded subcategory" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "category:category2 -=category:category2:category2-subcategory",
- )
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category2.id,
- topic_in_category2_subcategory_subcategory.id,
- )
- end
+ it "keeps the topics nested below the category excluded with -=" do
+ expect(
+ filtered("category:category2 -=category:category2:category2-subcategory"),
+ ).to contain_exactly(topic_in_category2.id, topic_in_category2_subcategory_subcategory.id)
end
end
@@ -982,28 +837,17 @@ RSpec.describe TopicsFilter do
category.update!(name: "日本語", slug: "日本語")
end
- describe "when query string is `category:日本語`" do
- it 'returns topics from the category with slug "日本語"' do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:日本語")
- .pluck(:id),
- ).to contain_exactly(topic_in_category.id, topic_in_category_subcategory.id)
- end
- end
+ it "resolves encoded slugs, including a parent:child chain" do
+ expect(filtered("category:日本語")).to contain_exactly(
+ topic_in_category.id,
+ topic_in_category_subcategory.id,
+ )
- describe "when query string is `category:日本語:안녕하세요`" do
- before { category_subcategory.update!(name: "안녕하세요 ", slug: "안녕하세요 ") }
+ category_subcategory.update!(name: "안녕하세요 ", slug: "안녕하세요 ")
- it "returns topics from the category with slug '안녕하세요'" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:日本語:안녕하세요")
- .pluck(:id),
- ).to contain_exactly(topic_in_category_subcategory.id)
- end
+ expect(filtered("category:日本語:안녕하세요")).to contain_exactly(
+ topic_in_category_subcategory.id,
+ )
end
end
@@ -1019,137 +863,79 @@ RSpec.describe TopicsFilter do
fab!(:topic_in_category_subcategory) { Fabricate(:topic, category: category_subcategory) }
fab!(:topic_in_category2_subcategory) { Fabricate(:topic, category: category2_subcategory) }
- describe "when query string is `category:subcategory`" do
- it "returns topics from subcategories of both categories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:subcategory")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category_subcategory.id,
- topic_in_category2_subcategory.id,
- )
- end
+ fab!(:category_subcategory_subcategory) do
+ SiteSetting.max_category_nesting = 3
+ Fabricate(:category, parent_category: category_subcategory, name: "sub-subcategory")
end
- describe "when query string is `category:category:subcategory`" do
- it "returns topics from subcategories of the specified category" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category:subcategory")
- .pluck(:id),
- ).to contain_exactly(topic_in_category_subcategory.id)
- end
+ fab!(:category2_subcategory_subcategory) do
+ SiteSetting.max_category_nesting = 3
+ Fabricate(:category, parent_category: category2_subcategory, name: "sub-subcategory")
end
- describe "when query string is `category:category2:subcategory`" do
- it "returns matching topics from the specified category's subcategories" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category2:subcategory")
- .pluck(:id),
- ).to contain_exactly(topic_in_category2_subcategory.id)
- end
+ fab!(:topic_in_category_subcategory_subcategory) do
+ Fabricate(:topic, category: category_subcategory_subcategory)
end
- describe "when query string is `category:category:subcategory,category2:subcategory`" do
- it "returns topics from either subcategory" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category:subcategory,category2:subcategory")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category_subcategory.id,
- topic_in_category2_subcategory.id,
- )
- end
+ fab!(:topic_in_category2_subcategory_subcategory) do
+ Fabricate(:topic, category: category2_subcategory_subcategory)
end
- describe "when max category nesting is 3" do
- fab!(:category_subcategory_subcategory) do
- SiteSetting.max_category_nesting = 3
- Fabricate(:category, parent_category: category_subcategory, name: "sub-subcategory")
- end
+ before { SiteSetting.max_category_nesting = 3 }
- fab!(:category2_subcategory_subcategory) do
- SiteSetting.max_category_nesting = 3
- Fabricate(:category, parent_category: category2_subcategory, name: "sub-subcategory")
- end
+ it "disambiguates same-named subcategories by their ancestor chain" do
+ expect(filtered("category:subcategory")).to contain_exactly(
+ topic_in_category_subcategory.id,
+ topic_in_category2_subcategory.id,
+ topic_in_category_subcategory_subcategory.id,
+ topic_in_category2_subcategory_subcategory.id,
+ )
- fab!(:topic_in_category_subcategory_subcategory) do
- Fabricate(:topic, category: category_subcategory_subcategory)
- end
+ expect(filtered("category:category:subcategory")).to contain_exactly(
+ topic_in_category_subcategory.id,
+ topic_in_category_subcategory_subcategory.id,
+ )
- fab!(:topic_in_category2_subcategory_subcategory) do
- Fabricate(:topic, category: category2_subcategory_subcategory)
- end
+ expect(filtered("category:category2:subcategory")).to contain_exactly(
+ topic_in_category2_subcategory.id,
+ topic_in_category2_subcategory_subcategory.id,
+ )
- before { SiteSetting.max_category_nesting = 3 }
+ expect(
+ filtered("category:category:subcategory,category2:subcategory"),
+ ).to contain_exactly(
+ topic_in_category_subcategory.id,
+ topic_in_category2_subcategory.id,
+ topic_in_category_subcategory_subcategory.id,
+ topic_in_category2_subcategory_subcategory.id,
+ )
+ end
- describe "when query string is `category:category:subcategory:sub-subcategory`" do
- it "return topics from category with slug 'sub-subcategory' with the category ancestor chain of 'subcategory' and 'category'" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category:subcategory:sub-subcategory")
- .pluck(:id),
- ).to contain_exactly(topic_in_category_subcategory_subcategory.id)
- end
- end
+ it "resolves a slug chain three categories deep" do
+ category2_subcategory_subcategory2 =
+ Fabricate(:category, parent_category: category2_subcategory, name: "sub-subcategory2")
- describe "when query string is `=category:category2:subcategory`" do
- it "return topics from category with slug 'subcategory' with the category ancestor chain of 'category2'" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("=category:category2:subcategory")
- .pluck(:id),
- ).to contain_exactly(topic_in_category2_subcategory.id)
- end
- end
+ topic_in_category2_subcategory_subcategory2 =
+ Fabricate(:topic, category: category2_subcategory_subcategory2)
- describe "when query string is `category:category2:subcategory`" do
- it "return topics and subcategories topics from category with slug 'subcategory' with the category ancestor chain of 'category2'" do
- category2_subcategory_subcategory2 =
- Fabricate(
- :category,
- parent_category: category2_subcategory,
- name: "sub-subcategory2",
- )
-
- topic_in_category2_subcategory_subcategory2 =
- Fabricate(:topic, category: category2_subcategory_subcategory2)
-
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:category2:subcategory")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category2_subcategory.id,
- topic_in_category2_subcategory_subcategory.id,
- topic_in_category2_subcategory_subcategory2.id,
- )
- end
- end
+ expect(filtered("category:category:subcategory:sub-subcategory")).to contain_exactly(
+ topic_in_category_subcategory_subcategory.id,
+ )
- describe "when query string is `category:sub-subcategory`" do
- it "return topics from either category with slug 'sub-subcategory'" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("category:sub-subcategory")
- .pluck(:id),
- ).to contain_exactly(
- topic_in_category_subcategory_subcategory.id,
- topic_in_category2_subcategory_subcategory.id,
- )
- end
- end
+ expect(filtered("=category:category2:subcategory")).to contain_exactly(
+ topic_in_category2_subcategory.id,
+ )
+
+ expect(filtered("category:category2:subcategory")).to contain_exactly(
+ topic_in_category2_subcategory.id,
+ topic_in_category2_subcategory_subcategory.id,
+ topic_in_category2_subcategory_subcategory2.id,
+ )
+
+ expect(filtered("category:sub-subcategory")).to contain_exactly(
+ topic_in_category_subcategory_subcategory.id,
+ topic_in_category2_subcategory_subcategory.id,
+ )
end
end
end
@@ -1178,114 +964,68 @@ RSpec.describe TopicsFilter do
end
it "applies the custom filter" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:foobar")
- .pluck(:id),
- ).to contain_exactly(foobar_topic.id)
+ expect(filtered("status:foobar")).to contain_exactly(foobar_topic.id)
end
context "when the filter is disabled" do
let(:enabled?) { false }
it "does not apply the custom filter" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:foobar")
- .pluck(:id),
- ).to contain_exactly(*Topic.all.pluck(:id))
+ expect(filtered("status:foobar")).to contain_exactly(*Topic.all.pluck(:id))
end
end
end
it "returns only open topics for `status:open`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:open")
- .pluck(:id),
- ).to contain_exactly(topic.id)
+ expect(filtered("status:open")).to contain_exactly(topic.id)
end
it "returns only deleted topics for authorized users with `status:deleted`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(admin))
- .filter_from_query_string("status:deleted")
- .pluck(:id),
- ).to contain_exactly(deleted_topic_id)
+ expect(filtered("status:deleted", Guardian.new(admin))).to contain_exactly(deleted_topic_id)
end
- it "ignores `status:deleted` when the user cannot see deleted topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:deleted")
- .pluck(:id),
- ).to contain_exactly(topic.id, closed_topic.id, archived_topic.id, foobar_topic.id)
+ it "returns nothing for `status:deleted` when the user cannot see deleted topics" do
+ expect(filtered("status:deleted")).to eq([])
end
it "returns only archived topics for `status:archived`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:archived")
- .pluck(:id),
- ).to contain_exactly(archived_topic.id)
+ expect(filtered("status:archived")).to contain_exactly(archived_topic.id)
end
it "returns only visible topics for `status:listed`" do
Topic.update_all(visible: false)
topic.update!(visible: true)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:listed")
- .pluck(:id),
- ).to contain_exactly(topic.id)
+ expect(filtered("status:listed")).to contain_exactly(topic.id)
end
it "returns only unlisted topics for `status:unlisted`" do
Topic.update_all(visible: true)
topic.update!(visible: false)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:unlisted")
- .pluck(:id),
- ).to contain_exactly(topic.id)
+ expect(filtered("status:unlisted")).to contain_exactly(topic.id)
end
it "returns only unrestricted topics for `status:public`" do
private_category = Fabricate(:private_category, group: group)
topic_in_private_category = Fabricate(:topic, category: private_category)
- expect(
- TopicsFilter.new(guardian: Guardian.new).filter_from_query_string("").pluck(:id),
- ).to include(topic_in_private_category.id)
+ # An admin can see the restricted topic, so the filter is what removes it here,
+ # not the guardian.
+ expect(filtered("", admin.guardian)).to include(topic_in_private_category.id)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:public")
- .pluck(:id),
- ).not_to include(topic_in_private_category.id)
+ expect(filtered("status:public", admin.guardian)).not_to include(
+ topic_in_private_category.id,
+ )
end
describe "when query string is `status:closed status:unlisted`" do
fab!(:closed_and_unlisted_topic) { Fabricate(:topic, closed: true, visible: false) }
it "returns only closed and unlisted topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:closed status:unlisted")
- .pluck(:id),
- ).to contain_exactly(closed_and_unlisted_topic.id)
+ expect(filtered("status:closed status:unlisted")).to contain_exactly(
+ closed_and_unlisted_topic.id,
+ )
end
end
@@ -1294,32 +1034,138 @@ RSpec.describe TopicsFilter do
fab!(:topic_with_replies) { Fabricate(:topic, posts_count: 2) }
it "returns only topics without replies" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:noreplies")
- .pluck(:id),
- ).to contain_exactly(topic_without_replies.id)
+ expect(filtered("status:noreplies")).to contain_exactly(topic_without_replies.id)
end
end
- describe "when query string is `status:single_user`" do
+ describe "when query string is `status:single-user`" do
fab!(:single_user_topic) { Fabricate(:topic, participant_count: 1) }
fab!(:multi_user_topic) { Fabricate(:topic, participant_count: 2) }
- it "returns only topics with one participant" do
- topic_ids =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("status:single_user")
- .pluck(:id)
+ it "returns only topics with one participant, in either spelling" do
+ %w[status:single-user status:single_user].each do |query|
+ topic_ids = filtered(query)
- expect(topic_ids).to include(single_user_topic.id)
- expect(topic_ids).not_to include(multi_user_topic.id)
+ expect(topic_ids).to include(single_user_topic.id), query
+ expect(topic_ids).not_to include(multi_user_topic.id), query
+ end
end
end
end
+ describe "when filtering by scheduled publication" do
+ fab!(:destination, :category)
+ fab!(:scheduled_topic, :topic)
+ fab!(:unscheduled_topic, :topic)
+ fab!(:closing_topic, :topic)
+
+ before do
+ Fabricate(
+ :topic_timer,
+ topic: scheduled_topic,
+ status_type: TopicTimer.types[:publish_to_category],
+ category: destination,
+ )
+
+ Fabricate(:topic_timer, topic: closing_topic, status_type: TopicTimer.types[:close])
+ end
+
+ it "returns only topics scheduled to publish for `status:scheduled`" do
+ expect(filtered("status:scheduled")).to contain_exactly(scheduled_topic.id)
+ end
+
+ it "excludes topics scheduled to publish for `-status:scheduled`" do
+ ids = filtered("-status:scheduled")
+
+ expect(ids).to include(unscheduled_topic.id, closing_topic.id)
+ expect(ids).not_to include(scheduled_topic.id)
+ end
+
+ it "ignores a timer that has been trashed" do
+ TopicTimer.find_by(timerable_id: scheduled_topic.id).trash!
+
+ expect(filtered("status:scheduled")).to eq([])
+ end
+ end
+
+ describe "when negating a filter" do
+ fab!(:closed_topic) { Fabricate(:topic, closed: true) }
+ fab!(:open_topic, :topic)
+ fab!(:popular_topic) { Fabricate(:topic, views: 100) }
+
+ it "excludes whatever the positive form would have included" do
+ authored = Fabricate(:topic, user: user)
+
+ {
+ "-status:closed" => closed_topic,
+ "-views-min:100" => popular_topic,
+ "-created-by:username" => authored,
+ }.each do |query, excluded|
+ ids = filtered(query)
+
+ expect(ids).to include(open_topic.id), query
+ expect(ids).not_to include(excluded.id), query
+ end
+ end
+
+ it "negates a status registered by a plugin" do
+ TopicsFilter.add_filter_by_status("wordy") { |scope| scope.where("word_count = 42") }
+ wordy = Fabricate(:topic, word_count: 42)
+
+ ids = filtered("-status:wordy")
+
+ expect(ids).to include(open_topic.id)
+ expect(ids).not_to include(wordy.id)
+ ensure
+ TopicsFilter.custom_status_filters.delete("wordy")
+ end
+
+ it "keeps the topic_users join available to a later filter" do
+ muted = Fabricate(:topic)
+ TopicUser.create!(user: user, topic: muted, notification_level: 0)
+ bookmarked = Fabricate(:topic)
+ TopicUser.create!(user: user, topic: bookmarked, notification_level: 1, bookmarked: true)
+
+ expect(filtered("-in:muted in:bookmarked", Guardian.new(user))).to contain_exactly(
+ bookmarked.id,
+ )
+ end
+
+ it "is a no-op when the negated filter matches nothing it can act on" do
+ all_ids = Topic.pluck(:id)
+
+ expect(filtered("-foo:bar")).to match_array(all_ids)
+
+ expect(filtered("-views-min:notanumber")).to match_array(all_ids)
+
+ expect(filtered("-category:category+category2")).to match_array(all_ids)
+ end
+
+ it "excludes each value separately when a keyword is negated twice" do
+ archived = Fabricate(:topic, archived: true)
+
+ ids = filtered("-status:closed -status:archived")
+
+ expect(ids).to include(open_topic.id)
+ expect(ids).not_to include(closed_topic.id, archived.id)
+ end
+
+ it "does not leak notification levels from the positive pass into the negated one" do
+ tracking = Fabricate(:topic)
+ TopicUser.create!(user: user, topic: tracking, notification_level: 2)
+ watching = Fabricate(:topic)
+ TopicUser.create!(user: user, topic: watching, notification_level: 3)
+
+ expect(filtered("in:tracking -in:watching", Guardian.new(user))).to contain_exactly(
+ tracking.id,
+ )
+ end
+
+ it "still sorts for `-order:views`, since a sort has no negation" do
+ expect(filtered("-order:views").first).to eq(popular_topic.id)
+ end
+ end
+
describe "when filtering by tags" do
fab!(:tag) { Fabricate(:tag, name: "tag1") }
fab!(:tag2) { Fabricate(:tag, name: "tag2") }
@@ -1347,30 +1193,22 @@ RSpec.describe TopicsFilter do
describe "when filtering by a tag synonym" do
it "returns topics with the target tag for `tag:synonym1`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tag:synonym1")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id, topic_with_tag_and_tag2.id)
+ expect(filtered("tag:synonym1")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ )
end
it "returns topics with the target or other tags for `tags:synonym1,tag2`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:synonym1,#{tag2.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id, topic_with_tag_and_tag2.id, topic_with_tag2.id)
+ expect(filtered("tags:synonym1,#{tag2.name}")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ topic_with_tag2.id,
+ )
end
it "excludes topics with the target tag for `-tag:synonym1`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-tag:synonym1")
- .pluck(:id),
- ).to contain_exactly(
+ expect(filtered("-tag:synonym1")).to contain_exactly(
topic_without_tag.id,
topic_with_tag2.id,
topic_with_group_only_tag.id,
@@ -1381,12 +1219,7 @@ RSpec.describe TopicsFilter do
it "does not filter topics by tag when tagging is disabled" do
SiteSetting.tagging_enabled = false
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name}+#{tag2.name}")
- .pluck(:id),
- ).to contain_exactly(
+ expect(filtered("tags:#{tag.name}+#{tag2.name}")).to contain_exactly(
topic_without_tag.id,
topic_with_tag.id,
topic_with_tag_and_tag2.id,
@@ -1395,47 +1228,28 @@ RSpec.describe TopicsFilter do
)
end
- describe "when query string is `tag:tag1+tag2`" do
- it "returns only topics with all specified tags" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tag:#{tag.name}+#{tag2.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag_and_tag2.id)
- end
- end
-
it "returns only topics with all tags for `tags:tag1+tag2`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name}+#{tag2.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag_and_tag2.id)
+ expect(filtered("tags:#{tag.name}+#{tag2.name}")).to contain_exactly(
+ topic_with_tag_and_tag2.id,
+ )
end
it "returns topics with period-delimited tag names" do
tag_with_period = Fabricate(:tag, name: "node.js")
topic_with_period_tag = Fabricate(:topic, tags: [tag_with_period])
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag_with_period.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_period_tag.id)
+ expect(filtered("tags:#{tag_with_period.name}")).to contain_exactly(
+ topic_with_period_tag.id,
+ )
end
it "returns only topics with tag1 and tag2 for repeated tag filters" do
topic_with_tag_and_tag2_and_tag3 = Fabricate(:topic, tags: [tag, tag2, tag3])
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name} tags:#{tag2.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag_and_tag2.id, topic_with_tag_and_tag2_and_tag3.id)
+ expect(filtered("tags:#{tag.name} tags:#{tag2.name}")).to contain_exactly(
+ topic_with_tag_and_tag2.id,
+ topic_with_tag_and_tag2_and_tag3.id,
+ )
end
describe "when query string is `tags:front-end,back-end tags:pri-high,pri-low`" do
@@ -1454,12 +1268,9 @@ RSpec.describe TopicsFilter do
Fabricate(:topic, tags: [front_end, back_end])
expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "tags:#{front_end.name},#{back_end.name} tags:#{pri_high.name},#{pri_low.name}",
- )
- .pluck(:id),
+ filtered(
+ "tags:#{front_end.name},#{back_end.name} tags:#{pri_high.name},#{pri_low.name}",
+ ),
).to contain_exactly(
topic_with_front_end_pri_high.id,
topic_with_front_end_pri_low.id,
@@ -1478,12 +1289,9 @@ RSpec.describe TopicsFilter do
Fabricate(:topic, tags: [front_end, back_end])
expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "tags:#{front_end.name},#{back_end.name} tags:#{pri_low.name},#{pri_high.name}",
- )
- .pluck(:id),
+ filtered(
+ "tags:#{front_end.name},#{back_end.name} tags:#{pri_low.name},#{pri_high.name}",
+ ),
).to contain_exactly(
topic_with_front_end_back_end_pri_low.id,
topic_with_front_end_back_end_pri_high.id,
@@ -1506,12 +1314,7 @@ RSpec.describe TopicsFilter do
Fabricate(:topic, tags: [pri_high, pri_low])
expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "tags:#{front_end.name} tags:#{pri_high.name},#{pri_low.name}",
- )
- .pluck(:id),
+ filtered("tags:#{front_end.name} tags:#{pri_high.name},#{pri_low.name}"),
).to contain_exactly(
topic_with_front_end_pri_high.id,
topic_with_front_end_pri_low.id,
@@ -1519,12 +1322,7 @@ RSpec.describe TopicsFilter do
)
expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "tags:#{pri_high.name},#{pri_low.name} tags:#{front_end.name}",
- )
- .pluck(:id),
+ filtered("tags:#{pri_high.name},#{pri_low.name} tags:#{front_end.name}"),
).to contain_exactly(
topic_with_front_end_pri_high.id,
topic_with_front_end_pri_low.id,
@@ -1533,111 +1331,56 @@ RSpec.describe TopicsFilter do
end
end
- describe "when query string is `tags:tag1,tag2,tag3`" do
- it "returns only topics with tag1, tag2, or tag3" do
- topic_with_tag3 = Fabricate(:topic, tags: [tag3])
-
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name},#{tag2.name},#{tag3.name}")
- .pluck(:id),
- ).to contain_exactly(
- topic_with_tag.id,
- topic_with_tag_and_tag2.id,
- topic_with_tag2.id,
- topic_with_tag3.id,
- )
- end
- end
-
- describe "when query string is `tags:tag1+tag2+tag3`" do
- it "returns only topics with tag1, tag2, and tag3" do
- topic_with_tag_tag2_tag3 = Fabricate(:topic, tags: [tag, tag2, tag3])
-
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name}+#{tag2.name}+#{tag3.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag_tag2_tag3.id)
- end
- end
-
it "returns topics with tag1 and tag2 but without tag3" do
_topic_with_tag_and_tag2_and_tag3 = Fabricate(:topic, tags: [tag, tag2, tag3])
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name} tags:#{tag2.name} -tags:tag3")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag_and_tag2.id)
+ expect(filtered("tags:#{tag.name} tags:#{tag2.name} -tags:tag3")).to contain_exactly(
+ topic_with_tag_and_tag2.id,
+ )
end
it "returns topics with any specified tag for `tags:tag1,tag2`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name},#{tag2.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id, topic_with_tag_and_tag2.id, topic_with_tag2.id)
+ expect(filtered("tags:#{tag.name},#{tag2.name}")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ topic_with_tag2.id,
+ )
end
it "returns no topics when an AND tag filter includes an invalid tag" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:tag1+tag2+invalid")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("tags:tag1+tag2+invalid")).to eq([])
end
it "filters by valid tags when an OR tag filter includes an invalid tag" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:tag1,tag2,invalid")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag_and_tag2.id, topic_with_tag.id, topic_with_tag2.id)
+ expect(filtered("tags:tag1,tag2,invalid")).to contain_exactly(
+ topic_with_tag_and_tag2.id,
+ topic_with_tag.id,
+ topic_with_tag2.id,
+ )
end
it "returns no topics when the specified tag is hidden from the user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:group-only-tag")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("tags:group-only-tag")).to eq([])
end
it "returns matching topics when the user can access the specified tag" do
group.add(admin)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(admin))
- .filter_from_query_string("tags:group-only-tag")
- .pluck(:id),
- ).to contain_exactly(topic_with_group_only_tag.id)
+ expect(filtered("tags:group-only-tag", Guardian.new(admin))).to contain_exactly(
+ topic_with_group_only_tag.id,
+ )
end
it "returns only topics without the specified tag for `-tags:tag1`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-tags:tag1")
- .pluck(:id),
- ).to contain_exactly(topic_without_tag.id, topic_with_tag2.id, topic_with_group_only_tag.id)
+ expect(filtered("-tags:tag1")).to contain_exactly(
+ topic_without_tag.id,
+ topic_with_tag2.id,
+ topic_with_group_only_tag.id,
+ )
end
it "excludes topics with all specified tags for `-tags:tag1+tag2`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-tags:tag1+tag2")
- .pluck(:id),
- ).to contain_exactly(
+ expect(filtered("-tags:tag1+tag2")).to contain_exactly(
topic_without_tag.id,
topic_with_tag.id,
topic_with_tag2.id,
@@ -1646,37 +1389,43 @@ RSpec.describe TopicsFilter do
end
it "excludes topics with any specified tag for `-tags:tag1,tag2`" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-tags:tag1,tag2")
- .pluck(:id),
- ).to contain_exactly(topic_without_tag.id, topic_with_group_only_tag.id)
+ expect(filtered("-tags:tag1,tag2")).to contain_exactly(
+ topic_without_tag.id,
+ topic_with_group_only_tag.id,
+ )
end
- describe "when query string is tag:日べé1" do
- before { tag.update!(name: "日べé1") }
+ it "keeps applying tag filters after one with an unsupported prefix" do
+ filter = TopicsFilter.new(guardian: Guardian.new)
+ ids = filter.filter_from_query_string("=tags:#{tag.name} tags:#{tag2.name}").pluck(:id)
- it "returns topics with the specified tag" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tag:日べé1")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id, topic_with_tag_and_tag2.id)
- end
+ expect(filter.invalid_filters).to contain_exactly("=tag:#{tag.name}")
+ expect(ids).to contain_exactly(topic_with_tag_and_tag2.id, topic_with_tag2.id)
end
- describe "when query string is `tags:tag_name`" do
- before { tag.update!(name: "tag_with_underscore") }
+ it "reports an unparseable tag value and returns no topics" do
+ filter = TopicsFilter.new(guardian: Guardian.new)
- it "returns topics when the tag contains an underscore" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:#{tag.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id, topic_with_tag_and_tag2.id)
+ expect(filter.filter_from_query_string("tags:!!!").pluck(:id)).to eq([])
+ expect(filter.invalid_filters).to contain_exactly("tag:!!!")
+ end
+
+ it "orders by an expression while filtering by tags" do
+ expect(filtered("tags:#{tag.name},#{tag2.name} order:title")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ topic_with_tag2.id,
+ )
+ end
+
+ describe "when query string is tag:日べé1" do
+ before { tag.update!(name: "日べé1") }
+
+ it "returns topics with the specified tag" do
+ expect(filtered("tag:日べé1")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ )
end
end
@@ -1687,21 +1436,15 @@ RSpec.describe TopicsFilter do
end
it "returns topics for comma-separated tags containing underscores" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:tag_one,tag_two")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id, topic_with_tag_and_tag2.id, topic_with_tag2.id)
+ expect(filtered("tags:tag_one,tag_two")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ topic_with_tag2.id,
+ )
end
it "returns topics for plus-separated tags containing underscores" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tags:tag_one+tag_two")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag_and_tag2.id)
+ expect(filtered("tags:tag_one+tag_two")).to contain_exactly(topic_with_tag_and_tag2.id)
end
end
end
@@ -1735,41 +1478,45 @@ RSpec.describe TopicsFilter do
fab!(:topic_with_staff_only_tag) { Fabricate(:topic, tags: [staff_only_tag]) }
it "returns topics with any tag in the specified tag group" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tag_group:#{tag_group.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id, topic_with_tag_and_tag2.id, topic_with_tag2.id)
+ expect(filtered("tag-group:#{tag_group.name}")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ topic_with_tag2.id,
+ )
end
it "excludes topics with tags in the specified excluded tag group" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-tag_group:#{tag_group.name}")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag3.id, topic_without_tag.id, topic_with_staff_only_tag.id)
+ expect(filtered("-tag_group:#{tag_group.name}")).to contain_exactly(
+ topic_with_tag3.id,
+ topic_without_tag.id,
+ topic_with_staff_only_tag.id,
+ )
+ end
+
+ it "excludes a topic that has only one of its tags in the excluded tag group" do
+ mixed_topic = Fabricate(:topic, tags: [tag, tag3])
+
+ expect(filtered("-tag_group:#{tag_group.name}")).not_to include(mixed_topic.id)
+ end
+
+ it "orders by an expression while filtering by tag group" do
+ expect(filtered("tag_group:#{tag_group.name} order:title")).to contain_exactly(
+ topic_with_tag.id,
+ topic_with_tag_and_tag2.id,
+ topic_with_tag2.id,
+ )
end
it "returns matching topics when the user can access the tag group" do
group.add(admin)
expect(
- TopicsFilter
- .new(guardian: Guardian.new(admin))
- .filter_from_query_string("tag_group:#{staff_tag_group.name}")
- .pluck(:id),
+ filtered("tag_group:#{staff_tag_group.name}", Guardian.new(admin)),
).to contain_exactly(topic_with_staff_only_tag.id)
end
it "returns no topics when the tag group is hidden from the user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tag_group:#{staff_tag_group.name}")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("tag_group:#{staff_tag_group.name}")).to eq([])
end
end
@@ -1787,71 +1534,16 @@ RSpec.describe TopicsFilter do
fab!(:topic_with_tag) { Fabricate(:topic, tags: [tag]) }
fab!(:topic_without_tag, :topic)
- it "filters a double-quoted tag group name containing spaces" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string('tag_group:"My Tag Group"')
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id)
- end
-
- it "filters a single-quoted tag group name containing spaces" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tag_group:'My Tag Group'")
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id)
- end
-
- it "filters a tag group name containing an ampersand" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string('tag_group:"News & Updates"')
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id)
- end
-
- it "filters a tag group name containing parentheses" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string('tag_group:"Group (Test)"')
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id)
- end
-
- it "looks up tag groups case-insensitively" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string('tag_group:"MY TAG GROUP"')
- .pluck(:id),
- ).to contain_exactly(topic_with_tag.id)
+ it "resolves tag group names regardless of quoting, casing, or punctuation" do
+ expect(filtered('tag_group:"My Tag Group"')).to contain_exactly(topic_with_tag.id)
+ expect(filtered("tag_group:'My Tag Group'")).to contain_exactly(topic_with_tag.id)
+ expect(filtered('tag_group:"MY TAG GROUP"')).to contain_exactly(topic_with_tag.id)
+ expect(filtered('tag_group:"News & Updates"')).to contain_exactly(topic_with_tag.id)
+ expect(filtered('tag_group:"Group (Test)"')).to contain_exactly(topic_with_tag.id)
end
it "handles the exclusion prefix with quoted tag group names" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string('-tag_group:"My Tag Group"')
- .pluck(:id),
- ).to contain_exactly(topic_without_tag.id)
- end
-
- it "supports unquoted tag group names" do
- simple_tag = Fabricate(:tag, name: "simple-tag")
- _simple_group = Fabricate(:tag_group, name: "simple", tag_names: [simple_tag.name])
- topic_simple = Fabricate(:topic, tags: [simple_tag])
-
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("tag_group:simple")
- .pluck(:id),
- ).to contain_exactly(topic_simple.id)
+ expect(filtered('-tag_group:"My Tag Group"')).to contain_exactly(topic_without_tag.id)
end
end
@@ -1863,67 +1555,41 @@ RSpec.describe TopicsFilter do
describe "when query string is `locale:en`" do
it "returns only topics with the en locale" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("locale:en")
- .pluck(:id),
- ).to contain_exactly(en_topic.id)
+ expect(filtered("locale:en")).to contain_exactly(en_topic.id)
end
end
describe "when query string is `locale:ja,es`" do
it "returns topics with the ja or es locale" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("locale:ja,es")
- .pluck(:id),
- ).to contain_exactly(ja_topic.id, es_topic.id)
+ expect(filtered("locale:ja,es")).to contain_exactly(ja_topic.id, es_topic.id)
end
end
describe "when query string is `locale:ja locale:es`" do
it "returns topics matching either ja or es locale filter" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("locale:ja locale:es")
- .pluck(:id),
- ).to contain_exactly(ja_topic.id, es_topic.id)
+ expect(filtered("locale:ja locale:es")).to contain_exactly(ja_topic.id, es_topic.id)
end
end
describe "when query string is `-locale:en`" do
it "returns topics without the en locale" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-locale:en")
- .pluck(:id),
- ).to contain_exactly(ja_topic.id, es_topic.id, no_locale_topic.id)
+ expect(filtered("-locale:en")).to contain_exactly(
+ ja_topic.id,
+ es_topic.id,
+ no_locale_topic.id,
+ )
end
end
describe "when query string is `-locale:en,ja`" do
it "returns topics without the en or ja locale" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("-locale:en,ja")
- .pluck(:id),
- ).to contain_exactly(es_topic.id, no_locale_topic.id)
+ expect(filtered("-locale:en,ja")).to contain_exactly(es_topic.id, no_locale_topic.id)
end
end
describe "when query string is `locale:invalid`" do
it "returns no topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("locale:invalid")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("locale:invalid")).to eq([])
end
end
@@ -1931,12 +1597,7 @@ RSpec.describe TopicsFilter do
before { en_topic.update!(closed: true) }
it "combines with status:closed" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("locale:en status:closed")
- .pluck(:id),
- ).to contain_exactly(en_topic.id)
+ expect(filtered("locale:en status:closed")).to contain_exactly(en_topic.id)
end
end
end
@@ -1949,89 +1610,56 @@ RSpec.describe TopicsFilter do
describe "when query string is `created-by:@username`" do
it "returns topics created by the specified user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:@#{user.username}")
- .pluck(:id),
- ).to contain_exactly(topic_by_user.id, topic2_by_user.id)
- end
- end
-
- describe "when query string is `created-by:@username2`" do
- it "returns topics created by the named user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:@#{user2.username}")
- .pluck(:id),
- ).to contain_exactly(topic_by_user2.id)
+ expect(filtered("created-by:@#{user.username}")).to contain_exactly(
+ topic_by_user.id,
+ topic2_by_user.id,
+ )
end
end
describe "when query string is `created-by:@username created-by:@username2`" do
it "returns topics created by either specified user" do
expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "created-by:@#{user.username} created-by:@#{user2.username}",
- )
- .pluck(:id),
+ filtered("created-by:@#{user.username} created-by:@#{user2.username}"),
).to contain_exactly(topic_by_user.id, topic2_by_user.id, topic_by_user2.id)
end
end
describe "when query string is `created-by:@username,invalid`" do
it "returns only topics created by the user with a valid username" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:@#{user.username},invalid")
- .pluck(:id),
- ).to contain_exactly(topic_by_user.id, topic2_by_user.id)
+ expect(filtered("created-by:@#{user.username},invalid")).to contain_exactly(
+ topic_by_user.id,
+ topic2_by_user.id,
+ )
end
end
- describe "when query string is `created-by:@username,@username2`" do
- it "returns topics created by any valid specified user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:@#{user.username},@#{user2.username}")
- .pluck(:id),
- ).to contain_exactly(topic_by_user.id, topic2_by_user.id, topic_by_user2.id)
+ describe "when query string is `created-by:@username,@username2`" do
+ it "returns topics created by any valid specified user" do
+ expect(filtered("created-by:@#{user.username},@#{user2.username}")).to contain_exactly(
+ topic_by_user.id,
+ topic2_by_user.id,
+ topic_by_user2.id,
+ )
end
end
describe "when query string is `created-by:@invalid`" do
it "returns no topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:@invalid")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("created-by:@invalid")).to eq([])
end
end
describe "when query string is `created-by:me`" do
it "returns topics created by the current user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("created-by:me")
- .pluck(:id),
- ).to contain_exactly(topic_by_user.id, topic2_by_user.id)
+ expect(filtered("created-by:me", Guardian.new(user))).to contain_exactly(
+ topic_by_user.id,
+ topic2_by_user.id,
+ )
end
it "returns no topics when there is no current user" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:me")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("created-by:me")).to eq([])
end
end
end
@@ -2053,63 +1681,31 @@ RSpec.describe TopicsFilter do
fab!(:topic_by_group2_user) { Fabricate(:topic, user: user_in_group2) }
fab!(:topic_by_both_groups_user) { Fabricate(:topic, user: user_in_both_groups) }
- describe "when query string is `created-by:group1`" do
- it "returns topics created by users in the specified group" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:group1")
- .pluck(:id),
- ).to contain_exactly(topic_by_group1_user.id, topic_by_both_groups_user.id)
- end
- end
+ it "returns topics created by members of the given groups, ignoring unknown names" do
+ expect(filtered("created-by:group1")).to contain_exactly(
+ topic_by_group1_user.id,
+ topic_by_both_groups_user.id,
+ )
- describe "when query string is `created-by:group2`" do
- it "returns topics from members of the named group" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:group2")
- .pluck(:id),
- ).to contain_exactly(topic_by_group2_user.id, topic_by_both_groups_user.id)
- end
- end
+ expect(filtered("created-by:group1,group2")).to contain_exactly(
+ topic_by_group1_user.id,
+ topic_by_group2_user.id,
+ topic_by_both_groups_user.id,
+ )
- describe "when query string is `created-by:group1,group2`" do
- it "returns topics created by users in any specified group" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:group1,group2")
- .pluck(:id),
- ).to contain_exactly(
- topic_by_group1_user.id,
- topic_by_group2_user.id,
- topic_by_both_groups_user.id,
- )
- end
- end
+ expect(filtered("created-by:group1,invalid")).to contain_exactly(
+ topic_by_group1_user.id,
+ topic_by_both_groups_user.id,
+ )
- describe "when query string is `created-by:invalid`" do
- it "returns no topics" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:invalid")
- .pluck(:id),
- ).to eq([])
- end
+ expect(filtered("created-by:invalid")).to eq([])
end
- describe "when query string is `created-by:group1,invalid`" do
- it "returns only topics created by users in the valid group" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:group1,invalid")
- .pluck(:id),
- ).to contain_exactly(topic_by_group1_user.id, topic_by_both_groups_user.id)
- end
+ it "orders by an expression while filtering by the creator's group" do
+ expect(filtered("created-by:group1 order:title")).to contain_exactly(
+ topic_by_group1_user.id,
+ topic_by_both_groups_user.id,
+ )
end
describe "with group visibility restrictions" do
@@ -2137,40 +1733,32 @@ RSpec.describe TopicsFilter do
Fabricate(:topic, user: user_in_super_private_group)
end
it "returns no topics when the user cannot see the group" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("created-by:#{private_group.name}")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("created-by:#{private_group.name}")).to eq([])
end
it "returns topics when the user belongs to the private group" do
private_group.add(user)
expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("created-by:#{private_group.name}")
- .pluck(:id),
+ filtered("created-by:#{private_group.name}", Guardian.new(user)),
).to contain_exactly(topic_by_private_group_user.id)
end
it "does not filter topics when user cannot see members of the group" do
expect(
- TopicsFilter
- .new(guardian: Guardian.new(user_in_super_private_group))
- .filter_from_query_string("created-by:#{super_private_group.name}")
- .pluck(:id),
+ filtered(
+ "created-by:#{super_private_group.name}",
+ Guardian.new(user_in_super_private_group),
+ ),
).to eq([])
end
it "returns topics when user can see group members" do
expect(
- TopicsFilter
- .new(guardian: Guardian.new(owner_of_super_private_group))
- .filter_from_query_string("created-by:#{super_private_group.name}")
- .pluck(:id),
+ filtered(
+ "created-by:#{super_private_group.name}",
+ Guardian.new(owner_of_super_private_group),
+ ),
).to contain_exactly(
topic_by_super_private_group_owner.id,
topic_by_super_private_group_user.id,
@@ -2180,83 +1768,20 @@ RSpec.describe TopicsFilter do
end
shared_examples "filtering for topics by counts" do |filter|
- describe "when query string is `#{filter}-min:1`" do
- it "returns only topics with at least one #{filter}" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-min:1")
- .pluck(:id),
- ).to contain_exactly(topic_with_1_count.id, topic_with_2_count.id, topic_with_3_count.id)
- end
- end
-
- describe "when query string is `#{filter}-min:3`" do
- it "returns only topics with at least three #{filter}" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-min:3")
- .pluck(:id),
- ).to contain_exactly(topic_with_3_count.id)
- end
- end
-
- describe "when query string is `#{filter}-max:1`" do
- it "returns only topics with at most one #{filter}" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-max:1")
- .pluck(:id),
- ).to contain_exactly(topic_with_1_count.id)
- end
- end
-
- describe "when query string is `#{filter}-max:3`" do
- it "returns only topics with at most three #{filter}" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-max:3")
- .pluck(:id),
- ).to contain_exactly(topic_with_1_count.id, topic_with_2_count.id, topic_with_3_count.id)
- end
- end
-
- describe "when query string is `#{filter}-min:1 #{filter}-max:2`" do
- it "returns topics with at least one like and at most two #{filter}" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-min:1 #{filter}-max:2")
- .pluck(:id),
- ).to contain_exactly(topic_with_1_count.id, topic_with_2_count.id)
- end
- end
-
- describe "when query string is `#{filter}-min:3 #{filter}-min:2 #{filter}-max:1 #{filter}-max:3`" do
- it "uses the last duplicate filters to constrain the #{filter} count" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string(
- "#{filter}-min:3 #{filter}-min:2 #{filter}-max:1 #{filter}-max:3",
- )
- .pluck(:id),
- ).to contain_exactly(topic_with_2_count.id, topic_with_3_count.id)
- end
- end
-
- describe "when query string is `#{filter}-min:invalid #{filter}-max:invalid`" do
- it "ignores filters with invalid values" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-min:invalid #{filter}-max:invalid")
- .pluck(:id),
- ).to contain_exactly(topic_with_1_count.id, topic_with_2_count.id, topic_with_3_count.id)
- end
+ it "filters by #{filter} min/max, keeping the last of duplicates and ignoring invalid values" do
+ all = [topic_with_1_count.id, topic_with_2_count.id, topic_with_3_count.id]
+
+ expect(filtered("#{filter}-min:1")).to contain_exactly(*all)
+ expect(filtered("#{filter}-min:3")).to contain_exactly(topic_with_3_count.id)
+ expect(filtered("#{filter}-max:1")).to contain_exactly(topic_with_1_count.id)
+ expect(filtered("#{filter}-min:1 #{filter}-max:2")).to contain_exactly(
+ topic_with_1_count.id,
+ topic_with_2_count.id,
+ )
+ expect(
+ filtered("#{filter}-min:3 #{filter}-min:2 #{filter}-max:1 #{filter}-max:3"),
+ ).to contain_exactly(topic_with_2_count.id, topic_with_3_count.id)
+ expect(filtered("#{filter}-min:invalid #{filter}-max:invalid")).to contain_exactly(*all)
end
end
@@ -2311,152 +1836,38 @@ RSpec.describe TopicsFilter do
include_examples("filtering for topics by counts", "likes-op")
end
- shared_examples "filtering for topics by date column" do |filter, column, description|
+ shared_examples "filtering for topics by date column" do |filter, column|
fab!(:topic) { Fabricate(:topic, column => Time.zone.local(2022, 1, 1)) }
fab!(:topic2) { Fabricate(:topic, column => Time.zone.local(2023, 5, 12)) }
- describe "when query string is `#{filter}-after:invalid-date-test`" do
- it "ignores the filter" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-after:invalid-date-test")
- .pluck(:id),
- ).to contain_exactly(topic.id, topic2.id)
- end
- end
-
- describe "when query string is `#{filter}-after:2022-01-01`" do
- it "returns only topics with #{description} after 2022-01-01" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-after:2022-01-01")
- .pluck(:id),
- ).to contain_exactly(topic.id, topic2.id)
- end
- end
-
- describe "when query string is `#{filter}-after:2023-01-1`" do
- it "returns only topics with #{description} after 2023-01-01" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-after:2023-01-1")
- .pluck(:id),
- ).to contain_exactly(topic2.id)
- end
- end
-
- describe "when query string is `#{filter}-after:2023-6-01`" do
- it "returns only topics with #{description} after 2023-06-01" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-after:2023-6-01")
- .pluck(:id),
- ).to eq([])
- end
- end
-
- describe "when query string is `#{filter}-before:2023-01-01`" do
- it "returns only topics with #{description} before 2023-01-01" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-before:2023-01-01")
- .pluck(:id),
- ).to contain_exactly(topic.id)
- end
- end
-
- describe "when query string is `#{filter}-before:2023-1-1`" do
- it "returns only matching topics with #{description} before 2023-01-01" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-before:2023-1-1")
- .pluck(:id),
- ).to contain_exactly(topic.id)
- end
- end
-
- describe "when query string is `#{filter}-before:2000-01-01`" do
- it "returns only topics with #{description} before 2000-01-01" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-before:2000-01-01")
- .pluck(:id),
- ).to eq([])
- end
- end
-
- describe "when query string is `#{filter}-after:1`" do
- it "returns only topics with #{description} after one day ago" do
- freeze_time do
- _old_topic = Fabricate(:topic, column => 2.days.ago)
- recent_topic = Fabricate(:topic, column => Time.zone.now)
-
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-after:1")
- .pluck(:id),
- ).to contain_exactly(recent_topic.id)
- end
- end
- end
-
- describe "when query string is `#{filter}-before:1`" do
- it "returns only topics with #{description} before one day ago" do
- freeze_time do
- old_topic = Fabricate(:topic, column => 2.days.ago)
- recent_topic = Fabricate(:topic, column => Time.zone.now)
-
- results =
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-before:1")
- .where(id: [old_topic.id, recent_topic.id])
- .pluck(:id)
-
- expect(results).to contain_exactly(old_topic.id)
- end
- end
+ it "filters #{filter} by absolute date, tolerating unpadded and invalid values" do
+ expect(filtered("#{filter}-after:2022-01-01")).to contain_exactly(topic.id, topic2.id)
+ expect(filtered("#{filter}-after:2023-01-1")).to contain_exactly(topic2.id)
+ expect(filtered("#{filter}-after:2023-6-01")).to eq([])
+ expect(filtered("#{filter}-before:2023-1-1")).to contain_exactly(topic.id)
+ expect(filtered("#{filter}-before:2000-01-01")).to eq([])
+ expect(filtered("#{filter}-after:invalid-date-test")).to contain_exactly(
+ topic.id,
+ topic2.id,
+ )
end
- describe "when query string is `#{filter}-after:0`" do
- it "returns only topics with #{description} after today" do
- freeze_time do
- _old_topic = Fabricate(:topic, column => 2.days.ago)
- recent_topic = Fabricate(:topic, column => Time.zone.now)
+ it "filters #{filter} by number of days ago" do
+ freeze_time do
+ old_topic = Fabricate(:topic, column => 2.days.ago)
+ recent_topic = Fabricate(:topic, column => Time.zone.now)
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("#{filter}-after:0")
- .pluck(:id),
- ).to contain_exactly(recent_topic.id)
- end
+ expect(filtered("#{filter}-after:1")).to contain_exactly(recent_topic.id)
+ expect(filtered("#{filter}-after:0")).to contain_exactly(recent_topic.id)
+ expect(filtered("#{filter}-before:1")).to include(old_topic.id)
+ expect(filtered("#{filter}-before:1")).not_to include(recent_topic.id)
end
end
end
- describe "when filtering by activity of topics" do
- include_examples "filtering for topics by date column", "activity", :bumped_at, "bumped date"
- end
-
- describe "when filtering by creation date of topics" do
- include_examples "filtering for topics by date column", "created", :created_at, "created date"
- end
-
- describe "when filtering by last post date of topics" do
- include_examples "filtering for topics by date column",
- "latest-post",
- :last_posted_at,
- "last posted date"
- end
+ it_behaves_like "filtering for topics by date column", "activity", :bumped_at
+ it_behaves_like "filtering for topics by date column", "created", :created_at
+ it_behaves_like "filtering for topics by date column", "latest-post", :last_posted_at
describe "when filtering by bookmark date of topics" do
fab!(:topic_1, :topic)
@@ -2464,48 +1875,37 @@ RSpec.describe TopicsFilter do
fab!(:topic_3, :topic)
it "returns no topics for anonymous users" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("bookmarked-after:2023-01-01")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("bookmarked-after:2023-01-01")).to eq([])
end
- it "returns topics bookmarked on or after the given date" do
+ it "filters topics by bookmark date, including a closed range" do
freeze_time Time.zone.local(2024, 1, 15)
- bookmark1 = Fabricate(:bookmark, user: user, bookmarkable: topic_1)
- bookmark1.update_column(:created_at, Time.zone.local(2023, 6, 1))
-
- bookmark2 = Fabricate(:bookmark, user: user, bookmarkable: topic_2)
- bookmark2.update_column(:created_at, Time.zone.local(2022, 6, 1))
+ Fabricate(:bookmark, user:, bookmarkable: topic_1).update_column(
+ :created_at,
+ Time.zone.local(2023, 6, 1),
+ )
+ Fabricate(:bookmark, user:, bookmarkable: topic_2).update_column(
+ :created_at,
+ Time.zone.local(2022, 6, 1),
+ )
+ Fabricate(:bookmark, user:, bookmarkable: topic_3).update_column(
+ :created_at,
+ Time.zone.local(2024, 1, 1),
+ )
+ expect(filtered("bookmarked-after:2023-01-01", user.guardian)).to contain_exactly(
+ topic_1.id,
+ topic_3.id,
+ )
+ expect(filtered("bookmarked-before:2023-01-01", user.guardian)).to contain_exactly(
+ topic_2.id,
+ )
expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:2023-01-01")
- .pluck(:id),
+ filtered("bookmarked-after:2023-01-01 bookmarked-before:2023-12-31", user.guardian),
).to contain_exactly(topic_1.id)
end
- it "returns topics bookmarked on or before the given date" do
- freeze_time Time.zone.local(2024, 1, 15)
-
- bookmark1 = Fabricate(:bookmark, user: user, bookmarkable: topic_1)
- bookmark1.update_column(:created_at, Time.zone.local(2023, 6, 1))
-
- bookmark2 = Fabricate(:bookmark, user: user, bookmarkable: topic_2)
- bookmark2.update_column(:created_at, Time.zone.local(2022, 6, 1))
-
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-before:2023-01-01")
- .pluck(:id),
- ).to contain_exactly(topic_2.id)
- end
-
it "supports integer days-ago format" do
freeze_time do
bookmark1 = Fabricate(:bookmark, user: user, bookmarkable: topic_1)
@@ -2514,12 +1914,7 @@ RSpec.describe TopicsFilter do
bookmark2 = Fabricate(:bookmark, user: user, bookmarkable: topic_2)
bookmark2.update_column(:created_at, 3.days.ago)
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:1")
- .pluck(:id),
- ).to contain_exactly(topic_1.id)
+ expect(filtered("bookmarked-after:1", user.guardian)).to contain_exactly(topic_1.id)
expect(
TopicsFilter
@@ -2538,12 +1933,9 @@ RSpec.describe TopicsFilter do
bookmark = Fabricate(:bookmark, user: user, bookmarkable: post)
bookmark.update_column(:created_at, Time.zone.local(2023, 6, 1))
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:2023-01-01")
- .pluck(:id),
- ).to contain_exactly(topic_1.id)
+ expect(filtered("bookmarked-after:2023-01-01", user.guardian)).to contain_exactly(
+ topic_1.id,
+ )
end
it "does not return deleted topics even if they are bookmarked" do
@@ -2553,12 +1945,7 @@ RSpec.describe TopicsFilter do
bookmark.update_column(:created_at, Time.zone.local(2023, 6, 1))
topic_1.destroy
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:2023-01-01")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("bookmarked-after:2023-01-01", user.guardian)).to eq([])
end
it "does not return topics if their posts are deleted even if they are bookmarked" do
@@ -2569,12 +1956,7 @@ RSpec.describe TopicsFilter do
bookmark.update_column(:created_at, Time.zone.local(2023, 6, 1))
post.destroy
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:2023-01-01")
- .pluck(:id),
- ).to eq([])
+ expect(filtered("bookmarked-after:2023-01-01", user.guardian)).to eq([])
end
it "does not include other users' bookmarks" do
@@ -2584,41 +1966,15 @@ RSpec.describe TopicsFilter do
bookmark = Fabricate(:bookmark, user: other_user, bookmarkable: topic_1)
bookmark.update_column(:created_at, Time.zone.local(2023, 6, 1))
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:2023-01-01")
- .pluck(:id),
- ).to eq([])
- end
-
- it "supports combined before and after for date range" do
- freeze_time Time.zone.local(2024, 1, 15)
-
- bookmark1 = Fabricate(:bookmark, user: user, bookmarkable: topic_1)
- bookmark1.update_column(:created_at, Time.zone.local(2023, 6, 1))
-
- bookmark2 = Fabricate(:bookmark, user: user, bookmarkable: topic_2)
- bookmark2.update_column(:created_at, Time.zone.local(2022, 6, 1))
-
- bookmark3 = Fabricate(:bookmark, user: user, bookmarkable: topic_3)
- bookmark3.update_column(:created_at, Time.zone.local(2024, 1, 1))
-
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:2023-01-01 bookmarked-before:2023-12-31")
- .pluck(:id),
- ).to contain_exactly(topic_1.id)
+ expect(filtered("bookmarked-after:2023-01-01", user.guardian)).to eq([])
end
it "ignores invalid date values" do
- expect(
- TopicsFilter
- .new(guardian: user.guardian)
- .filter_from_query_string("bookmarked-after:invalid-date")
- .pluck(:id),
- ).to include(topic_1.id, topic_2.id, topic_3.id)
+ expect(filtered("bookmarked-after:invalid-date", user.guardian)).to include(
+ topic_1.id,
+ topic_2.id,
+ topic_3.id,
+ )
end
end
@@ -2633,37 +1989,10 @@ RSpec.describe TopicsFilter do
# Requires the fabrication of `topic`, `topic2` and `topic3` such that the order of the topics is `topic2`, `topic1`, `topic3`
# when ordered by the given filter in descending order.
shared_examples "ordering topics filters" do |order, order_description|
- describe "when query string is `order:#{order}`" do
- it "returns topics ordered by #{order_description} descending" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:#{order}")
- .pluck(:id),
- ).to eq([topic2.id, topic.id, topic3.id])
- end
- end
-
- describe "when query string is `order:#{order}-asc`" do
- it "returns topics ordered by #{order_description} ascending" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:#{order}-asc")
- .pluck(:id),
- ).to eq([topic3.id, topic.id, topic2.id])
- end
- end
-
- describe "when query string is `order:#{order}-invalid`" do
- it "returns topics in the database's default order" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:#{order}-invalid")
- .pluck(:id),
- ).to contain_exactly(*Topic.all.pluck(:id))
- end
+ it "orders topics by #{order_description}, honouring -asc and ignoring an invalid suffix" do
+ expect(filtered("order:#{order}")).to eq([topic2.id, topic.id, topic3.id])
+ expect(filtered("order:#{order}-asc")).to eq([topic3.id, topic.id, topic2.id])
+ expect(filtered("order:#{order}-invalid")).to contain_exactly(*Topic.all.pluck(:id))
end
end
@@ -2699,6 +2028,14 @@ RSpec.describe TopicsFilter do
include_examples "ordering topics filters", "posters", "number of participants in the topic"
end
+ describe "when ordering topics by number of posts" do
+ fab!(:topic) { Fabricate(:topic, posts_count: 2) }
+ fab!(:topic2) { Fabricate(:topic, posts_count: 3) }
+ fab!(:topic3) { Fabricate(:topic, posts_count: 1) }
+
+ include_examples "ordering topics filters", "posts", "number of posts"
+ end
+
describe "when ordering topics by number of topics views" do
fab!(:topic) { Fabricate(:topic, views: 2) }
fab!(:topic2) { Fabricate(:topic, views: 3) }
@@ -2776,12 +2113,9 @@ RSpec.describe TopicsFilter do
describe "when query string is `order:read`" do
it "orders topics by last visit descending for logged-in users" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("order:read")
- .pluck(:id),
- ).to eq([topic2.id, topic.id, topic3.id])
+ expect(filtered("order:read", Guardian.new(user))).to eq(
+ [topic2.id, topic.id, topic3.id],
+ )
end
it "does not apply special ordering for anonymous users" do
@@ -2797,12 +2131,9 @@ RSpec.describe TopicsFilter do
describe "when query string is `order:read-asc`" do
it "orders topics by last visit ascending for logged-in users" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("order:read-asc")
- .pluck(:id),
- ).to eq([topic3.id, topic.id, topic2.id])
+ expect(filtered("order:read-asc", Guardian.new(user))).to eq(
+ [topic3.id, topic.id, topic2.id],
+ )
end
end
end
@@ -2814,23 +2145,13 @@ RSpec.describe TopicsFilter do
describe "when query string is `order:created,views`" do
it "orders topics by creation date and view count descending" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:created,views")
- .pluck(:id),
- ).to eq([topic2.id, topic3.id, topic.id])
+ expect(filtered("order:created,views")).to eq([topic2.id, topic3.id, topic.id])
end
end
describe "when query string is `order:created order:views`" do
it "uses creation date and view count as descending tie-breakers" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:created order:views")
- .pluck(:id),
- ).to eq([topic2.id, topic3.id, topic.id])
+ expect(filtered("order:created order:views")).to eq([topic2.id, topic3.id, topic.id])
end
end
end
@@ -2848,21 +2169,11 @@ RSpec.describe TopicsFilter do
end
it "applies ASC order correctly" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:bumped-asc")
- .pluck(:id),
- ).to eq([earlier_topic.id, now_topic.id])
+ expect(filtered("order:bumped-asc")).to eq([earlier_topic.id, now_topic.id])
end
it "applies default order correctly" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new)
- .filter_from_query_string("order:bumped")
- .pluck(:id),
- ).to eq([now_topic.id, earlier_topic.id])
+ expect(filtered("order:bumped")).to eq([now_topic.id, earlier_topic.id])
end
end
end
@@ -2903,67 +2214,44 @@ RSpec.describe TopicsFilter do
end
it "can guard against the current user" do
- expect(
- TopicsFilter.new(guardian: Guardian.new).filter_from_query_string("foo:bar").pluck(:id),
- ).to be_empty
+ expect(filtered("foo:bar")).to be_empty
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(admin))
- .filter_from_query_string("foo:bar")
- .pluck(:id),
- ).to contain_exactly(topic.id)
+ expect(filtered("foo:bar", Guardian.new(admin))).to contain_exactly(topic.id)
end
end
end
- describe "custom filter mappings for in: and status: operators" do
+ describe "custom in: filter mappings" do
fab!(:topic)
fab!(:solved_topic) { Fabricate(:topic, closed: true) }
- describe "custom in: filter" do
- around do |example|
- registered = DiscoursePluginRegistry._raw_custom_filter_mappings.dup
-
- Plugin::Instance.new.add_filter_custom_filter(
- "in:solved",
- &->(scope, value, guardian) { scope.where(closed: true) }
- )
+ around do |example|
+ registered = DiscoursePluginRegistry._raw_custom_filter_mappings.dup
- example.run
- ensure
- DiscoursePluginRegistry._raw_custom_filter_mappings.replace(registered)
- end
+ Plugin::Instance.new.add_filter_custom_filter(
+ "in:solved",
+ &->(scope, value, guardian) { scope.where(closed: true) }
+ )
- it "applies custom in: filter" do
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:solved")
- .pluck(:id),
- ).to contain_exactly(solved_topic.id)
- end
+ example.run
+ ensure
+ DiscoursePluginRegistry._raw_custom_filter_mappings.replace(registered)
+ end
- it "handles comma-separated values with custom filters" do
- TopicUser.change(
- user.id,
- topic.id,
- notification_level: TopicUser.notification_levels[:watching],
- )
+ it "applies a custom in: value" do
+ expect(filtered("in:solved", Guardian.new(user))).to contain_exactly(solved_topic.id)
+ end
+ it "combines a custom in: value with a built-in one" do
+ [topic, solved_topic].each do |t|
TopicUser.change(
user.id,
- solved_topic.id,
+ t.id,
notification_level: TopicUser.notification_levels[:watching],
)
-
- expect(
- TopicsFilter
- .new(guardian: Guardian.new(user))
- .filter_from_query_string("in:watching,solved")
- .pluck(:id),
- ).to contain_exactly(solved_topic.id)
end
+
+ expect(filtered("in:watching,solved", Guardian.new(user))).to contain_exactly(solved_topic.id)
end
end
end