Merge branch 'develop' into feature/polls-2-electric-boogalo
[akkoma] / lib / pleroma / conversation.ex
index 5a2a3fc6de302ff0e311918532c679f4c58c5261..bc97b39ca6e6229d888f6fd721747e48f3579115 100644 (file)
@@ -13,6 +13,7 @@ defmodule Pleroma.Conversation do
     # This is the context ap id.
     field(:ap_id, :string)
     has_many(:participations, Participation)
+    has_many(:users, through: [:participations, :user])
 
     timestamps()
   end
@@ -44,11 +45,12 @@ defmodule Pleroma.Conversation do
   2. Create a participation for all the people involved who don't have one already
   3. Bump all relevant participations to 'unread'
   """
-  def create_or_bump_for(activity) do
+  def create_or_bump_for(activity, opts \\ []) do
     with true <- Pleroma.Web.ActivityPub.Visibility.is_direct?(activity),
          "Create" <- activity.data["type"],
-         "Note" <- activity.data["object"]["type"],
-         ap_id when is_binary(ap_id) <- activity.data["object"]["context"] do
+         object <- Pleroma.Object.normalize(activity),
+         true <- object.data["type"] in ["Note", "Question"],
+         ap_id when is_binary(ap_id) and byte_size(ap_id) > 0 <- object.data["context"] do
       {:ok, conversation} = create_for_ap_id(ap_id)
 
       users = User.get_users_from_set(activity.recipients, false)
@@ -56,15 +58,35 @@ defmodule Pleroma.Conversation do
       participations =
         Enum.map(users, fn user ->
           {:ok, participation} =
-            Participation.create_for_user_and_conversation(user, conversation)
+            Participation.create_for_user_and_conversation(user, conversation, opts)
 
           participation
         end)
 
-      %{
-        conversation
-        | participations: participations
-      }
+      {:ok,
+       %{
+         conversation
+         | participations: participations
+       }}
+    else
+      e -> {:error, e}
     end
   end
+
+  @doc """
+  This is only meant to be run by a mix task. It creates conversations/participations for all direct messages in the database.
+  """
+  def bump_for_all_activities do
+    stream =
+      Pleroma.Web.ActivityPub.ActivityPub.fetch_direct_messages_query()
+      |> Repo.stream()
+
+    Repo.transaction(
+      fn ->
+        stream
+        |> Enum.each(fn a -> create_or_bump_for(a, read: true) end)
+      end,
+      timeout: :infinity
+    )
+  end
 end