Merge remote-tracking branch 'pleroma/develop' into feature/disable-account
[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.Object
11 alias Pleroma.Repo
12 alias Pleroma.User
13 alias Pleroma.Web.CommonAPI
14 alias Pleroma.Web.CommonAPI.Utils
15 alias Pleroma.Web.MastodonAPI.AccountView
16 alias Pleroma.Web.MastodonAPI.StatusView
17 alias Pleroma.Web.MediaProxy
18
19 # TODO: Add cached version.
20 defp get_replied_to_activities(activities) do
21 activities
22 |> Enum.map(fn
23 %{data: %{"type" => "Create", "object" => object}} ->
24 object = Object.normalize(object)
25 object.data["inReplyTo"] != "" && object.data["inReplyTo"]
26
27 _ ->
28 nil
29 end)
30 |> Enum.filter(& &1)
31 |> Activity.create_by_object_ap_id()
32 |> Repo.all()
33 |> Enum.reduce(%{}, fn activity, acc ->
34 object = Object.normalize(activity)
35 Map.put(acc, object.data["id"], activity)
36 end)
37 end
38
39 defp get_user(ap_id) do
40 cond do
41 user = User.get_cached_by_ap_id(ap_id) ->
42 user
43
44 user = User.get_by_guessed_nickname(ap_id) ->
45 user
46
47 true ->
48 User.error_user(ap_id)
49 end
50 end
51
52 defp get_context_id(%{data: %{"context_id" => context_id}}) when not is_nil(context_id),
53 do: context_id
54
55 defp get_context_id(%{data: %{"context" => context}}) when is_binary(context),
56 do: Utils.context_to_conversation_id(context)
57
58 defp get_context_id(_), do: nil
59
60 defp reblogged?(activity, user) do
61 object = Object.normalize(activity) || %{}
62 present?(user && user.ap_id in (object.data["announcements"] || []))
63 end
64
65 def render("index.json", opts) do
66 replied_to_activities = get_replied_to_activities(opts.activities)
67
68 opts.activities
69 |> safe_render_many(
70 StatusView,
71 "status.json",
72 Map.put(opts, :replied_to_activities, replied_to_activities)
73 )
74 end
75
76 def render(
77 "status.json",
78 %{activity: %{data: %{"type" => "Announce", "object" => object}} = activity} = opts
79 ) do
80 user = get_user(activity.data["actor"])
81 created_at = Utils.to_masto_date(activity.data["published"])
82
83 reblogged_activity = Activity.get_create_by_object_ap_id(object)
84 reblogged = render("status.json", Map.put(opts, :activity, reblogged_activity))
85
86 activity_object = Object.normalize(activity)
87 favorited = opts[:for] && opts[:for].ap_id in (activity_object.data["likes"] || [])
88
89 bookmarked = opts[:for] && CommonAPI.bookmarked?(opts[:for], reblogged_activity)
90
91 mentions =
92 activity.recipients
93 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
94 |> Enum.filter(& &1)
95 |> Enum.map(fn user -> AccountView.render("mention.json", %{user: user}) end)
96
97 %{
98 id: to_string(activity.id),
99 uri: object,
100 url: object,
101 account: AccountView.render("account.json", %{user: user}),
102 in_reply_to_id: nil,
103 in_reply_to_account_id: nil,
104 reblog: reblogged,
105 content: reblogged[:content] || "",
106 created_at: created_at,
107 reblogs_count: 0,
108 replies_count: 0,
109 favourites_count: 0,
110 reblogged: reblogged?(reblogged_activity, opts[:for]),
111 favourited: present?(favorited),
112 bookmarked: present?(bookmarked),
113 muted: false,
114 pinned: pinned?(activity, user),
115 sensitive: false,
116 spoiler_text: "",
117 visibility: "public",
118 media_attachments: reblogged[:media_attachments] || [],
119 mentions: mentions,
120 tags: reblogged[:tags] || [],
121 application: %{
122 name: "Web",
123 website: nil
124 },
125 language: nil,
126 emojis: [],
127 pleroma: %{
128 local: activity.local
129 }
130 }
131 end
132
133 def render("status.json", %{activity: %{data: %{"object" => _object}} = activity} = opts) do
134 object = Object.normalize(activity)
135
136 user = get_user(activity.data["actor"])
137
138 like_count = object.data["like_count"] || 0
139 announcement_count = object.data["announcement_count"] || 0
140
141 tags = object.data["tag"] || []
142 sensitive = object.data["sensitive"] || Enum.member?(tags, "nsfw")
143
144 mentions =
145 activity.recipients
146 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
147 |> Enum.filter(& &1)
148 |> Enum.map(fn user -> AccountView.render("mention.json", %{user: user}) end)
149
150 favorited = opts[:for] && opts[:for].ap_id in (object.data["likes"] || [])
151
152 bookmarked = opts[:for] && CommonAPI.bookmarked?(opts[:for], activity)
153
154 attachment_data = object.data["attachment"] || []
155 attachments = render_many(attachment_data, StatusView, "attachment.json", as: :attachment)
156
157 created_at = Utils.to_masto_date(object.data["published"])
158
159 reply_to = get_reply_to(activity, opts)
160
161 reply_to_user = reply_to && get_user(reply_to.data["actor"])
162
163 content =
164 object
165 |> render_content()
166
167 content_html =
168 content
169 |> HTML.get_cached_scrubbed_html_for_activity(
170 User.html_filter_policy(opts[:for]),
171 activity,
172 "mastoapi:content"
173 )
174
175 content_plaintext =
176 content
177 |> HTML.get_cached_stripped_html_for_activity(
178 activity,
179 "mastoapi:content"
180 )
181
182 summary = object.data["summary"] || ""
183
184 summary_html =
185 summary
186 |> HTML.get_cached_scrubbed_html_for_activity(
187 User.html_filter_policy(opts[:for]),
188 activity,
189 "mastoapi:summary"
190 )
191
192 summary_plaintext =
193 summary
194 |> HTML.get_cached_stripped_html_for_activity(
195 activity,
196 "mastoapi:summary"
197 )
198
199 card = render("card.json", Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity))
200
201 url =
202 if user.local do
203 Pleroma.Web.Router.Helpers.o_status_url(Pleroma.Web.Endpoint, :notice, activity)
204 else
205 object.data["external_url"] || object.data["id"]
206 end
207
208 %{
209 id: to_string(activity.id),
210 uri: object.data["id"],
211 url: url,
212 account: AccountView.render("account.json", %{user: user}),
213 in_reply_to_id: reply_to && to_string(reply_to.id),
214 in_reply_to_account_id: reply_to_user && to_string(reply_to_user.id),
215 reblog: nil,
216 card: card,
217 content: content_html,
218 created_at: created_at,
219 reblogs_count: announcement_count,
220 replies_count: object.data["repliesCount"] || 0,
221 favourites_count: like_count,
222 reblogged: reblogged?(activity, opts[:for]),
223 favourited: present?(favorited),
224 bookmarked: present?(bookmarked),
225 muted: CommonAPI.thread_muted?(user, activity) || User.mutes?(opts[:for], user),
226 pinned: pinned?(activity, user),
227 sensitive: sensitive,
228 spoiler_text: summary_html,
229 visibility: get_visibility(object),
230 media_attachments: attachments,
231 mentions: mentions,
232 tags: build_tags(tags),
233 application: %{
234 name: "Web",
235 website: nil
236 },
237 language: nil,
238 emojis: build_emojis(object.data["emoji"]),
239 pleroma: %{
240 local: activity.local,
241 conversation_id: get_context_id(activity),
242 in_reply_to_account_acct: reply_to_user && reply_to_user.nickname,
243 content: %{"text/plain" => content_plaintext},
244 spoiler_text: %{"text/plain" => summary_plaintext}
245 }
246 }
247 end
248
249 def render("status.json", _) do
250 nil
251 end
252
253 def render("card.json", %{rich_media: rich_media, page_url: page_url}) do
254 page_url_data = URI.parse(page_url)
255
256 page_url_data =
257 if rich_media[:url] != nil do
258 URI.merge(page_url_data, URI.parse(rich_media[:url]))
259 else
260 page_url_data
261 end
262
263 page_url = page_url_data |> to_string
264
265 image_url =
266 if rich_media[:image] != nil do
267 URI.merge(page_url_data, URI.parse(rich_media[:image]))
268 |> to_string
269 else
270 nil
271 end
272
273 site_name = rich_media[:site_name] || page_url_data.host
274
275 %{
276 type: "link",
277 provider_name: site_name,
278 provider_url: page_url_data.scheme <> "://" <> page_url_data.host,
279 url: page_url,
280 image: image_url |> MediaProxy.url(),
281 title: rich_media[:title],
282 description: rich_media[:description],
283 pleroma: %{
284 opengraph: rich_media
285 }
286 }
287 end
288
289 def render("card.json", _) do
290 nil
291 end
292
293 def render("attachment.json", %{attachment: attachment}) do
294 [attachment_url | _] = attachment["url"]
295 media_type = attachment_url["mediaType"] || attachment_url["mimeType"] || "image"
296 href = attachment_url["href"] |> MediaProxy.url()
297
298 type =
299 cond do
300 String.contains?(media_type, "image") -> "image"
301 String.contains?(media_type, "video") -> "video"
302 String.contains?(media_type, "audio") -> "audio"
303 true -> "unknown"
304 end
305
306 <<hash_id::signed-32, _rest::binary>> = :crypto.hash(:md5, href)
307
308 %{
309 id: to_string(attachment["id"] || hash_id),
310 url: href,
311 remote_url: href,
312 preview_url: href,
313 text_url: href,
314 type: type,
315 description: attachment["name"],
316 pleroma: %{mime_type: media_type}
317 }
318 end
319
320 def get_reply_to(activity, %{replied_to_activities: replied_to_activities}) do
321 object = Object.normalize(activity)
322
323 with nil <- replied_to_activities[object.data["inReplyTo"]] do
324 # If user didn't participate in the thread
325 Activity.get_in_reply_to_activity(activity)
326 end
327 end
328
329 def get_reply_to(%{data: %{"object" => _object}} = activity, _) do
330 object = Object.normalize(activity)
331
332 if object.data["inReplyTo"] && object.data["inReplyTo"] != "" do
333 Activity.get_create_by_object_ap_id(object.data["inReplyTo"])
334 else
335 nil
336 end
337 end
338
339 def get_visibility(object) do
340 public = "https://www.w3.org/ns/activitystreams#Public"
341 to = object.data["to"] || []
342 cc = object.data["cc"] || []
343
344 cond do
345 public in to ->
346 "public"
347
348 public in cc ->
349 "unlisted"
350
351 # this should use the sql for the object's activity
352 Enum.any?(to, &String.contains?(&1, "/followers")) ->
353 "private"
354
355 length(cc) > 0 ->
356 "private"
357
358 true ->
359 "direct"
360 end
361 end
362
363 def render_content(%{data: %{"type" => "Video"}} = object) do
364 with name when not is_nil(name) and name != "" <- object.data["name"] do
365 "<p><a href=\"#{object.data["id"]}\">#{name}</a></p>#{object.data["content"]}"
366 else
367 _ -> object.data["content"] || ""
368 end
369 end
370
371 def render_content(%{data: %{"type" => object_type}} = object)
372 when object_type in ["Article", "Page"] do
373 with summary when not is_nil(summary) and summary != "" <- object.data["name"],
374 url when is_bitstring(url) <- object.data["url"] do
375 "<p><a href=\"#{url}\">#{summary}</a></p>#{object.data["content"]}"
376 else
377 _ -> object.data["content"] || ""
378 end
379 end
380
381 def render_content(object), do: object.data["content"] || ""
382
383 @doc """
384 Builds a dictionary tags.
385
386 ## Examples
387
388 iex> Pleroma.Web.MastodonAPI.StatusView.build_tags(["fediverse", "nextcloud"])
389 [{"name": "fediverse", "url": "/tag/fediverse"},
390 {"name": "nextcloud", "url": "/tag/nextcloud"}]
391
392 """
393 @spec build_tags(list(any())) :: list(map())
394 def build_tags(object_tags) when is_list(object_tags) do
395 object_tags = for tag when is_binary(tag) <- object_tags, do: tag
396
397 Enum.reduce(object_tags, [], fn tag, tags ->
398 tags ++ [%{name: tag, url: "/tag/#{tag}"}]
399 end)
400 end
401
402 def build_tags(_), do: []
403
404 @doc """
405 Builds list emojis.
406
407 Arguments: `nil` or list tuple of name and url.
408
409 Returns list emojis.
410
411 ## Examples
412
413 iex> Pleroma.Web.MastodonAPI.StatusView.build_emojis([{"2hu", "corndog.png"}])
414 [%{shortcode: "2hu", static_url: "corndog.png", url: "corndog.png", visible_in_picker: false}]
415
416 """
417 @spec build_emojis(nil | list(tuple())) :: list(map())
418 def build_emojis(nil), do: []
419
420 def build_emojis(emojis) do
421 emojis
422 |> Enum.map(fn {name, url} ->
423 name = HTML.strip_tags(name)
424
425 url =
426 url
427 |> HTML.strip_tags()
428 |> MediaProxy.url()
429
430 %{shortcode: name, url: url, static_url: url, visible_in_picker: false}
431 end)
432 end
433
434 defp present?(nil), do: false
435 defp present?(false), do: false
436 defp present?(_), do: true
437
438 defp pinned?(%Activity{id: id}, %User{info: %{pinned_activities: pinned_activities}}),
439 do: id in pinned_activities
440 end