Refactor query to return only 1 message instead of 20

This commit is contained in:
Roman Chvanikov 2019-04-21 00:40:41 +07:00
parent 76999c73a7
commit 24073f829f
2 changed files with 33 additions and 33 deletions

View file

@ -65,22 +65,13 @@ defmodule Pleroma.Conversation.Participation do
def for_user_with_last_activity_id(user, params \\ %{}) do def for_user_with_last_activity_id(user, params \\ %{}) do
for_user(user, params) for_user(user, params)
|> Repo.preload(:conversation)
|> Enum.map(fn participation -> |> Enum.map(fn participation ->
# TODO: Don't load all those activities, just get the most recent activity_id =
# Involves splitting up the query. ActivityPub.fetch_latest_activity_id_for_context(participation.conversation.ap_id, %{
activities =
ActivityPub.fetch_activities_for_context(participation.conversation.ap_id, %{
"user" => user, "user" => user,
"blocking_user" => user "blocking_user" => user
}) })
activity_id =
case activities do
[activity | _] -> activity.id
_ -> nil
end
%{ %{
participation participation
| last_activity_id: activity_id | last_activity_id: activity_id

View file

@ -459,35 +459,44 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end end
end end
def fetch_activities_for_context(context, opts \\ %{}) do defp fetch_activities_for_context_query(context, opts) do
public = ["https://www.w3.org/ns/activitystreams#Public"] public = ["https://www.w3.org/ns/activitystreams#Public"]
recipients = recipients =
if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
query = from(activity in Activity) from(activity in Activity)
|> restrict_blocked(opts)
query = |> restrict_recipients(recipients, opts["user"])
query |> where(
|> restrict_blocked(opts) [activity],
|> restrict_recipients(recipients, opts["user"]) fragment(
"?->>'type' = ? and ?->>'context' = ?",
query = activity.data,
from( "Create",
activity in query, activity.data,
where: ^context
fragment(
"?->>'type' = ? and ?->>'context' = ?",
activity.data,
"Create",
activity.data,
^context
),
order_by: [desc: :id]
) )
|> Activity.with_preloaded_object() )
|> order_by([activity], desc: activity.id)
end
Repo.all(query) @spec fetch_activities_for_context(String.t(), keyword() | map()) :: [Activity.t()]
def fetch_activities_for_context(context, opts \\ %{}) do
context
|> fetch_activities_for_context_query(opts)
|> Activity.with_preloaded_object()
|> Repo.all()
end
@spec fetch_latest_activity_id_for_context(String.t(), keyword() | map()) ::
Pleroma.FlakeId.t() | nil
def fetch_latest_activity_id_for_context(context, opts \\ %{}) do
context
|> fetch_activities_for_context_query(opts)
|> limit(1)
|> select([a], a.id)
|> Repo.one()
end end
def fetch_public_activities(opts \\ %{}) do def fetch_public_activities(opts \\ %{}) do