1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OStatus do
6 @httpoison Application.get_env(:pleroma, :httpoison)
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}
17 def is_representable?(%Activity{data: data}) do
18 object = Object.normalize(data["object"])
24 object.data["type"] == "Note" ->
32 def feed_path(user) do
33 "#{user.ap_id}/feed.atom"
36 def pubsub_path(user) do
37 "#{Web.base_url()}/push/hub/#{user.nickname}"
40 def salmon_path(user) do
41 "#{user.ap_id}/salmon"
44 def remote_follow_path do
45 "#{Web.base_url()}/ostatus_subscribe?acct={uri}"
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)
53 entries = :xmerl_xpath.string('//entry', doc)
56 Enum.map(entries, fn entry ->
57 {:xmlObj, :string, object_type} =
58 :xmerl_xpath.string('string(/entry/activity:object-type[1])', entry)
60 {:xmlObj, :string, verb} = :xmerl_xpath.string('string(/entry/activity:verb[1])', entry)
61 Logger.debug("Handling #{verb}")
65 'http://activitystrea.ms/schema/1.0/delete' ->
66 with {:ok, activity} <- DeleteHandler.handle_delete(entry, doc), do: activity
68 'http://activitystrea.ms/schema/1.0/follow' ->
69 with {:ok, activity} <- FollowHandler.handle(entry, doc), do: activity
71 'http://activitystrea.ms/schema/1.0/unfollow' ->
72 with {:ok, activity} <- UnfollowHandler.handle(entry, doc), do: activity
74 'http://activitystrea.ms/schema/1.0/share' ->
75 with {:ok, activity, retweeted_activity} <- handle_share(entry, doc),
76 do: [activity, retweeted_activity]
78 'http://activitystrea.ms/schema/1.0/favorite' ->
79 with {:ok, activity, favorited_activity} <- handle_favorite(entry, doc),
80 do: [activity, favorited_activity]
84 'http://activitystrea.ms/schema/1.0/note' ->
85 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
87 'http://activitystrea.ms/schema/1.0/comment' ->
88 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
91 Logger.error("Couldn't parse incoming document")
97 Logger.error("Error occured while handling activity")
98 Logger.error(xml_string)
99 Logger.error(inspect(e))
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
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}
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
138 def get_or_build_object(entry) do
139 with {:ok, activity} <- get_or_try_fetching(entry) do
143 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry) do
144 NoteHandler.handle_note(object, object)
149 def get_or_try_fetching(entry) do
150 Logger.debug("Trying to get entry from db")
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
157 Logger.debug("Couldn't get, will try to fetch")
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}
164 e -> Logger.debug("Couldn't find href: #{inspect(e)}")
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}
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
184 "type" => "Attachment",
199 Gets the content from a an entry.
201 def get_content(entry) do
202 string_from_xpath("//content", entry)
206 Get the cw that mastodon uses.
209 with cw when not is_nil(cw) <- string_from_xpath("/*/summary", entry) do
216 def get_tags(entry) do
217 :xmerl_xpath.string('//category', entry)
218 |> Enum.map(fn category -> string_from_xpath("/category/@term", category) end)
220 |> Enum.map(&String.downcase/1)
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)
227 maybe_update_ostatus(doc, user)
231 def maybe_update_ostatus(doc, user) do
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),
243 avatar: avatar || old_data.avatar,
244 name: name || old_data.name,
245 bio: bio || old_data.bio
247 false <- new_data == old_data do
248 change = Ecto.Changeset.change(user, new_data)
249 User.update_and_set_cache(change)
256 def find_make_or_update_user(doc) do
257 uri = string_from_xpath("//author/uri[1]", doc)
259 with {:ok, user} <- find_or_make_user(uri) do
260 maybe_update(doc, user)
264 def find_or_make_user(uri) do
265 query = from(user in User, where: user.ap_id == ^uri)
267 user = Repo.one(query)
276 def make_user(uri, update \\ false) do
277 with {:ok, info} <- gather_user_info(uri) do
280 nickname: info["nickname"] <> "@" <> info["host"],
283 avatar: info["avatar"],
287 with false <- update,
288 %User{} = user <- User.get_by_ap_id(data.ap_id) do
291 _e -> User.insert_or_update_user(data)
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)
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)}
323 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
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
335 Regex.match?(@mastodon_regex, body) ->
336 [[_, match]] = Regex.scan(@mastodon_regex, body)
339 Regex.match?(@gs_regex, body) ->
340 [[_, match]] = Regex.scan(@gs_regex, body)
343 Regex.match?(@gs_classic_regex, body) ->
344 [[_, match]] = Regex.scan(@gs_classic_regex, body)
348 Logger.debug(fn -> "Couldn't find Atom link in #{inspect(body)}" end)
349 {:error, "Couldn't find the Atom link"}
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 <-
358 [{:Accept, "application/atom+xml"}]
360 Logger.debug("Got document from #{url}, handling...")
361 handle_incoming(body)
364 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
369 def fetch_activity_from_html_url(url) do
370 Logger.debug("Trying to fetch #{url}")
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)
378 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
383 def fetch_activity_from_url(url) do
384 with {:ok, [_ | _] = activities} <- fetch_activity_from_atom_url(url) do
387 _e -> fetch_activity_from_html_url(url)
391 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
392 {:error, "Couldn't get #{url}: #{inspect(e)}"}