Put correct migration
[akkoma] / lib / pleroma / conversation / participation.ex
index d17b6f7c5a045c63032cb8d118a1b0ffc1a21e88..41918fa78e4cd21962c902563b95fa004ebe50d9 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])
@@ -48,10 +48,38 @@ defmodule Pleroma.Conversation.Participation do
     |> validate_required([:read])
   end
 
+  def mark_as_read(%User{} = user, %Conversation{} = conversation) do
+    with %__MODULE__{} = participation <- for_user_and_conversation(user, conversation) do
+      mark_as_read(participation)
+    end
+  end
+
   def mark_as_read(participation) do
     participation
     |> read_cng(%{read: true})
     |> Repo.update()
+    |> case do
+      {:ok, participation} ->
+        participation = Repo.preload(participation, :user)
+        User.set_unread_conversation_count(participation.user)
+        {:ok, participation}
+
+      error ->
+        error
+    end
+  end
+
+  def mark_all_as_read(user) do
+    {_, participations} =
+      __MODULE__
+      |> where([p], p.user_id == ^user.id)
+      |> where([p], not p.read)
+      |> update([p], set: [read: true])
+      |> select([p], p)
+      |> Repo.update_all([])
+
+    User.set_unread_conversation_count(user)
+    {:ok, participations}
   end
 
   def mark_as_unread(participation) do
@@ -94,10 +122,20 @@ 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, params) do
+    query =
+      if preload = params[:preload] do
+        from(p in __MODULE__,
+          preload: ^preload
+        )
+      else
+        __MODULE__
+      end
 
-  def get(id) do
-    Repo.get(__MODULE__, id)
+    Repo.get(query, id)
   end
 
   def set_recipients(participation, user_ids) do
@@ -125,4 +163,12 @@ defmodule Pleroma.Conversation.Participation do
 
     {:ok, Repo.preload(participation, :recipients, force: true)}
   end
+
+  def unread_conversation_count_for_user(user) do
+    from(p in __MODULE__,
+      where: p.user_id == ^user.id,
+      where: not p.read,
+      select: %{count: count(p.id)}
+    )
+  end
 end