common api: use the optimized Object.normalize whenever possible
[akkoma] / lib / pleroma / web / common_api / utils.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.CommonAPI.Utils do
6 alias Calendar.Strftime
7 alias Comeonin.Pbkdf2
8 alias Pleroma.Activity
9 alias Pleroma.Config
10 alias Pleroma.Formatter
11 alias Pleroma.Object
12 alias Pleroma.Repo
13 alias Pleroma.User
14 alias Pleroma.Web.ActivityPub.Utils
15 alias Pleroma.Web.Endpoint
16 alias Pleroma.Web.MediaProxy
17
18 # This is a hack for twidere.
19 def get_by_id_or_ap_id(id) do
20 activity = Activity.get_by_id_with_object(id) || Activity.get_create_by_object_ap_id_with_object(id)
21
22 activity &&
23 if activity.data["type"] == "Create" do
24 activity
25 else
26 Activity.get_create_by_object_ap_id_with_object(activity.data["object"])
27 end
28 end
29
30 def get_replied_to_activity(""), do: nil
31
32 def get_replied_to_activity(id) when not is_nil(id) do
33 Repo.get(Activity, id)
34 end
35
36 def get_replied_to_activity(_), do: nil
37
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"])
41 else
42 attachments_from_ids_no_descs(data["media_ids"])
43 end
44 end
45
46 def attachments_from_ids_no_descs(ids) do
47 Enum.map(ids || [], fn media_id ->
48 Repo.get(Object, media_id).data
49 end)
50 end
51
52 def attachments_from_ids_descs(ids, descs_str) do
53 {_, descs} = Jason.decode(descs_str)
54
55 Enum.map(ids || [], fn media_id ->
56 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
57 end)
58 end
59
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)
62
63 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
64 cc = [user.follower_address]
65
66 if inReplyTo do
67 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
68 else
69 {to, cc}
70 end
71 end
72
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)
75
76 to = [user.follower_address | mentioned_users]
77 cc = ["https://www.w3.org/ns/activitystreams#Public"]
78
79 if inReplyTo do
80 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
81 else
82 {to, cc}
83 end
84 end
85
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}
89 end
90
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)
93
94 if inReplyTo do
95 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
96 else
97 {mentioned_users, []}
98 end
99 end
100
101 def make_content_html(
102 status,
103 attachments,
104 data,
105 visibility
106 ) do
107 no_attachment_links =
108 data
109 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
110 |> Kernel.in([true, "true"])
111
112 content_type = get_content_type(data["content_type"])
113
114 options =
115 if visibility == "direct" && Config.get([:instance, :safe_dm_mentions]) do
116 [safe_mention: true]
117 else
118 []
119 end
120
121 status
122 |> format_input(content_type, options)
123 |> maybe_add_attachments(attachments, no_attachment_links)
124 |> maybe_add_nsfw_tag(data)
125 end
126
127 defp get_content_type(content_type) do
128 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
129 content_type
130 else
131 "text/plain"
132 end
133 end
134
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]}
138 end
139
140 defp maybe_add_nsfw_tag(data, _), do: data
141
142 def make_context(%Activity{data: %{"context" => context}}), do: context
143 def make_context(_), do: Utils.generate_context_id()
144
145 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
146
147 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
148 text = add_attachments(text, attachments)
149 {text, mentions, tags}
150 end
151
152 def add_attachments(text, attachments) do
153 attachment_text =
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>"
159
160 _ ->
161 ""
162 end)
163
164 Enum.join([text | attachment_text], "<br>")
165 end
166
167 def format_input(text, format, options \\ [])
168
169 @doc """
170 Formatting text to plain text.
171 """
172 def format_input(text, "text/plain", options) do
173 text
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}
178 end).()
179 end
180
181 @doc """
182 Formatting text to html.
183 """
184 def format_input(text, "text/html", options) do
185 text
186 |> Formatter.html_escape("text/html")
187 |> Formatter.linkify(options)
188 end
189
190 @doc """
191 Formatting text to markdown.
192 """
193 def format_input(text, "text/markdown", options) do
194 options = Keyword.put(options, :mentions_escape, true)
195
196 text
197 |> Formatter.linkify(options)
198 |> (fn {text, mentions, tags} -> {Earmark.as_html!(text), mentions, tags} end).()
199 |> Formatter.html_escape("text/html")
200 end
201
202 def make_note_data(
203 actor,
204 to,
205 context,
206 content_html,
207 attachments,
208 inReplyTo,
209 tags,
210 cw \\ nil,
211 cc \\ []
212 ) do
213 object = %{
214 "type" => "Note",
215 "to" => to,
216 "cc" => cc,
217 "content" => content_html,
218 "summary" => cw,
219 "context" => context,
220 "attachment" => attachments,
221 "actor" => actor,
222 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
223 }
224
225 if inReplyTo do
226 object
227 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
228 |> Map.put("inReplyToStatusId", inReplyTo.id)
229 else
230 object
231 end
232 end
233
234 def format_naive_asctime(date) do
235 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
236 end
237
238 def format_asctime(date) do
239 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
240 end
241
242 def date_to_asctime(date) do
243 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
244 format_asctime(date)
245 else
246 _e ->
247 ""
248 end
249 end
250
251 def to_masto_date(%NaiveDateTime{} = date) do
252 date
253 |> NaiveDateTime.to_iso8601()
254 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
255 end
256
257 def to_masto_date(date) do
258 try do
259 date
260 |> NaiveDateTime.from_iso8601!()
261 |> NaiveDateTime.to_iso8601()
262 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
263 rescue
264 _e -> ""
265 end
266 end
267
268 defp shortname(name) do
269 if String.length(name) < 30 do
270 name
271 else
272 String.slice(name, 0..30) <> "…"
273 end
274 end
275
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
279 {:ok, db_user}
280 else
281 _ -> {:error, "Invalid password."}
282 end
283 end
284
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} ->
288 %{
289 "type" => "Emoji",
290 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
291 "name" => ":#{shortcode}:"
292 }
293 end)
294 end
295
296 def maybe_notify_to_recipients(
297 recipients,
298 %Activity{data: %{"to" => to, "type" => _type}} = _activity
299 ) do
300 recipients ++ to
301 end
302
303 def maybe_notify_mentioned_recipients(
304 recipients,
305 %Activity{data: %{"to" => _to, "type" => type} = data} = activity
306 )
307 when type == "Create" do
308 object = Object.normalize(activity)
309
310 object_data =
311 cond do
312 !is_nil(object) ->
313 object.data
314
315 is_map(data["object"]) ->
316 data["object"]
317
318 true ->
319 %{}
320 end
321
322 tagged_mentions = maybe_extract_mentions(object_data)
323
324 recipients ++ tagged_mentions
325 end
326
327 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
328
329 def maybe_extract_mentions(%{"tag" => tag}) do
330 tag
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)
334 end
335
336 def maybe_extract_mentions(_), do: []
337
338 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
339
340 def make_report_content_html(comment) do
341 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
342
343 if String.length(comment) <= max_size do
344 {:ok, format_input(comment, "text/plain")}
345 else
346 {:error, "Comment must be up to #{max_size} characters"}
347 end
348 end
349
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)}
352 end
353
354 def get_report_statuses(_, _), do: {:ok, nil}
355
356 # DEPRECATED mostly, context objects are now created at insertion time.
357 def context_to_conversation_id(context) do
358 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
359 id
360 else
361 _e ->
362 changeset = Object.context_mapping(context)
363
364 case Repo.insert(changeset) do
365 {:ok, %{id: id}} ->
366 id
367
368 # This should be solved by an upsert, but it seems ecto
369 # has problems accessing the constraint inside the jsonb.
370 {:error, _} ->
371 Object.get_cached_by_ap_id(context).id
372 end
373 end
374 end
375
376 def conversation_id_to_context(id) do
377 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
378 context
379 else
380 _e ->
381 {:error, "No such conversation"}
382 end
383 end
384 end