Merge branch '1149-oban-job-queue' into 'develop'
[akkoma] / lib / pleroma / pagination.ex
index 7c864deef8feb05b79d8001bba03389c94e77294..b55379c4a96c767978b57c894fd237030b693d6d 100644 (file)
@@ -1,3 +1,7 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
 defmodule Pleroma.Pagination do
   @moduledoc """
   Implements Mastodon-compatible pagination.
@@ -10,16 +14,46 @@ defmodule Pleroma.Pagination do
 
   @default_limit 20
 
-  def fetch_paginated(query, params) do
+  def fetch_paginated(query, params, type \\ :keyset)
+
+  def fetch_paginated(query, %{"total" => true} = params, :keyset) do
+    total = Repo.aggregate(query, :count, :id)
+
+    %{
+      total: total,
+      items: fetch_paginated(query, Map.drop(params, ["total"]), :keyset)
+    }
+  end
+
+  def fetch_paginated(query, params, :keyset) do
     options = cast_params(params)
 
     query
-    |> paginate(options)
+    |> paginate(options, :keyset)
     |> Repo.all()
     |> enforce_order(options)
   end
 
-  def paginate(query, options) do
+  def fetch_paginated(query, %{"total" => true} = params, :offset) do
+    total = Repo.aggregate(query, :count, :id)
+
+    %{
+      total: total,
+      items: fetch_paginated(query, Map.drop(params, ["total"]), :offset)
+    }
+  end
+
+  def fetch_paginated(query, params, :offset) do
+    options = cast_params(params)
+
+    query
+    |> paginate(options, :offset)
+    |> Repo.all()
+  end
+
+  def paginate(query, options, method \\ :keyset)
+
+  def paginate(query, options, :keyset) do
     query
     |> restrict(:min_id, options)
     |> restrict(:since_id, options)
@@ -28,14 +62,27 @@ defmodule Pleroma.Pagination do
     |> restrict(:limit, options)
   end
 
+  def paginate(query, options, :offset) do
+    query
+    |> restrict(:offset, options)
+    |> restrict(:limit, options)
+  end
+
   defp cast_params(params) do
     param_types = %{
       min_id: :string,
       since_id: :string,
       max_id: :string,
+      offset: :integer,
       limit: :integer
     }
 
+    params =
+      Enum.reduce(params, %{}, fn
+        {key, _value}, acc when is_atom(key) -> Map.drop(acc, [key])
+        {key, value}, acc -> Map.put(acc, key, value)
+      end)
+
     changeset = cast({%{}, param_types}, params, Map.keys(param_types))
     changeset.changes
   end
@@ -60,6 +107,10 @@ defmodule Pleroma.Pagination do
     order_by(query, [u], fragment("? desc nulls last", u.id))
   end
 
+  defp restrict(query, :offset, %{offset: offset}) do
+    offset(query, ^offset)
+  end
+
   defp restrict(query, :limit, options) do
     limit = Map.get(options, :limit, @default_limit)