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