fcc9603119c8ada805ec14dc3a08ce89190d1cfc
[akkoma] / lib / pleroma / web / metadata / opengraph.ex
1 defmodule Pleroma.Web.Metadata.Providers.OpenGraph do
2 alias Pleroma.Web.Metadata.Providers.Provider
3 alias Pleroma.{HTML, Formatter, User}
4 alias Pleroma.Web.MediaProxy
5
6 @behaviour Provider
7
8 @impl Provider
9 def build_tags(%{activity: activity, user: user}) do
10 with truncated_content = scrub_html_and_truncate(activity.data["object"]["content"]) do
11 attachments = build_attachments(activity)
12
13 [
14 {:meta,
15 [
16 property: "og:title",
17 content: user_name_string(user)
18 ], []},
19 {:meta, [property: "og:url", content: activity.data["id"]], []},
20 {:meta, [property: "og:description", content: truncated_content], []}
21 ] ++
22 if attachments == [] or Enum.any?(activity.data["object"]["tag"], fn tag -> tag == "nsfw" end) do
23 [
24 {:meta, [property: "og:image", content: attachment_url(User.avatar_url(user))], []},
25 {:meta, [property: "og:image:width", content: 120], []},
26 {:meta, [property: "og:image:height", content: 120], []}
27 ]
28 else
29 attachments
30 end
31 end
32 end
33
34 @impl Provider
35 def build_tags(%{user: user}) do
36 with truncated_bio = scrub_html_and_truncate(user.bio || "") do
37 [
38 {:meta,
39 [
40 property: "og:title",
41 content: user_name_string(user)
42 ], []},
43 {:meta, [property: "og:url", content: User.profile_url(user)], []},
44 {:meta, [property: "og:description", content: truncated_bio], []},
45 {:meta, [property: "og:image", content: attachment_url(User.avatar_url(user))], []},
46 {:meta, [property: "og:image:width", content: 120], []},
47 {:meta, [property: "og:image:height", content: 120], []}
48 ]
49 end
50 end
51
52 defp build_attachments(activity) do
53 Enum.reduce(activity.data["object"]["attachment"], [], fn attachment, acc ->
54 rendered_tags =
55 Enum.map(attachment["url"], fn url ->
56 media_type =
57 Enum.find(["image", "audio", "video"], fn media_type ->
58 String.starts_with?(url["mediaType"], media_type)
59 end)
60
61 if media_type do
62 {:meta, [property: "og:" <> media_type, content: attachment_url(url["href"])], []}
63 else
64 nil
65 end
66 end)
67
68 Enum.reject(rendered_tags, &is_nil/1)
69 acc ++ rendered_tags
70 end)
71 end
72
73 defp scrub_html_and_truncate(content) do
74 content
75 # html content comes from DB already encoded, decode first and scrub after
76 |> HtmlEntities.decode()
77 |> String.replace(~r/<br\s?\/?>/, " ")
78 |> HTML.strip_tags()
79 |> Formatter.truncate()
80 end
81
82 defp attachment_url(url) do
83 MediaProxy.url(url)
84 end
85
86 defp user_name_string(user) do
87 "#{user.name} " <>
88 if user.local do
89 "(@#{user.nickname}@#{Pleroma.Web.Endpoint.host()})"
90 else
91 "(@#{user.nickname})"
92 end
93 end
94 end