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
23 # This is a hack for twidere.
24 def get_by_id_or_ap_id(id) do
26 Activity.get_by_id_with_object(id) || Activity.get_create_by_object_ap_id_with_object(id)
29 if activity.data["type"] == "Create" do
32 Activity.get_create_by_object_ap_id_with_object(activity.data["object"])
36 def get_replied_to_activity(""), do: nil
38 def get_replied_to_activity(id) when not is_nil(id) do
39 Activity.get_by_id(id)
42 def get_replied_to_activity(_), do: nil
44 def attachments_from_ids(data) do
45 if Map.has_key?(data, "descriptions") do
46 attachments_from_ids_descs(data["media_ids"], data["descriptions"])
48 attachments_from_ids_no_descs(data["media_ids"])
52 def attachments_from_ids_no_descs(ids) do
53 Enum.map(ids || [], fn media_id ->
54 Repo.get(Object, media_id).data
58 def attachments_from_ids_descs(ids, descs_str) do
59 {_, descs} = Jason.decode(descs_str)
61 Enum.map(ids || [], fn media_id ->
62 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
66 @spec get_to_and_cc(User.t(), list(String.t()), Activity.t() | nil, String.t()) ::
67 {list(String.t()), list(String.t())}
68 def get_to_and_cc(user, mentioned_users, inReplyTo, "public") do
69 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
70 cc = [user.follower_address]
73 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
79 def get_to_and_cc(user, mentioned_users, inReplyTo, "unlisted") do
80 to = [user.follower_address | mentioned_users]
81 cc = ["https://www.w3.org/ns/activitystreams#Public"]
84 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
90 def get_to_and_cc(user, mentioned_users, inReplyTo, "private") do
91 {to, cc} = get_to_and_cc(user, mentioned_users, inReplyTo, "direct")
92 {[user.follower_address | to], cc}
95 def get_to_and_cc(_user, mentioned_users, inReplyTo, "direct") do
97 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
103 def get_to_and_cc(_user, mentions, _inReplyTo, {:list, _}), do: {mentions, []}
105 def get_addressed_users(_, to) when is_list(to) do
106 User.get_ap_ids_by_nicknames(to)
109 def get_addressed_users(mentioned_users, _), do: mentioned_users
111 def maybe_add_list_data(activity_params, user, {:list, list_id}) do
112 case Pleroma.List.get(list_id, user) do
113 %Pleroma.List{} = list ->
115 |> put_in([:additional, "bcc"], [list.ap_id])
116 |> put_in([:additional, "listMessage"], list.ap_id)
117 |> put_in([:object, "listMessage"], list.ap_id)
124 def maybe_add_list_data(activity_params, _, _), do: activity_params
126 def make_poll_data(%{"poll" => %{"options" => options, "expires_in" => expires_in}} = data)
127 when is_list(options) do
128 %{max_expiration: max_expiration, min_expiration: min_expiration} =
129 limits = Pleroma.Config.get([:instance, :poll_limits])
131 # XXX: There is probably a cleaner way of doing this
133 # In some cases mastofe sends out strings instead of integers
134 expires_in = if is_binary(expires_in), do: String.to_integer(expires_in), else: expires_in
136 if Enum.count(options) > limits.max_options do
137 raise ArgumentError, message: "Poll can't contain more than #{limits.max_options} options"
141 Enum.map_reduce(options, %{}, fn option, emoji ->
142 if String.length(option) > limits.max_option_chars do
145 "Poll options cannot be longer than #{limits.max_option_chars} characters each"
151 "replies" => %{"type" => "Collection", "totalItems" => 0}
152 }, Map.merge(emoji, Formatter.get_emoji_map(option))}
156 expires_in when expires_in > max_expiration ->
157 raise ArgumentError, message: "Expiration date is too far in the future"
159 expires_in when expires_in < min_expiration ->
160 raise ArgumentError, message: "Expiration date is too soon"
167 NaiveDateTime.utc_now()
168 |> NaiveDateTime.add(expires_in)
169 |> NaiveDateTime.to_iso8601()
172 if Pleroma.Web.ControllerHelper.truthy_param?(data["poll"]["multiple"]) do
173 %{"type" => "Question", "anyOf" => poll, "closed" => end_time}
175 %{"type" => "Question", "oneOf" => poll, "closed" => end_time}
180 e in ArgumentError -> e.message
184 def make_poll_data(%{"poll" => poll}) when is_map(poll) do
188 def make_poll_data(_data) do
192 def make_content_html(
198 no_attachment_links =
200 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
201 |> Kernel.in([true, "true"])
203 content_type = get_content_type(data["content_type"])
206 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
213 |> format_input(content_type, options)
214 |> maybe_add_attachments(attachments, no_attachment_links)
215 |> maybe_add_nsfw_tag(data)
218 defp get_content_type(content_type) do
219 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
226 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
227 when sensitive in [true, "True", "true", "1"] do
228 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
231 defp maybe_add_nsfw_tag(data, _), do: data
233 def make_context(%Activity{data: %{"context" => context}}), do: context
234 def make_context(_), do: Utils.generate_context_id()
236 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
238 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
239 text = add_attachments(text, attachments)
240 {text, mentions, tags}
243 def add_attachments(text, attachments) do
245 Enum.map(attachments, fn
246 %{"url" => [%{"href" => href} | _]} = attachment ->
247 name = attachment["name"] || URI.decode(Path.basename(href))
248 href = MediaProxy.url(href)
249 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
255 Enum.join([text | attachment_text], "<br>")
258 def format_input(text, format, options \\ [])
261 Formatting text to plain text.
263 def format_input(text, "text/plain", options) do
265 |> Formatter.html_escape("text/plain")
266 |> Formatter.linkify(options)
267 |> (fn {text, mentions, tags} ->
268 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
273 Formatting text as BBCode.
275 def format_input(text, "text/bbcode", options) do
277 |> String.replace(~r/\r/, "")
278 |> Formatter.html_escape("text/plain")
280 |> (fn {:ok, html} -> html end).()
281 |> Formatter.linkify(options)
285 Formatting text to html.
287 def format_input(text, "text/html", options) do
289 |> Formatter.html_escape("text/html")
290 |> Formatter.linkify(options)
294 Formatting text to markdown.
296 def format_input(text, "text/markdown", options) do
298 |> Formatter.mentions_escape(options)
299 |> Earmark.as_html!()
300 |> Formatter.linkify(options)
301 |> Formatter.html_escape("text/html")
321 "content" => content_html,
323 "sensitive" => !Enum.member?(["false", "False", "0", false], sensitive),
324 "context" => context,
325 "attachment" => attachments,
327 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
331 with false <- is_nil(in_reply_to),
332 %Object{} = in_reply_to_object <- Object.normalize(in_reply_to) do
333 Map.put(object, "inReplyTo", in_reply_to_object.data["id"])
338 Map.merge(object, merge)
341 def format_naive_asctime(date) do
342 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
345 def format_asctime(date) do
346 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
349 def date_to_asctime(date) when is_binary(date) do
350 with {:ok, date, _offset} <- DateTime.from_iso8601(date) do
354 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
359 def date_to_asctime(date) do
360 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
364 def to_masto_date(%NaiveDateTime{} = date) do
366 |> NaiveDateTime.to_iso8601()
367 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
370 def to_masto_date(date) do
373 |> NaiveDateTime.from_iso8601!()
374 |> NaiveDateTime.to_iso8601()
375 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
381 defp shortname(name) do
382 if String.length(name) < 30 do
385 String.slice(name, 0..30) <> "…"
389 def confirm_current_password(user, password) do
390 with %User{local: true} = db_user <- User.get_cached_by_id(user.id),
391 true <- AuthenticationPlug.checkpw(password, db_user.password_hash) do
394 _ -> {:error, dgettext("errors", "Invalid password.")}
398 def emoji_from_profile(%{info: _info} = user) do
399 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
400 |> Enum.map(fn {shortcode, url, _} ->
403 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
404 "name" => ":#{shortcode}:"
409 def maybe_notify_to_recipients(
411 %Activity{data: %{"to" => to, "type" => _type}} = _activity
416 def maybe_notify_mentioned_recipients(
418 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
420 when type == "Create" do
421 object = Object.normalize(activity)
428 is_map(data["object"]) ->
435 tagged_mentions = maybe_extract_mentions(object_data)
437 recipients ++ tagged_mentions
440 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
442 # Do not notify subscribers if author is making a reply
443 def maybe_notify_subscribers(recipients, %Activity{
444 object: %Object{data: %{"inReplyTo" => _ap_id}}
449 def maybe_notify_subscribers(
451 %Activity{data: %{"actor" => actor, "type" => type}} = activity
453 when type == "Create" do
454 with %User{} = user <- User.get_cached_by_ap_id(actor) do
457 |> User.subscribers()
458 |> Enum.filter(&Visibility.visible_for_user?(activity, &1))
459 |> Enum.map(& &1.ap_id)
461 recipients ++ subscriber_ids
465 def maybe_notify_subscribers(recipients, _), do: recipients
467 def maybe_extract_mentions(%{"tag" => tag}) do
469 |> Enum.filter(fn x -> is_map(x) end)
470 |> Enum.filter(fn x -> x["type"] == "Mention" end)
471 |> Enum.map(fn x -> x["href"] end)
474 def maybe_extract_mentions(_), do: []
476 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
478 def make_report_content_html(comment) do
479 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
481 if String.length(comment) <= max_size do
482 {:ok, format_input(comment, "text/plain")}
485 dgettext("errors", "Comment must be up to %{max_size} characters", max_size: max_size)}
489 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
490 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
493 def get_report_statuses(_, _), do: {:ok, nil}
495 # DEPRECATED mostly, context objects are now created at insertion time.
496 def context_to_conversation_id(context) do
497 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
501 changeset = Object.context_mapping(context)
503 case Repo.insert(changeset) do
507 # This should be solved by an upsert, but it seems ecto
508 # has problems accessing the constraint inside the jsonb.
510 Object.get_cached_by_ap_id(context).id
515 def conversation_id_to_context(id) do
516 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
520 {:error, dgettext("errors", "No such conversation")}
524 def make_answer_data(%User{ap_id: ap_id}, object, name) do
528 "cc" => [object.data["actor"]],
531 "inReplyTo" => object.data["id"]
535 def validate_character_limit(full_payload, attachments, limit) do
536 length = String.length(full_payload)
539 if length > 0 or Enum.count(attachments) > 0 do
542 {:error, dgettext("errors", "Cannot post an empty status without attachments")}
545 {:error, dgettext("errors", "The status is over the character limit")}