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 alias Calendar.Strftime
10 alias Pleroma.Formatter
14 alias Pleroma.Web.ActivityPub.Utils
15 alias Pleroma.Web.ActivityPub.Visibility
16 alias Pleroma.Web.Endpoint
17 alias Pleroma.Web.MediaProxy
21 # This is a hack for twidere.
22 def get_by_id_or_ap_id(id) do
24 Activity.get_by_id_with_object(id) || Activity.get_create_by_object_ap_id_with_object(id)
27 if activity.data["type"] == "Create" do
30 Activity.get_create_by_object_ap_id_with_object(activity.data["object"])
34 def get_replied_to_activity(""), do: nil
36 def get_replied_to_activity(id) when not is_nil(id) do
37 Activity.get_by_id(id)
40 def get_replied_to_activity(_), do: nil
42 def attachments_from_ids(data) do
43 if Map.has_key?(data, "descriptions") do
44 attachments_from_ids_descs(data["media_ids"], data["descriptions"])
46 attachments_from_ids_no_descs(data["media_ids"])
50 def attachments_from_ids_no_descs(ids) do
51 Enum.map(ids || [], fn media_id ->
52 Repo.get(Object, media_id).data
56 def attachments_from_ids_descs(ids, descs_str) do
57 {_, descs} = Jason.decode(descs_str)
59 Enum.map(ids || [], fn media_id ->
60 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
64 @spec get_to_and_cc(User.t(), list(String.t()), Activity.t() | nil, String.t()) ::
65 {list(String.t()), list(String.t())}
66 def get_to_and_cc(user, mentioned_users, inReplyTo, "public") do
67 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
68 cc = [user.follower_address]
71 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
77 def get_to_and_cc(user, mentioned_users, inReplyTo, "unlisted") do
78 to = [user.follower_address | mentioned_users]
79 cc = ["https://www.w3.org/ns/activitystreams#Public"]
82 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
88 def get_to_and_cc(user, mentioned_users, inReplyTo, "private") do
89 {to, cc} = get_to_and_cc(user, mentioned_users, inReplyTo, "direct")
90 {[user.follower_address | to], cc}
93 def get_to_and_cc(_user, mentioned_users, inReplyTo, "direct") do
95 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
101 def get_addressed_users(_, to) when is_list(to) do
102 User.get_ap_ids_by_nicknames(to)
105 def get_addressed_users(mentioned_users, _), do: mentioned_users
107 def make_poll_data(%{"poll" => %{"options" => options, "expires_in" => expires_in}} = data)
108 when is_list(options) do
109 %{max_expiration: max_expiration, min_expiration: min_expiration} =
110 limits = Pleroma.Config.get([:instance, :poll_limits])
112 # XXX: There is probably a cleaner way of doing this
114 # In some cases mastofe sends out strings instead of integers
115 expires_in = if is_binary(expires_in), do: String.to_integer(expires_in), else: expires_in
117 if Enum.count(options) > limits.max_options do
118 raise ArgumentError, message: "Poll can't contain more than #{limits.max_options} options"
122 Enum.map_reduce(options, %{}, fn option, emoji ->
123 if String.length(option) > limits.max_option_chars do
126 "Poll options cannot be longer than #{limits.max_option_chars} characters each"
132 "replies" => %{"type" => "Collection", "totalItems" => 0}
133 }, Map.merge(emoji, Formatter.get_emoji_map(option))}
137 expires_in when expires_in > max_expiration ->
138 raise ArgumentError, message: "Expiration date is too far in the future"
140 expires_in when expires_in < min_expiration ->
141 raise ArgumentError, message: "Expiration date is too soon"
148 NaiveDateTime.utc_now()
149 |> NaiveDateTime.add(expires_in)
150 |> NaiveDateTime.to_iso8601()
153 if Pleroma.Web.ControllerHelper.truthy_param?(data["poll"]["multiple"]) do
154 %{"type" => "Question", "anyOf" => poll, "closed" => end_time}
156 %{"type" => "Question", "oneOf" => poll, "closed" => end_time}
161 e in ArgumentError -> e.message
165 def make_poll_data(%{"poll" => poll}) when is_map(poll) do
169 def make_poll_data(_data) do
173 def make_content_html(
179 no_attachment_links =
181 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
182 |> Kernel.in([true, "true"])
184 content_type = get_content_type(data["content_type"])
187 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
194 |> format_input(content_type, options)
195 |> maybe_add_attachments(attachments, no_attachment_links)
196 |> maybe_add_nsfw_tag(data)
199 defp get_content_type(content_type) do
200 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
207 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
208 when sensitive in [true, "True", "true", "1"] do
209 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
212 defp maybe_add_nsfw_tag(data, _), do: data
214 def make_context(%Activity{data: %{"context" => context}}), do: context
215 def make_context(_), do: Utils.generate_context_id()
217 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
219 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
220 text = add_attachments(text, attachments)
221 {text, mentions, tags}
224 def add_attachments(text, attachments) do
226 Enum.map(attachments, fn
227 %{"url" => [%{"href" => href} | _]} = attachment ->
228 name = attachment["name"] || URI.decode(Path.basename(href))
229 href = MediaProxy.url(href)
230 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
236 Enum.join([text | attachment_text], "<br>")
239 def format_input(text, format, options \\ [])
242 Formatting text to plain text.
244 def format_input(text, "text/plain", options) do
246 |> Formatter.html_escape("text/plain")
247 |> Formatter.linkify(options)
248 |> (fn {text, mentions, tags} ->
249 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
254 Formatting text as BBCode.
256 def format_input(text, "text/bbcode", options) do
258 |> String.replace(~r/\r/, "")
259 |> Formatter.html_escape("text/plain")
261 |> (fn {:ok, html} -> html end).()
262 |> Formatter.linkify(options)
266 Formatting text to html.
268 def format_input(text, "text/html", options) do
270 |> Formatter.html_escape("text/html")
271 |> Formatter.linkify(options)
275 Formatting text to markdown.
277 def format_input(text, "text/markdown", options) do
279 |> Formatter.mentions_escape(options)
280 |> Earmark.as_html!()
281 |> Formatter.linkify(options)
282 |> Formatter.html_escape("text/html")
302 "content" => content_html,
304 "sensitive" => !Enum.member?(["false", "False", "0", false], sensitive),
305 "context" => context,
306 "attachment" => attachments,
308 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
312 with false <- is_nil(in_reply_to),
313 %Object{} = in_reply_to_object <- Object.normalize(in_reply_to) do
314 Map.put(object, "inReplyTo", in_reply_to_object.data["id"])
319 Map.merge(object, merge)
322 def format_naive_asctime(date) do
323 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
326 def format_asctime(date) do
327 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
330 def date_to_asctime(date) when is_binary(date) do
331 with {:ok, date, _offset} <- DateTime.from_iso8601(date) do
335 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
340 def date_to_asctime(date) do
341 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
345 def to_masto_date(%NaiveDateTime{} = date) do
347 |> NaiveDateTime.to_iso8601()
348 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
351 def to_masto_date(date) do
354 |> NaiveDateTime.from_iso8601!()
355 |> NaiveDateTime.to_iso8601()
356 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
362 defp shortname(name) do
363 if String.length(name) < 30 do
366 String.slice(name, 0..30) <> "…"
370 def confirm_current_password(user, password) do
371 with %User{local: true} = db_user <- User.get_cached_by_id(user.id),
372 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
375 _ -> {:error, "Invalid password."}
379 def emoji_from_profile(%{info: _info} = user) do
380 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
381 |> Enum.map(fn {shortcode, url, _} ->
384 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
385 "name" => ":#{shortcode}:"
390 def maybe_notify_to_recipients(
392 %Activity{data: %{"to" => to, "type" => _type}} = _activity
397 def maybe_notify_mentioned_recipients(
399 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
401 when type == "Create" do
402 object = Object.normalize(activity)
409 is_map(data["object"]) ->
416 tagged_mentions = maybe_extract_mentions(object_data)
418 recipients ++ tagged_mentions
421 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
423 def maybe_notify_subscribers(
425 %Activity{data: %{"actor" => actor, "type" => type}} = activity
427 when type == "Create" do
428 with %User{} = user <- User.get_cached_by_ap_id(actor) do
431 |> User.subscribers()
432 |> Enum.filter(&Visibility.visible_for_user?(activity, &1))
433 |> Enum.map(& &1.ap_id)
435 recipients ++ subscriber_ids
439 def maybe_notify_subscribers(recipients, _), do: recipients
441 def maybe_extract_mentions(%{"tag" => tag}) do
443 |> Enum.filter(fn x -> is_map(x) end)
444 |> Enum.filter(fn x -> x["type"] == "Mention" end)
445 |> Enum.map(fn x -> x["href"] end)
448 def maybe_extract_mentions(_), do: []
450 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
452 def make_report_content_html(comment) do
453 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
455 if String.length(comment) <= max_size do
456 {:ok, format_input(comment, "text/plain")}
458 {:error, "Comment must be up to #{max_size} characters"}
462 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
463 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
466 def get_report_statuses(_, _), do: {:ok, nil}
468 # DEPRECATED mostly, context objects are now created at insertion time.
469 def context_to_conversation_id(context) do
470 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
474 changeset = Object.context_mapping(context)
476 case Repo.insert(changeset) do
480 # This should be solved by an upsert, but it seems ecto
481 # has problems accessing the constraint inside the jsonb.
483 Object.get_cached_by_ap_id(context).id
488 def conversation_id_to_context(id) do
489 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
493 {:error, "No such conversation"}
497 def make_answer_data(%User{ap_id: ap_id}, object, name) do
501 "cc" => [object.data["actor"]],
504 "inReplyTo" => object.data["id"]
508 def validate_character_limit(full_payload, attachments, limit) do
509 length = String.length(full_payload)
512 if length > 0 or Enum.count(attachments) > 0 do
515 {:error, "Cannot post an empty status without attachments"}
518 {:error, "The status is over the character limit"}