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
15 alias Pleroma.Web.ActivityPub.Utils
16 alias Pleroma.Web.ActivityPub.Visibility
17 alias Pleroma.Web.Endpoint
18 alias Pleroma.Web.MediaProxy
22 # This is a hack for twidere.
23 def get_by_id_or_ap_id(id) do
25 Activity.get_by_id_with_object(id) || Activity.get_create_by_object_ap_id_with_object(id)
28 if activity.data["type"] == "Create" do
31 Activity.get_create_by_object_ap_id_with_object(activity.data["object"])
35 def get_replied_to_activity(""), do: nil
37 def get_replied_to_activity(id) when not is_nil(id) do
38 Activity.get_by_id(id)
41 def get_replied_to_activity(_), do: nil
43 def attachments_from_ids(data) do
44 if Map.has_key?(data, "descriptions") do
45 attachments_from_ids_descs(data["media_ids"], data["descriptions"])
47 attachments_from_ids_no_descs(data["media_ids"])
51 def attachments_from_ids_no_descs(ids) do
52 Enum.map(ids || [], fn media_id ->
53 Repo.get(Object, media_id).data
57 def attachments_from_ids_descs(ids, descs_str) do
58 {_, descs} = Jason.decode(descs_str)
60 Enum.map(ids || [], fn media_id ->
61 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
65 def to_for_user_and_mentions(user, mentions, inReplyTo, "public") do
66 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
68 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
69 cc = [user.follower_address]
72 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
78 def to_for_user_and_mentions(user, mentions, inReplyTo, "unlisted") do
79 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
81 to = [user.follower_address | mentioned_users]
82 cc = ["https://www.w3.org/ns/activitystreams#Public"]
85 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
91 def to_for_user_and_mentions(user, mentions, inReplyTo, "private") do
92 {to, cc} = to_for_user_and_mentions(user, mentions, inReplyTo, "direct")
93 {[user.follower_address | to], cc}
96 def to_for_user_and_mentions(_user, mentions, inReplyTo, "direct") do
97 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
100 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
102 {mentioned_users, []}
106 def to_for_user_and_mentions(_user, _mentions, _inReplyTo, _), do: {[], []}
108 def bcc_for_list(user, {:list, list_id}) do
109 with {_, %List{} = list} <- {:list, List.get(list_id, user)},
110 {:ok, following} <- List.get_following(list) do
111 {:ok, Enum.map(following, & &1.ap_id)}
113 {:list, _} -> {:error, "List not found"}
118 def bcc_for_list(_, _), do: {:ok, []}
120 def make_content_html(
126 no_attachment_links =
128 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
129 |> Kernel.in([true, "true"])
131 content_type = get_content_type(data["content_type"])
134 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
141 |> format_input(content_type, options)
142 |> maybe_add_attachments(attachments, no_attachment_links)
143 |> maybe_add_nsfw_tag(data)
146 defp get_content_type(content_type) do
147 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
154 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
155 when sensitive in [true, "True", "true", "1"] do
156 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
159 defp maybe_add_nsfw_tag(data, _), do: data
161 def make_context(%Activity{data: %{"context" => context}}), do: context
162 def make_context(_), do: Utils.generate_context_id()
164 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
166 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
167 text = add_attachments(text, attachments)
168 {text, mentions, tags}
171 def add_attachments(text, attachments) do
173 Enum.map(attachments, fn
174 %{"url" => [%{"href" => href} | _]} = attachment ->
175 name = attachment["name"] || URI.decode(Path.basename(href))
176 href = MediaProxy.url(href)
177 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
183 Enum.join([text | attachment_text], "<br>")
186 def format_input(text, format, options \\ [])
189 Formatting text to plain text.
191 def format_input(text, "text/plain", options) do
193 |> Formatter.html_escape("text/plain")
194 |> Formatter.linkify(options)
195 |> (fn {text, mentions, tags} ->
196 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
201 Formatting text to html.
203 def format_input(text, "text/html", options) do
205 |> Formatter.html_escape("text/html")
206 |> Formatter.linkify(options)
210 Formatting text to markdown.
212 def format_input(text, "text/markdown", options) do
214 |> Formatter.mentions_escape(options)
215 |> Earmark.as_html!()
216 |> Formatter.linkify(options)
217 |> Formatter.html_escape("text/html")
235 "content" => content_html,
237 "context" => context,
238 "attachment" => attachments,
240 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
244 in_reply_to_object = Object.normalize(in_reply_to)
247 |> Map.put("inReplyTo", in_reply_to_object.data["id"])
253 def format_naive_asctime(date) do
254 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
257 def format_asctime(date) do
258 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
261 def date_to_asctime(date) when is_binary(date) do
262 with {:ok, date, _offset} <- DateTime.from_iso8601(date) do
266 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
271 def date_to_asctime(date) do
272 Logger.warn("Date #{date} in wrong format, must be ISO 8601")
276 def to_masto_date(%NaiveDateTime{} = date) do
278 |> NaiveDateTime.to_iso8601()
279 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
282 def to_masto_date(date) do
285 |> NaiveDateTime.from_iso8601!()
286 |> NaiveDateTime.to_iso8601()
287 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
293 defp shortname(name) do
294 if String.length(name) < 30 do
297 String.slice(name, 0..30) <> "…"
301 def confirm_current_password(user, password) do
302 with %User{local: true} = db_user <- User.get_cached_by_id(user.id),
303 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
306 _ -> {:error, "Invalid password."}
310 def emoji_from_profile(%{info: _info} = user) do
311 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
312 |> Enum.map(fn {shortcode, url, _} ->
315 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
316 "name" => ":#{shortcode}:"
321 def maybe_notify_to_recipients(
323 %Activity{data: %{"to" => to, "type" => _type}} = _activity
328 def maybe_notify_mentioned_recipients(
330 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
332 when type == "Create" do
333 object = Object.normalize(activity)
340 is_map(data["object"]) ->
347 tagged_mentions = maybe_extract_mentions(object_data)
349 recipients ++ tagged_mentions
352 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
354 def maybe_notify_subscribers(
356 %Activity{data: %{"actor" => actor, "type" => type}} = activity
358 when type == "Create" do
359 with %User{} = user <- User.get_cached_by_ap_id(actor) do
362 |> User.subscribers()
363 |> Enum.filter(&Visibility.visible_for_user?(activity, &1))
364 |> Enum.map(& &1.ap_id)
366 recipients ++ subscriber_ids
370 def maybe_notify_subscribers(recipients, _), do: recipients
372 def maybe_extract_mentions(%{"tag" => tag}) do
374 |> Enum.filter(fn x -> is_map(x) end)
375 |> Enum.filter(fn x -> x["type"] == "Mention" end)
376 |> Enum.map(fn x -> x["href"] end)
379 def maybe_extract_mentions(_), do: []
381 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
383 def make_report_content_html(comment) do
384 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
386 if String.length(comment) <= max_size do
387 {:ok, format_input(comment, "text/plain")}
389 {:error, "Comment must be up to #{max_size} characters"}
393 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
394 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
397 def get_report_statuses(_, _), do: {:ok, nil}
399 # DEPRECATED mostly, context objects are now created at insertion time.
400 def context_to_conversation_id(context) do
401 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
405 changeset = Object.context_mapping(context)
407 case Repo.insert(changeset) do
411 # This should be solved by an upsert, but it seems ecto
412 # has problems accessing the constraint inside the jsonb.
414 Object.get_cached_by_ap_id(context).id
419 def conversation_id_to_context(id) do
420 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
424 {:error, "No such conversation"}