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
20 activity = Repo.get(Activity, id) || Activity.get_create_by_object_ap_id(id)
23 if activity.data["type"] == "Create" do
26 Activity.get_create_by_object_ap_id(activity.data["object"])
30 def get_replied_to_activity(""), do: nil
32 def get_replied_to_activity(id) when not is_nil(id) do
33 Repo.get(Activity, id)
36 def get_replied_to_activity(_), do: nil
38 def attachments_from_ids(data) do
39 if Map.has_key?(data, "descriptions") do
40 attachments_from_ids_descs(data["media_ids"], data["descriptions"])
42 attachments_from_ids_no_descs(data["media_ids"])
46 def attachments_from_ids_no_descs(ids) do
47 Enum.map(ids || [], fn media_id ->
48 Repo.get(Object, media_id).data
52 def attachments_from_ids_descs(ids, descs_str) do
53 {_, descs} = Jason.decode(descs_str)
55 Enum.map(ids || [], fn media_id ->
56 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
60 def to_for_user_and_mentions(user, mentions, inReplyTo, "public") do
61 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
63 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
64 cc = [user.follower_address]
67 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
73 def to_for_user_and_mentions(user, mentions, inReplyTo, "unlisted") do
74 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
76 to = [user.follower_address | mentioned_users]
77 cc = ["https://www.w3.org/ns/activitystreams#Public"]
80 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
86 def to_for_user_and_mentions(user, mentions, inReplyTo, "private") do
87 {to, cc} = to_for_user_and_mentions(user, mentions, inReplyTo, "direct")
88 {[user.follower_address | to], cc}
91 def to_for_user_and_mentions(_user, mentions, inReplyTo, "direct") do
92 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
95 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
101 def make_content_html(
107 no_attachment_links =
109 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
110 |> Kernel.in([true, "true"])
112 content_type = get_content_type(data["content_type"])
115 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
122 |> format_input(content_type, options)
123 |> maybe_add_attachments(attachments, no_attachment_links)
124 |> maybe_add_nsfw_tag(data)
127 defp get_content_type(content_type) do
128 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
135 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
136 when sensitive in [true, "True", "true", "1"] do
137 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
140 defp maybe_add_nsfw_tag(data, _), do: data
142 def make_context(%Activity{data: %{"context" => context}}), do: context
143 def make_context(_), do: Utils.generate_context_id()
145 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
147 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
148 text = add_attachments(text, attachments)
149 {text, mentions, tags}
152 def add_attachments(text, attachments) do
154 Enum.map(attachments, fn
155 %{"url" => [%{"href" => href} | _]} = attachment ->
156 name = attachment["name"] || URI.decode(Path.basename(href))
157 href = MediaProxy.url(href)
158 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
164 Enum.join([text | attachment_text], "<br>")
167 def format_input(text, format, options \\ [])
170 Formatting text to plain text.
172 def format_input(text, "text/plain", options) do
174 |> Formatter.html_escape("text/plain")
175 |> Formatter.linkify(options)
176 |> (fn {text, mentions, tags} ->
177 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
182 Formatting text to html.
184 def format_input(text, "text/html", options) do
186 |> Formatter.html_escape("text/html")
187 |> Formatter.linkify(options)
191 Formatting text to markdown.
193 def format_input(text, "text/markdown", options) do
194 options = Keyword.put(options, :mentions_escape, true)
197 |> Formatter.linkify(options)
198 |> (fn {text, mentions, tags} -> {Earmark.as_html!(text), mentions, tags} end).()
199 |> Formatter.html_escape("text/html")
217 "content" => content_html,
219 "context" => context,
220 "attachment" => attachments,
222 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
227 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
228 |> Map.put("inReplyToStatusId", inReplyTo.id)
234 def format_naive_asctime(date) do
235 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
238 def format_asctime(date) do
239 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
242 def date_to_asctime(date) do
243 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
251 def to_masto_date(%NaiveDateTime{} = date) do
253 |> NaiveDateTime.to_iso8601()
254 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
257 def to_masto_date(date) do
260 |> NaiveDateTime.from_iso8601!()
261 |> NaiveDateTime.to_iso8601()
262 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
268 defp shortname(name) do
269 if String.length(name) < 30 do
272 String.slice(name, 0..30) <> "…"
276 def confirm_current_password(user, password) do
277 with %User{local: true} = db_user <- Repo.get(User, user.id),
278 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
281 _ -> {:error, "Invalid password."}
285 def emoji_from_profile(%{info: _info} = user) do
286 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
287 |> Enum.map(fn {shortcode, url} ->
290 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
291 "name" => ":#{shortcode}:"
296 def maybe_notify_to_recipients(
298 %Activity{data: %{"to" => to, "type" => _type}} = _activity
303 def maybe_notify_mentioned_recipients(
305 %Activity{data: %{"to" => _to, "type" => type} = data} = _activity
307 when type == "Create" do
308 object = Object.normalize(data["object"])
315 is_map(data["object"]) ->
322 tagged_mentions = maybe_extract_mentions(object_data)
324 recipients ++ tagged_mentions
327 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
329 def maybe_extract_mentions(%{"tag" => tag}) do
331 |> Enum.filter(fn x -> is_map(x) end)
332 |> Enum.filter(fn x -> x["type"] == "Mention" end)
333 |> Enum.map(fn x -> x["href"] end)
336 def maybe_extract_mentions(_), do: []
338 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
340 def make_report_content_html(comment) do
341 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
343 if String.length(comment) <= max_size do
344 {:ok, format_input(comment, "text/plain")}
346 {:error, "Comment must be up to #{max_size} characters"}
350 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
351 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
354 def get_report_statuses(_, _), do: {:ok, nil}