Merge remote-tracking branch 'MAIN/develop' into feature/jobs
[akkoma] / lib / pleroma / web / mastodon_api / views / status_view.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.StatusView do
6 use Pleroma.Web, :view
7
8 alias Pleroma.Activity
9 alias Pleroma.HTML
10 alias Pleroma.Repo
11 alias Pleroma.User
12 alias Pleroma.Web.CommonAPI.Utils
13 alias Pleroma.Web.MediaProxy
14 alias Pleroma.Web.MastodonAPI.AccountView
15 alias Pleroma.Web.MastodonAPI.StatusView
16
17 # TODO: Add cached version.
18 defp get_replied_to_activities(activities) do
19 activities
20 |> Enum.map(fn
21 %{data: %{"type" => "Create", "object" => %{"inReplyTo" => in_reply_to}}} ->
22 in_reply_to != "" && in_reply_to
23
24 _ ->
25 nil
26 end)
27 |> Enum.filter(& &1)
28 |> Activity.create_by_object_ap_id()
29 |> Repo.all()
30 |> Enum.reduce(%{}, fn activity, acc ->
31 Map.put(acc, activity.data["object"]["id"], activity)
32 end)
33 end
34
35 defp get_user(ap_id) do
36 cond do
37 user = User.get_cached_by_ap_id(ap_id) ->
38 user
39
40 user = User.get_by_guessed_nickname(ap_id) ->
41 user
42
43 true ->
44 User.error_user(ap_id)
45 end
46 end
47
48 def render("index.json", opts) do
49 replied_to_activities = get_replied_to_activities(opts.activities)
50
51 opts.activities
52 |> safe_render_many(
53 StatusView,
54 "status.json",
55 Map.put(opts, :replied_to_activities, replied_to_activities)
56 )
57 end
58
59 def render(
60 "status.json",
61 %{activity: %{data: %{"type" => "Announce", "object" => object}} = activity} = opts
62 ) do
63 user = get_user(activity.data["actor"])
64 created_at = Utils.to_masto_date(activity.data["published"])
65
66 reblogged = Activity.get_create_by_object_ap_id(object)
67 reblogged = render("status.json", Map.put(opts, :activity, reblogged))
68
69 mentions =
70 activity.recipients
71 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
72 |> Enum.filter(& &1)
73 |> Enum.map(fn user -> AccountView.render("mention.json", %{user: user}) end)
74
75 %{
76 id: to_string(activity.id),
77 uri: object,
78 url: object,
79 account: AccountView.render("account.json", %{user: user}),
80 in_reply_to_id: nil,
81 in_reply_to_account_id: nil,
82 reblog: reblogged,
83 content: reblogged[:content] || "",
84 created_at: created_at,
85 reblogs_count: 0,
86 replies_count: 0,
87 favourites_count: 0,
88 reblogged: false,
89 favourited: false,
90 muted: false,
91 pinned: pinned?(activity, user),
92 sensitive: false,
93 spoiler_text: "",
94 visibility: "public",
95 media_attachments: reblogged[:media_attachments] || [],
96 mentions: mentions,
97 tags: reblogged[:tags] || [],
98 application: %{
99 name: "Web",
100 website: nil
101 },
102 language: nil,
103 emojis: []
104 }
105 end
106
107 def render("status.json", %{activity: %{data: %{"object" => object}} = activity} = opts) do
108 user = get_user(activity.data["actor"])
109
110 like_count = object["like_count"] || 0
111 announcement_count = object["announcement_count"] || 0
112
113 tags = object["tag"] || []
114 sensitive = object["sensitive"] || Enum.member?(tags, "nsfw")
115
116 mentions =
117 activity.recipients
118 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
119 |> Enum.filter(& &1)
120 |> Enum.map(fn user -> AccountView.render("mention.json", %{user: user}) end)
121
122 repeated = opts[:for] && opts[:for].ap_id in (object["announcements"] || [])
123 favorited = opts[:for] && opts[:for].ap_id in (object["likes"] || [])
124
125 attachment_data = object["attachment"] || []
126 attachments = render_many(attachment_data, StatusView, "attachment.json", as: :attachment)
127
128 created_at = Utils.to_masto_date(object["published"])
129
130 reply_to = get_reply_to(activity, opts)
131 reply_to_user = reply_to && get_user(reply_to.data["actor"])
132
133 content =
134 object
135 |> render_content()
136 |> HTML.get_cached_scrubbed_html_for_object(
137 User.html_filter_policy(opts[:for]),
138 activity,
139 __MODULE__
140 )
141
142 card = render("card.json", Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity))
143
144 %{
145 id: to_string(activity.id),
146 uri: object["id"],
147 url: object["external_url"] || object["id"],
148 account: AccountView.render("account.json", %{user: user}),
149 in_reply_to_id: reply_to && to_string(reply_to.id),
150 in_reply_to_account_id: reply_to_user && to_string(reply_to_user.id),
151 reblog: nil,
152 card: card,
153 content: content,
154 created_at: created_at,
155 reblogs_count: announcement_count,
156 replies_count: 0,
157 favourites_count: like_count,
158 reblogged: present?(repeated),
159 favourited: present?(favorited),
160 muted: false,
161 pinned: pinned?(activity, user),
162 sensitive: sensitive,
163 spoiler_text: object["summary"] || "",
164 visibility: get_visibility(object),
165 media_attachments: attachments |> Enum.take(4),
166 mentions: mentions,
167 tags: build_tags(tags),
168 application: %{
169 name: "Web",
170 website: nil
171 },
172 language: nil,
173 emojis: build_emojis(activity.data["object"]["emoji"])
174 }
175 end
176
177 def render("status.json", _) do
178 nil
179 end
180
181 def render("card.json", %{rich_media: rich_media, page_url: page_url}) do
182 page_url = rich_media[:url] || page_url
183 page_url_data = URI.parse(page_url)
184 site_name = rich_media[:site_name] || page_url_data.host
185
186 %{
187 type: "link",
188 provider_name: site_name,
189 provider_url: page_url_data.scheme <> "://" <> page_url_data.host,
190 url: page_url,
191 image: rich_media[:image] |> MediaProxy.url(),
192 title: rich_media[:title],
193 description: rich_media[:description],
194 pleroma: %{
195 opengraph: rich_media
196 }
197 }
198 end
199
200 def render("card.json", _) do
201 nil
202 end
203
204 def render("attachment.json", %{attachment: attachment}) do
205 [attachment_url | _] = attachment["url"]
206 media_type = attachment_url["mediaType"] || attachment_url["mimeType"] || "image"
207 href = attachment_url["href"] |> MediaProxy.url()
208
209 type =
210 cond do
211 String.contains?(media_type, "image") -> "image"
212 String.contains?(media_type, "video") -> "video"
213 String.contains?(media_type, "audio") -> "audio"
214 true -> "unknown"
215 end
216
217 <<hash_id::signed-32, _rest::binary>> = :crypto.hash(:md5, href)
218
219 %{
220 id: to_string(attachment["id"] || hash_id),
221 url: href,
222 remote_url: href,
223 preview_url: href,
224 text_url: href,
225 type: type,
226 description: attachment["name"]
227 }
228 end
229
230 def get_reply_to(activity, %{replied_to_activities: replied_to_activities}) do
231 _id = activity.data["object"]["inReplyTo"]
232 replied_to_activities[activity.data["object"]["inReplyTo"]]
233 end
234
235 def get_reply_to(%{data: %{"object" => object}}, _) do
236 if object["inReplyTo"] && object["inReplyTo"] != "" do
237 Activity.get_create_by_object_ap_id(object["inReplyTo"])
238 else
239 nil
240 end
241 end
242
243 def get_visibility(object) do
244 public = "https://www.w3.org/ns/activitystreams#Public"
245 to = object["to"] || []
246 cc = object["cc"] || []
247
248 cond do
249 public in to ->
250 "public"
251
252 public in cc ->
253 "unlisted"
254
255 # this should use the sql for the object's activity
256 Enum.any?(to, &String.contains?(&1, "/followers")) ->
257 "private"
258
259 length(cc) > 0 ->
260 "private"
261
262 true ->
263 "direct"
264 end
265 end
266
267 def render_content(%{"type" => "Video"} = object) do
268 with name when not is_nil(name) and name != "" <- object["name"] do
269 "<p><a href=\"#{object["id"]}\">#{name}</a></p>#{object["content"]}"
270 else
271 _ -> object["content"] || ""
272 end
273 end
274
275 def render_content(%{"type" => object_type} = object)
276 when object_type in ["Article", "Page"] do
277 with summary when not is_nil(summary) and summary != "" <- object["name"],
278 url when is_bitstring(url) <- object["url"] do
279 "<p><a href=\"#{url}\">#{summary}</a></p>#{object["content"]}"
280 else
281 _ -> object["content"] || ""
282 end
283 end
284
285 def render_content(object), do: object["content"] || ""
286
287 @doc """
288 Builds a dictionary tags.
289
290 ## Examples
291
292 iex> Pleroma.Web.MastodonAPI.StatusView.build_tags(["fediverse", "nextcloud"])
293 [{"name": "fediverse", "url": "/tag/fediverse"},
294 {"name": "nextcloud", "url": "/tag/nextcloud"}]
295
296 """
297 @spec build_tags(list(any())) :: list(map())
298 def build_tags(object_tags) when is_list(object_tags) do
299 object_tags = for tag when is_binary(tag) <- object_tags, do: tag
300
301 Enum.reduce(object_tags, [], fn tag, tags ->
302 tags ++ [%{name: tag, url: "/tag/#{tag}"}]
303 end)
304 end
305
306 def build_tags(_), do: []
307
308 @doc """
309 Builds list emojis.
310
311 Arguments: `nil` or list tuple of name and url.
312
313 Returns list emojis.
314
315 ## Examples
316
317 iex> Pleroma.Web.MastodonAPI.StatusView.build_emojis([{"2hu", "corndog.png"}])
318 [%{shortcode: "2hu", static_url: "corndog.png", url: "corndog.png", visible_in_picker: false}]
319
320 """
321 @spec build_emojis(nil | list(tuple())) :: list(map())
322 def build_emojis(nil), do: []
323
324 def build_emojis(emojis) do
325 emojis
326 |> Enum.map(fn {name, url} ->
327 name = HTML.strip_tags(name)
328
329 url =
330 url
331 |> HTML.strip_tags()
332 |> MediaProxy.url()
333
334 %{shortcode: name, url: url, static_url: url, visible_in_picker: false}
335 end)
336 end
337
338 defp present?(nil), do: false
339 defp present?(false), do: false
340 defp present?(_), do: true
341
342 defp pinned?(%Activity{id: id}, %User{info: %{pinned_activities: pinned_activities}}),
343 do: id in pinned_activities
344 end