metadata.ex 2.34 KB
Newer Older
1 2
defmodule Pleroma.Web.Metadata do
  alias Phoenix.HTML
3
  alias Pleroma.{Formatter, User}
4 5
  alias Pleroma.Web.MediaProxy

6 7
  def build_tags(params) do
    if(meta_enabled?(:opengraph), do: opengraph_tags(params), else: [])
8 9 10 11 12 13
    |> Enum.map(&to_tag/1)
    |> Enum.map(&HTML.safe_to_string/1)
    |> Enum.join("\n")
  end

  def meta_enabled?(type) do
14
    Pleroma.Config.get([:metadata, type], false)
15 16
  end

17 18 19
  # opengraph for single status
  defp opengraph_tags(%{activity: activity, user: user}) do
    with truncated_content = Formatter.truncate(activity.data["object"]["content"]) do
20 21
      [
        {:meta,
22 23 24 25
         [
           property: "og:title",
           content: "#{user.name} (@#{user.nickname}@#{pleroma_domain()}) post ##{activity.id}"
         ], []},
26
        {:meta, [property: "og:url", content: activity.data["id"]], []},
27
        {:meta, [property: "og:description", content: truncated_content], []},
28 29 30 31 32 33 34 35 36 37 38 39 40
        {:meta, [property: "og:image", content: user_avatar_url(user)], []},
        {:meta, [property: "og:image:width", content: 120], []},
        {:meta, [property: "og:image:height", content: 120], []},
        {:meta, [property: "twitter:card", content: "summary"], []}
      ]
    end
  end

  # opengraph for user card
  defp opengraph_tags(%{user: user}) do
    with truncated_bio = Formatter.truncate(user.bio) do
      [
        {:meta,
41 42 43 44
         [
           property: "og:title",
           content: "#{user.name} (@#{user.nickname}@#{pleroma_domain()}) profile"
         ], []},
45 46 47
        {:meta, [property: "og:url", content: User.profile_url(user)], []},
        {:meta, [property: "og:description", content: truncated_bio], []},
        {:meta, [property: "og:image", content: user_avatar_url(user)], []},
48 49 50 51 52 53 54
        {:meta, [property: "og:image:width", content: 120], []},
        {:meta, [property: "og:image:height", content: 120], []},
        {:meta, [property: "twitter:card", content: "summary"], []}
      ]
    end
  end

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  def to_tag(data) do
    with {name, attrs, _content = []} <- data do
      HTML.Tag.tag(name, attrs)
    else
      {name, attrs, content} ->
        HTML.Tag.content_tag(name, content, attrs)

      _ ->
        raise ArgumentError, message: "make_tag invalid args"
    end
  end

  defp user_avatar_url(user) do
    User.avatar_url(user) |> MediaProxy.url()
  end

  def pleroma_domain do
72
    Pleroma.Web.Endpoint.host()
73
  end
74
end