1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.CommonAPI.Utils do
6 import Pleroma.Web.Gettext
8 alias Calendar.Strftime
11 alias Pleroma.Formatter
13 alias Pleroma.Plugs.AuthenticationPlug
16 alias Pleroma.Web.ActivityPub.Utils
17 alias Pleroma.Web.ActivityPub.Visibility
18 alias Pleroma.Web.Endpoint
19 alias Pleroma.Web.MediaProxy
22 require Pleroma.Constants
24 # This is a hack for twidere.
25 def get_by_id_or_ap_id(id) do
27 Activity.get_by_id_with_object(id) || Activity.get_create_by_object_ap_id_with_object(id)
30 if activity.data["type"] == "Create" do
33 Activity.get_create_by_object_ap_id_with_object(activity.data["object"])
37 def get_replied_to_activity(""), do: nil
39 def get_replied_to_activity(id) when not is_nil(id) do
40 Activity.get_by_id(id)
43 def get_replied_to_activity(_), do: nil
45 def attachments_from_ids(data) do
46 if Map.has_key?(data, "descriptions") do
47 attachments_from_ids_descs(data["media_ids"], data["descriptions"])
49 attachments_from_ids_no_descs(data["media_ids"])
53 def attachments_from_ids_no_descs(ids) do
54 Enum.map(ids || [], fn media_id ->
55 Repo.get(Object, media_id).data
59 def attachments_from_ids_descs(ids, descs_str) do
60 {_, descs} = Jason.decode(descs_str)
62 Enum.map(ids || [], fn media_id ->
63 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
67 @spec get_to_and_cc(User.t(), list(String.t()), Activity.t() | nil, String.t()) ::
68 {list(String.t()), list(String.t())}
69 def get_to_and_cc(user, mentioned_users, inReplyTo, "public") do
70 to = [Pleroma.Constants.as_public() | mentioned_users]
71 cc = [user.follower_address]
74 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
80 def get_to_and_cc(user, mentioned_users, inReplyTo, "unlisted") do
81 to = [user.follower_address | mentioned_users]
82 cc = [Pleroma.Constants.as_public()]
85 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
91 def get_to_and_cc(user, mentioned_users, inReplyTo, "private") do
92 {to, cc} = get_to_and_cc(user, mentioned_users, inReplyTo, "direct")
93 {[user.follower_address | to], cc}
96 def get_to_and_cc(_user, mentioned_users, inReplyTo, "direct") do
98 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
100 {mentioned_users, []}
104 def get_to_and_cc(_user, mentions, _inReplyTo, {:list, _}), do: {mentions, []}
106 def get_addressed_users(_, to) when is_list(to) do
107 User.get_ap_ids_by_nicknames(to)
110 def get_addressed_users(mentioned_users, _), do: mentioned_users
112 def maybe_add_list_data(activity_params, user, {:list, list_id}) do
113 case Pleroma.List.get(list_id, user) do
114 %Pleroma.List{} = list ->
116 |> put_in([:additional, "bcc"], [list.ap_id])
117 |> put_in([:additional, "listMessage"], list.ap_id)
118 |> put_in([:object, "listMessage"], list.ap_id)
125 def maybe_add_list_data(activity_params, _, _), do: activity_params
127 def make_poll_data(%{"poll" => %{"options" => options, "expires_in" => expires_in}} = data)
128 when is_list(options) do
129 %{max_expiration: max_expiration, min_expiration: min_expiration} =
130 limits = Pleroma.Config.get([:instance, :poll_limits])
132 # XXX: There is probably a cleaner way of doing this
134 # In some cases mastofe sends out strings instead of integers
135 expires_in = if is_binary(expires_in), do: String.to_integer(expires_in), else: expires_in
137 if Enum.count(options) > limits.max_options do
138 raise ArgumentError, message: "Poll can't contain more than #{limits.max_options} options"
142 Enum.map_reduce(options, %{}, fn option, emoji ->
143 if String.length(option) > limits.max_option_chars do
146 "Poll options cannot be longer than #{limits.max_option_chars} characters each"
152 "replies" => %{"type" => "Collection", "totalItems" => 0}
153 }, Map.merge(emoji, Formatter.get_emoji_map(option))}
157 expires_in when expires_in > max_expiration ->
158 raise ArgumentError, message: "Expiration date is too far in the future"
160 expires_in when expires_in < min_expiration ->
161 raise ArgumentError, message: "Expiration date is too soon"
168 NaiveDateTime.utc_now()
169 |> NaiveDateTime.add(expires_in)
170 |> NaiveDateTime.to_iso8601()
173 if Pleroma.Web.ControllerHelper.truthy_param?(data["poll"]["multiple"]) do
174 %{"type" => "Question", "anyOf" => poll, "closed" => end_time}
176 %{"type" => "Question", "oneOf" => poll, "closed" => end_time}
181 e in ArgumentError -> e.message
185 def make_poll_data(%{"poll" => poll}) when is_map(poll) do
189 def make_poll_data(_data) do
193 def make_content_html(
199 no_attachment_links =
201 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
202 |> Kernel.in([true, "true"])
204 content_type = get_content_type(data["content_type"])
207 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
214 |> format_input(content_type, options)
215 |> maybe_add_attachments(attachments, no_attachment_links)
216 |> maybe_add_nsfw_tag(data)
219 defp get_content_type(content_type) do
220 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
227 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
228 when sensitive in [true, "True", "true", "1"] do
229 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
232 defp maybe_add_nsfw_tag(data, _), do: data
234 def make_context(%Activity{data: %{"context" => context}}), do: context
235 def make_context(_), do: Utils.generate_context_id()
237 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
239 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
240 text = add_attachments(text, attachments)
241 {text, mentions, tags}
244 def add_attachments(text, attachments) do
246 Enum.map(attachments, fn
247 %{"url" => [%{"href" => href} | _]} = attachment ->
248 name = attachment["name"] || URI.decode(Path.basename(href))
249 href = MediaProxy.url(href)
250 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
256 Enum.join([text | attachment_text], "<br>")
259 def format_input(text, format, options \\ [])
262 Formatting text to plain text.
264 def format_input(text, "text/plain", options) do
266 |> Formatter.html_escape("text/plain")
267 |> Formatter.linkify(options)
268 |> (fn {text, mentions, tags} ->
269 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
274 Formatting text as BBCode.
276 def format_input(text, "text/bbcode", options) do
278 |> String.replace(~r/\r/, "")
279 |> Formatter.html_escape("text/plain")
281 |> (fn {:ok, html} -> html end).()
282 |> Formatter.linkify(options)
286 Formatting text to html.
288 def format_input(text, "text/html", options) do
290 |> Formatter.html_escape("text/html")
291 |> Formatter.linkify(options)
295 Formatting text to markdown.
297 def format_input(text, "text/markdown", options) do
299 |> Formatter.mentions_escape(options)
300 |> Earmark.as_html!()
301 |> Formatter.linkify(options)
302 |> Formatter.html_escape("text/html")
322 "content" => content_html,
324 "sensitive" => !Enum.member?(["false", "False", "0", false], sensitive),
325 "context" => context,
326 "attachment" => attachments,
328 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
332 with false <- is_nil(in_reply_to),
333 %Object{} = in_reply_to_object <- Object.normalize(in_reply_to) do
334 Map.put(object, "inReplyTo", in_reply_to_object.data["id"])
339 Map.merge(object, merge)
342 def format_naive_asctime(date) do
343 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
346 def format_asctime(date) do
347 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
350 def date_to_asctime(date) when is_binary(date) do
351 with {:ok, date, _offset} <- DateTime.from_iso8601(date) do
355 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
360 def date_to_asctime(date) do
361 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
365 def to_masto_date(%NaiveDateTime{} = date) do
367 |> NaiveDateTime.to_iso8601()
368 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
371 def to_masto_date(date) do
374 |> NaiveDateTime.from_iso8601!()
375 |> NaiveDateTime.to_iso8601()
376 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
382 defp shortname(name) do
383 if String.length(name) < 30 do
386 String.slice(name, 0..30) <> "…"
390 def confirm_current_password(user, password) do
391 with %User{local: true} = db_user <- User.get_cached_by_id(user.id),
392 true <- AuthenticationPlug.checkpw(password, db_user.password_hash) do
395 _ -> {:error, dgettext("errors", "Invalid password.")}
399 def emoji_from_profile(%{info: _info} = user) do
400 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
401 |> Enum.map(fn {shortcode, url, _} ->
404 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
405 "name" => ":#{shortcode}:"
410 def maybe_notify_to_recipients(
412 %Activity{data: %{"to" => to, "type" => _type}} = _activity
417 def maybe_notify_mentioned_recipients(
419 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
421 when type == "Create" do
422 object = Object.normalize(activity)
429 is_map(data["object"]) ->
436 tagged_mentions = maybe_extract_mentions(object_data)
438 recipients ++ tagged_mentions
441 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
443 # Do not notify subscribers if author is making a reply
444 def maybe_notify_subscribers(recipients, %Activity{
445 object: %Object{data: %{"inReplyTo" => _ap_id}}
450 def maybe_notify_subscribers(
452 %Activity{data: %{"actor" => actor, "type" => type}} = activity
454 when type == "Create" do
455 with %User{} = user <- User.get_cached_by_ap_id(actor) do
458 |> User.subscribers()
459 |> Enum.filter(&Visibility.visible_for_user?(activity, &1))
460 |> Enum.map(& &1.ap_id)
462 recipients ++ subscriber_ids
466 def maybe_notify_subscribers(recipients, _), do: recipients
468 def maybe_extract_mentions(%{"tag" => tag}) do
470 |> Enum.filter(fn x -> is_map(x) end)
471 |> Enum.filter(fn x -> x["type"] == "Mention" end)
472 |> Enum.map(fn x -> x["href"] end)
475 def maybe_extract_mentions(_), do: []
477 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
479 def make_report_content_html(comment) do
480 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
482 if String.length(comment) <= max_size do
483 {:ok, format_input(comment, "text/plain")}
486 dgettext("errors", "Comment must be up to %{max_size} characters", max_size: max_size)}
490 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
491 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
494 def get_report_statuses(_, _), do: {:ok, nil}
496 # DEPRECATED mostly, context objects are now created at insertion time.
497 def context_to_conversation_id(context) do
498 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
502 changeset = Object.context_mapping(context)
504 case Repo.insert(changeset) do
508 # This should be solved by an upsert, but it seems ecto
509 # has problems accessing the constraint inside the jsonb.
511 Object.get_cached_by_ap_id(context).id
516 def conversation_id_to_context(id) do
517 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
521 {:error, dgettext("errors", "No such conversation")}
525 def make_answer_data(%User{ap_id: ap_id}, object, name) do
529 "cc" => [object.data["actor"]],
532 "inReplyTo" => object.data["id"]
536 def validate_character_limit(full_payload, attachments, limit) do
537 length = String.length(full_payload)
540 if length > 0 or Enum.count(attachments) > 0 do
543 {:error, dgettext("errors", "Cannot post an empty status without attachments")}
546 {:error, dgettext("errors", "The status is over the character limit")}