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