Credo fixes: alias grouping/ordering
[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, Formatter, Object, Repo}
9 alias Pleroma.{User, Web}
10 alias Pleroma.Web.{Endpoint, MediaProxy}
11 alias Pleroma.Web.ActivityPub.Utils
12
13 # This is a hack for twidere.
14 def get_by_id_or_ap_id(id) do
15 activity = Repo.get(Activity, id) || Activity.get_create_by_object_ap_id(id)
16
17 activity &&
18 if activity.data["type"] == "Create" do
19 activity
20 else
21 Activity.get_create_by_object_ap_id(activity.data["object"])
22 end
23 end
24
25 def get_replied_to_activity(""), do: nil
26
27 def get_replied_to_activity(id) when not is_nil(id) do
28 Repo.get(Activity, id)
29 end
30
31 def get_replied_to_activity(_), do: nil
32
33 def attachments_from_ids(ids) do
34 Enum.map(ids || [], fn media_id ->
35 Repo.get(Object, media_id).data
36 end)
37 end
38
39 def to_for_user_and_mentions(user, mentions, inReplyTo, "public") do
40 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
41
42 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
43 cc = [user.follower_address]
44
45 if inReplyTo do
46 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
47 else
48 {to, cc}
49 end
50 end
51
52 def to_for_user_and_mentions(user, mentions, inReplyTo, "unlisted") do
53 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
54
55 to = [user.follower_address | mentioned_users]
56 cc = ["https://www.w3.org/ns/activitystreams#Public"]
57
58 if inReplyTo do
59 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
60 else
61 {to, cc}
62 end
63 end
64
65 def to_for_user_and_mentions(user, mentions, inReplyTo, "private") do
66 {to, cc} = to_for_user_and_mentions(user, mentions, inReplyTo, "direct")
67 {[user.follower_address | to], cc}
68 end
69
70 def to_for_user_and_mentions(_user, mentions, inReplyTo, "direct") do
71 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
72
73 if inReplyTo do
74 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
75 else
76 {mentioned_users, []}
77 end
78 end
79
80 def make_content_html(
81 status,
82 mentions,
83 attachments,
84 tags,
85 content_type,
86 no_attachment_links \\ false
87 ) do
88 status
89 |> format_input(mentions, tags, content_type)
90 |> maybe_add_attachments(attachments, no_attachment_links)
91 end
92
93 def make_context(%Activity{data: %{"context" => context}}), do: context
94 def make_context(_), do: Utils.generate_context_id()
95
96 def maybe_add_attachments(text, _attachments, true = _no_links), do: text
97
98 def maybe_add_attachments(text, attachments, _no_links) do
99 add_attachments(text, attachments)
100 end
101
102 def add_attachments(text, attachments) do
103 attachment_text =
104 Enum.map(attachments, fn
105 %{"url" => [%{"href" => href} | _]} = attachment ->
106 name = attachment["name"] || URI.decode(Path.basename(href))
107 href = MediaProxy.url(href)
108 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
109
110 _ ->
111 ""
112 end)
113
114 Enum.join([text | attachment_text], "<br>")
115 end
116
117 def format_input(text, mentions, tags, format, options \\ [])
118
119 @doc """
120 Formatting text to plain text.
121 """
122 def format_input(text, mentions, tags, "text/plain", options) do
123 text
124 |> Formatter.html_escape("text/plain")
125 |> String.replace(~r/\r?\n/, "<br>")
126 |> (&{[], &1}).()
127 |> Formatter.add_links()
128 |> Formatter.add_user_links(mentions, options[:user_links] || [])
129 |> Formatter.add_hashtag_links(tags)
130 |> Formatter.finalize()
131 end
132
133 @doc """
134 Formatting text to html.
135 """
136 def format_input(text, mentions, _tags, "text/html", options) do
137 text
138 |> Formatter.html_escape("text/html")
139 |> (&{[], &1}).()
140 |> Formatter.add_user_links(mentions, options[:user_links] || [])
141 |> Formatter.finalize()
142 end
143
144 @doc """
145 Formatting text to markdown.
146 """
147 def format_input(text, mentions, tags, "text/markdown", options) do
148 text
149 |> Formatter.mentions_escape(mentions)
150 |> Earmark.as_html!()
151 |> Formatter.html_escape("text/html")
152 |> (&{[], &1}).()
153 |> Formatter.add_user_links(mentions, options[:user_links] || [])
154 |> Formatter.add_hashtag_links(tags)
155 |> Formatter.finalize()
156 end
157
158 def add_tag_links(text, tags) do
159 tags =
160 tags
161 |> Enum.sort_by(fn {tag, _} -> -String.length(tag) end)
162
163 Enum.reduce(tags, text, fn {full, tag}, text ->
164 url = "<a href='#{Web.base_url()}/tag/#{tag}' rel='tag'>##{tag}</a>"
165 String.replace(text, full, url)
166 end)
167 end
168
169 def make_note_data(
170 actor,
171 to,
172 context,
173 content_html,
174 attachments,
175 inReplyTo,
176 tags,
177 cw \\ nil,
178 cc \\ []
179 ) do
180 object = %{
181 "type" => "Note",
182 "to" => to,
183 "cc" => cc,
184 "content" => content_html,
185 "summary" => cw,
186 "context" => context,
187 "attachment" => attachments,
188 "actor" => actor,
189 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
190 }
191
192 if inReplyTo do
193 object
194 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
195 |> Map.put("inReplyToStatusId", inReplyTo.id)
196 else
197 object
198 end
199 end
200
201 def format_naive_asctime(date) do
202 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
203 end
204
205 def format_asctime(date) do
206 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
207 end
208
209 def date_to_asctime(date) do
210 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
211 format_asctime(date)
212 else
213 _e ->
214 ""
215 end
216 end
217
218 def to_masto_date(%NaiveDateTime{} = date) do
219 date
220 |> NaiveDateTime.to_iso8601()
221 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
222 end
223
224 def to_masto_date(date) do
225 try do
226 date
227 |> NaiveDateTime.from_iso8601!()
228 |> NaiveDateTime.to_iso8601()
229 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
230 rescue
231 _e -> ""
232 end
233 end
234
235 defp shortname(name) do
236 if String.length(name) < 30 do
237 name
238 else
239 String.slice(name, 0..30) <> "…"
240 end
241 end
242
243 def confirm_current_password(user, password) do
244 with %User{local: true} = db_user <- Repo.get(User, user.id),
245 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
246 {:ok, db_user}
247 else
248 _ -> {:error, "Invalid password."}
249 end
250 end
251
252 def emoji_from_profile(%{info: _info} = user) do
253 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
254 |> Enum.map(fn {shortcode, url} ->
255 %{
256 "type" => "Emoji",
257 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
258 "name" => ":#{shortcode}:"
259 }
260 end)
261 end
262
263 def maybe_notify_to_recipients(
264 recipients,
265 %Activity{data: %{"to" => to, "type" => _type}} = _activity
266 ) do
267 recipients ++ to
268 end
269
270 def maybe_notify_mentioned_recipients(
271 recipients,
272 %Activity{data: %{"to" => _to, "type" => type} = data} = _activity
273 )
274 when type == "Create" do
275 object = Object.normalize(data["object"])
276
277 object_data =
278 cond do
279 !is_nil(object) ->
280 object.data
281
282 is_map(data["object"]) ->
283 data["object"]
284
285 true ->
286 %{}
287 end
288
289 tagged_mentions = maybe_extract_mentions(object_data)
290
291 recipients ++ tagged_mentions
292 end
293
294 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
295
296 def maybe_extract_mentions(%{"tag" => tag}) do
297 tag
298 |> Enum.filter(fn x -> is_map(x) end)
299 |> Enum.filter(fn x -> x["type"] == "Mention" end)
300 |> Enum.map(fn x -> x["href"] end)
301 end
302
303 def maybe_extract_mentions(_), do: []
304 end