a124bb8b6a07edc811ea389c45e9ad92c28e0b20
[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 |> Map.put("#{property}_count", length(element))
179 |> Map.put("#{property}s", element),
180 changeset <- Changeset.change(object, data: new_data),
181 {:ok, object} <- Repo.update(changeset),
182 _ <- update_object_in_activities(object) do
183 {:ok, object}
184 end
185 end
186
187 def update_likes_in_object(likes, object) do
188 update_element_in_object("like", likes, object)
189 end
190
191 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
192 with likes <- [actor | object.data["likes"] || []] |> Enum.uniq() do
193 update_likes_in_object(likes, object)
194 end
195 end
196
197 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
198 with likes <- (object.data["likes"] || []) |> List.delete(actor) do
199 update_likes_in_object(likes, object)
200 end
201 end
202
203 #### Follow-related helpers
204
205 @doc """
206 Makes a follow activity data for the given follower and followed
207 """
208 def make_follow_data(%User{ap_id: follower_id}, %User{ap_id: followed_id}, activity_id) do
209 data = %{
210 "type" => "Follow",
211 "actor" => follower_id,
212 "to" => [followed_id],
213 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
214 "object" => followed_id
215 }
216
217 if activity_id, do: Map.put(data, "id", activity_id), else: data
218 end
219
220 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
221 query =
222 from(
223 activity in Activity,
224 where:
225 fragment(
226 "? @> ?",
227 activity.data,
228 ^%{type: "Follow", actor: follower_id, object: followed_id}
229 ),
230 order_by: [desc: :id],
231 limit: 1
232 )
233
234 Repo.one(query)
235 end
236
237 #### Announce-related helpers
238
239 @doc """
240 Retruns an existing announce activity if the notice has already been announced
241 """
242 def get_existing_announce(actor, %{data: %{"id" => id}}) do
243 query =
244 from(
245 activity in Activity,
246 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
247 # this is to use the index
248 where:
249 fragment(
250 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
251 activity.data,
252 activity.data,
253 ^id
254 ),
255 where: fragment("(?)->>'type' = 'Announce'", activity.data)
256 )
257
258 Repo.one(query)
259 end
260
261 @doc """
262 Make announce activity data for the given actor and object
263 """
264 def make_announce_data(
265 %User{ap_id: ap_id} = user,
266 %Object{data: %{"id" => id}} = object,
267 activity_id
268 ) do
269 data = %{
270 "type" => "Announce",
271 "actor" => ap_id,
272 "object" => id,
273 "to" => [user.follower_address, object.data["actor"]],
274 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
275 "context" => object.data["context"]
276 }
277
278 if activity_id, do: Map.put(data, "id", activity_id), else: data
279 end
280
281 @doc """
282 Make unannounce activity data for the given actor and object
283 """
284 def make_unannounce_data(
285 %User{ap_id: ap_id} = user,
286 %Object{data: %{"id" => id}} = object
287 ) do
288 %{
289 "type" => "Undo",
290 "actor" => ap_id,
291 "object" => id,
292 "to" => [user.follower_address, object.data["actor"]],
293 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
294 "context" => object.data["context"]
295 }
296 end
297
298 def add_announce_to_object(%Activity{data: %{"actor" => actor}}, object) do
299 with announcements <- [actor | object.data["announcements"] || []] |> Enum.uniq() do
300 update_element_in_object("announcement", announcements, object)
301 end
302 end
303
304 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
305 with announcements <- (object.data["announcements"] || []) |> List.delete(actor) do
306 update_element_in_object("announcement", announcements, object)
307 end
308 end
309
310 #### Unfollow-related helpers
311
312 def make_unfollow_data(follower, followed, follow_activity) do
313 %{
314 "type" => "Undo",
315 "actor" => follower.ap_id,
316 "to" => [followed.ap_id],
317 "object" => follow_activity.data["id"]
318 }
319 end
320
321 #### Create-related helpers
322
323 def make_create_data(params, additional) do
324 published = params.published || make_date()
325
326 %{
327 "type" => "Create",
328 "to" => params.to |> Enum.uniq(),
329 "actor" => params.actor.ap_id,
330 "object" => params.object,
331 "published" => published,
332 "context" => params.context
333 }
334 |> Map.merge(additional)
335 end
336 end