8f660a3340a0e0131249ec9d547294c5f7e2d682
[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 announce_data <- make_announce_data(user, object, activity_id),
88 {:ok, activity} <- insert(announce_data, local),
89 {:ok, object} <- add_announce_to_object(activity, object),
90 :ok <- maybe_federate(activity) do
91 {:ok, activity, object}
92 else
93 error -> {:error, error}
94 end
95 end
96
97 def follow(follower, followed, activity_id \\ nil, local \\ true) do
98 with data <- make_follow_data(follower, followed, activity_id),
99 {:ok, activity} <- insert(data, local),
100 :ok <- maybe_federate(activity) do
101 {:ok, activity}
102 end
103 end
104
105 def unfollow(follower, followed, local \\ true) do
106 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
107 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
108 {:ok, activity} <- insert(unfollow_data, local),
109 :ok, maybe_federate(activity) do
110 {:ok, activity}
111 end
112 end
113
114 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
115 user = User.get_cached_by_ap_id(actor)
116 data = %{
117 "type" => "Delete",
118 "actor" => actor,
119 "object" => id,
120 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
121 }
122 with Repo.delete(object),
123 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
124 {:ok, activity} <- insert(data, local),
125 :ok <- maybe_federate(activity) do
126 {:ok, activity}
127 end
128 end
129
130 def fetch_activities_for_context(context, opts \\ %{}) do
131 query = from activity in Activity,
132 where: fragment("?->>'type' = ? and ?->>'context' = ?", activity.data, "Create", activity.data, ^context),
133 order_by: [desc: :id]
134 query = query
135 |> restrict_blocked(opts)
136 |> restrict_recipients(["https://www.w3.org/ns/activitystreams#Public"], opts["user"])
137 Repo.all(query)
138 end
139
140 def fetch_public_activities(opts \\ %{}) do
141 public = %{to: ["https://www.w3.org/ns/activitystreams#Public"]}
142 q = fetch_activities_query([], opts)
143 q = from activity in q,
144 where: fragment(~s(? @> ?), activity.data, ^public)
145 q
146 |> Repo.all
147 |> Enum.reverse
148 end
149
150 defp restrict_since(query, %{"since_id" => since_id}) do
151 from activity in query, where: activity.id > ^since_id
152 end
153 defp restrict_since(query, _), do: query
154
155 defp restrict_tag(query, %{"tag" => tag}) do
156 from activity in query,
157 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
158 end
159 defp restrict_tag(query, _), do: query
160
161 defp restrict_recipients(query, [], user), do: query
162 defp restrict_recipients(query, recipients, nil) do
163 from activity in query,
164 where: fragment("? && ?", ^recipients, activity.recipients)
165 end
166 defp restrict_recipients(query, recipients, user) do
167 from activity in query,
168 where: fragment("? && ?", ^recipients, activity.recipients),
169 or_where: activity.actor == ^user.ap_id
170 end
171
172 defp restrict_local(query, %{"local_only" => true}) do
173 from activity in query, where: activity.local == true
174 end
175 defp restrict_local(query, _), do: query
176
177 defp restrict_max(query, %{"max_id" => max_id}) do
178 from activity in query, where: activity.id < ^max_id
179 end
180 defp restrict_max(query, _), do: query
181
182 defp restrict_actor(query, %{"actor_id" => actor_id}) do
183 from activity in query,
184 where: activity.actor == ^actor_id
185 end
186 defp restrict_actor(query, _), do: query
187
188 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
189 restrict_type(query, %{"type" => [type]})
190 end
191 defp restrict_type(query, %{"type" => type}) do
192 from activity in query,
193 where: fragment("?->>'type' = ANY(?)", activity.data, ^type)
194 end
195 defp restrict_type(query, _), do: query
196
197 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
198 from activity in query,
199 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
200 end
201 defp restrict_favorited_by(query, _), do: query
202
203 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
204 from activity in query,
205 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
206 end
207 defp restrict_media(query, _), do: query
208
209 # Only search through last 100_000 activities by default
210 defp restrict_recent(query, %{"whole_db" => true}), do: query
211 defp restrict_recent(query, _) do
212 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
213
214 from activity in query,
215 where: activity.id > ^since
216 end
217
218 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
219 blocks = info["blocks"] || []
220 from activity in query,
221 where: fragment("not (? = ANY(?))", activity.actor, ^blocks)
222 end
223 defp restrict_blocked(query, _), do: query
224
225 def fetch_activities_query(recipients, opts \\ %{}) do
226 base_query = from activity in Activity,
227 limit: 20,
228 order_by: [fragment("? desc nulls last", activity.id)]
229
230 base_query
231 |> restrict_recipients(recipients, opts["user"])
232 |> restrict_tag(opts)
233 |> restrict_since(opts)
234 |> restrict_local(opts)
235 |> restrict_max(opts)
236 |> restrict_actor(opts)
237 |> restrict_type(opts)
238 |> restrict_favorited_by(opts)
239 |> restrict_recent(opts)
240 |> restrict_blocked(opts)
241 |> restrict_media(opts)
242 end
243
244 def fetch_activities(recipients, opts \\ %{}) do
245 fetch_activities_query(recipients, opts)
246 |> Repo.all
247 |> Enum.reverse
248 end
249
250 def upload(file) do
251 data = Upload.store(file)
252 Repo.insert(%Object{data: data})
253 end
254
255 def make_user_from_ap_id(ap_id) do
256 with {:ok, %{status_code: 200, body: body}} <- @httpoison.get(ap_id, ["Accept": "application/activity+json"]),
257 {:ok, data} <- Poison.decode(body)
258 do
259 user_data = %{
260 ap_id: data["id"],
261 info: %{
262 "ap_enabled" => true,
263 "source_data" => data
264 },
265 nickname: "#{data["preferredUsername"]}@#{URI.parse(ap_id).host}",
266 name: data["name"]
267 }
268
269 User.insert_or_update_user(user_data)
270 end
271 end
272
273 def make_user_from_nickname(nickname) do
274 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
275 make_user_from_ap_id(ap_id)
276 end
277 end
278
279 def publish(actor, activity) do
280 {:ok, followers} = User.get_followers(actor)
281
282 remote_inboxes = Pleroma.Web.Salmon.remote_users(activity) ++ followers
283 |> Enum.filter(fn (user) -> User.ap_enabled?(user) end)
284 |> Enum.map(fn (%{info: %{"source_data" => data}}) ->
285 (data["endpoints"] && data["endpoints"]["sharedInbox"]) ||data["inbox"]
286 end)
287 |> Enum.uniq
288
289 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
290
291 Enum.each remote_inboxes, fn(inbox) ->
292 Logger.info("Federating #{activity.data["id"]} to #{inbox}")
293 host = URI.parse(inbox).host
294 signature = Pleroma.Web.HTTPSignatures.sign(actor, %{host: host})
295 @httpoison.post(inbox, Poison.encode!(data), [{"Content-Type", "application/activity+json"}, {"signature", signature}])
296 end
297 end
298
299 # TODO:
300 # This will create a Create activity, which we need internally at the moment.
301 def fetch_object_from_id(id) do
302 if object = Object.get_cached_by_ap_id(id) do
303 {:ok, object}
304 else
305 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),
306 {:ok, data} <- Poison.decode(body),
307 data <- Transmogrifier.fix_object(data),
308 nil <- Object.get_by_ap_id(data["id"]),
309 %User{} = user <- User.get_or_fetch_by_ap_id(data["attributedTo"]),
310 {:ok, activity} = create(%{to: data["to"], actor: user, context: data["context"], object: data, local: false, additional: %{"cc" => data["cc"]}}) do
311 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
312 else
313 object = %Object{} -> {:ok, object}
314 e -> e
315 end
316 end
317 end
318
319 def visible_for_user?(activity, nil) do
320 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++ (activity.data["cc"] || []))
321 end
322 def visible_for_user?(activity, user) do
323 x = [user.ap_id | user.following]
324 y = (activity.data["to"] ++ (activity.data["cc"] || []))
325 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
326 end
327 end