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