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
9 alias Pleroma.Formatter
14 alias Pleroma.Web.Endpoint
15 alias Pleroma.Web.MediaProxy
16 alias Pleroma.Web.ActivityPub.Utils
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(
106 no_attachment_links =
108 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
109 |> Kernel.in([true, "true"])
111 content_type = get_content_type(data["content_type"])
114 |> format_input(content_type)
115 |> maybe_add_attachments(attachments, no_attachment_links)
116 |> maybe_add_nsfw_tag(data)
119 defp get_content_type(content_type) do
120 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
127 defp maybe_add_nsfw_tag({text, mentions, tags}, %{"sensitive" => sensitive})
128 when sensitive in [true, "True", "true", "1"] do
129 {text, mentions, [{"#nsfw", "nsfw"} | tags]}
132 defp maybe_add_nsfw_tag(data, _), do: data
134 def make_context(%Activity{data: %{"context" => context}}), do: context
135 def make_context(_), do: Utils.generate_context_id()
137 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
139 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
140 text = add_attachments(text, attachments)
141 {text, mentions, tags}
144 def add_attachments(text, attachments) do
146 Enum.map(attachments, fn
147 %{"url" => [%{"href" => href} | _]} = attachment ->
148 name = attachment["name"] || URI.decode(Path.basename(href))
149 href = MediaProxy.url(href)
150 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
156 Enum.join([text | attachment_text], "<br>")
159 def format_input(text, format, options \\ [])
162 Formatting text to plain text.
164 def format_input(text, "text/plain", options) do
166 |> Formatter.html_escape("text/plain")
167 |> Formatter.linkify(options)
168 |> (fn {text, mentions, tags} ->
169 {String.replace(text, ~r/\r?\n/, "<br>"), mentions, tags}
174 Formatting text to html.
176 def format_input(text, "text/html", options) do
178 |> Formatter.html_escape("text/html")
179 |> Formatter.linkify(options)
183 Formatting text to markdown.
185 def format_input(text, "text/markdown", options) do
186 options = Keyword.put(options, :mentions_escape, true)
189 |> Formatter.linkify(options)
190 |> (fn {text, mentions, tags} -> {Earmark.as_html!(text), mentions, tags} end).()
191 |> Formatter.html_escape("text/html")
209 "content" => content_html,
211 "context" => context,
212 "attachment" => attachments,
214 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
219 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
220 |> Map.put("inReplyToStatusId", inReplyTo.id)
226 def format_naive_asctime(date) do
227 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
230 def format_asctime(date) do
231 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
234 def date_to_asctime(date) do
235 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
243 def to_masto_date(%NaiveDateTime{} = date) do
245 |> NaiveDateTime.to_iso8601()
246 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
249 def to_masto_date(date) do
252 |> NaiveDateTime.from_iso8601!()
253 |> NaiveDateTime.to_iso8601()
254 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
260 defp shortname(name) do
261 if String.length(name) < 30 do
264 String.slice(name, 0..30) <> "…"
268 def confirm_current_password(user, password) do
269 with %User{local: true} = db_user <- Repo.get(User, user.id),
270 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
273 _ -> {:error, "Invalid password."}
277 def emoji_from_profile(%{info: _info} = user) do
278 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
279 |> Enum.map(fn {shortcode, url} ->
282 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
283 "name" => ":#{shortcode}:"
288 def maybe_notify_to_recipients(
290 %Activity{data: %{"to" => to, "type" => _type}} = _activity
295 def maybe_notify_mentioned_recipients(
297 %Activity{data: %{"to" => _to, "type" => type} = data} = _activity
299 when type == "Create" do
300 object = Object.normalize(data["object"])
307 is_map(data["object"]) ->
314 tagged_mentions = maybe_extract_mentions(object_data)
316 recipients ++ tagged_mentions
319 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
321 def maybe_extract_mentions(%{"tag" => tag}) do
323 |> Enum.filter(fn x -> is_map(x) end)
324 |> Enum.filter(fn x -> x["type"] == "Mention" end)
325 |> Enum.map(fn x -> x["href"] end)
328 def maybe_extract_mentions(_), do: []
330 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
332 def make_report_content_html(comment) do
333 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
335 if String.length(comment) <= max_size do
336 {:ok, format_input(comment, "text/plain")}
338 {:error, "Comment must be up to #{max_size} characters"}
342 def get_report_statuses(%User{ap_id: actor}, %{"status_ids" => status_ids}) do
343 {:ok, Activity.all_by_actor_and_id(actor, status_ids)}
346 def get_report_statuses(_, _), do: {:ok, nil}