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 defmodule Pleroma.Web.Metadata.Providers.OpenGraph do
5 alias Pleroma.Web.Metadata.Providers.Provider
6 alias Pleroma.{HTML, Formatter, User}
7 alias Pleroma.Web.MediaProxy
12 def build_tags(%{activity: activity, user: user}) do
13 with truncated_content = scrub_html_and_truncate(activity) do
14 attachments = build_attachments(activity)
20 content: user_name_string(user)
22 {:meta, [property: "og:url", content: activity.data["id"]], []},
23 {:meta, [property: "og:description", content: truncated_content], []}
25 if attachments == [] or
26 Enum.any?(activity.data["object"]["tag"], fn tag -> tag == "nsfw" end) do
28 {:meta, [property: "og:image", content: attachment_url(User.avatar_url(user))], []},
29 {:meta, [property: "og:image:width", content: 120], []},
30 {:meta, [property: "og:image:height", content: 120], []}
39 def build_tags(%{user: user}) do
40 with truncated_bio = scrub_html_and_truncate(user.bio || "") do
45 content: user_name_string(user)
47 {:meta, [property: "og:url", content: User.profile_url(user)], []},
48 {:meta, [property: "og:description", content: truncated_bio], []},
49 {:meta, [property: "og:image", content: attachment_url(User.avatar_url(user))], []},
50 {:meta, [property: "og:image:width", content: 120], []},
51 {:meta, [property: "og:image:height", content: 120], []}
56 defp build_attachments(%{data: %{"object" => %{"attachment" => attachments}}} = _activity) do
57 Enum.reduce(attachments, [], fn attachment, acc ->
59 Enum.reduce(attachment["url"], [], fn url, acc ->
61 Enum.find(["image", "audio", "video"], fn media_type ->
62 String.starts_with?(url["mediaType"], media_type)
67 {:meta, [property: "og:" <> media_type, content: attachment_url(url["href"])], []}
79 defp scrub_html_and_truncate(%{data: %{"object" => %{"content" => content}}} = activity) do
81 # html content comes from DB already encoded, decode first and scrub after
82 |> HtmlEntities.decode()
83 |> String.replace(~r/<br\s?\/?>/, " ")
84 |> HTML.get_cached_stripped_html_for_object(activity, __MODULE__)
85 |> Formatter.truncate()
88 defp scrub_html_and_truncate(content) when is_binary(content) do
90 # html content comes from DB already encoded, decode first and scrub after
91 |> HtmlEntities.decode()
92 |> String.replace(~r/<br\s?\/?>/, " ")
94 |> Formatter.truncate()
97 defp attachment_url(url) do
101 defp user_name_string(user) do
104 "(@#{user.nickname}@#{Pleroma.Web.Endpoint.host()})"
106 "(@#{user.nickname})"