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