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