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 with true <- Pleroma.FlakeId.is_flake_id?(id),
28 %Activity{} = activity <- Activity.get_by_id_with_object(id) do
31 _ -> Activity.get_create_by_object_ap_id_with_object(id)
35 if activity.data["type"] == "Create" do
38 Activity.get_create_by_object_ap_id_with_object(activity.data["object"])
42 def get_replied_to_activity(""), do: nil
44 def get_replied_to_activity(id) when not is_nil(id) do
45 Activity.get_by_id(id)
48 def get_replied_to_activity(_), do: nil
50 def attachments_from_ids(%{"media_ids" => ids, "descriptions" => desc} = _) do
51 attachments_from_ids_descs(ids, desc)
54 def attachments_from_ids(%{"media_ids" => ids} = _) do
55 attachments_from_ids_no_descs(ids)
58 def attachments_from_ids(_), do: []
60 def attachments_from_ids_no_descs([]), do: []
62 def attachments_from_ids_no_descs(ids) do
63 Enum.map(ids, fn media_id ->
64 case Repo.get(Object, media_id) do
65 %Object{data: data} = _ -> data
72 def attachments_from_ids_descs([], _), do: []
74 def attachments_from_ids_descs(ids, descs_str) do
75 {_, descs} = Jason.decode(descs_str)
77 Enum.map(ids, fn media_id ->
78 case Repo.get(Object, media_id) do
79 %Object{data: data} = _ ->
80 Map.put(data, "name", descs[media_id])
89 @spec get_to_and_cc(User.t(), list(String.t()), Activity.t() | nil, String.t()) ::
90 {list(String.t()), list(String.t())}
91 def get_to_and_cc(user, mentioned_users, inReplyTo, "public") do
92 to = [Pleroma.Constants.as_public() | mentioned_users]
93 cc = [user.follower_address]
96 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
102 def get_to_and_cc(user, mentioned_users, inReplyTo, "unlisted") do
103 to = [user.follower_address | mentioned_users]
104 cc = [Pleroma.Constants.as_public()]
107 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
113 def get_to_and_cc(user, mentioned_users, inReplyTo, "private") do
114 {to, cc} = get_to_and_cc(user, mentioned_users, inReplyTo, "direct")
115 {[user.follower_address | to], cc}
118 def get_to_and_cc(_user, mentioned_users, inReplyTo, "direct") do
120 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
122 {mentioned_users, []}
126 def get_to_and_cc(_user, mentions, _inReplyTo, {:list, _}), do: {mentions, []}
128 def get_addressed_users(_, to) when is_list(to) do
129 User.get_ap_ids_by_nicknames(to)
132 def get_addressed_users(mentioned_users, _), do: mentioned_users
134 def maybe_add_list_data(activity_params, user, {:list, list_id}) do
135 case Pleroma.List.get(list_id, user) do
136 %Pleroma.List{} = list ->
138 |> put_in([:additional, "bcc"], [list.ap_id])
139 |> put_in([:additional, "listMessage"], list.ap_id)
140 |> put_in([:object, "listMessage"], list.ap_id)
147 def maybe_add_list_data(activity_params, _, _), do: activity_params
149 def make_poll_data(%{"poll" => %{"options" => options, "expires_in" => expires_in}} = data)
150 when is_list(options) do
151 %{max_expiration: max_expiration, min_expiration: min_expiration} =
152 limits = Pleroma.Config.get([:instance, :poll_limits])
154 # XXX: There is probably a cleaner way of doing this
156 # In some cases mastofe sends out strings instead of integers
157 expires_in = if is_binary(expires_in), do: String.to_integer(expires_in), else: expires_in
159 if Enum.count(options) > limits.max_options do
160 raise ArgumentError, message: "Poll can't contain more than #{limits.max_options} options"
164 Enum.map_reduce(options, %{}, fn option, emoji ->
165 if String.length(option) > limits.max_option_chars do
168 "Poll options cannot be longer than #{limits.max_option_chars} characters each"
174 "replies" => %{"type" => "Collection", "totalItems" => 0}
175 }, Map.merge(emoji, Formatter.get_emoji_map(option))}
179 expires_in when expires_in > max_expiration ->
180 raise ArgumentError, message: "Expiration date is too far in the future"
182 expires_in when expires_in < min_expiration ->
183 raise ArgumentError, message: "Expiration date is too soon"
190 NaiveDateTime.utc_now()
191 |> NaiveDateTime.add(expires_in)
192 |> NaiveDateTime.to_iso8601()
195 if Pleroma.Web.ControllerHelper.truthy_param?(data["poll"]["multiple"]) do
196 %{"type" => "Question", "anyOf" => poll, "closed" => end_time}
198 %{"type" => "Question", "oneOf" => poll, "closed" => end_time}
203 e in ArgumentError -> e.message
207 def make_poll_data(%{"poll" => poll}) when is_map(poll) do
211 def make_poll_data(_data) do
215 def make_content_html(
221 no_attachment_links =
223 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
224 |> Kernel.in([true, "true"])
226 content_type = get_content_type(data["content_type"])
229 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
236 |> format_input(content_type, options)
237 |> maybe_add_attachments(attachments, no_attachment_links)
238 |> maybe_add_nsfw_tag(data)
241 defp get_content_type(content_type) do
242 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
249 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
250 when sensitive in [true, "True", "true", "1"] do
251 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
254 defp maybe_add_nsfw_tag(data, _), do: data
256 def make_context(%Activity{data: %{"context" => context}}), do: context
257 def make_context(_), do: Utils.generate_context_id()
259 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
261 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
262 text = add_attachments(text, attachments)
263 {text, mentions, tags}
266 def add_attachments(text, attachments) do
267 attachment_text = Enum.map(attachments, &build_attachment_link/1)
268 Enum.join([text | attachment_text], "<br>")
271 defp build_attachment_link(%{"url" => [%{"href" => href} | _]} = attachment) do
272 name = attachment["name"] || URI.decode(Path.basename(href))
273 href = MediaProxy.url(href)
274 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
277 defp build_attachment_link(_), do: ""
279 def format_input(text, format, options \\ [])
282 Formatting text to plain text.
284 def format_input(text, "text/plain", options) do
286 |> Formatter.html_escape("text/plain")
287 |> Formatter.linkify(options)
288 |> (fn {text, mentions, tags} ->
289 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
294 Formatting text as BBCode.
296 def format_input(text, "text/bbcode", options) do
298 |> String.replace(~r/\r/, "")
299 |> Formatter.html_escape("text/plain")
301 |> (fn {:ok, html} -> html end).()
302 |> Formatter.linkify(options)
306 Formatting text to html.
308 def format_input(text, "text/html", options) do
310 |> Formatter.html_escape("text/html")
311 |> Formatter.linkify(options)
315 Formatting text to markdown.
317 def format_input(text, "text/markdown", options) do
319 |> Formatter.mentions_escape(options)
320 |> Earmark.as_html!()
321 |> Formatter.linkify(options)
322 |> Formatter.html_escape("text/html")
342 "content" => content_html,
344 "sensitive" => !Enum.member?(["false", "False", "0", false], sensitive),
345 "context" => context,
346 "attachment" => attachments,
348 "tag" => Keyword.values(tags) |> Enum.uniq()
350 |> add_in_reply_to(in_reply_to)
354 defp add_in_reply_to(object, nil), do: object
356 defp add_in_reply_to(object, in_reply_to) do
357 with %Object{} = in_reply_to_object <- Object.normalize(in_reply_to) do
358 Map.put(object, "inReplyTo", in_reply_to_object.data["id"])
364 def format_naive_asctime(date) do
365 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
368 def format_asctime(date) do
369 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
372 def date_to_asctime(date) when is_binary(date) do
373 with {:ok, date, _offset} <- DateTime.from_iso8601(date) do
377 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
382 def date_to_asctime(date) do
383 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
387 def to_masto_date(%NaiveDateTime{} = date) do
389 |> NaiveDateTime.to_iso8601()
390 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
393 def to_masto_date(date) when is_binary(date) do
394 with {:ok, date} <- NaiveDateTime.from_iso8601(date) do
401 def to_masto_date(_), do: ""
403 defp shortname(name) do
404 if String.length(name) < 30 do
407 String.slice(name, 0..30) <> "…"
411 def confirm_current_password(user, password) do
412 with %User{local: true} = db_user <- User.get_cached_by_id(user.id),
413 true <- AuthenticationPlug.checkpw(password, db_user.password_hash) do
416 _ -> {:error, dgettext("errors", "Invalid password.")}
420 def emoji_from_profile(%{info: _info} = user) do
421 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
422 |> Enum.map(fn {shortcode, url, _} ->
425 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
426 "name" => ":#{shortcode}:"
431 def maybe_notify_to_recipients(
433 %Activity{data: %{"to" => to, "type" => _type}} = _activity
438 def maybe_notify_mentioned_recipients(
440 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
442 when type == "Create" do
443 object = Object.normalize(activity)
447 not is_nil(object) ->
450 is_map(data["object"]) ->
457 tagged_mentions = maybe_extract_mentions(object_data)
459 recipients ++ tagged_mentions
462 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
464 # Do not notify subscribers if author is making a reply
465 def maybe_notify_subscribers(recipients, %Activity{
466 object: %Object{data: %{"inReplyTo" => _ap_id}}
471 def maybe_notify_subscribers(
473 %Activity{data: %{"actor" => actor, "type" => type}} = activity
475 when type == "Create" do
476 with %User{} = user <- User.get_cached_by_ap_id(actor) do
479 |> User.subscribers()
480 |> Enum.filter(&Visibility.visible_for_user?(activity, &1))
481 |> Enum.map(& &1.ap_id)
483 recipients ++ subscriber_ids
487 def maybe_notify_subscribers(recipients, _), do: recipients
489 def maybe_extract_mentions(%{"tag" => tag}) do
491 |> Enum.filter(fn x -> is_map(x) && x["type"] == "Mention" end)
492 |> Enum.map(fn x -> x["href"] end)
496 def maybe_extract_mentions(_), do: []
498 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
500 def make_report_content_html(comment) do
501 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
503 if String.length(comment) <= max_size do
504 {:ok, format_input(comment, "text/plain")}
507 dgettext("errors", "Comment must be up to %{max_size} characters", max_size: max_size)}
511 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
512 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
515 def get_report_statuses(_, _), do: {:ok, nil}
517 # DEPRECATED mostly, context objects are now created at insertion time.
518 def context_to_conversation_id(context) do
519 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
523 changeset = Object.context_mapping(context)
525 case Repo.insert(changeset) do
529 # This should be solved by an upsert, but it seems ecto
530 # has problems accessing the constraint inside the jsonb.
532 Object.get_cached_by_ap_id(context).id
537 def conversation_id_to_context(id) do
538 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
542 {:error, dgettext("errors", "No such conversation")}
546 def make_answer_data(%User{ap_id: ap_id}, object, name) do
550 "cc" => [object.data["actor"]],
553 "inReplyTo" => object.data["id"]
557 def validate_character_limit(full_payload, attachments, limit) do
558 length = String.length(full_payload)
561 if length > 0 or Enum.count(attachments) > 0 do
564 {:error, dgettext("errors", "Cannot post an empty status without attachments")}
567 {:error, dgettext("errors", "The status is over the character limit")}