Refactor query to return only 1 message instead of 20
[akkoma] / lib / pleroma / activity.ex
index 3dfabe9f35a7926ac7671006e19c0021876c1ac3..ab8861b277b7683660e6ca031dd8f69db664522c 100644 (file)
@@ -31,7 +31,7 @@ defmodule Pleroma.Activity do
     field(:data, :map)
     field(:local, :boolean, default: true)
     field(:actor, :string)
-    field(:recipients, {:array, :string})
+    field(:recipients, {:array, :string}, default: [])
     has_many(:notifications, Notification, on_delete: :delete_all)
 
     # Attention: this is a fake relation, don't try to preload it blindly and expect it to work!
@@ -245,4 +245,50 @@ defmodule Pleroma.Activity do
     |> where([s], s.actor == ^actor)
     |> Repo.all()
   end
+
+  def increase_replies_count(id) do
+    Activity
+    |> where(id: ^id)
+    |> update([a],
+      set: [
+        data:
+          fragment(
+            """
+            jsonb_set(?, '{object, repliesCount}',
+              (coalesce((?->'object'->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
+            """,
+            a.data,
+            a.data
+          )
+      ]
+    )
+    |> Repo.update_all([])
+    |> case do
+      {1, [activity]} -> activity
+      _ -> {:error, "Not found"}
+    end
+  end
+
+  def decrease_replies_count(id) do
+    Activity
+    |> where(id: ^id)
+    |> update([a],
+      set: [
+        data:
+          fragment(
+            """
+            jsonb_set(?, '{object, repliesCount}',
+              (greatest(0, (?->'object'->>'repliesCount')::int - 1))::varchar::jsonb, true)
+            """,
+            a.data,
+            a.data
+          )
+      ]
+    )
+    |> Repo.update_all([])
+    |> case do
+      {1, [activity]} -> activity
+      _ -> {:error, "Not found"}
+    end
+  end
 end