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