a7b2988b9afe506c352e107c304c852e8a06e836
[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 import Ecto.Query
4 import Pleroma.Web.ActivityPub.Utils
5 require Logger
6
7 @httpoison Application.get_env(:pleroma, :httpoison)
8
9 def get_recipients(data) do
10 (data["to"] || []) ++ (data["cc"] || [])
11 end
12
13 def insert(map, local \\ true) when is_map(map) do
14 with nil <- Activity.get_by_ap_id(map["id"]),
15 map <- lazy_put_activity_defaults(map),
16 :ok <- insert_full_object(map) do
17 {:ok, activity} = Repo.insert(%Activity{data: map, local: local, actor: map["actor"], recipients: get_recipients(map)})
18 Notification.create_notifications(activity)
19 stream_out(activity)
20 {:ok, activity}
21 else
22 %Activity{} = activity -> {:ok, activity}
23 error -> {:error, error}
24 end
25 end
26
27 def stream_out(activity) do
28 if activity.data["type"] in ["Create", "Announce"] do
29 Pleroma.Web.Streamer.stream("user", activity)
30 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
31 Pleroma.Web.Streamer.stream("public", activity)
32 if activity.local do
33 Pleroma.Web.Streamer.stream("public:local", activity)
34 end
35 end
36 end
37 end
38
39 def create(%{to: to, actor: actor, context: context, object: object} = params) do
40 additional = params[:additional] || %{}
41 local = !(params[:local] == false) # only accept false as false value
42 published = params[:published]
43
44 with create_data <- make_create_data(%{to: to, actor: actor, published: published, context: context, object: object}, additional),
45 {:ok, activity} <- insert(create_data, local),
46 :ok <- maybe_federate(activity) do
47 {:ok, activity}
48 end
49 end
50
51 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
52 def like(%User{ap_id: ap_id} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
53 with nil <- get_existing_like(ap_id, object),
54 like_data <- make_like_data(user, object, activity_id),
55 {:ok, activity} <- insert(like_data, local),
56 {:ok, object} <- add_like_to_object(activity, object),
57 :ok <- maybe_federate(activity) do
58 {:ok, activity, object}
59 else
60 %Activity{} = activity -> {:ok, activity, object}
61 error -> {:error, error}
62 end
63 end
64
65 def unlike(%User{} = actor, %Object{} = object) do
66 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
67 {:ok, _activity} <- Repo.delete(activity),
68 {:ok, object} <- remove_like_from_object(activity, object) do
69 {:ok, object}
70 else _e -> {:ok, object}
71 end
72 end
73
74 def announce(%User{ap_id: _} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
75 with announce_data <- make_announce_data(user, object, activity_id),
76 {:ok, activity} <- insert(announce_data, local),
77 {:ok, object} <- add_announce_to_object(activity, object),
78 :ok <- maybe_federate(activity) do
79 {:ok, activity, object}
80 else
81 error -> {:error, error}
82 end
83 end
84
85 def follow(follower, followed, activity_id \\ nil, local \\ true) do
86 with data <- make_follow_data(follower, followed, activity_id),
87 {:ok, activity} <- insert(data, local),
88 :ok <- maybe_federate(activity) do
89 {:ok, activity}
90 end
91 end
92
93 def unfollow(follower, followed, local \\ true) do
94 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
95 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
96 {:ok, activity} <- insert(unfollow_data, local),
97 :ok, maybe_federate(activity) do
98 {:ok, activity}
99 end
100 end
101
102 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
103 user = User.get_cached_by_ap_id(actor)
104 data = %{
105 "type" => "Delete",
106 "actor" => actor,
107 "object" => id,
108 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
109 }
110 with Repo.delete(object),
111 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
112 {:ok, activity} <- insert(data, local),
113 :ok <- maybe_federate(activity) do
114 {:ok, activity}
115 end
116 end
117
118 def fetch_activities_for_context(context, opts \\ %{}) do
119 query = from activity in Activity,
120 where: fragment("?->>'type' = ? and ?->>'context' = ?", activity.data, "Create", activity.data, ^context),
121 order_by: [desc: :id]
122 query = restrict_blocked(query, opts)
123 Repo.all(query)
124 end
125
126 def fetch_public_activities(opts \\ %{}) do
127 public = ["https://www.w3.org/ns/activitystreams#Public"]
128 fetch_activities(public, opts)
129 end
130
131 defp restrict_since(query, %{"since_id" => since_id}) do
132 from activity in query, where: activity.id > ^since_id
133 end
134 defp restrict_since(query, _), do: query
135
136 defp restrict_tag(query, %{"tag" => tag}) do
137 from activity in query,
138 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
139 end
140 defp restrict_tag(query, _), do: query
141
142 defp restrict_recipients(query, recipients) do
143 Enum.reduce(recipients, query, fn (recipient, q) ->
144 map = %{ to: [recipient] }
145 from activity in q,
146 or_where: fragment(~s(? @> ?), activity.data, ^map)
147 end)
148 end
149
150 defp restrict_local(query, %{"local_only" => true}) do
151 from activity in query, where: activity.local == true
152 end
153 defp restrict_local(query, _), do: query
154
155 defp restrict_max(query, %{"max_id" => max_id}) do
156 from activity in query, where: activity.id < ^max_id
157 end
158 defp restrict_max(query, _), do: query
159
160 defp restrict_actor(query, %{"actor_id" => actor_id}) do
161 from activity in query,
162 where: activity.actor == ^actor_id
163 end
164 defp restrict_actor(query, _), do: query
165
166 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
167 restrict_type(query, %{"type" => [type]})
168 end
169 defp restrict_type(query, %{"type" => type}) do
170 from activity in query,
171 where: fragment("?->>'type' = ANY(?)", activity.data, ^type)
172 end
173 defp restrict_type(query, _), do: query
174
175 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
176 from activity in query,
177 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
178 end
179 defp restrict_favorited_by(query, _), do: query
180
181 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
182 from activity in query,
183 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
184 end
185 defp restrict_media(query, _), do: query
186
187 # Only search through last 100_000 activities by default
188 defp restrict_recent(query, %{"whole_db" => true}), do: query
189 defp restrict_recent(query, _) do
190 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
191
192 from activity in query,
193 where: activity.id > ^since
194 end
195
196 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
197 blocks = info["blocks"] || []
198 from activity in query,
199 where: fragment("not (? = ANY(?))", activity.actor, ^blocks)
200 end
201 defp restrict_blocked(query, _), do: query
202
203 def fetch_activities(recipients, opts \\ %{}) do
204 base_query = from activity in Activity,
205 limit: 20,
206 order_by: [fragment("? desc nulls last", activity.id)]
207
208 base_query
209 |> restrict_recipients(recipients)
210 |> restrict_tag(opts)
211 |> restrict_since(opts)
212 |> restrict_local(opts)
213 |> restrict_max(opts)
214 |> restrict_actor(opts)
215 |> restrict_type(opts)
216 |> restrict_favorited_by(opts)
217 |> restrict_recent(opts)
218 |> restrict_blocked(opts)
219 |> restrict_media(opts)
220 |> Repo.all
221 |> Enum.reverse
222 end
223
224 def upload(file) do
225 data = Upload.store(file)
226 Repo.insert(%Object{data: data})
227 end
228
229 def make_user_from_ap_id(ap_id) do
230 with {:ok, %{status_code: 200, body: body}} <- @httpoison.get(ap_id, ["Accept": "application/activity+json"]),
231 {:ok, data} <- Poison.decode(body)
232 do
233 user_data = %{
234 ap_id: data["id"],
235 info: %{
236 "ap_enabled" => true,
237 "source_data" => data
238 },
239 nickname: "#{data["preferredUsername"]}@#{URI.parse(ap_id).host}",
240 name: data["name"]
241 }
242
243 User.insert_or_update_user(user_data)
244 end
245 end
246
247 # TODO: Extract to own module, align as close to Mastodon format as possible.
248 def sanitize_outgoing_activity_data(data) do
249 data
250 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
251 end
252
253 def publish(actor, activity) do
254 remote_users = Pleroma.Web.Salmon.remote_users(activity)
255 data = sanitize_outgoing_activity_data(activity.data)
256 Enum.each remote_users, fn(user) ->
257 if user.info["ap_enabled"] do
258 inbox = user.info["source_data"]["inbox"]
259 Logger.info("Federating #{activity.data["id"]} to #{inbox}")
260 host = URI.parse(inbox).host
261 signature = Pleroma.Web.HTTPSignatures.sign(actor, %{host: host})
262 @httpoison.post(inbox, Poison.encode!(data), [{"Content-Type", "application/activity+json"}, {"signature", signature}])
263 end
264 end
265 end
266 end