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