A platform for community discussion. Free, open, simple.
DEV: Extract directory, latest posts and topic view queries (#43513)
Natalie Tay834f96d09e7a
diff --git a/app/controllers/directory_items_controller.rb b/app/controllers/directory_items_controller.rbindex eb0396ef316..e1451fe1a37 100644--- a/app/controllers/directory_items_controller.rb+++ b/app/controllers/directory_items_controller.rb@@ -1,10 +1,8 @@# frozen_string_literal: trueclass DirectoryItemsController < ApplicationController- PAGE_SIZE = 50- PAGE_LIMIT = 10-- before_action :set_groups_exclusion, if: -> { params[:exclude_groups].present? }+ PAGE_SIZE = DirectoryItemsQuery::PAGE_SIZE+ PAGE_LIMIT = DirectoryItemsQuery::PAGE_LIMITdef indexdiscourse_expires_in 1.minute@@ -16,109 +14,32 @@ class DirectoryItemsController < ApplicationControllerperiod = params.require(:period)period_type = DirectoryItem.period_types[period.to_sym]raise Discourse::InvalidAccess.new(:period_type) unless period_type- result = DirectoryItem.where(period_type: period_type).includes(user: :user_custom_fields)-- if params[:group]- group = Group.find_by(name: params[:group])- raise Discourse::InvalidParameters.new(:group) if group.blank?- guardian.ensure_can_see_group_and_members!(group)-- result = result.includes(user: :groups).where(users: { groups: { id: group.id } })- else- result = result.includes(user: :primary_group)- end-- result = apply_exclude_groups_filter(result)-- if params[:exclude_usernames]- result =- result- .references(:user)- .where.not(users: { username: params[:exclude_usernames].split(",") })- end-- default_order = DirectoryColumn.automatic_column_names.first- order = params[:order] || default_order- dir = params[:asc] ? "ASC" : "DESC"- active_directory_column_names = DirectoryColumn.active_column_names- if active_directory_column_names.include?(order.to_sym)- result = result.order("directory_items.#{order} #{dir}, directory_items.id")- elsif order == "username"- result = result.order("users.#{order} #{dir}, directory_items.id")- else- # Ordering by user field value- user_field_scope = guardian.is_staff? ? UserField.all : UserField.public_fields- user_field = user_field_scope.find_by(name: order)- if user_field- result =- result- .references(:user)- .joins(- "LEFT OUTER JOIN user_custom_fields ON user_custom_fields.user_id = users.id AND user_custom_fields.name = 'user_field_#{user_field.id}'",- )- .order(- "user_custom_fields.name = 'user_field_#{user_field.id}' ASC, user_custom_fields.value #{dir}",- )- else- result = result.order("directory_items.#{default_order} #{dir}, directory_items.id")- end- end-- result = result.includes(:user_stat) if period_type == DirectoryItem.period_types[:all]page = fetch_int_from_params(:page, default: 0, max: PAGE_LIMIT)-- user_ids = nil- if params[:name].present?- opts = {- include_staged_users: true,- user_directory_search: true,- limit: 200,- search_custom_fields: true,- }- user_ids = UserSearch.new(params[:name], opts).search.pluck(:id)- if user_ids.present?- # Add the current user if we have at least one other match- user_ids << current_user.id if current_user && result.dup.where(user_id: user_ids).exists?- result = result.where(user_id: user_ids)- else- result = result.where("false")- end- end-- if params[:username]- user_id = User.where(username_lower: params[:username].to_s.downcase).pick(:id)- if user_id- result = result.where(user_id: user_id)- else- result = result.where("false")- end- end-limit = fetch_limit_from_params(default: PAGE_SIZE, max: PAGE_SIZE)-- result_count = result.count- result = result.limit(limit).offset(limit * page).to_a+ begin+ query_result =+ DirectoryItemsQuery.new(user: current_user, guardian:).call(+ period_type:,+ group_name: params[:group],+ exclude_group_names: params[:exclude_groups]&.split("|"),+ exclude_usernames: params[:exclude_usernames]&.split(","),+ order: params[:order],+ ascending: params[:asc].present?,+ name: params[:name],+ username: params[:username],+ page:,+ limit:,+ prioritize_user: true,+ )+ rescue DirectoryItemsQuery::GroupNotFound+ raise Discourse::InvalidParameters.new(:group)+ endmore_params = params.slice(:period, :order, :asc, :group, :user_field_ids, :name).permit!more_params[:page] = page + 1load_more_uri = URI.parse(directory_items_path(more_params))load_more_directory_items_json = "#{load_more_uri.path}.json?#{load_more_uri.query}"- # Put yourself at the top of the first page- if result.present? && current_user.present? && page == 0 && !params[:group].present?- position = result.index { |r| r.user_id == current_user.id }-- # Don't show the record unless you're not in the top positions already- if (position || 10) >= 10- unless @users_in_exclude_groups&.include?(current_user.id)- your_item = DirectoryItem.where(period_type: period_type, user_id: current_user.id).first- result.insert(0, your_item) if your_item- end- end- end-- last_updated_at = DirectoryItem.last_updated_at(period_type)-serializer_opts = {}if params[:user_field_ids]serializer_opts[:user_custom_field_map] = {}@@ -142,34 +63,19 @@ class DirectoryItemsController < ApplicationControllerserializer_opts[:plugin_column_ids] = params[:plugin_column_ids]&.split("|")&.map(&:to_i)end- serializer_opts[:attributes] = active_directory_column_names+ serializer_opts[:attributes] = query_result.active_column_namesserializer_opts[:searchable_fields] = UserField.where(searchable: true) if serializer_opts[:user_custom_field_map].present?- serialized = serialize_data(result, DirectoryItemSerializer, serializer_opts)+ serialized = serialize_data(query_result.items, DirectoryItemSerializer, serializer_opts)render_json_dump(directory_items: serialized,meta: {- last_updated_at: last_updated_at,- total_rows_directory_items: result_count,+ last_updated_at: query_result.last_updated_at,+ total_rows_directory_items: query_result.total,load_more_directory_items: load_more_directory_items_json,},)end-- private-- def set_groups_exclusion- @exclude_group_names = params[:exclude_groups].split("|")- groups = Group.where(name: @exclude_group_names)- groups = groups.select { |g| guardian.can_see_group_and_members?(g) }- @exclude_group_ids = groups.map(&:id)- @users_in_exclude_groups = GroupUser.where(group_id: @exclude_group_ids).pluck(:user_id)- end-- def apply_exclude_groups_filter(result)- result = result.where.not(user_id: @users_in_exclude_groups) if params[:exclude_groups]- result- endenddiff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rbindex b46e8ec99c0..5c422c04984 100644--- a/app/controllers/posts_controller.rb+++ b/app/controllers/posts_controller.rb@@ -51,50 +51,21 @@ class PostsController < ApplicationControllerif params[:id] == "private_posts"raise Discourse::NotFound if current_user.nil?-- allowed_private_topics = TopicAllowedUser.where(user_id: current_user.id).select(:topic_id)-- allowed_groups = GroupUser.where(user_id: current_user.id).select(:group_id)- allowed_private_topics_by_group =- TopicAllowedGroup.where(group_id: allowed_groups).select(:topic_id)-- all_allowed =- Topic- .where(id: allowed_private_topics)- .or(Topic.where(id: allowed_private_topics_by_group))- .select(:id)-posts =- Post- .private_posts- .where(post_type: Topic.visible_post_types(current_user))- .order(id: :desc)- .includes(topic: :category)- .includes(user: %i[primary_group flair_group])- .includes(:reply_to_user)- .limit(50)+ LatestPostsQuery.new(user: current_user, guardian:).private_posts(+ before_post_id: last_post_id,+ )rss_description = I18n.t("rss_description.private_posts")-- posts = posts.where(topic_id: all_allowed) if !current_user.admin?elseposts =- Post- .public_posts- .visible- .where(post_type: Post.types[:regular])- .order(id: :desc)- .includes(topic: %i[category localizations])- .includes(user: %i[primary_group flair_group])- .includes(:reply_to_user)- .where("categories.id" => Category.secured(guardian).select(:id))- .limit(50)+ LatestPostsQuery.new(user: current_user, guardian:).public_posts(+ before_post_id: last_post_id,+ )rss_description = I18n.t("rss_description.posts")@use_canonical = trueend- posts = posts.where("posts.id < ?", last_post_id) if last_post_id-posts = posts.to_acounts = PostAction.counts_for(posts, current_user)diff --git a/app/controllers/topic_view_stats_controller.rb b/app/controllers/topic_view_stats_controller.rbindex d84a79f57b1..c61454b19d4 100644--- a/app/controllers/topic_view_stats_controller.rb+++ b/app/controllers/topic_view_stats_controller.rb@@ -1,11 +1,8 @@# frozen_string_literal: trueclass TopicViewStatsController < ApplicationController- MAX_STATS_PER_API_REQUEST = 300-def indextopic = Topic.find(params[:topic_id].to_i)- guardian.ensure_can_see!(topic)from = 30.days.ago.to_dateto = Date.today@@ -18,11 +15,7 @@ class TopicViewStatsController < ApplicationControllerreturnend- stats =- TopicViewStat- .where(topic_id: topic.id, viewed_at: from..to)- .order(viewed_at: :desc)- .limit(MAX_STATS_PER_API_REQUEST)+ stats = TopicViewStatsQuery.call(topic:, guardian:, from:, to:)rows = []@@ -30,6 +23,6 @@ class TopicViewStatsController < ApplicationControllerrows << { viewed_at: stat.viewed_at, views: stat.anonymous_views + stat.logged_in_views }end- render json: { topic_id: topic.id, stats: rows.reverse }+ render json: { topic_id: topic.id, stats: rows }endenddiff --git a/lib/directory_items_query.rb b/lib/directory_items_query.rbnew file mode 100644index 00000000000..7e10d852aa8--- /dev/null+++ b/lib/directory_items_query.rb@@ -0,0 +1,163 @@+# frozen_string_literal: true++class DirectoryItemsQuery+ PAGE_SIZE = 50+ PAGE_LIMIT = 10++ GroupNotFound = Class.new(StandardError)+ Result = Data.define(:items, :total, :last_updated_at, :period_type, :active_column_names)++ def initialize(user:, guardian:)+ @user = user+ @guardian = guardian+ end++ def call(+ period_type:,+ group_name: nil,+ exclude_group_names: nil,+ exclude_usernames: nil,+ order: nil,+ ascending: false,+ name: nil,+ username: nil,+ page: 0,+ limit: PAGE_SIZE,+ prioritize_user: false+ )+ items = DirectoryItem.where(period_type:).includes(user: %i[user_custom_fields primary_group])+ items = filter_group(items, group_name) if group_name.present?+ items, excluded_user_ids = exclude_groups(items, exclude_group_names)+ items = exclude_usernames(items, exclude_usernames)+ items = filter_name(items, name, prioritize_user:)+ items = filter_username(items, username)+ items = order_items(items, order, ascending)+ items = items.includes(:user_stat) if period_type == DirectoryItem.period_types[:all]++ total = items.count+ page_items = items.limit(limit).offset(limit * page).to_a+ if prioritize_user+ prioritize_user!(page_items, period_type:, page:, group_name:, excluded_user_ids:)+ end++ Result.new(+ items: page_items,+ total:,+ last_updated_at: DirectoryItem.last_updated_at(period_type),+ period_type:,+ active_column_names: DirectoryColumn.active_column_names,+ )+ end++ private++ attr_reader :guardian, :user++ def filter_group(items, group_name)+ group = Group.find_by(name: group_name)+ raise GroupNotFound if group.blank?++ guardian.ensure_can_see_group_and_members!(group)+ items.joins(user: :groups).where(groups: { id: group.id })+ end++ def exclude_groups(items, group_names)+ return items, [] if group_names.blank?++ group_ids =+ Group+ .where(name: group_names)+ .select { |group| guardian.can_see_group_and_members?(group) }+ .map(&:id)+ excluded_user_ids = GroupUser.where(group_id: group_ids).pluck(:user_id)+ [items.where.not(user_id: excluded_user_ids), excluded_user_ids]+ end++ def exclude_usernames(items, usernames)+ return items if usernames.blank?++ user_ids = User.where(username_lower: usernames.map(&:downcase)).select(:id)+ items.where.not(user_id: user_ids)+ end++ def filter_name(items, name, prioritize_user:)+ return items if name.blank?++ user_ids =+ UserSearch+ .new(+ name,+ include_staged_users: true,+ user_directory_search: true,+ limit: 200,+ search_custom_fields: true,+ searching_user: user,+ )+ .search+ .pluck(:id)+ return items.where("false") if user_ids.empty?++ user_ids << user.id if prioritize_user && user && items.where(user_id: user_ids).exists?+ items.where(user_id: user_ids)+ end++ def filter_username(items, username)+ return items if username.blank?++ user_id = User.where(username_lower: username.downcase).pick(:id)+ user_id ? items.where(user_id:) : items.where("false")+ end++ def order_items(items, requested_order, ascending)+ default_order = DirectoryColumn.automatic_column_names.first+ order = requested_order.presence || default_order.to_s+ direction = ascending ? :asc : :desc++ if DirectoryColumn.active_column_names.include?(order.to_sym)+ items.order(order => direction, :id => :asc)+ elsif order == "username"+ items.joins(:user).order(users: { username: direction }, id: :asc)+ else+ order_by_user_field(items, order, direction, default_order)+ end+ end++ def order_by_user_field(items, order, direction, default_order)+ user_field_scope = guardian.is_staff? ? UserField.all : UserField.public_fields+ user_field = user_field_scope.find_by(name: order)+ return items.order(default_order => direction, :id => :asc) if user_field.blank?++ field_name = "#{User::USER_FIELD_PREFIX}#{user_field.id}"+ items+ .joins(+ ActiveRecord::Base.sanitize_sql_array(+ [+ "LEFT OUTER JOIN user_custom_fields ON " \+ "user_custom_fields.user_id = directory_items.user_id AND " \+ "user_custom_fields.name = ?",+ field_name,+ ],+ ),+ )+ .order(+ Arel.sql(+ "user_custom_fields.name = #{ActiveRecord::Base.connection.quote(field_name)} ASC",+ ),+ )+ .order(user_custom_fields: { value: direction })+ end++ def prioritize_user!(items, period_type:, page:, group_name:, excluded_user_ids:)+ return if items.empty? || user.blank? || page != 0 || group_name.present?++ position = items.index { |item| item.user_id == user.id }+ return if (position || 10) < 10 || excluded_user_ids.include?(user.id)++ user_item =+ DirectoryItem+ .where(period_type:, user_id: user.id)+ .includes(:user_stat, user: %i[user_custom_fields primary_group])+ .first+ items.insert(0, user_item) if user_item+ end+enddiff --git a/lib/latest_posts_query.rb b/lib/latest_posts_query.rbnew file mode 100644index 00000000000..1345672f946--- /dev/null+++ b/lib/latest_posts_query.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++class LatestPostsQuery+ PAGE_SIZE = 50++ def initialize(user:, guardian:)+ @user = user+ @guardian = guardian+ end++ def public_posts(before_post_id: nil)+ posts =+ Post+ .public_posts+ .visible+ .where(post_type: Post.types[:regular])+ .where(categories: { id: Category.secured(guardian).select(:id) })+ .order(id: :desc)+ .includes(topic: %i[category localizations])+ .includes(user: %i[primary_group flair_group])+ .includes(:reply_to_user)+ .limit(PAGE_SIZE)+ before_post_id ? posts.where("posts.id < ?", before_post_id) : posts+ end++ def private_posts(before_post_id: nil)+ allowed_user_topics = TopicAllowedUser.where(user_id: user.id).select(:topic_id)+ allowed_group_ids = GroupUser.where(user_id: user.id).select(:group_id)+ allowed_group_topics = TopicAllowedGroup.where(group_id: allowed_group_ids).select(:topic_id)+ allowed_topics =+ Topic.where(id: allowed_user_topics).or(Topic.where(id: allowed_group_topics)).select(:id)++ posts =+ Post+ .private_posts+ .where(post_type: Topic.visible_post_types(user))+ .order(id: :desc)+ .includes(topic: :category)+ .includes(user: %i[primary_group flair_group])+ .includes(:reply_to_user)+ .limit(PAGE_SIZE)+ posts = posts.where(topic_id: allowed_topics) if !user.admin?+ before_post_id ? posts.where("posts.id < ?", before_post_id) : posts+ end++ private++ attr_reader :user, :guardian+enddiff --git a/lib/topic_view_stats_query.rb b/lib/topic_view_stats_query.rbnew file mode 100644index 00000000000..cbaacae860c--- /dev/null+++ b/lib/topic_view_stats_query.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++class TopicViewStatsQuery+ MAX_STATS = 300++ def self.call(topic:, guardian:, from:, to:)+ guardian.ensure_can_see!(topic)++ TopicViewStat+ .where(topic_id: topic.id, viewed_at: from..to)+ .order(viewed_at: :desc)+ .limit(MAX_STATS)+ .reverse+ end+end