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