add a fallback function
[akkoma] / lib / pleroma / web / metadata.ex
1 defmodule Pleroma.Web.Metadata do
2 alias Phoenix.HTML
3 alias Pleroma.{Formatter, User}
4 alias Pleroma.Web.MediaProxy
5
6 def build_tags(params) do
7 if(meta_enabled?(:opengraph), do: opengraph_tags(params), else: [])
8 |> Enum.map(&to_tag/1)
9 |> Enum.map(&HTML.safe_to_string/1)
10 |> Enum.join("\n")
11 end
12
13 def meta_enabled?(type) do
14 Pleroma.Config.get([:metadata, type], false)
15 end
16
17 # opengraph for single status
18 defp opengraph_tags(%{activity: activity, user: user}) do
19 with truncated_content = scrub_html_and_truncate(activity.data["object"]["content"]) do
20 [
21 {:meta,
22 [
23 property: "og:title",
24 content:
25 "#{user.name}" <>
26 if user.local do
27 "(@#{user.nickname}@{pleroma_domain})"
28 else
29 "(@#{user.nickname})"
30 end
31 ], []},
32 {:meta, [property: "og:url", content: activity.data["id"]], []},
33 {:meta, [property: "og:description", content: truncated_content], []},
34 {:meta, [property: "og:image", content: user_avatar_url(user)], []},
35 {:meta, [property: "og:image:width", content: 120], []},
36 {:meta, [property: "og:image:height", content: 120], []},
37 {:meta, [property: "twitter:card", content: "summary"], []}
38 ]
39 end
40 end
41
42 # opengraph for user card
43 defp opengraph_tags(%{user: user}) do
44 with truncated_bio = scrub_html_and_truncate(user.bio || "") do
45 [
46 {:meta,
47 [
48 property: "og:title",
49 content: "#{user.name} (@#{user.nickname}@#{pleroma_domain()}) profile"
50 ], []},
51 {:meta, [property: "og:url", content: User.profile_url(user)], []},
52 {:meta, [property: "og:description", content: truncated_bio], []},
53 {:meta, [property: "og:image", content: user_avatar_url(user)], []},
54 {:meta, [property: "og:image:width", content: 120], []},
55 {:meta, [property: "og:image:height", content: 120], []},
56 {:meta, [property: "twitter:card", content: "summary"], []}
57 ]
58 end
59 end
60 defp opengraph_tags(_) do
61 []
62 end
63 def to_tag(data) do
64 with {name, attrs, _content = []} <- data do
65 HTML.Tag.tag(name, attrs)
66 else
67 {name, attrs, content} ->
68 HTML.Tag.content_tag(name, content, attrs)
69
70 _ ->
71 raise ArgumentError, message: "make_tag invalid args"
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 |> Pleroma.HTML.strip_tags()
80 |> Formatter.truncate()
81 end
82
83 defp user_avatar_url(user) do
84 User.avatar_url(user) |> MediaProxy.url()
85 end
86
87 def pleroma_domain do
88 Pleroma.Web.Endpoint.host()
89 end
90 end