Merge branch 'develop' into dtluna/pleroma-feature/unfollow-activity
[akkoma] / lib / pleroma / web / activity_pub / activity_pub.ex
index 82aed7ce42a41eb08a39bd0f9bc557c6b419ee42..f3e94b1010c54f978af1ed088f0076ab8038da8a 100644 (file)
@@ -205,12 +205,60 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
     {:ok, activity, object}
   end
 
+  def follow(%User{ap_id: follower_id, local: actor_local}, %User{ap_id: followed_id}, local \\ true) do
+    data = %{
+      "type" => "Follow",
+      "actor" => follower_id,
+      "to" => [followed_id],
+      "object" => followed_id,
+      "published" => make_date()
+    }
+
+    with {:ok, activity} <- insert(data, local) do
+      if actor_local do
+        Pleroma.Web.Federator.enqueue(:publish, activity)
+       end
+
+      {:ok, activity}
+    end
+  end
+
+  def unfollow(follower, followed, local \\ true) do
+    with follow_activity when not is_nil(follow_activity) <- fetch_latest_follow(follower, followed) do
+      data = %{
+        "type" => "Undo",
+        "actor" => follower.ap_id,
+        "to" => [followed.ap_id],
+        "object" => follow_activity.data["id"],
+        "published" => make_date()
+      }
+
+      with {:ok, activity} <- insert(data, local) do
+        if follower.local do
+          Pleroma.Web.Federator.enqueue(:publish, activity)
+        end
+
+        {:ok, activity}
+      end
+    end
+  end
+
   def fetch_activities_for_context(context) do
     query = from activity in Activity,
       where: fragment("? @> ?", activity.data, ^%{ context: context })
     Repo.all(query)
   end
 
+  def fetch_latest_follow(%User{ap_id: follower_id},
+                          %User{ap_id: followed_id}) do
+    query = from activity in Activity,
+      where: fragment("? @> ?", activity.data, ^%{type: "Follow", actor: follower_id,
+                                                  object: followed_id}),
+      order_by: [desc: :inserted_at],
+      limit: 1
+    Repo.one(query)
+  end
+
   def upload(file) do
     data = Upload.store(file)
     Repo.insert(%Object{data: data})