Merge branch 'fix/activitypub-user-view-badmap' 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.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 bookmarked: false,
91 muted: false,
92 pinned: pinned?(activity, user),
93 sensitive: false,
94 spoiler_text: "",
95 visibility: "public",
96 media_attachments: reblogged[:media_attachments] || [],
97 mentions: mentions,
98 tags: reblogged[:tags] || [],
99 application: %{
100 name: "Web",
101 website: nil
102 },
103 language: nil,
104 emojis: []
105 }
106 end
107
108 def render("status.json", %{activity: %{data: %{"object" => object}} = activity} = opts) do
109 user = get_user(activity.data["actor"])
110
111 like_count = object["like_count"] || 0
112 announcement_count = object["announcement_count"] || 0
113
114 tags = object["tag"] || []
115 sensitive = object["sensitive"] || Enum.member?(tags, "nsfw")
116
117 mentions =
118 activity.recipients
119 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
120 |> Enum.filter(& &1)
121 |> Enum.map(fn user -> AccountView.render("mention.json", %{user: user}) end)
122
123 repeated = opts[:for] && opts[:for].ap_id in (object["announcements"] || [])
124 favorited = opts[:for] && opts[:for].ap_id in (object["likes"] || [])
125 bookmarked = opts[:for] && object["id"] in opts[:for].bookmarks
126
127 attachment_data = object["attachment"] || []
128 attachments = render_many(attachment_data, StatusView, "attachment.json", as: :attachment)
129
130 created_at = Utils.to_masto_date(object["published"])
131
132 reply_to = get_reply_to(activity, opts)
133 reply_to_user = reply_to && get_user(reply_to.data["actor"])
134
135 content =
136 object
137 |> render_content()
138 |> HTML.get_cached_scrubbed_html_for_object(
139 User.html_filter_policy(opts[:for]),
140 activity,
141 __MODULE__
142 )
143
144 card = render("card.json", Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity))
145
146 %{
147 id: to_string(activity.id),
148 uri: object["id"],
149 url: object["external_url"] || object["id"],
150 account: AccountView.render("account.json", %{user: user}),
151 in_reply_to_id: reply_to && to_string(reply_to.id),
152 in_reply_to_account_id: reply_to_user && to_string(reply_to_user.id),
153 reblog: nil,
154 card: card,
155 content: content,
156 created_at: created_at,
157 reblogs_count: announcement_count,
158 replies_count: 0,
159 favourites_count: like_count,
160 reblogged: present?(repeated),
161 favourited: present?(favorited),
162 bookmarked: present?(bookmarked),
163 muted: false,
164 pinned: pinned?(activity, user),
165 sensitive: sensitive,
166 spoiler_text: object["summary"] || "",
167 visibility: get_visibility(object),
168 media_attachments: attachments |> Enum.take(4),
169 mentions: mentions,
170 tags: build_tags(tags),
171 application: %{
172 name: "Web",
173 website: nil
174 },
175 language: nil,
176 emojis: build_emojis(activity.data["object"]["emoji"])
177 }
178 end
179
180 def render("status.json", _) do
181 nil
182 end
183
184 def render("card.json", %{rich_media: rich_media, page_url: page_url}) do
185 page_url_data =
186 if rich_media[:url] != nil do
187 URI.merge(URI.parse(page_url), URI.parse(rich_media[:url]))
188 else
189 page_url
190 end
191
192 page_url = page_url_data |> to_string
193
194 image_url =
195 if rich_media[:image] != nil do
196 URI.merge(page_url_data, URI.parse(rich_media[:image]))
197 |> to_string
198 else
199 nil
200 end
201
202 site_name = rich_media[:site_name] || page_url_data.host
203
204 %{
205 type: "link",
206 provider_name: site_name,
207 provider_url: page_url_data.scheme <> "://" <> page_url_data.host,
208 url: page_url,
209 image: image_url |> MediaProxy.url(),
210 title: rich_media[:title],
211 description: rich_media[:description],
212 pleroma: %{
213 opengraph: rich_media
214 }
215 }
216 end
217
218 def render("card.json", _) do
219 nil
220 end
221
222 def render("attachment.json", %{attachment: attachment}) do
223 [attachment_url | _] = attachment["url"]
224 media_type = attachment_url["mediaType"] || attachment_url["mimeType"] || "image"
225 href = attachment_url["href"] |> MediaProxy.url()
226
227 type =
228 cond do
229 String.contains?(media_type, "image") -> "image"
230 String.contains?(media_type, "video") -> "video"
231 String.contains?(media_type, "audio") -> "audio"
232 true -> "unknown"
233 end
234
235 <<hash_id::signed-32, _rest::binary>> = :crypto.hash(:md5, href)
236
237 %{
238 id: to_string(attachment["id"] || hash_id),
239 url: href,
240 remote_url: href,
241 preview_url: href,
242 text_url: href,
243 type: type,
244 description: attachment["name"]
245 }
246 end
247
248 def get_reply_to(activity, %{replied_to_activities: replied_to_activities}) do
249 _id = activity.data["object"]["inReplyTo"]
250 replied_to_activities[activity.data["object"]["inReplyTo"]]
251 end
252
253 def get_reply_to(%{data: %{"object" => object}}, _) do
254 if object["inReplyTo"] && object["inReplyTo"] != "" do
255 Activity.get_create_by_object_ap_id(object["inReplyTo"])
256 else
257 nil
258 end
259 end
260
261 def get_visibility(object) do
262 public = "https://www.w3.org/ns/activitystreams#Public"
263 to = object["to"] || []
264 cc = object["cc"] || []
265
266 cond do
267 public in to ->
268 "public"
269
270 public in cc ->
271 "unlisted"
272
273 # this should use the sql for the object's activity
274 Enum.any?(to, &String.contains?(&1, "/followers")) ->
275 "private"
276
277 length(cc) > 0 ->
278 "private"
279
280 true ->
281 "direct"
282 end
283 end
284
285 def render_content(%{"type" => "Video"} = object) do
286 with name when not is_nil(name) and name != "" <- object["name"] do
287 "<p><a href=\"#{object["id"]}\">#{name}</a></p>#{object["content"]}"
288 else
289 _ -> object["content"] || ""
290 end
291 end
292
293 def render_content(%{"type" => object_type} = object)
294 when object_type in ["Article", "Page"] do
295 with summary when not is_nil(summary) and summary != "" <- object["name"],
296 url when is_bitstring(url) <- object["url"] do
297 "<p><a href=\"#{url}\">#{summary}</a></p>#{object["content"]}"
298 else
299 _ -> object["content"] || ""
300 end
301 end
302
303 def render_content(object), do: object["content"] || ""
304
305 @doc """
306 Builds a dictionary tags.
307
308 ## Examples
309
310 iex> Pleroma.Web.MastodonAPI.StatusView.build_tags(["fediverse", "nextcloud"])
311 [{"name": "fediverse", "url": "/tag/fediverse"},
312 {"name": "nextcloud", "url": "/tag/nextcloud"}]
313
314 """
315 @spec build_tags(list(any())) :: list(map())
316 def build_tags(object_tags) when is_list(object_tags) do
317 object_tags = for tag when is_binary(tag) <- object_tags, do: tag
318
319 Enum.reduce(object_tags, [], fn tag, tags ->
320 tags ++ [%{name: tag, url: "/tag/#{tag}"}]
321 end)
322 end
323
324 def build_tags(_), do: []
325
326 @doc """
327 Builds list emojis.
328
329 Arguments: `nil` or list tuple of name and url.
330
331 Returns list emojis.
332
333 ## Examples
334
335 iex> Pleroma.Web.MastodonAPI.StatusView.build_emojis([{"2hu", "corndog.png"}])
336 [%{shortcode: "2hu", static_url: "corndog.png", url: "corndog.png", visible_in_picker: false}]
337
338 """
339 @spec build_emojis(nil | list(tuple())) :: list(map())
340 def build_emojis(nil), do: []
341
342 def build_emojis(emojis) do
343 emojis
344 |> Enum.map(fn {name, url} ->
345 name = HTML.strip_tags(name)
346
347 url =
348 url
349 |> HTML.strip_tags()
350 |> MediaProxy.url()
351
352 %{shortcode: name, url: url, static_url: url, visible_in_picker: false}
353 end)
354 end
355
356 defp present?(nil), do: false
357 defp present?(false), do: false
358 defp present?(_), do: true
359
360 defp pinned?(%Activity{id: id}, %User{info: %{pinned_activities: pinned_activities}}),
361 do: id in pinned_activities
362 end