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 def to_for_user_and_mentions(user, mentions, inReplyTo, "public") do
65 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
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 to_for_user_and_mentions(user, mentions, inReplyTo, "unlisted") do
78 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
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 to_for_user_and_mentions(user, mentions, inReplyTo, "private") do
91 {to, cc} = to_for_user_and_mentions(user, mentions, inReplyTo, "direct")
92 {[user.follower_address | to], cc}
95 def to_for_user_and_mentions(_user, mentions, inReplyTo, "direct") do
96 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
99 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
101 {mentioned_users, []}
105 def to_for_user_and_mentions(_user, _mentions, _inReplyTo, _), do: {[], []}
107 def bcc_for_list(user, {:list, list_id}) do
108 [Pleroma.List.ap_id(user, list_id)]
111 def bcc_for_list(_, _), do: []
113 def make_content_html(
119 no_attachment_links =
121 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
122 |> Kernel.in([true, "true"])
124 content_type = get_content_type(data["content_type"])
127 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
134 |> format_input(content_type, options)
135 |> maybe_add_attachments(attachments, no_attachment_links)
136 |> maybe_add_nsfw_tag(data)
139 defp get_content_type(content_type) do
140 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
147 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
148 when sensitive in [true, "True", "true", "1"] do
149 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
152 defp maybe_add_nsfw_tag(data, _), do: data
154 def make_context(%Activity{data: %{"context" => context}}), do: context
155 def make_context(_), do: Utils.generate_context_id()
157 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
159 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
160 text = add_attachments(text, attachments)
161 {text, mentions, tags}
164 def add_attachments(text, attachments) do
166 Enum.map(attachments, fn
167 %{"url" => [%{"href" => href} | _]} = attachment ->
168 name = attachment["name"] || URI.decode(Path.basename(href))
169 href = MediaProxy.url(href)
170 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
176 Enum.join([text | attachment_text], "<br>")
179 def format_input(text, format, options \\ [])
182 Formatting text to plain text.
184 def format_input(text, "text/plain", options) do
186 |> Formatter.html_escape("text/plain")
187 |> Formatter.linkify(options)
188 |> (fn {text, mentions, tags} ->
189 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
194 Formatting text as BBCode.
196 def format_input(text, "text/bbcode", options) do
198 |> String.replace(~r/\r/, "")
199 |> Formatter.html_escape("text/plain")
201 |> (fn {:ok, html} -> html end).()
202 |> Formatter.linkify(options)
206 Formatting text to html.
208 def format_input(text, "text/html", options) do
210 |> Formatter.html_escape("text/html")
211 |> Formatter.linkify(options)
215 Formatting text to markdown.
217 def format_input(text, "text/markdown", options) do
219 |> Formatter.mentions_escape(options)
220 |> Earmark.as_html!()
221 |> Formatter.linkify(options)
222 |> Formatter.html_escape("text/html")
240 "content" => content_html,
242 "context" => context,
243 "attachment" => attachments,
245 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
249 in_reply_to_object = Object.normalize(in_reply_to)
252 |> Map.put("inReplyTo", in_reply_to_object.data["id"])
258 def format_naive_asctime(date) do
259 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
262 def format_asctime(date) do
263 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
266 def date_to_asctime(date) when is_binary(date) do
267 with {:ok, date, _offset} <- DateTime.from_iso8601(date) do
271 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
276 def date_to_asctime(date) do
277 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
281 def to_masto_date(%NaiveDateTime{} = date) do
283 |> NaiveDateTime.to_iso8601()
284 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
287 def to_masto_date(date) do
290 |> NaiveDateTime.from_iso8601!()
291 |> NaiveDateTime.to_iso8601()
292 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
298 defp shortname(name) do
299 if String.length(name) < 30 do
302 String.slice(name, 0..30) <> "…"
306 def confirm_current_password(user, password) do
307 with %User{local: true} = db_user <- User.get_cached_by_id(user.id),
308 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
311 _ -> {:error, "Invalid password."}
315 def emoji_from_profile(%{info: _info} = user) do
316 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
317 |> Enum.map(fn {shortcode, url, _} ->
320 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
321 "name" => ":#{shortcode}:"
326 def maybe_notify_to_recipients(
328 %Activity{data: %{"to" => to, "type" => _type}} = _activity
333 def maybe_notify_mentioned_recipients(
335 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
337 when type == "Create" do
338 object = Object.normalize(activity)
345 is_map(data["object"]) ->
352 tagged_mentions = maybe_extract_mentions(object_data)
354 recipients ++ tagged_mentions
357 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
359 def maybe_notify_subscribers(
361 %Activity{data: %{"actor" => actor, "type" => type}} = activity
363 when type == "Create" do
364 with %User{} = user <- User.get_cached_by_ap_id(actor) do
367 |> User.subscribers()
368 |> Enum.filter(&Visibility.visible_for_user?(activity, &1))
369 |> Enum.map(& &1.ap_id)
371 recipients ++ subscriber_ids
375 def maybe_notify_subscribers(recipients, _), do: recipients
377 def maybe_extract_mentions(%{"tag" => tag}) do
379 |> Enum.filter(fn x -> is_map(x) end)
380 |> Enum.filter(fn x -> x["type"] == "Mention" end)
381 |> Enum.map(fn x -> x["href"] end)
384 def maybe_extract_mentions(_), do: []
386 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
388 def make_report_content_html(comment) do
389 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
391 if String.length(comment) <= max_size do
392 {:ok, format_input(comment, "text/plain")}
394 {:error, "Comment must be up to #{max_size} characters"}
398 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
399 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
402 def get_report_statuses(_, _), do: {:ok, nil}
404 # DEPRECATED mostly, context objects are now created at insertion time.
405 def context_to_conversation_id(context) do
406 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
410 changeset = Object.context_mapping(context)
412 case Repo.insert(changeset) do
416 # This should be solved by an upsert, but it seems ecto
417 # has problems accessing the constraint inside the jsonb.
419 Object.get_cached_by_ap_id(context).id
424 def conversation_id_to_context(id) do
425 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
429 {:error, "No such conversation"}