2020-03-12 13:20:56 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
##
|
|
|
|
# Allows us to query Bookmark records for lists. Used mainly
|
|
|
|
# in the user/activity/bookmarks page.
|
|
|
|
|
|
|
|
class BookmarkQuery
|
2020-03-19 13:48:23 +08:00
|
|
|
cattr_accessor :preloaded_custom_fields
|
|
|
|
self.preloaded_custom_fields = Set.new
|
|
|
|
|
|
|
|
def self.on_preload(&blk)
|
|
|
|
(@preload ||= Set.new) << blk
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.preload(bookmarks, object)
|
|
|
|
if @preload
|
|
|
|
@preload.each { |preload| preload.call(bookmarks, object) }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-03-23 19:04:39 +08:00
|
|
|
def initialize(user:, guardian: nil, params: {})
|
2020-03-12 13:20:56 +08:00
|
|
|
@user = user
|
|
|
|
@params = params
|
2020-03-23 19:04:39 +08:00
|
|
|
@guardian = guardian || Guardian.new(@user)
|
2020-04-01 12:09:07 +08:00
|
|
|
@page = @params[:page].to_i
|
|
|
|
@limit = @params[:limit].present? ? @params[:limit].to_i : @params[:per_page]
|
2020-03-12 13:20:56 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def list_all
|
2021-03-22 07:50:22 +08:00
|
|
|
results = user_bookmarks.order(
|
|
|
|
'(CASE WHEN bookmarks.pinned THEN 0 ELSE 1 END), bookmarks.updated_at DESC'
|
|
|
|
)
|
2020-03-12 13:20:56 +08:00
|
|
|
|
2020-03-23 19:04:39 +08:00
|
|
|
topics = Topic.listable_topics.secured(@guardian)
|
|
|
|
pms = Topic.private_messages_for_user(@user)
|
|
|
|
results = results.merge(topics.or(pms))
|
|
|
|
|
|
|
|
results = results.merge(Post.secured(@guardian))
|
|
|
|
|
2020-07-14 12:43:41 +08:00
|
|
|
if @params[:q].present?
|
2020-07-17 13:55:07 +08:00
|
|
|
term = @params[:q]
|
|
|
|
bookmark_ts_query = Search.ts_query(term: term)
|
|
|
|
results = results
|
|
|
|
.joins("LEFT JOIN post_search_data ON post_search_data.post_id = bookmarks.post_id")
|
|
|
|
.where(
|
|
|
|
"bookmarks.name ILIKE :q OR #{bookmark_ts_query} @@ post_search_data.search_data",
|
|
|
|
q: "%#{term}%"
|
|
|
|
)
|
2020-07-14 12:43:41 +08:00
|
|
|
end
|
|
|
|
|
2020-04-01 12:09:07 +08:00
|
|
|
if @page.positive?
|
|
|
|
results = results.offset(@page * @params[:per_page])
|
2020-03-12 13:20:56 +08:00
|
|
|
end
|
|
|
|
|
2020-04-01 12:09:07 +08:00
|
|
|
results = results.limit(@limit)
|
|
|
|
|
2020-03-19 13:48:23 +08:00
|
|
|
if BookmarkQuery.preloaded_custom_fields.any?
|
|
|
|
Topic.preload_custom_fields(
|
|
|
|
results.map(&:topic), BookmarkQuery.preloaded_custom_fields
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
BookmarkQuery.preload(results, self)
|
|
|
|
|
2020-03-23 19:04:39 +08:00
|
|
|
@guardian.filter_allowed_categories(results)
|
2020-03-12 13:20:56 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def user_bookmarks
|
2020-03-19 13:48:23 +08:00
|
|
|
Bookmark.where(user: @user)
|
|
|
|
.includes(topic: :tags)
|
|
|
|
.includes(post: :user)
|
2020-03-23 19:04:39 +08:00
|
|
|
.references(:topic)
|
|
|
|
.references(:post)
|
2020-03-12 13:20:56 +08:00
|
|
|
end
|
|
|
|
end
|