9935726fc5008a58551234a86df2015d14564c38
[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: "#{user.name} (@#{user.nickname}@#{pleroma_domain()}) post ##{activity.id}"
25 ], []},
26 {:meta, [property: "og:url", content: activity.data["id"]], []},
27 {:meta, [property: "og:description", content: truncated_content], []},
28 {:meta, [property: "og:image", content: user_avatar_url(user)], []},
29 {:meta, [property: "og:image:width", content: 120], []},
30 {:meta, [property: "og:image:height", content: 120], []},
31 {:meta, [property: "twitter:card", content: "summary"], []}
32 ]
33 end
34 end
35
36 # opengraph for user card
37 defp opengraph_tags(%{user: user}) do
38 with truncated_bio = scrub_html_and_truncate(user.bio) do
39 [
40 {:meta,
41 [
42 property: "og:title",
43 content: "#{user.name} (@#{user.nickname}@#{pleroma_domain()}) profile"
44 ], []},
45 {:meta, [property: "og:url", content: User.profile_url(user)], []},
46 {:meta, [property: "og:description", content: truncated_bio], []},
47 {:meta, [property: "og:image", content: user_avatar_url(user)], []},
48 {:meta, [property: "og:image:width", content: 120], []},
49 {:meta, [property: "og:image:height", content: 120], []},
50 {:meta, [property: "twitter:card", content: "summary"], []}
51 ]
52 end
53 end
54
55 def to_tag(data) do
56 with {name, attrs, _content = []} <- data do
57 HTML.Tag.tag(name, attrs)
58 else
59 {name, attrs, content} ->
60 HTML.Tag.content_tag(name, content, attrs)
61
62 _ ->
63 raise ArgumentError, message: "make_tag invalid args"
64 end
65 end
66
67 defp scrub_html_and_truncate(content) do
68 content
69 # html content comes from DB already encoded, decode first and scrub after
70 |> HtmlEntities.decode()
71 |> Pleroma.HTML.strip_tags()
72 |> Formatter.truncate()
73 end
74
75 defp user_avatar_url(user) do
76 User.avatar_url(user) |> MediaProxy.url()
77 end
78
79 def pleroma_domain do
80 Pleroma.Web.Endpoint.host()
81 end
82 end