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.Endpoint
16 alias Pleroma.Web.MediaProxy
18 # This is a hack for twidere.
19 def get_by_id_or_ap_id(id) do
21 Activity.get_by_id_with_object(id) || Activity.get_create_by_object_ap_id_with_object(id)
24 if activity.data["type"] == "Create" do
27 Activity.get_create_by_object_ap_id_with_object(activity.data["object"])
31 def get_replied_to_activity(""), do: nil
33 def get_replied_to_activity(id) when not is_nil(id) do
34 Repo.get(Activity, id)
37 def get_replied_to_activity(_), do: nil
39 def attachments_from_ids(data) do
40 if Map.has_key?(data, "descriptions") do
41 attachments_from_ids_descs(data["media_ids"], data["descriptions"])
43 attachments_from_ids_no_descs(data["media_ids"])
47 def attachments_from_ids_no_descs(ids) do
48 Enum.map(ids || [], fn media_id ->
49 Repo.get(Object, media_id).data
53 def attachments_from_ids_descs(ids, descs_str) do
54 {_, descs} = Jason.decode(descs_str)
56 Enum.map(ids || [], fn media_id ->
57 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
61 def to_for_user_and_mentions(user, mentions, inReplyTo, "public") do
62 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
64 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
65 cc = [user.follower_address]
68 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
74 def to_for_user_and_mentions(user, mentions, inReplyTo, "unlisted") do
75 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
77 to = [user.follower_address | mentioned_users]
78 cc = ["https://www.w3.org/ns/activitystreams#Public"]
81 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
87 def to_for_user_and_mentions(user, mentions, inReplyTo, "private") do
88 {to, cc} = to_for_user_and_mentions(user, mentions, inReplyTo, "direct")
89 {[user.follower_address | to], cc}
92 def to_for_user_and_mentions(_user, mentions, inReplyTo, "direct") do
93 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
96 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
102 def make_content_html(
108 no_attachment_links =
110 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
111 |> Kernel.in([true, "true"])
113 content_type = get_content_type(data["content_type"])
116 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
123 |> format_input(content_type, options)
124 |> maybe_add_attachments(attachments, no_attachment_links)
125 |> maybe_add_nsfw_tag(data)
128 defp get_content_type(content_type) do
129 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
136 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
137 when sensitive in [true, "True", "true", "1"] do
138 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
141 defp maybe_add_nsfw_tag(data, _), do: data
143 def make_context(%Activity{data: %{"context" => context}}), do: context
144 def make_context(_), do: Utils.generate_context_id()
146 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
148 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
149 text = add_attachments(text, attachments)
150 {text, mentions, tags}
153 def add_attachments(text, attachments) do
155 Enum.map(attachments, fn
156 %{"url" => [%{"href" => href} | _]} = attachment ->
157 name = attachment["name"] || URI.decode(Path.basename(href))
158 href = MediaProxy.url(href)
159 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
165 Enum.join([text | attachment_text], "<br>")
168 def format_input(text, format, options \\ [])
171 Formatting text to plain text.
173 def format_input(text, "text/plain", options) do
175 |> Formatter.html_escape("text/plain")
176 |> Formatter.linkify(options)
177 |> (fn {text, mentions, tags} ->
178 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
183 Formatting text to html.
185 def format_input(text, "text/html", options) do
187 |> Formatter.html_escape("text/html")
188 |> Formatter.linkify(options)
192 Formatting text to markdown.
194 def format_input(text, "text/markdown", options) do
195 options = Keyword.put(options, :mentions_escape, true)
198 |> Formatter.linkify(options)
199 |> (fn {text, mentions, tags} -> {Earmark.as_html!(text), mentions, tags} end).()
200 |> Formatter.html_escape("text/html")
218 "content" => content_html,
220 "context" => context,
221 "attachment" => attachments,
223 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
228 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
229 |> Map.put("inReplyToStatusId", inReplyTo.id)
235 def format_naive_asctime(date) do
236 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
239 def format_asctime(date) do
240 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
243 def date_to_asctime(date) do
244 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
252 def to_masto_date(%NaiveDateTime{} = date) do
254 |> NaiveDateTime.to_iso8601()
255 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
258 def to_masto_date(date) do
261 |> NaiveDateTime.from_iso8601!()
262 |> NaiveDateTime.to_iso8601()
263 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
269 defp shortname(name) do
270 if String.length(name) < 30 do
273 String.slice(name, 0..30) <> "…"
277 def confirm_current_password(user, password) do
278 with %User{local: true} = db_user <- Repo.get(User, user.id),
279 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
282 _ -> {:error, "Invalid password."}
286 def emoji_from_profile(%{info: _info} = user) do
287 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
288 |> Enum.map(fn {shortcode, url} ->
291 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
292 "name" => ":#{shortcode}:"
297 def maybe_notify_to_recipients(
299 %Activity{data: %{"to" => to, "type" => _type}} = _activity
304 def maybe_notify_mentioned_recipients(
306 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
308 when type == "Create" do
309 object = Object.normalize(activity)
316 is_map(data["object"]) ->
323 tagged_mentions = maybe_extract_mentions(object_data)
325 recipients ++ tagged_mentions
328 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
330 def maybe_extract_mentions(%{"tag" => tag}) do
332 |> Enum.filter(fn x -> is_map(x) end)
333 |> Enum.filter(fn x -> x["type"] == "Mention" end)
334 |> Enum.map(fn x -> x["href"] end)
337 def maybe_extract_mentions(_), do: []
339 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
341 def make_report_content_html(comment) do
342 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
344 if String.length(comment) <= max_size do
345 {:ok, format_input(comment, "text/plain")}
347 {:error, "Comment must be up to #{max_size} characters"}
351 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
352 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
355 def get_report_statuses(_, _), do: {:ok, nil}
357 # DEPRECATED mostly, context objects are now created at insertion time.
358 def context_to_conversation_id(context) do
359 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
363 changeset = Object.context_mapping(context)
365 case Repo.insert(changeset) do
369 # This should be solved by an upsert, but it seems ecto
370 # has problems accessing the constraint inside the jsonb.
372 Object.get_cached_by_ap_id(context).id
377 def conversation_id_to_context(id) do
378 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
382 {:error, "No such conversation"}