Merge branch 'develop' into tests/mastodon_api_controller.ex
[akkoma] / lib / pleroma / conversation / participation.ex
index f1e1a69580e4c41b0ee8056fe52ab37a4ef3c64a..e946f6de26eff61247f4618be47be3c5de14c72f 100644 (file)
@@ -13,10 +13,10 @@ defmodule Pleroma.Conversation.Participation do
   import Ecto.Query
 
   schema "conversation_participations" do
-    belongs_to(:user, User, type: Pleroma.FlakeId)
+    belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
     belongs_to(:conversation, Conversation)
     field(:read, :boolean, default: false)
-    field(:last_activity_id, Pleroma.FlakeId, virtual: true)
+    field(:last_activity_id, FlakeId.Ecto.CompatType, virtual: true)
 
     has_many(:recipient_ships, RecipientShip)
     has_many(:recipients, through: [:recipient_ships, :user])
@@ -94,9 +94,45 @@ defmodule Pleroma.Conversation.Participation do
     |> Enum.filter(& &1.last_activity_id)
   end
 
-  def get(nil), do: nil
+  def get(_, _ \\ [])
+  def get(nil, _), do: nil
 
-  def get(id) do
-    Repo.get(__MODULE__, id)
+  def get(id, params) do
+    query =
+      if preload = params[:preload] do
+        from(p in __MODULE__,
+          preload: ^preload
+        )
+      else
+        __MODULE__
+      end
+
+    Repo.get(query, id)
+  end
+
+  def set_recipients(participation, user_ids) do
+    user_ids =
+      [participation.user_id | user_ids]
+      |> Enum.uniq()
+
+    Repo.transaction(fn ->
+      query =
+        from(r in RecipientShip,
+          where: r.participation_id == ^participation.id
+        )
+
+      Repo.delete_all(query)
+
+      users =
+        from(u in User,
+          where: u.id in ^user_ids
+        )
+        |> Repo.all()
+
+      RecipientShip.create(users, participation)
+      :ok
+    end)
+
+    {:ok, Repo.preload(participation, :recipients, force: true)}
   end
 end