TwitterAPI: Fix mentions.
[akkoma] / lib / pleroma / web / activity_pub / activity_pub.ex
1 defmodule Pleroma.Web.ActivityPub.ActivityPub do
2 alias Pleroma.{Activity, Repo, Object, Upload, User, Notification}
3 alias Pleroma.Web.ActivityPub.Transmogrifier
4 alias Pleroma.Web.WebFinger
5 alias Pleroma.Web.Federator
6 import Ecto.Query
7 import Pleroma.Web.ActivityPub.Utils
8 require Logger
9
10 @httpoison Application.get_env(:pleroma, :httpoison)
11
12 def get_recipients(data) do
13 (data["to"] || []) ++ (data["cc"] || [])
14 end
15
16 def insert(map, local \\ true) when is_map(map) do
17 with nil <- Activity.get_by_ap_id(map["id"]),
18 map <- lazy_put_activity_defaults(map),
19 :ok <- insert_full_object(map) do
20 {:ok, activity} = Repo.insert(%Activity{data: map, local: local, actor: map["actor"], recipients: get_recipients(map)})
21 Notification.create_notifications(activity)
22 stream_out(activity)
23 {:ok, activity}
24 else
25 %Activity{} = activity -> {:ok, activity}
26 error -> {:error, error}
27 end
28 end
29
30 def stream_out(activity) do
31 if activity.data["type"] in ["Create", "Announce"] do
32 Pleroma.Web.Streamer.stream("user", activity)
33 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
34 Pleroma.Web.Streamer.stream("public", activity)
35 if activity.local do
36 Pleroma.Web.Streamer.stream("public:local", activity)
37 end
38 end
39 end
40 end
41
42 def create(%{to: to, actor: actor, context: context, object: object} = params) do
43 additional = params[:additional] || %{}
44 local = !(params[:local] == false) # only accept false as false value
45 published = params[:published]
46
47 with create_data <- make_create_data(%{to: to, actor: actor, published: published, context: context, object: object}, additional),
48 {:ok, activity} <- insert(create_data, local),
49 :ok <- maybe_federate(activity) do
50 {:ok, activity}
51 end
52 end
53
54 def accept(%{to: to, actor: actor, object: object} = params) do
55 local = !(params[:local] == false) # only accept false as false value
56
57 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
58 {:ok, activity} <- insert(data, local),
59 :ok <- maybe_federate(activity) do
60 {:ok, activity}
61 end
62 end
63
64 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
65 def like(%User{ap_id: ap_id} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
66 with nil <- get_existing_like(ap_id, object),
67 like_data <- make_like_data(user, object, activity_id),
68 {:ok, activity} <- insert(like_data, local),
69 {:ok, object} <- add_like_to_object(activity, object),
70 :ok <- maybe_federate(activity) do
71 {:ok, activity, object}
72 else
73 %Activity{} = activity -> {:ok, activity, object}
74 error -> {:error, error}
75 end
76 end
77
78 def unlike(%User{} = actor, %Object{} = object) do
79 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
80 {:ok, _activity} <- Repo.delete(activity),
81 {:ok, object} <- remove_like_from_object(activity, object) do
82 {:ok, object}
83 else _e -> {:ok, object}
84 end
85 end
86
87 def announce(%User{ap_id: _} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
88 with true <- is_public?(object),
89 announce_data <- make_announce_data(user, object, activity_id),
90 {:ok, activity} <- insert(announce_data, local),
91 {:ok, object} <- add_announce_to_object(activity, object),
92 :ok <- maybe_federate(activity) do
93 {:ok, activity, object}
94 else
95 error -> {:error, error}
96 end
97 end
98
99 def follow(follower, followed, activity_id \\ nil, local \\ true) do
100 with data <- make_follow_data(follower, followed, activity_id),
101 {:ok, activity} <- insert(data, local),
102 :ok <- maybe_federate(activity) do
103 {:ok, activity}
104 end
105 end
106
107 def unfollow(follower, followed, local \\ true) do
108 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
109 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
110 {:ok, activity} <- insert(unfollow_data, local),
111 :ok, maybe_federate(activity) do
112 {:ok, activity}
113 end
114 end
115
116 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
117 user = User.get_cached_by_ap_id(actor)
118 data = %{
119 "type" => "Delete",
120 "actor" => actor,
121 "object" => id,
122 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
123 }
124 with Repo.delete(object),
125 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
126 {:ok, activity} <- insert(data, local),
127 :ok <- maybe_federate(activity) do
128 {:ok, activity}
129 end
130 end
131
132 def fetch_activities_for_context(context, opts \\ %{}) do
133 public = ["https://www.w3.org/ns/activitystreams#Public"]
134 recipients = if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
135
136 query = from activity in Activity
137 query = query
138 |> restrict_blocked(opts)
139 |> restrict_recipients(recipients, opts["user"])
140
141 query = from activity in query,
142 where: fragment("?->>'type' = ? and ?->>'context' = ?", activity.data, "Create", activity.data, ^context),
143 order_by: [desc: :id]
144 Repo.all(query)
145 end
146
147 def fetch_public_activities(opts \\ %{}) do
148 public = %{to: ["https://www.w3.org/ns/activitystreams#Public"]}
149 q = fetch_activities_query([], opts)
150 q = from activity in q,
151 where: fragment(~s(? @> ?), activity.data, ^public)
152 q
153 |> Repo.all
154 |> Enum.reverse
155 end
156
157 defp restrict_since(query, %{"since_id" => since_id}) do
158 from activity in query, where: activity.id > ^since_id
159 end
160 defp restrict_since(query, _), do: query
161
162 defp restrict_tag(query, %{"tag" => tag}) do
163 from activity in query,
164 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
165 end
166 defp restrict_tag(query, _), do: query
167
168 defp restrict_recipients(query, [], user), do: query
169 defp restrict_recipients(query, recipients, nil) do
170 from activity in query,
171 where: fragment("? && ?", ^recipients, activity.recipients)
172 end
173 defp restrict_recipients(query, recipients, user) do
174 from activity in query,
175 where: fragment("? && ?", ^recipients, activity.recipients),
176 or_where: activity.actor == ^user.ap_id
177 end
178
179 defp restrict_local(query, %{"local_only" => true}) do
180 from activity in query, where: activity.local == true
181 end
182 defp restrict_local(query, _), do: query
183
184 defp restrict_max(query, %{"max_id" => max_id}) do
185 from activity in query, where: activity.id < ^max_id
186 end
187 defp restrict_max(query, _), do: query
188
189 defp restrict_actor(query, %{"actor_id" => actor_id}) do
190 from activity in query,
191 where: activity.actor == ^actor_id
192 end
193 defp restrict_actor(query, _), do: query
194
195 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
196 restrict_type(query, %{"type" => [type]})
197 end
198 defp restrict_type(query, %{"type" => type}) do
199 from activity in query,
200 where: fragment("?->>'type' = ANY(?)", activity.data, ^type)
201 end
202 defp restrict_type(query, _), do: query
203
204 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
205 from activity in query,
206 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
207 end
208 defp restrict_favorited_by(query, _), do: query
209
210 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
211 from activity in query,
212 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
213 end
214 defp restrict_media(query, _), do: query
215
216 # Only search through last 100_000 activities by default
217 defp restrict_recent(query, %{"whole_db" => true}), do: query
218 defp restrict_recent(query, _) do
219 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
220
221 from activity in query,
222 where: activity.id > ^since
223 end
224
225 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
226 blocks = info["blocks"] || []
227 from activity in query,
228 where: fragment("not (? = ANY(?))", activity.actor, ^blocks)
229 end
230 defp restrict_blocked(query, _), do: query
231
232 def fetch_activities_query(recipients, opts \\ %{}) do
233 base_query = from activity in Activity,
234 limit: 20,
235 order_by: [fragment("? desc nulls last", activity.id)]
236
237 base_query
238 |> restrict_recipients(recipients, opts["user"])
239 |> restrict_tag(opts)
240 |> restrict_since(opts)
241 |> restrict_local(opts)
242 |> restrict_max(opts)
243 |> restrict_actor(opts)
244 |> restrict_type(opts)
245 |> restrict_favorited_by(opts)
246 |> restrict_recent(opts)
247 |> restrict_blocked(opts)
248 |> restrict_media(opts)
249 end
250
251 def fetch_activities(recipients, opts \\ %{}) do
252 fetch_activities_query(recipients, opts)
253 |> Repo.all
254 |> Enum.reverse
255 end
256
257 def upload(file) do
258 data = Upload.store(file)
259 Repo.insert(%Object{data: data})
260 end
261
262 def make_user_from_ap_id(ap_id) do
263 with {:ok, %{status_code: 200, body: body}} <- @httpoison.get(ap_id, ["Accept": "application/activity+json"]),
264 {:ok, data} <- Poison.decode(body)
265 do
266 user_data = %{
267 ap_id: data["id"],
268 info: %{
269 "ap_enabled" => true,
270 "source_data" => data
271 },
272 nickname: "#{data["preferredUsername"]}@#{URI.parse(ap_id).host}",
273 name: data["name"]
274 }
275
276 if user = User.get_by_ap_id(ap_id) do
277 User.info_changeset(user, user_data)
278 |> Repo.update
279 else
280 User.insert_or_update_user(user_data)
281 end
282 end
283 end
284
285 def make_user_from_nickname(nickname) do
286 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
287 make_user_from_ap_id(ap_id)
288 end
289 end
290
291 def publish(actor, activity) do
292 followers = if actor.follower_address in activity.recipients do
293 {:ok, followers} = User.get_followers(actor)
294 followers
295 else
296 []
297 end
298
299 remote_inboxes = (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
300 |> Enum.filter(fn (user) -> User.ap_enabled?(user) end)
301 |> Enum.map(fn (%{info: %{"source_data" => data}}) ->
302 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
303 end)
304 |> Enum.uniq
305
306 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
307 json = Poison.encode!(data)
308 Enum.each remote_inboxes, fn(inbox) ->
309 Federator.enqueue(:publish_single_ap, %{inbox: inbox, json: json, actor: actor, id: activity.data["id"]})
310 end
311 end
312
313 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
314 Logger.info("Federating #{id} to #{inbox}")
315 host = URI.parse(inbox).host
316 signature = Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
317 @httpoison.post(inbox, json, [{"Content-Type", "application/activity+json"}, {"signature", signature}])
318 end
319
320 # TODO:
321 # This will create a Create activity, which we need internally at the moment.
322 def fetch_object_from_id(id) do
323 if object = Object.get_cached_by_ap_id(id) do
324 {:ok, object}
325 else
326 with {:ok, %{body: body, status_code: code}} when code in 200..299 <- @httpoison.get(id, [Accept: "application/activity+json"], follow_redirect: true, timeout: 10000, recv_timeout: 20000),
327 {:ok, data} <- Poison.decode(body),
328 data <- Transmogrifier.fix_object(data),
329 nil <- Object.get_by_ap_id(data["id"]),
330 %User{} = user <- User.get_or_fetch_by_ap_id(data["attributedTo"]),
331 {:ok, activity} = create(%{to: data["to"], actor: user, context: data["context"], object: data, local: false, additional: %{"cc" => data["cc"]}}) do
332 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
333 else
334 object = %Object{} -> {:ok, object}
335 e -> e
336 end
337 end
338 end
339
340 def is_public?(activity) do
341 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++ (activity.data["cc"] || []))
342 end
343
344 def visible_for_user?(activity, nil) do
345 is_public?(activity)
346 end
347 def visible_for_user?(activity, user) do
348 x = [user.ap_id | user.following]
349 y = (activity.data["to"] ++ (activity.data["cc"] || []))
350 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
351 end
352 end