Merge branch 'develop' into 'feature/local-only-scope'
[akkoma] / lib / pleroma / web / common_api / utils.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.CommonAPI.Utils do
6 import Pleroma.Web.Gettext
7 import Pleroma.Web.ControllerHelper, only: [truthy_param?: 1]
8
9 alias Calendar.Strftime
10 alias Pleroma.Activity
11 alias Pleroma.Config
12 alias Pleroma.Conversation.Participation
13 alias Pleroma.Formatter
14 alias Pleroma.Object
15 alias Pleroma.Repo
16 alias Pleroma.User
17 alias Pleroma.Web.ActivityPub.Utils
18 alias Pleroma.Web.ActivityPub.Visibility
19 alias Pleroma.Web.CommonAPI.ActivityDraft
20 alias Pleroma.Web.MediaProxy
21 alias Pleroma.Web.Plugs.AuthenticationPlug
22
23 require Logger
24 require Pleroma.Constants
25
26 def attachments_from_ids(%{media_ids: ids, descriptions: desc}) do
27 attachments_from_ids_descs(ids, desc)
28 end
29
30 def attachments_from_ids(%{media_ids: ids}) do
31 attachments_from_ids_no_descs(ids)
32 end
33
34 def attachments_from_ids(_), do: []
35
36 def attachments_from_ids_no_descs([]), do: []
37
38 def attachments_from_ids_no_descs(ids) do
39 Enum.map(ids, fn media_id ->
40 case Repo.get(Object, media_id) do
41 %Object{data: data} -> data
42 _ -> nil
43 end
44 end)
45 |> Enum.reject(&is_nil/1)
46 end
47
48 def attachments_from_ids_descs([], _), do: []
49
50 def attachments_from_ids_descs(ids, descs_str) do
51 {_, descs} = Jason.decode(descs_str)
52
53 Enum.map(ids, fn media_id ->
54 with %Object{data: data} <- Repo.get(Object, media_id) do
55 Map.put(data, "name", descs[media_id])
56 end
57 end)
58 |> Enum.reject(&is_nil/1)
59 end
60
61 @spec get_to_and_cc(ActivityDraft.t()) :: {list(String.t()), list(String.t())}
62
63 def get_to_and_cc(%{in_reply_to_conversation: %Participation{} = participation}) do
64 participation = Repo.preload(participation, :recipients)
65 {Enum.map(participation.recipients, & &1.ap_id), []}
66 end
67
68 def get_to_and_cc(%{visibility: "public"} = draft) do
69 to = [public_uri(draft) | draft.mentions]
70 cc = [draft.user.follower_address]
71
72 if draft.in_reply_to do
73 {Enum.uniq([draft.in_reply_to.data["actor"] | to]), cc}
74 else
75 {to, cc}
76 end
77 end
78
79 def get_to_and_cc(%{visibility: "unlisted"} = draft) do
80 to = [draft.user.follower_address | draft.mentions]
81 cc = [public_uri(draft)]
82
83 if draft.in_reply_to do
84 {Enum.uniq([draft.in_reply_to.data["actor"] | to]), cc}
85 else
86 {to, cc}
87 end
88 end
89
90 def get_to_and_cc(%{visibility: "private"} = draft) do
91 {to, cc} = get_to_and_cc(struct(draft, visibility: "direct"))
92 {[draft.user.follower_address | to], cc}
93 end
94
95 def get_to_and_cc(%{visibility: "direct"} = draft) do
96 # If the OP is a DM already, add the implicit actor.
97 if draft.in_reply_to && Visibility.is_direct?(draft.in_reply_to) do
98 {Enum.uniq([draft.in_reply_to.data["actor"] | draft.mentions]), []}
99 else
100 {draft.mentions, []}
101 end
102 end
103
104 def get_to_and_cc(%{visibility: {:list, _}, mentions: mentions}), do: {mentions, []}
105
106 defp public_uri(%{params: %{local_only: true}}), do: Pleroma.Constants.as_local_public()
107 defp public_uri(_), do: Pleroma.Constants.as_public()
108
109 def get_addressed_users(_, to) when is_list(to) do
110 User.get_ap_ids_by_nicknames(to)
111 end
112
113 def get_addressed_users(mentioned_users, _), do: mentioned_users
114
115 def maybe_add_list_data(activity_params, user, {:list, list_id}) do
116 case Pleroma.List.get(list_id, user) do
117 %Pleroma.List{} = list ->
118 activity_params
119 |> put_in([:additional, "bcc"], [list.ap_id])
120 |> put_in([:additional, "listMessage"], list.ap_id)
121 |> put_in([:object, "listMessage"], list.ap_id)
122
123 _ ->
124 activity_params
125 end
126 end
127
128 def maybe_add_list_data(activity_params, _, _), do: activity_params
129
130 def make_poll_data(%{"poll" => %{"expires_in" => expires_in}} = data)
131 when is_binary(expires_in) do
132 # In some cases mastofe sends out strings instead of integers
133 data
134 |> put_in(["poll", "expires_in"], String.to_integer(expires_in))
135 |> make_poll_data()
136 end
137
138 def make_poll_data(%{poll: %{options: options, expires_in: expires_in}} = data)
139 when is_list(options) do
140 limits = Config.get([:instance, :poll_limits])
141
142 with :ok <- validate_poll_expiration(expires_in, limits),
143 :ok <- validate_poll_options_amount(options, limits),
144 :ok <- validate_poll_options_length(options, limits) do
145 {option_notes, emoji} =
146 Enum.map_reduce(options, %{}, fn option, emoji ->
147 note = %{
148 "name" => option,
149 "type" => "Note",
150 "replies" => %{"type" => "Collection", "totalItems" => 0}
151 }
152
153 {note, Map.merge(emoji, Pleroma.Emoji.Formatter.get_emoji_map(option))}
154 end)
155
156 end_time =
157 DateTime.utc_now()
158 |> DateTime.add(expires_in)
159 |> DateTime.to_iso8601()
160
161 key = if truthy_param?(data.poll[:multiple]), do: "anyOf", else: "oneOf"
162 poll = %{"type" => "Question", key => option_notes, "closed" => end_time}
163
164 {:ok, {poll, emoji}}
165 end
166 end
167
168 def make_poll_data(%{"poll" => poll}) when is_map(poll) do
169 {:error, "Invalid poll"}
170 end
171
172 def make_poll_data(_data) do
173 {:ok, {%{}, %{}}}
174 end
175
176 defp validate_poll_options_amount(options, %{max_options: max_options}) do
177 if Enum.count(options) > max_options do
178 {:error, "Poll can't contain more than #{max_options} options"}
179 else
180 :ok
181 end
182 end
183
184 defp validate_poll_options_length(options, %{max_option_chars: max_option_chars}) do
185 if Enum.any?(options, &(String.length(&1) > max_option_chars)) do
186 {:error, "Poll options cannot be longer than #{max_option_chars} characters each"}
187 else
188 :ok
189 end
190 end
191
192 defp validate_poll_expiration(expires_in, %{min_expiration: min, max_expiration: max}) do
193 cond do
194 expires_in > max -> {:error, "Expiration date is too far in the future"}
195 expires_in < min -> {:error, "Expiration date is too soon"}
196 true -> :ok
197 end
198 end
199
200 def make_content_html(%ActivityDraft{} = draft) do
201 attachment_links =
202 draft.params
203 |> Map.get("attachment_links", Config.get([:instance, :attachment_links]))
204 |> truthy_param?()
205
206 content_type = get_content_type(draft.params[:content_type])
207
208 options =
209 if draft.visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
210 [safe_mention: true]
211 else
212 []
213 end
214
215 draft.status
216 |> format_input(content_type, options)
217 |> maybe_add_attachments(draft.attachments, attachment_links)
218 |> maybe_add_nsfw_tag(draft.params)
219 end
220
221 defp get_content_type(content_type) do
222 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
223 content_type
224 else
225 "text/plain"
226 end
227 end
228
229 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
230 when sensitive in [true, "True", "true", "1"] do
231 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
232 end
233
234 defp maybe_add_nsfw_tag(data, _), do: data
235
236 def make_context(_, %Participation{} = participation) do
237 Repo.preload(participation, :conversation).conversation.ap_id
238 end
239
240 def make_context(%Activity{data: %{"context" => context}}, _), do: context
241 def make_context(_, _), do: Utils.generate_context_id()
242
243 def maybe_add_attachments(parsed, _attachments, false = _no_links), do: parsed
244
245 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
246 text = add_attachments(text, attachments)
247 {text, mentions, tags}
248 end
249
250 def add_attachments(text, attachments) do
251 attachment_text = Enum.map(attachments, &build_attachment_link/1)
252 Enum.join([text | attachment_text], "<br>")
253 end
254
255 defp build_attachment_link(%{"url" => [%{"href" => href} | _]} = attachment) do
256 name = attachment["name"] || URI.decode(Path.basename(href))
257 href = MediaProxy.url(href)
258 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
259 end
260
261 defp build_attachment_link(_), do: ""
262
263 def format_input(text, format, options \\ [])
264
265 @doc """
266 Formatting text to plain text, BBCode, HTML, or Markdown
267 """
268 def format_input(text, "text/plain", options) do
269 text
270 |> Formatter.html_escape("text/plain")
271 |> Formatter.linkify(options)
272 |> (fn {text, mentions, tags} ->
273 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
274 end).()
275 end
276
277 def format_input(text, "text/bbcode", options) do
278 text
279 |> String.replace(~r/\r/, "")
280 |> Formatter.html_escape("text/plain")
281 |> BBCode.to_html()
282 |> (fn {:ok, html} -> html end).()
283 |> Formatter.linkify(options)
284 end
285
286 def format_input(text, "text/html", options) do
287 text
288 |> Formatter.html_escape("text/html")
289 |> Formatter.linkify(options)
290 end
291
292 def format_input(text, "text/markdown", options) do
293 text
294 |> Formatter.mentions_escape(options)
295 |> Earmark.as_html!(%Earmark.Options{renderer: Pleroma.EarmarkRenderer})
296 |> Formatter.linkify(options)
297 |> Formatter.html_escape("text/html")
298 end
299
300 def make_note_data(%ActivityDraft{} = draft) do
301 %{
302 "type" => "Note",
303 "to" => draft.to,
304 "cc" => draft.cc,
305 "content" => draft.content_html,
306 "summary" => draft.summary,
307 "sensitive" => draft.sensitive,
308 "context" => draft.context,
309 "attachment" => draft.attachments,
310 "actor" => draft.user.ap_id,
311 "tag" => Keyword.values(draft.tags) |> Enum.uniq()
312 }
313 |> add_in_reply_to(draft.in_reply_to)
314 |> Map.merge(draft.extra)
315 end
316
317 defp add_in_reply_to(object, nil), do: object
318
319 defp add_in_reply_to(object, in_reply_to) do
320 with %Object{} = in_reply_to_object <- Object.normalize(in_reply_to) do
321 Map.put(object, "inReplyTo", in_reply_to_object.data["id"])
322 else
323 _ -> object
324 end
325 end
326
327 def format_naive_asctime(date) do
328 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
329 end
330
331 def format_asctime(date) do
332 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
333 end
334
335 def date_to_asctime(date) when is_binary(date) do
336 with {:ok, date, _offset} <- DateTime.from_iso8601(date) do
337 format_asctime(date)
338 else
339 _e ->
340 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
341 ""
342 end
343 end
344
345 def date_to_asctime(date) do
346 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
347 ""
348 end
349
350 def to_masto_date(%NaiveDateTime{} = date) do
351 date
352 |> NaiveDateTime.to_iso8601()
353 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
354 end
355
356 def to_masto_date(date) when is_binary(date) do
357 with {:ok, date} <- NaiveDateTime.from_iso8601(date) do
358 to_masto_date(date)
359 else
360 _ -> ""
361 end
362 end
363
364 def to_masto_date(_), do: ""
365
366 defp shortname(name) do
367 with max_length when max_length > 0 <-
368 Config.get([Pleroma.Upload, :filename_display_max_length], 30),
369 true <- String.length(name) > max_length do
370 String.slice(name, 0..max_length) <> "…"
371 else
372 _ -> name
373 end
374 end
375
376 @spec confirm_current_password(User.t(), String.t()) :: {:ok, User.t()} | {:error, String.t()}
377 def confirm_current_password(user, password) do
378 with %User{local: true} = db_user <- User.get_cached_by_id(user.id),
379 true <- AuthenticationPlug.checkpw(password, db_user.password_hash) do
380 {:ok, db_user}
381 else
382 _ -> {:error, dgettext("errors", "Invalid password.")}
383 end
384 end
385
386 def maybe_notify_to_recipients(
387 recipients,
388 %Activity{data: %{"to" => to, "type" => _type}} = _activity
389 ) do
390 recipients ++ to
391 end
392
393 def maybe_notify_to_recipients(recipients, _), do: recipients
394
395 def maybe_notify_mentioned_recipients(
396 recipients,
397 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
398 )
399 when type == "Create" do
400 object = Object.normalize(activity, false)
401
402 object_data =
403 cond do
404 not is_nil(object) ->
405 object.data
406
407 is_map(data["object"]) ->
408 data["object"]
409
410 true ->
411 %{}
412 end
413
414 tagged_mentions = maybe_extract_mentions(object_data)
415
416 recipients ++ tagged_mentions
417 end
418
419 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
420
421 # Do not notify subscribers if author is making a reply
422 def maybe_notify_subscribers(recipients, %Activity{
423 object: %Object{data: %{"inReplyTo" => _ap_id}}
424 }) do
425 recipients
426 end
427
428 def maybe_notify_subscribers(
429 recipients,
430 %Activity{data: %{"actor" => actor, "type" => type}} = activity
431 )
432 when type == "Create" do
433 with %User{} = user <- User.get_cached_by_ap_id(actor) do
434 subscriber_ids =
435 user
436 |> User.subscriber_users()
437 |> Enum.filter(&Visibility.visible_for_user?(activity, &1))
438 |> Enum.map(& &1.ap_id)
439
440 recipients ++ subscriber_ids
441 else
442 _e -> recipients
443 end
444 end
445
446 def maybe_notify_subscribers(recipients, _), do: recipients
447
448 def maybe_notify_followers(recipients, %Activity{data: %{"type" => "Move"}} = activity) do
449 with %User{} = user <- User.get_cached_by_ap_id(activity.actor) do
450 user
451 |> User.get_followers()
452 |> Enum.map(& &1.ap_id)
453 |> Enum.concat(recipients)
454 else
455 _e -> recipients
456 end
457 end
458
459 def maybe_notify_followers(recipients, _), do: recipients
460
461 def maybe_extract_mentions(%{"tag" => tag}) do
462 tag
463 |> Enum.filter(fn x -> is_map(x) && x["type"] == "Mention" end)
464 |> Enum.map(fn x -> x["href"] end)
465 |> Enum.uniq()
466 end
467
468 def maybe_extract_mentions(_), do: []
469
470 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
471
472 def make_report_content_html(comment) do
473 max_size = Config.get([:instance, :max_report_comment_size], 1000)
474
475 if String.length(comment) <= max_size do
476 {:ok, format_input(comment, "text/plain")}
477 else
478 {:error,
479 dgettext("errors", "Comment must be up to %{max_size} characters", max_size: max_size)}
480 end
481 end
482
483 def get_report_statuses(%User{ap_id: actor}, %{status_ids: status_ids})
484 when is_list(status_ids) do
485 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
486 end
487
488 def get_report_statuses(_, _), do: {:ok, nil}
489
490 # DEPRECATED mostly, context objects are now created at insertion time.
491 def context_to_conversation_id(context) do
492 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
493 id
494 else
495 _e ->
496 changeset = Object.context_mapping(context)
497
498 case Repo.insert(changeset) do
499 {:ok, %{id: id}} ->
500 id
501
502 # This should be solved by an upsert, but it seems ecto
503 # has problems accessing the constraint inside the jsonb.
504 {:error, _} ->
505 Object.get_cached_by_ap_id(context).id
506 end
507 end
508 end
509
510 def conversation_id_to_context(id) do
511 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
512 context
513 else
514 _e ->
515 {:error, dgettext("errors", "No such conversation")}
516 end
517 end
518
519 def validate_character_limit("" = _full_payload, [] = _attachments) do
520 {:error, dgettext("errors", "Cannot post an empty status without attachments")}
521 end
522
523 def validate_character_limit(full_payload, _attachments) do
524 limit = Config.get([:instance, :limit])
525 length = String.length(full_payload)
526
527 if length <= limit do
528 :ok
529 else
530 {:error, dgettext("errors", "The status is over the character limit")}
531 end
532 end
533 end