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