Merge develop to 770-add-emoji-tags
[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 |> HTML.get_cached_scrubbed_html_for_activity(
151 User.html_filter_policy(opts[:for]),
152 activity,
153 "mastoapi:content"
154 )
155
156 summary =
157 (object["summary"] || "")
158 |> HTML.get_cached_scrubbed_html_for_activity(
159 User.html_filter_policy(opts[:for]),
160 activity,
161 "mastoapi:summary"
162 )
163
164 card = render("card.json", Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity))
165
166 url =
167 if user.local do
168 Pleroma.Web.Router.Helpers.o_status_url(Pleroma.Web.Endpoint, :notice, activity)
169 else
170 object["external_url"] || object["id"]
171 end
172
173 %{
174 id: to_string(activity.id),
175 uri: object["id"],
176 url: url,
177 account: AccountView.render("account.json", %{user: user}),
178 in_reply_to_id: reply_to && to_string(reply_to.id),
179 in_reply_to_account_id: reply_to_user && to_string(reply_to_user.id),
180 reblog: nil,
181 card: card,
182 content: content,
183 created_at: created_at,
184 reblogs_count: announcement_count,
185 replies_count: object["repliesCount"] || 0,
186 favourites_count: like_count,
187 reblogged: present?(repeated),
188 favourited: present?(favorited),
189 bookmarked: present?(bookmarked),
190 muted: CommonAPI.thread_muted?(user, activity) || User.mutes?(opts[:for], user),
191 pinned: pinned?(activity, user),
192 sensitive: sensitive,
193 spoiler_text: summary,
194 visibility: get_visibility(object),
195 media_attachments: attachments,
196 mentions: mentions,
197 tags: build_tags(tags),
198 application: %{
199 name: "Web",
200 website: nil
201 },
202 language: nil,
203 emojis: build_emojis(activity.data["object"]["emoji"]),
204 pleroma: %{
205 local: activity.local,
206 conversation_id: get_context_id(activity)
207 }
208 }
209 end
210
211 def render("status.json", _) do
212 nil
213 end
214
215 def render("card.json", %{rich_media: rich_media, page_url: page_url}) do
216 page_url_data = URI.parse(page_url)
217
218 page_url_data =
219 if rich_media[:url] != nil do
220 URI.merge(page_url_data, URI.parse(rich_media[:url]))
221 else
222 page_url_data
223 end
224
225 page_url = page_url_data |> to_string
226
227 image_url =
228 if rich_media[:image] != nil do
229 URI.merge(page_url_data, URI.parse(rich_media[:image]))
230 |> to_string
231 else
232 nil
233 end
234
235 site_name = rich_media[:site_name] || page_url_data.host
236
237 %{
238 type: "link",
239 provider_name: site_name,
240 provider_url: page_url_data.scheme <> "://" <> page_url_data.host,
241 url: page_url,
242 image: image_url |> MediaProxy.url(),
243 title: rich_media[:title],
244 description: rich_media[:description],
245 pleroma: %{
246 opengraph: rich_media
247 }
248 }
249 end
250
251 def render("card.json", _) do
252 nil
253 end
254
255 def render("attachment.json", %{attachment: attachment}) do
256 [attachment_url | _] = attachment["url"]
257 media_type = attachment_url["mediaType"] || attachment_url["mimeType"] || "image"
258 href = attachment_url["href"] |> MediaProxy.url()
259
260 type =
261 cond do
262 String.contains?(media_type, "image") -> "image"
263 String.contains?(media_type, "video") -> "video"
264 String.contains?(media_type, "audio") -> "audio"
265 true -> "unknown"
266 end
267
268 <<hash_id::signed-32, _rest::binary>> = :crypto.hash(:md5, href)
269
270 %{
271 id: to_string(attachment["id"] || hash_id),
272 url: href,
273 remote_url: href,
274 preview_url: href,
275 text_url: href,
276 type: type,
277 description: attachment["name"],
278 pleroma: %{mime_type: media_type}
279 }
280 end
281
282 def get_reply_to(activity, %{replied_to_activities: replied_to_activities}) do
283 _id = activity.data["object"]["inReplyTo"]
284 replied_to_activities[activity.data["object"]["inReplyTo"]]
285 end
286
287 def get_reply_to(%{data: %{"object" => object}}, _) do
288 if object["inReplyTo"] && object["inReplyTo"] != "" do
289 Activity.get_create_by_object_ap_id(object["inReplyTo"])
290 else
291 nil
292 end
293 end
294
295 def get_visibility(object) do
296 public = "https://www.w3.org/ns/activitystreams#Public"
297 to = object["to"] || []
298 cc = object["cc"] || []
299
300 cond do
301 public in to ->
302 "public"
303
304 public in cc ->
305 "unlisted"
306
307 # this should use the sql for the object's activity
308 Enum.any?(to, &String.contains?(&1, "/followers")) ->
309 "private"
310
311 length(cc) > 0 ->
312 "private"
313
314 true ->
315 "direct"
316 end
317 end
318
319 def render_content(%{"type" => "Video"} = object) do
320 with name when not is_nil(name) and name != "" <- object["name"] do
321 "<p><a href=\"#{object["id"]}\">#{name}</a></p>#{object["content"]}"
322 else
323 _ -> object["content"] || ""
324 end
325 end
326
327 def render_content(%{"type" => object_type} = object)
328 when object_type in ["Article", "Page"] do
329 with summary when not is_nil(summary) and summary != "" <- object["name"],
330 url when is_bitstring(url) <- object["url"] do
331 "<p><a href=\"#{url}\">#{summary}</a></p>#{object["content"]}"
332 else
333 _ -> object["content"] || ""
334 end
335 end
336
337 def render_content(object), do: object["content"] || ""
338
339 @doc """
340 Builds a dictionary tags.
341
342 ## Examples
343
344 iex> Pleroma.Web.MastodonAPI.StatusView.build_tags(["fediverse", "nextcloud"])
345 [{"name": "fediverse", "url": "/tag/fediverse"},
346 {"name": "nextcloud", "url": "/tag/nextcloud"}]
347
348 """
349 @spec build_tags(list(any())) :: list(map())
350 def build_tags(object_tags) when is_list(object_tags) do
351 object_tags = for tag when is_binary(tag) <- object_tags, do: tag
352
353 Enum.reduce(object_tags, [], fn tag, tags ->
354 tags ++ [%{name: tag, url: "/tag/#{tag}"}]
355 end)
356 end
357
358 def build_tags(_), do: []
359
360 @doc """
361 Builds list emojis.
362
363 Arguments: `nil` or list tuple of name and url.
364
365 Returns list emojis.
366
367 ## Examples
368
369 iex> Pleroma.Web.MastodonAPI.StatusView.build_emojis([{"2hu", "corndog.png"}])
370 [%{shortcode: "2hu", static_url: "corndog.png", url: "corndog.png", visible_in_picker: false}]
371
372 """
373 @spec build_emojis(nil | list(tuple())) :: list(map())
374 def build_emojis(nil), do: []
375
376 def build_emojis(emojis) do
377 emojis
378 |> Enum.map(fn {name, url} ->
379 name = HTML.strip_tags(name)
380
381 url =
382 url
383 |> HTML.strip_tags()
384 |> MediaProxy.url()
385
386 %{shortcode: name, url: url, static_url: url, visible_in_picker: false}
387 end)
388 end
389
390 defp present?(nil), do: false
391 defp present?(false), do: false
392 defp present?(_), do: true
393
394 defp pinned?(%Activity{id: id}, %User{info: %{pinned_activities: pinned_activities}}),
395 do: id in pinned_activities
396 end