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