Merge branch 'feld-varnish' into 'develop'
[akkoma] / lib / pleroma / web / ostatus / ostatus.ex
1 defmodule Pleroma.Web.OStatus do
2 @httpoison Application.get_env(:pleroma, :httpoison)
3
4 import Ecto.Query
5 import Pleroma.Web.XML
6 require Logger
7
8 alias Pleroma.{Repo, User, Web, Object, Activity}
9 alias Pleroma.Web.ActivityPub.ActivityPub
10 alias Pleroma.Web.{WebFinger, Websub}
11 alias Pleroma.Web.OStatus.{FollowHandler, NoteHandler, DeleteHandler}
12 alias Pleroma.Web.ActivityPub.Transmogrifier
13
14 def feed_path(user) do
15 "#{user.ap_id}/feed.atom"
16 end
17
18 def pubsub_path(user) do
19 "#{Web.base_url()}/push/hub/#{user.nickname}"
20 end
21
22 def salmon_path(user) do
23 "#{user.ap_id}/salmon"
24 end
25
26 def remote_follow_path do
27 "#{Web.base_url()}/ostatus_subscribe?acct={uri}"
28 end
29
30 def handle_incoming(xml_string) do
31 with doc when doc != :error <- parse_document(xml_string) do
32 entries = :xmerl_xpath.string('//entry', doc)
33
34 activities =
35 Enum.map(entries, fn entry ->
36 {:xmlObj, :string, object_type} =
37 :xmerl_xpath.string('string(/entry/activity:object-type[1])', entry)
38
39 {:xmlObj, :string, verb} = :xmerl_xpath.string('string(/entry/activity:verb[1])', entry)
40 Logger.debug("Handling #{verb}")
41
42 try do
43 case verb do
44 'http://activitystrea.ms/schema/1.0/delete' ->
45 with {:ok, activity} <- DeleteHandler.handle_delete(entry, doc), do: activity
46
47 'http://activitystrea.ms/schema/1.0/follow' ->
48 with {:ok, activity} <- FollowHandler.handle(entry, doc), do: activity
49
50 'http://activitystrea.ms/schema/1.0/share' ->
51 with {:ok, activity, retweeted_activity} <- handle_share(entry, doc),
52 do: [activity, retweeted_activity]
53
54 'http://activitystrea.ms/schema/1.0/favorite' ->
55 with {:ok, activity, favorited_activity} <- handle_favorite(entry, doc),
56 do: [activity, favorited_activity]
57
58 _ ->
59 case object_type do
60 'http://activitystrea.ms/schema/1.0/note' ->
61 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
62
63 'http://activitystrea.ms/schema/1.0/comment' ->
64 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
65
66 _ ->
67 Logger.error("Couldn't parse incoming document")
68 nil
69 end
70 end
71 rescue
72 e ->
73 Logger.error("Error occured while handling activity")
74 Logger.error(xml_string)
75 Logger.error(inspect(e))
76 nil
77 end
78 end)
79 |> Enum.filter(& &1)
80
81 {:ok, activities}
82 else
83 _e -> {:error, []}
84 end
85 end
86
87 def make_share(entry, doc, retweeted_activity) do
88 with {:ok, actor} <- find_make_or_update_user(doc),
89 %Object{} = object <- Object.get_by_ap_id(retweeted_activity.data["object"]["id"]),
90 id when not is_nil(id) <- string_from_xpath("/entry/id", entry),
91 {:ok, activity, _object} = ActivityPub.announce(actor, object, id, false) do
92 {:ok, activity}
93 end
94 end
95
96 def handle_share(entry, doc) do
97 with {:ok, retweeted_activity} <- get_or_build_object(entry),
98 {:ok, activity} <- make_share(entry, doc, retweeted_activity) do
99 {:ok, activity, retweeted_activity}
100 else
101 e -> {:error, e}
102 end
103 end
104
105 def make_favorite(entry, doc, favorited_activity) do
106 with {:ok, actor} <- find_make_or_update_user(doc),
107 %Object{} = object <- Object.get_by_ap_id(favorited_activity.data["object"]["id"]),
108 id when not is_nil(id) <- string_from_xpath("/entry/id", entry),
109 {:ok, activity, _object} = ActivityPub.like(actor, object, id, false) do
110 {:ok, activity}
111 end
112 end
113
114 def get_or_build_object(entry) do
115 with {:ok, activity} <- get_or_try_fetching(entry) do
116 {:ok, activity}
117 else
118 _e ->
119 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry) do
120 NoteHandler.handle_note(object, object)
121 end
122 end
123 end
124
125 def get_or_try_fetching(entry) do
126 Logger.debug("Trying to get entry from db")
127
128 with id when not is_nil(id) <- string_from_xpath("//activity:object[1]/id", entry),
129 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
130 {:ok, activity}
131 else
132 _ ->
133 Logger.debug("Couldn't get, will try to fetch")
134
135 with href when not is_nil(href) <-
136 string_from_xpath("//activity:object[1]/link[@type=\"text/html\"]/@href", entry),
137 {:ok, [favorited_activity]} <- fetch_activity_from_url(href) do
138 {:ok, favorited_activity}
139 else
140 e -> Logger.debug("Couldn't find href: #{inspect(e)}")
141 end
142 end
143 end
144
145 def handle_favorite(entry, doc) do
146 with {:ok, favorited_activity} <- get_or_try_fetching(entry),
147 {:ok, activity} <- make_favorite(entry, doc, favorited_activity) do
148 {:ok, activity, favorited_activity}
149 else
150 e -> {:error, e}
151 end
152 end
153
154 def get_attachments(entry) do
155 :xmerl_xpath.string('/entry/link[@rel="enclosure"]', entry)
156 |> Enum.map(fn enclosure ->
157 with href when not is_nil(href) <- string_from_xpath("/link/@href", enclosure),
158 type when not is_nil(type) <- string_from_xpath("/link/@type", enclosure) do
159 %{
160 "type" => "Attachment",
161 "url" => [
162 %{
163 "type" => "Link",
164 "mediaType" => type,
165 "href" => href
166 }
167 ]
168 }
169 end
170 end)
171 |> Enum.filter(& &1)
172 end
173
174 @doc """
175 Gets the content from a an entry.
176 """
177 def get_content(entry) do
178 string_from_xpath("//content", entry)
179 end
180
181 @doc """
182 Get the cw that mastodon uses.
183 """
184 def get_cw(entry) do
185 with cw when not is_nil(cw) <- string_from_xpath("/*/summary", entry) do
186 cw
187 else
188 _e -> nil
189 end
190 end
191
192 def get_tags(entry) do
193 :xmerl_xpath.string('//category', entry)
194 |> Enum.map(fn category -> string_from_xpath("/category/@term", category) end)
195 |> Enum.filter(& &1)
196 |> Enum.map(&String.downcase/1)
197 end
198
199 def maybe_update(doc, user) do
200 if "true" == string_from_xpath("//author[1]/ap_enabled", doc) do
201 Transmogrifier.upgrade_user_from_ap_id(user.ap_id)
202 else
203 maybe_update_ostatus(doc, user)
204 end
205 end
206
207 def maybe_update_ostatus(doc, user) do
208 old_data = %{
209 avatar: user.avatar,
210 bio: user.bio,
211 name: user.name,
212 info: user.info
213 }
214
215 with false <- user.local,
216 avatar <- make_avatar_object(doc),
217 bio <- string_from_xpath("//author[1]/summary", doc),
218 name <- string_from_xpath("//author[1]/poco:displayName", doc),
219 info <-
220 Map.put(user.info, "banner", make_avatar_object(doc, "header") || user.info["banner"]),
221 new_data <- %{
222 avatar: avatar || old_data.avatar,
223 name: name || old_data.name,
224 bio: bio || old_data.bio,
225 info: info || old_data.info
226 },
227 false <- new_data == old_data do
228 change = Ecto.Changeset.change(user, new_data)
229 Repo.update(change)
230 else
231 _ ->
232 {:ok, user}
233 end
234 end
235
236 def find_make_or_update_user(doc) do
237 uri = string_from_xpath("//author/uri[1]", doc)
238
239 with {:ok, user} <- find_or_make_user(uri) do
240 maybe_update(doc, user)
241 end
242 end
243
244 def find_or_make_user(uri) do
245 query = from(user in User, where: user.ap_id == ^uri)
246
247 user = Repo.one(query)
248
249 if is_nil(user) do
250 make_user(uri)
251 else
252 {:ok, user}
253 end
254 end
255
256 def make_user(uri, update \\ false) do
257 with {:ok, info} <- gather_user_info(uri) do
258 data = %{
259 name: info["name"],
260 nickname: info["nickname"] <> "@" <> info["host"],
261 ap_id: info["uri"],
262 info: info,
263 avatar: info["avatar"],
264 bio: info["bio"]
265 }
266
267 with false <- update,
268 %User{} = user <- User.get_by_ap_id(data.ap_id) do
269 {:ok, user}
270 else
271 _e -> User.insert_or_update_user(data)
272 end
273 end
274 end
275
276 # TODO: Just takes the first one for now.
277 def make_avatar_object(author_doc, rel \\ "avatar") do
278 href = string_from_xpath("//author[1]/link[@rel=\"#{rel}\"]/@href", author_doc)
279 type = string_from_xpath("//author[1]/link[@rel=\"#{rel}\"]/@type", author_doc)
280
281 if href do
282 %{
283 "type" => "Image",
284 "url" => [
285 %{
286 "type" => "Link",
287 "mediaType" => type,
288 "href" => href
289 }
290 ]
291 }
292 else
293 nil
294 end
295 end
296
297 def gather_user_info(username) do
298 with {:ok, webfinger_data} <- WebFinger.finger(username),
299 {:ok, feed_data} <- Websub.gather_feed_data(webfinger_data["topic"]) do
300 {:ok, Map.merge(webfinger_data, feed_data) |> Map.put("fqn", username)}
301 else
302 e ->
303 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
304 {:error, e}
305 end
306 end
307
308 # Regex-based 'parsing' so we don't have to pull in a full html parser
309 # It's a hack anyway. Maybe revisit this in the future
310 @mastodon_regex ~r/<link href='(.*)' rel='alternate' type='application\/atom\+xml'>/
311 @gs_regex ~r/<link title=.* href="(.*)" type="application\/atom\+xml" rel="alternate">/
312 @gs_classic_regex ~r/<link rel="alternate" href="(.*)" type="application\/atom\+xml" title=.*>/
313 def get_atom_url(body) do
314 cond do
315 Regex.match?(@mastodon_regex, body) ->
316 [[_, match]] = Regex.scan(@mastodon_regex, body)
317 {:ok, match}
318
319 Regex.match?(@gs_regex, body) ->
320 [[_, match]] = Regex.scan(@gs_regex, body)
321 {:ok, match}
322
323 Regex.match?(@gs_classic_regex, body) ->
324 [[_, match]] = Regex.scan(@gs_classic_regex, body)
325 {:ok, match}
326
327 true ->
328 Logger.debug(fn -> "Couldn't find Atom link in #{inspect(body)}" end)
329 {:error, "Couldn't find the Atom link"}
330 end
331 end
332
333 def fetch_activity_from_atom_url(url) do
334 with true <- String.starts_with?(url, "http"),
335 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
336 @httpoison.get(
337 url,
338 [Accept: "application/atom+xml"],
339 follow_redirect: true,
340 timeout: 10000,
341 recv_timeout: 20000
342 ) do
343 Logger.debug("Got document from #{url}, handling...")
344 handle_incoming(body)
345 else
346 e ->
347 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
348 e
349 end
350 end
351
352 def fetch_activity_from_html_url(url) do
353 Logger.debug("Trying to fetch #{url}")
354
355 with true <- String.starts_with?(url, "http"),
356 {:ok, %{body: body}} <-
357 @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000),
358 {:ok, atom_url} <- get_atom_url(body) do
359 fetch_activity_from_atom_url(atom_url)
360 else
361 e ->
362 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
363 e
364 end
365 end
366
367 def fetch_activity_from_url(url) do
368 try do
369 with {:ok, activities} when length(activities) > 0 <- fetch_activity_from_atom_url(url) do
370 {:ok, activities}
371 else
372 _e ->
373 with {:ok, activities} <- fetch_activity_from_html_url(url) do
374 {:ok, activities}
375 end
376 end
377 rescue
378 e ->
379 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
380 {:error, "Couldn't get #{url}: #{inspect(e)}"}
381 end
382 end
383 end