fix formatter
[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.Formatter
10 alias Pleroma.Object
11 alias Pleroma.Repo
12 alias Pleroma.User
13 alias Pleroma.Config
14 alias Pleroma.Web.Endpoint
15 alias Pleroma.Web.MediaProxy
16 alias Pleroma.Web.ActivityPub.Utils
17
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)
21
22 activity &&
23 if activity.data["type"] == "Create" do
24 activity
25 else
26 Activity.get_create_by_object_ap_id(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 ) do
106 no_attachment_links =
107 data
108 |> Map.get("no_attachment_links", Config.get([:instance, :no_attachment_links]))
109 |> Kernel.in([true, "true"])
110
111 content_type = get_content_type(data["content_type"])
112
113 status
114 |> format_input(content_type)
115 |> maybe_add_attachments(attachments, no_attachment_links)
116 |> maybe_add_nsfw_tag(data)
117 end
118
119 defp get_content_type(content_type) do
120 if Enum.member?(Config.get([:instance, :allowed_post_formats]), content_type) do
121 content_type
122 else
123 "text/plain"
124 end
125 end
126
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]}
130 end
131
132 defp maybe_add_nsfw_tag(data, _), do: data
133
134 def make_context(%Activity{data: %{"context" => context}}), do: context
135 def make_context(_), do: Utils.generate_context_id()
136
137 def maybe_add_attachments(parsed, _attachments, true = _no_links), do: parsed
138
139 def maybe_add_attachments({text, mentions, tags}, attachments, _no_links) do
140 text = add_attachments(text, attachments)
141 {text, mentions, tags}
142 end
143
144 def add_attachments(text, attachments) do
145 attachment_text =
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>"
151
152 _ ->
153 ""
154 end)
155
156 Enum.join([text | attachment_text], "<br>")
157 end
158
159 def format_input(text, format, options \\ [])
160
161 @doc """
162 Formatting text to plain text.
163 """
164 def format_input(text, "text/plain", options) do
165 text
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}
170 end).()
171 end
172
173 @doc """
174 Formatting text to html.
175 """
176 def format_input(text, "text/html", options) do
177 text
178 |> Formatter.html_escape("text/html")
179 |> Formatter.linkify(options)
180 end
181
182 @doc """
183 Formatting text to markdown.
184 """
185 def format_input(text, "text/markdown", options) do
186 options = Keyword.put(options, :mentions_escape, true)
187
188 text
189 |> Formatter.linkify(options)
190 |> (fn {text, mentions, tags} -> {Earmark.as_html!(text), mentions, tags} end).()
191 |> Formatter.html_escape("text/html")
192 end
193
194 def make_note_data(
195 actor,
196 to,
197 context,
198 content_html,
199 attachments,
200 inReplyTo,
201 tags,
202 cw \\ nil,
203 cc \\ []
204 ) do
205 object = %{
206 "type" => "Note",
207 "to" => to,
208 "cc" => cc,
209 "content" => content_html,
210 "summary" => cw,
211 "context" => context,
212 "attachment" => attachments,
213 "actor" => actor,
214 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
215 }
216
217 if inReplyTo do
218 object
219 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
220 |> Map.put("inReplyToStatusId", inReplyTo.id)
221 else
222 object
223 end
224 end
225
226 def format_naive_asctime(date) do
227 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
228 end
229
230 def format_asctime(date) do
231 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
232 end
233
234 def date_to_asctime(date) do
235 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
236 format_asctime(date)
237 else
238 _e ->
239 ""
240 end
241 end
242
243 def to_masto_date(%NaiveDateTime{} = date) do
244 date
245 |> NaiveDateTime.to_iso8601()
246 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
247 end
248
249 def to_masto_date(date) do
250 try do
251 date
252 |> NaiveDateTime.from_iso8601!()
253 |> NaiveDateTime.to_iso8601()
254 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
255 rescue
256 _e -> ""
257 end
258 end
259
260 defp shortname(name) do
261 if String.length(name) < 30 do
262 name
263 else
264 String.slice(name, 0..30) <> "…"
265 end
266 end
267
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
271 {:ok, db_user}
272 else
273 _ -> {:error, "Invalid password."}
274 end
275 end
276
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} ->
280 %{
281 "type" => "Emoji",
282 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
283 "name" => ":#{shortcode}:"
284 }
285 end)
286 end
287
288 def maybe_notify_to_recipients(
289 recipients,
290 %Activity{data: %{"to" => to, "type" => _type}} = _activity
291 ) do
292 recipients ++ to
293 end
294
295 def maybe_notify_mentioned_recipients(
296 recipients,
297 %Activity{data: %{"to" => _to, "type" => type} = data} = _activity
298 )
299 when type == "Create" do
300 object = Object.normalize(data["object"])
301
302 object_data =
303 cond do
304 !is_nil(object) ->
305 object.data
306
307 is_map(data["object"]) ->
308 data["object"]
309
310 true ->
311 %{}
312 end
313
314 tagged_mentions = maybe_extract_mentions(object_data)
315
316 recipients ++ tagged_mentions
317 end
318
319 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
320
321 def maybe_extract_mentions(%{"tag" => tag}) do
322 tag
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)
326 end
327
328 def maybe_extract_mentions(_), do: []
329
330 def make_report_content_html(nil), do: {:ok, {nil, [], []}}
331
332 def make_report_content_html(comment) do
333 max_size = Pleroma.Config.get([:instance, :max_report_comment_size], 1000)
334
335 if String.length(comment) <= max_size do
336 {:ok, format_input(comment, "text/plain")}
337 else
338 {:error, "Comment must be up to #{max_size} characters"}
339 end
340 end
341
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)}
344 end
345
346 def get_report_statuses(_, _), do: {:ok, nil}
347 end