remove useless newlines after every tag. Make domain.com/username provide opengraph too
[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()
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
61 defp opengraph_tags(_) do
62 []
63 end
64
65 def to_tag(data) do
66 with {name, attrs, _content = []} <- data do
67 HTML.Tag.tag(name, attrs)
68 else
69 {name, attrs, content} ->
70 HTML.Tag.content_tag(name, content, attrs)
71
72 _ ->
73 raise ArgumentError, message: "make_tag invalid args"
74 end
75 end
76
77 defp scrub_html_and_truncate(content) do
78 content
79 # html content comes from DB already encoded, decode first and scrub after
80 |> HtmlEntities.decode()
81 |> Pleroma.HTML.strip_tags()
82 |> Formatter.truncate()
83 end
84
85 defp user_avatar_url(user) do
86 User.avatar_url(user) |> MediaProxy.url()
87 end
88
89 def pleroma_domain do
90 Pleroma.Web.Endpoint.host()
91 end
92 end