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