Handle Undo activites containing an Announce
[akkoma] / lib / pleroma / web / activity_pub / utils.ex
1 defmodule Pleroma.Web.ActivityPub.Utils do
2 alias Pleroma.{Repo, Web, Object, Activity, User}
3 alias Pleroma.Web.Router.Helpers
4 alias Pleroma.Web.Endpoint
5 alias Ecto.{Changeset, UUID}
6 import Ecto.Query
7
8 def make_json_ld_header do
9 %{
10 "@context" => [
11 "https://www.w3.org/ns/activitystreams",
12 "https://w3id.org/security/v1",
13 %{
14 "manuallyApprovesFollowers" => "as:manuallyApprovesFollowers",
15 "sensitive" => "as:sensitive",
16 "Hashtag" => "as:Hashtag",
17 "ostatus" => "http://ostatus.org#",
18 "atomUri" => "ostatus:atomUri",
19 "inReplyToAtomUri" => "ostatus:inReplyToAtomUri",
20 "conversation" => "ostatus:conversation",
21 "toot" => "http://joinmastodon.org/ns#",
22 "Emoji" => "toot:Emoji"
23 }
24 ]
25 }
26 end
27
28 def make_date do
29 DateTime.utc_now() |> DateTime.to_iso8601()
30 end
31
32 def generate_activity_id do
33 generate_id("activities")
34 end
35
36 def generate_context_id do
37 generate_id("contexts")
38 end
39
40 def generate_object_id do
41 Helpers.o_status_url(Endpoint, :object, UUID.generate())
42 end
43
44 def generate_id(type) do
45 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
46 end
47
48 def create_context(context) do
49 context = context || generate_id("contexts")
50 changeset = Object.context_mapping(context)
51
52 case Repo.insert(changeset) do
53 {:ok, object} ->
54 object
55
56 # This should be solved by an upsert, but it seems ecto
57 # has problems accessing the constraint inside the jsonb.
58 {:error, _} ->
59 Object.get_cached_by_ap_id(context)
60 end
61 end
62
63 @doc """
64 Enqueues an activity for federation if it's local
65 """
66 def maybe_federate(%Activity{local: true} = activity) do
67 priority =
68 case activity.data["type"] do
69 "Delete" -> 10
70 "Create" -> 1
71 _ -> 5
72 end
73
74 Pleroma.Web.Federator.enqueue(:publish, activity, priority)
75 :ok
76 end
77
78 def maybe_federate(_), do: :ok
79
80 @doc """
81 Adds an id and a published data if they aren't there,
82 also adds it to an included object
83 """
84 def lazy_put_activity_defaults(map) do
85 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
86
87 map =
88 map
89 |> Map.put_new_lazy("id", &generate_activity_id/0)
90 |> Map.put_new_lazy("published", &make_date/0)
91 |> Map.put_new("context", context)
92 |> Map.put_new("context_id", context_id)
93
94 if is_map(map["object"]) do
95 object = lazy_put_object_defaults(map["object"], map)
96 %{map | "object" => object}
97 else
98 map
99 end
100 end
101
102 @doc """
103 Adds an id and published date if they aren't there.
104 """
105 def lazy_put_object_defaults(map, activity \\ %{}) do
106 map
107 |> Map.put_new_lazy("id", &generate_object_id/0)
108 |> Map.put_new_lazy("published", &make_date/0)
109 |> Map.put_new("context", activity["context"])
110 |> Map.put_new("context_id", activity["context_id"])
111 end
112
113 @doc """
114 Inserts a full object if it is contained in an activity.
115 """
116 def insert_full_object(%{"object" => %{"type" => type} = object_data})
117 when is_map(object_data) and type in ["Note"] do
118 with {:ok, _} <- Object.create(object_data) do
119 :ok
120 end
121 end
122
123 def insert_full_object(_), do: :ok
124
125 def update_object_in_activities(%{data: %{"id" => id}} = object) do
126 # TODO
127 # Update activities that already had this. Could be done in a seperate process.
128 # Alternatively, just don't do this and fetch the current object each time. Most
129 # could probably be taken from cache.
130 relevant_activities = Activity.all_by_object_ap_id(id)
131
132 Enum.map(relevant_activities, fn activity ->
133 new_activity_data = activity.data |> Map.put("object", object.data)
134 changeset = Changeset.change(activity, data: new_activity_data)
135 Repo.update(changeset)
136 end)
137 end
138
139 #### Like-related helpers
140
141 @doc """
142 Returns an existing like if a user already liked an object
143 """
144 def get_existing_like(actor, %{data: %{"id" => id}}) do
145 query =
146 from(
147 activity in Activity,
148 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
149 # this is to use the index
150 where:
151 fragment(
152 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
153 activity.data,
154 activity.data,
155 ^id
156 ),
157 where: fragment("(?)->>'type' = 'Like'", activity.data)
158 )
159
160 Repo.one(query)
161 end
162
163 def make_like_data(%User{ap_id: ap_id} = actor, %{data: %{"id" => id}} = object, activity_id) do
164 data = %{
165 "type" => "Like",
166 "actor" => ap_id,
167 "object" => id,
168 "to" => [actor.follower_address, object.data["actor"]],
169 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
170 "context" => object.data["context"]
171 }
172
173 if activity_id, do: Map.put(data, "id", activity_id), else: data
174 end
175
176 def update_element_in_object(property, element, object) do
177 with new_data <-
178 object.data
179 |> Map.put("#{property}_count", length(element))
180 |> Map.put("#{property}s", element),
181 changeset <- Changeset.change(object, data: new_data),
182 {:ok, object} <- Repo.update(changeset),
183 _ <- update_object_in_activities(object) do
184 {:ok, object}
185 end
186 end
187
188 def update_likes_in_object(likes, object) do
189 update_element_in_object("like", likes, object)
190 end
191
192 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
193 with likes <- [actor | object.data["likes"] || []] |> Enum.uniq() do
194 update_likes_in_object(likes, object)
195 end
196 end
197
198 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
199 with likes <- (object.data["likes"] || []) |> List.delete(actor) do
200 update_likes_in_object(likes, object)
201 end
202 end
203
204 #### Follow-related helpers
205
206 @doc """
207 Makes a follow activity data for the given follower and followed
208 """
209 def make_follow_data(%User{ap_id: follower_id}, %User{ap_id: followed_id}, activity_id) do
210 data = %{
211 "type" => "Follow",
212 "actor" => follower_id,
213 "to" => [followed_id],
214 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
215 "object" => followed_id
216 }
217
218 if activity_id, do: Map.put(data, "id", activity_id), else: data
219 end
220
221 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
222 query =
223 from(
224 activity in Activity,
225 where:
226 fragment(
227 "? @> ?",
228 activity.data,
229 ^%{type: "Follow", actor: follower_id, object: followed_id}
230 ),
231 order_by: [desc: :id],
232 limit: 1
233 )
234
235 Repo.one(query)
236 end
237
238 #### Announce-related helpers
239
240 @doc """
241 Retruns an existing announce activity if the notice has already been announced
242 """
243 def get_existing_announce(actor, %{data: %{"id" => id}}) do
244 query =
245 from(
246 activity in Activity,
247 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
248 # this is to use the index
249 where:
250 fragment(
251 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
252 activity.data,
253 activity.data,
254 ^id
255 ),
256 where: fragment("(?)->>'type' = 'Announce'", activity.data)
257 )
258
259 Repo.one(query)
260 end
261
262 @doc """
263 Make announce activity data for the given actor and object
264 """
265 def make_announce_data(
266 %User{ap_id: ap_id} = user,
267 %Object{data: %{"id" => id}} = object,
268 activity_id
269 ) do
270 data = %{
271 "type" => "Announce",
272 "actor" => ap_id,
273 "object" => id,
274 "to" => [user.follower_address, object.data["actor"]],
275 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
276 "context" => object.data["context"]
277 }
278
279 if activity_id, do: Map.put(data, "id", activity_id), else: data
280 end
281
282 @doc """
283 Make unannounce activity data for the given actor and object
284 """
285 def make_unannounce_data(
286 %User{ap_id: ap_id} = user,
287 %Activity{data: %{"context" => context}} = activity,
288 activity_id
289 ) do
290 data = %{
291 "type" => "Undo",
292 "actor" => ap_id,
293 "object" => activity.data,
294 "to" => [user.follower_address, activity.data["actor"]],
295 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
296 "context" => context
297 }
298
299 if activity_id, do: Map.put(data, "id", activity_id), else: data
300 end
301
302 def add_announce_to_object(%Activity{data: %{"actor" => actor}}, object) do
303 with announcements <- [actor | object.data["announcements"] || []] |> Enum.uniq() do
304 update_element_in_object("announcement", announcements, object)
305 end
306 end
307
308 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
309 with announcements <- (object.data["announcements"] || []) |> List.delete(actor) do
310 update_element_in_object("announcement", announcements, object)
311 end
312 end
313
314 #### Unfollow-related helpers
315
316 def make_unfollow_data(follower, followed, follow_activity) do
317 %{
318 "type" => "Undo",
319 "actor" => follower.ap_id,
320 "to" => [followed.ap_id],
321 "object" => follow_activity.data["id"]
322 }
323 end
324
325 #### Create-related helpers
326
327 def make_create_data(params, additional) do
328 published = params.published || make_date()
329
330 %{
331 "type" => "Create",
332 "to" => params.to |> Enum.uniq(),
333 "actor" => params.actor.ap_id,
334 "object" => params.object,
335 "published" => published,
336 "context" => params.context
337 }
338 |> Map.merge(additional)
339 end
340 end