1 defmodule Pleroma.Web.OStatus do
2 @httpoison Application.get_env(:pleroma, :httpoison)
8 alias Pleroma.{Repo, User, Web, Object, Activity, Formatter}
9 alias Pleroma.Web.ActivityPub.ActivityPub
10 alias Pleroma.Web.{WebFinger, Websub, MediaProxy}
11 alias Pleroma.Web.OStatus.{FollowHandler, UnfollowHandler, NoteHandler, DeleteHandler}
12 alias Pleroma.Web.ActivityPub.Transmogrifier
15 def is_representable?(%Activity{data: data}) do
16 object = Object.normalize(data["object"])
22 object.data["type"] == "Note" ->
30 def metadata(activity, user, url) do
32 if(meta_enabled?(:opengraph), do: opengraph_tags(activity, user), else: []),
33 if(meta_enabled?(:oembed), do: oembed_links(url), else: [])
35 |> Enum.map(&to_tag/1)
36 |> Enum.map(&HTML.safe_to_string/1)
40 def meta_enabled?(type) do
41 config = Pleroma.Config.get(:metadata, [])
42 Keyword.get(config, type, false)
46 with {name, attrs, _content = []} <- data do
47 HTML.Tag.tag(name, attrs)
49 {name, attrs, content} ->
50 HTML.Tag.content_tag(name, content, attrs)
53 raise ArgumentError, message: "make_tag invalid args"
57 def oembed_links(url) do
58 Enum.map(["xml", "json"], fn format ->
59 href = HTML.raw(oembed_path(url, format))
60 { :link, [ type: ["application/#{format}+oembed"], href: href, rel: 'alternate'], [] }
64 def opengraph_tags(activity, user) do
65 with image = User.avatar_url(user) |> MediaProxy.url(),
66 truncated_content = Formatter.truncate(activity.data["object"]["content"]),
67 domain = Pleroma.Config.get([:instance, :domain], "UNKNOWN_DOMAIN") do
72 content: "#{user.name} (@#{user.nickname}@#{domain}) post ##{activity.id}"
74 {:meta, [property: "og:url", content: activity.data["id"]], []},
75 {:meta, [property: "og:description", content: truncated_content],
77 {:meta, [property: "og:image", content: image], []},
78 {:meta, [property: "og:image:width", content: 120], []},
79 {:meta, [property: "og:image:height", content: 120], []},
80 {:meta, [property: "twitter:card", content: "summary"], []}
85 def feed_path(user) do
86 "#{user.ap_id}/feed.atom"
89 def pubsub_path(user) do
90 "#{Web.base_url()}/push/hub/#{user.nickname}"
93 def salmon_path(user) do
94 "#{user.ap_id}/salmon"
97 def remote_follow_path do
98 "#{Web.base_url()}/ostatus_subscribe?acct={uri}"
101 def oembed_path(url, format) do
102 query = URI.encode_query(%{url: url, format: format})
103 "#{Web.base_url()}/oembed?#{query}"
106 def handle_incoming(xml_string) do
107 with doc when doc != :error <- parse_document(xml_string) do
108 entries = :xmerl_xpath.string('//entry', doc)
111 Enum.map(entries, fn entry ->
112 {:xmlObj, :string, object_type} =
113 :xmerl_xpath.string('string(/entry/activity:object-type[1])', entry)
115 {:xmlObj, :string, verb} = :xmerl_xpath.string('string(/entry/activity:verb[1])', entry)
116 Logger.debug("Handling #{verb}")
120 'http://activitystrea.ms/schema/1.0/delete' ->
121 with {:ok, activity} <- DeleteHandler.handle_delete(entry, doc), do: activity
123 'http://activitystrea.ms/schema/1.0/follow' ->
124 with {:ok, activity} <- FollowHandler.handle(entry, doc), do: activity
126 'http://activitystrea.ms/schema/1.0/unfollow' ->
127 with {:ok, activity} <- UnfollowHandler.handle(entry, doc), do: activity
129 'http://activitystrea.ms/schema/1.0/share' ->
130 with {:ok, activity, retweeted_activity} <- handle_share(entry, doc),
131 do: [activity, retweeted_activity]
133 'http://activitystrea.ms/schema/1.0/favorite' ->
134 with {:ok, activity, favorited_activity} <- handle_favorite(entry, doc),
135 do: [activity, favorited_activity]
139 'http://activitystrea.ms/schema/1.0/note' ->
140 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
142 'http://activitystrea.ms/schema/1.0/comment' ->
143 with {:ok, activity} <- NoteHandler.handle_note(entry, doc), do: activity
146 Logger.error("Couldn't parse incoming document")
152 Logger.error("Error occured while handling activity")
153 Logger.error(xml_string)
154 Logger.error(inspect(e))
166 def make_share(entry, doc, retweeted_activity) do
167 with {:ok, actor} <- find_make_or_update_user(doc),
168 %Object{} = object <- Object.normalize(retweeted_activity.data["object"]),
169 id when not is_nil(id) <- string_from_xpath("/entry/id", entry),
170 {:ok, activity, _object} = ActivityPub.announce(actor, object, id, false) do
175 def handle_share(entry, doc) do
176 with {:ok, retweeted_activity} <- get_or_build_object(entry),
177 {:ok, activity} <- make_share(entry, doc, retweeted_activity) do
178 {:ok, activity, retweeted_activity}
184 def make_favorite(entry, doc, favorited_activity) do
185 with {:ok, actor} <- find_make_or_update_user(doc),
186 %Object{} = object <- Object.normalize(favorited_activity.data["object"]),
187 id when not is_nil(id) <- string_from_xpath("/entry/id", entry),
188 {:ok, activity, _object} = ActivityPub.like(actor, object, id, false) do
193 def get_or_build_object(entry) do
194 with {:ok, activity} <- get_or_try_fetching(entry) do
198 with [object] <- :xmerl_xpath.string('/entry/activity:object', entry) do
199 NoteHandler.handle_note(object, object)
204 def get_or_try_fetching(entry) do
205 Logger.debug("Trying to get entry from db")
207 with id when not is_nil(id) <- string_from_xpath("//activity:object[1]/id", entry),
208 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
212 Logger.debug("Couldn't get, will try to fetch")
214 with href when not is_nil(href) <-
215 string_from_xpath("//activity:object[1]/link[@type=\"text/html\"]/@href", entry),
216 {:ok, [favorited_activity]} <- fetch_activity_from_url(href) do
217 {:ok, favorited_activity}
219 e -> Logger.debug("Couldn't find href: #{inspect(e)}")
224 def handle_favorite(entry, doc) do
225 with {:ok, favorited_activity} <- get_or_try_fetching(entry),
226 {:ok, activity} <- make_favorite(entry, doc, favorited_activity) do
227 {:ok, activity, favorited_activity}
233 def get_attachments(entry) do
234 :xmerl_xpath.string('/entry/link[@rel="enclosure"]', entry)
235 |> Enum.map(fn enclosure ->
236 with href when not is_nil(href) <- string_from_xpath("/link/@href", enclosure),
237 type when not is_nil(type) <- string_from_xpath("/link/@type", enclosure) do
239 "type" => "Attachment",
254 Gets the content from a an entry.
256 def get_content(entry) do
257 string_from_xpath("//content", entry)
261 Get the cw that mastodon uses.
264 with cw when not is_nil(cw) <- string_from_xpath("/*/summary", entry) do
271 def get_tags(entry) do
272 :xmerl_xpath.string('//category', entry)
273 |> Enum.map(fn category -> string_from_xpath("/category/@term", category) end)
275 |> Enum.map(&String.downcase/1)
278 def maybe_update(doc, user) do
279 if "true" == string_from_xpath("//author[1]/ap_enabled", doc) do
280 Transmogrifier.upgrade_user_from_ap_id(user.ap_id)
282 maybe_update_ostatus(doc, user)
286 def maybe_update_ostatus(doc, user) do
293 with false <- user.local,
294 avatar <- make_avatar_object(doc),
295 bio <- string_from_xpath("//author[1]/summary", doc),
296 name <- string_from_xpath("//author[1]/poco:displayName", doc),
298 avatar: avatar || old_data.avatar,
299 name: name || old_data.name,
300 bio: bio || old_data.bio
302 false <- new_data == old_data do
303 change = Ecto.Changeset.change(user, new_data)
304 User.update_and_set_cache(change)
311 def find_make_or_update_user(doc) do
312 uri = string_from_xpath("//author/uri[1]", doc)
314 with {:ok, user} <- find_or_make_user(uri) do
315 maybe_update(doc, user)
319 def find_or_make_user(uri) do
320 query = from(user in User, where: user.ap_id == ^uri)
322 user = Repo.one(query)
331 def make_user(uri, update \\ false) do
332 with {:ok, info} <- gather_user_info(uri) do
335 nickname: info["nickname"] <> "@" <> info["host"],
338 avatar: info["avatar"],
342 with false <- update,
343 %User{} = user <- User.get_by_ap_id(data.ap_id) do
346 _e -> User.insert_or_update_user(data)
351 # TODO: Just takes the first one for now.
352 def make_avatar_object(author_doc, rel \\ "avatar") do
353 href = string_from_xpath("//author[1]/link[@rel=\"#{rel}\"]/@href", author_doc)
354 type = string_from_xpath("//author[1]/link[@rel=\"#{rel}\"]/@type", author_doc)
372 def gather_user_info(username) do
373 with {:ok, webfinger_data} <- WebFinger.finger(username),
374 {:ok, feed_data} <- Websub.gather_feed_data(webfinger_data["topic"]) do
375 {:ok, Map.merge(webfinger_data, feed_data) |> Map.put("fqn", username)}
378 Logger.debug(fn -> "Couldn't gather info for #{username}" end)
383 # Regex-based 'parsing' so we don't have to pull in a full html parser
384 # It's a hack anyway. Maybe revisit this in the future
385 @mastodon_regex ~r/<link href='(.*)' rel='alternate' type='application\/atom\+xml'>/
386 @gs_regex ~r/<link title=.* href="(.*)" type="application\/atom\+xml" rel="alternate">/
387 @gs_classic_regex ~r/<link rel="alternate" href="(.*)" type="application\/atom\+xml" title=.*>/
388 def get_atom_url(body) do
390 Regex.match?(@mastodon_regex, body) ->
391 [[_, match]] = Regex.scan(@mastodon_regex, body)
394 Regex.match?(@gs_regex, body) ->
395 [[_, match]] = Regex.scan(@gs_regex, body)
398 Regex.match?(@gs_classic_regex, body) ->
399 [[_, match]] = Regex.scan(@gs_classic_regex, body)
403 Logger.debug(fn -> "Couldn't find Atom link in #{inspect(body)}" end)
404 {:error, "Couldn't find the Atom link"}
408 def fetch_activity_from_atom_url(url) do
409 with true <- String.starts_with?(url, "http"),
410 {:ok, %{body: body, status: code}} when code in 200..299 <-
413 [{:Accept, "application/atom+xml"}]
415 Logger.debug("Got document from #{url}, handling...")
416 handle_incoming(body)
419 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
424 def fetch_activity_from_html_url(url) do
425 Logger.debug("Trying to fetch #{url}")
427 with true <- String.starts_with?(url, "http"),
428 {:ok, %{body: body}} <- @httpoison.get(url, []),
429 {:ok, atom_url} <- get_atom_url(body) do
430 fetch_activity_from_atom_url(atom_url)
433 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
438 def fetch_activity_from_url(url) do
439 with {:ok, [_ | _] = activities} <- fetch_activity_from_atom_url(url) do
442 _e -> fetch_activity_from_html_url(url)
446 Logger.debug("Couldn't get #{url}: #{inspect(e)}")
447 {:error, "Couldn't get #{url}: #{inspect(e)}"}