Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into remake-remodel-dms
[akkoma] / lib / pleroma / web / activity_pub / side_effects.ex
1 defmodule Pleroma.Web.ActivityPub.SideEffects do
2 @moduledoc """
3 This module looks at an inserted object and executes the side effects that it
4 implies. For example, a `Like` activity will increase the like count on the
5 liked object, a `Follow` activity will add the user to the follower
6 collection, and so on.
7 """
8 alias Pleroma.Chat
9 alias Pleroma.Notification
10 alias Pleroma.Object
11 alias Pleroma.Repo
12 alias Pleroma.User
13 alias Pleroma.Web.ActivityPub.Pipeline
14 alias Pleroma.Web.ActivityPub.Utils
15
16 def handle(object, meta \\ [])
17
18 # Tasks this handles:
19 # - Add like to object
20 # - Set up notification
21 def handle(%{data: %{"type" => "Like"}} = object, meta) do
22 {:ok, result} =
23 Pleroma.Repo.transaction(fn ->
24 liked_object = Object.get_by_ap_id(object.data["object"])
25 Utils.add_like_to_object(object, liked_object)
26
27 Notification.create_notifications(object)
28
29 {:ok, object, meta}
30 end)
31
32 result
33 end
34
35 # Tasks this handles
36 # - Actually create object
37 # - Rollback if we couldn't create it
38 # - Set up notifications
39 def handle(%{data: %{"type" => "Create"}} = activity, meta) do
40 with {:ok, _object, _meta} <- handle_object_creation(meta[:object_data], meta) do
41 Notification.create_notifications(activity)
42 {:ok, activity, meta}
43 else
44 e -> Repo.rollback(e)
45 end
46 end
47
48 # Nothing to do
49 def handle(object, meta) do
50 {:ok, object, meta}
51 end
52
53 def handle_object_creation(%{"type" => "ChatMessage"} = object, meta) do
54 with {:ok, object, meta} <- Pipeline.common_pipeline(object, meta) do
55 actor = User.get_cached_by_ap_id(object.data["actor"])
56 recipient = User.get_cached_by_ap_id(hd(object.data["to"]))
57
58 [[actor, recipient], [recipient, actor]]
59 |> Enum.each(fn [user, other_user] ->
60 if user.local do
61 Chat.bump_or_create(user.id, other_user.ap_id)
62 end
63 end)
64
65 {:ok, object, meta}
66 end
67 end
68
69 # Nothing to do
70 def handle_object_creation(object) do
71 {:ok, object}
72 end
73 end