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