/api/v1/favourites: added sorting for activites by adds to favorites
authorMaksim Pechnikov <parallel588@gmail.com>
Mon, 18 Nov 2019 06:44:08 +0000 (09:44 +0300)
committerMaksim Pechnikov <parallel588@gmail.com>
Mon, 18 Nov 2019 06:44:08 +0000 (09:44 +0300)
lib/pleroma/web/activity_pub/activity_pub.ex
lib/pleroma/web/mastodon_api/controllers/status_controller.ex

index d0c014e9dba96052e96e9719db35b33f7a9a924e..95d97615cec507b66d4dc890dc2c54651ad74e30 100644 (file)
@@ -1055,6 +1055,45 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
     |> maybe_update_cc(list_memberships, opts["user"])
   end
 
+  @doc """
+  Fetch favorites activities of user with order by sort adds to favorites
+  """
+  @spec fetch_favourites(list(String.t()), User.t(), map(), atom()) :: list(Activity.t())
+  def fetch_favourites(recipients, user, params \\ %{}, pagination \\ :keyset) do
+    opts =
+      %{
+        "type" => "Create",
+        "favorited_by" => user.ap_id,
+        "blocking_user" => user
+      }
+      |> Map.merge(params)
+
+    recipients
+    |> fetch_activities_query(opts)
+    |> order_by_favourites(user)
+    |> Pagination.fetch_paginated(opts, pagination)
+  end
+
+  # sorts by adds to favorites
+  #
+  @spec order_by_favourites(Ecto.Query.t(), User.t()) :: Ecto.Query.t()
+  defp order_by_favourites(query, user) do
+    join(query, :inner, [activity, object], a1 in Activity,
+      on:
+        fragment(
+          "(?->>'id') = COALESCE(?->'object'->>'id', ?->>'object') AND (?->>'type' = 'Like') AND (?.actor = ?)",
+          object.data,
+          a1.data,
+          a1.data,
+          a1.data,
+          a1,
+          ^user.ap_id
+        ),
+      as: :like_activity
+    )
+    |> order_by([_, _, like_activity], desc: like_activity.updated_at)
+  end
+
   defp maybe_update_cc(activities, list_memberships, %User{ap_id: user_ap_id})
        when is_list(list_memberships) and length(list_memberships) > 0 do
     Enum.map(activities, fn
index 74b223cf4efcfa1771c999c364bf80bcc808aae0..cdc4cec9c07d87f277e7b341afad660985cd260c 100644 (file)
@@ -346,15 +346,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusController do
 
   @doc "GET /api/v1/favourites"
   def favourites(%{assigns: %{user: user}} = conn, params) do
-    params =
-      params
-      |> Map.put("type", "Create")
-      |> Map.put("favorited_by", user.ap_id)
-      |> Map.put("blocking_user", user)
-
-    activities =
-      ActivityPub.fetch_activities([], params)
-      |> Enum.reverse()
+    activities = ActivityPub.fetch_favourites([], user, Map.take(params, ["limit"]))
 
     conn
     |> add_link_headers(activities)