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