Merge remote-tracking branch 'upstream/develop' into patch-image-description
[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(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 mentions,
104 attachments,
105 tags,
106 content_type,
107 no_attachment_links \\ false
108 ) do
109 status
110 |> format_input(mentions, tags, content_type)
111 |> maybe_add_attachments(attachments, no_attachment_links)
112 end
113
114 def make_context(%Activity{data: %{"context" => context}}), do: context
115 def make_context(_), do: Utils.generate_context_id()
116
117 def maybe_add_attachments(text, _attachments, true = _no_links), do: text
118
119 def maybe_add_attachments(text, attachments, _no_links) do
120 add_attachments(text, attachments)
121 end
122
123 def add_attachments(text, attachments) do
124 attachment_text =
125 Enum.map(attachments, fn
126 %{"url" => [%{"href" => href} | _]} = attachment ->
127 name = attachment["name"] || URI.decode(Path.basename(href))
128 href = MediaProxy.url(href)
129 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
130
131 _ ->
132 ""
133 end)
134
135 Enum.join([text | attachment_text], "<br>")
136 end
137
138 def format_input(text, mentions, tags, format, options \\ [])
139
140 @doc """
141 Formatting text to plain text.
142 """
143 def format_input(text, mentions, tags, "text/plain", options) do
144 text
145 |> Formatter.html_escape("text/plain")
146 |> String.replace(~r/\r?\n/, "<br>")
147 |> (&{[], &1}).()
148 |> Formatter.add_links()
149 |> Formatter.add_user_links(mentions, options[:user_links] || [])
150 |> Formatter.add_hashtag_links(tags)
151 |> Formatter.finalize()
152 end
153
154 @doc """
155 Formatting text to html.
156 """
157 def format_input(text, mentions, _tags, "text/html", options) do
158 text
159 |> Formatter.html_escape("text/html")
160 |> (&{[], &1}).()
161 |> Formatter.add_user_links(mentions, options[:user_links] || [])
162 |> Formatter.finalize()
163 end
164
165 @doc """
166 Formatting text to markdown.
167 """
168 def format_input(text, mentions, tags, "text/markdown", options) do
169 text
170 |> Formatter.mentions_escape(mentions)
171 |> Earmark.as_html!()
172 |> Formatter.html_escape("text/html")
173 |> (&{[], &1}).()
174 |> Formatter.add_user_links(mentions, options[:user_links] || [])
175 |> Formatter.add_hashtag_links(tags)
176 |> Formatter.finalize()
177 end
178
179 def add_tag_links(text, tags) do
180 tags =
181 tags
182 |> Enum.sort_by(fn {tag, _} -> -String.length(tag) end)
183
184 Enum.reduce(tags, text, fn {full, tag}, text ->
185 url = "<a href='#{Web.base_url()}/tag/#{tag}' rel='tag'>##{tag}</a>"
186 String.replace(text, full, url)
187 end)
188 end
189
190 def make_note_data(
191 actor,
192 to,
193 context,
194 content_html,
195 attachments,
196 inReplyTo,
197 tags,
198 cw \\ nil,
199 cc \\ []
200 ) do
201 object = %{
202 "type" => "Note",
203 "to" => to,
204 "cc" => cc,
205 "content" => content_html,
206 "summary" => cw,
207 "context" => context,
208 "attachment" => attachments,
209 "actor" => actor,
210 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
211 }
212
213 if inReplyTo do
214 object
215 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
216 |> Map.put("inReplyToStatusId", inReplyTo.id)
217 else
218 object
219 end
220 end
221
222 def format_naive_asctime(date) do
223 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
224 end
225
226 def format_asctime(date) do
227 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
228 end
229
230 def date_to_asctime(date) do
231 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
232 format_asctime(date)
233 else
234 _e ->
235 ""
236 end
237 end
238
239 def to_masto_date(%NaiveDateTime{} = date) do
240 date
241 |> NaiveDateTime.to_iso8601()
242 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
243 end
244
245 def to_masto_date(date) do
246 try do
247 date
248 |> NaiveDateTime.from_iso8601!()
249 |> NaiveDateTime.to_iso8601()
250 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
251 rescue
252 _e -> ""
253 end
254 end
255
256 defp shortname(name) do
257 if String.length(name) < 30 do
258 name
259 else
260 String.slice(name, 0..30) <> "…"
261 end
262 end
263
264 def confirm_current_password(user, password) do
265 with %User{local: true} = db_user <- Repo.get(User, user.id),
266 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
267 {:ok, db_user}
268 else
269 _ -> {:error, "Invalid password."}
270 end
271 end
272
273 def emoji_from_profile(%{info: _info} = user) do
274 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
275 |> Enum.map(fn {shortcode, url} ->
276 %{
277 "type" => "Emoji",
278 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
279 "name" => ":#{shortcode}:"
280 }
281 end)
282 end
283
284 def maybe_notify_to_recipients(
285 recipients,
286 %Activity{data: %{"to" => to, "type" => _type}} = _activity
287 ) do
288 recipients ++ to
289 end
290
291 def maybe_notify_mentioned_recipients(
292 recipients,
293 %Activity{data: %{"to" => _to, "type" => type} = data} = _activity
294 )
295 when type == "Create" do
296 object = Object.normalize(data["object"])
297
298 object_data =
299 cond do
300 !is_nil(object) ->
301 object.data
302
303 is_map(data["object"]) ->
304 data["object"]
305
306 true ->
307 %{}
308 end
309
310 tagged_mentions = maybe_extract_mentions(object_data)
311
312 recipients ++ tagged_mentions
313 end
314
315 def maybe_notify_mentioned_recipients(recipients, _), do: recipients
316
317 def maybe_extract_mentions(%{"tag" => tag}) do
318 tag
319 |> Enum.filter(fn x -> is_map(x) end)
320 |> Enum.filter(fn x -> x["type"] == "Mention" end)
321 |> Enum.map(fn x -> x["href"] end)
322 end
323
324 def maybe_extract_mentions(_), do: []
325 end