5fe21fb99c367d5f01ccbb3d51bf42b030c375a7
[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_activity_by_object_ap_id(id)
18
19 activity &&
20 if activity.data["type"] == "Create" do
21 activity
22 else
23 Activity.get_create_activity_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, descs_str) do
36 {_, descs} = Jason.decode(descs_str)
37
38 Enum.map(ids || [], fn media_id ->
39 Map.put(Repo.get(Object, media_id).data, "name", descs[media_id])
40 end)
41 end
42
43 def to_for_user_and_mentions(user, mentions, inReplyTo, "public") do
44 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
45
46 to = ["https://www.w3.org/ns/activitystreams#Public" | mentioned_users]
47 cc = [user.follower_address]
48
49 if inReplyTo do
50 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
51 else
52 {to, cc}
53 end
54 end
55
56 def to_for_user_and_mentions(user, mentions, inReplyTo, "unlisted") do
57 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
58
59 to = [user.follower_address | mentioned_users]
60 cc = ["https://www.w3.org/ns/activitystreams#Public"]
61
62 if inReplyTo do
63 {Enum.uniq([inReplyTo.data["actor"] | to]), cc}
64 else
65 {to, cc}
66 end
67 end
68
69 def to_for_user_and_mentions(user, mentions, inReplyTo, "private") do
70 {to, cc} = to_for_user_and_mentions(user, mentions, inReplyTo, "direct")
71 {[user.follower_address | to], cc}
72 end
73
74 def to_for_user_and_mentions(_user, mentions, inReplyTo, "direct") do
75 mentioned_users = Enum.map(mentions, fn {_, %{ap_id: ap_id}} -> ap_id end)
76
77 if inReplyTo do
78 {Enum.uniq([inReplyTo.data["actor"] | mentioned_users]), []}
79 else
80 {mentioned_users, []}
81 end
82 end
83
84 def make_content_html(
85 status,
86 mentions,
87 attachments,
88 tags,
89 content_type,
90 no_attachment_links \\ false
91 ) do
92 status
93 |> format_input(mentions, tags, content_type)
94 |> maybe_add_attachments(attachments, no_attachment_links)
95 end
96
97 def make_context(%Activity{data: %{"context" => context}}), do: context
98 def make_context(_), do: Utils.generate_context_id()
99
100 def maybe_add_attachments(text, _attachments, _no_links = true), do: text
101
102 def maybe_add_attachments(text, attachments, _no_links) do
103 add_attachments(text, attachments)
104 end
105
106 def add_attachments(text, attachments) do
107 attachment_text =
108 Enum.map(attachments, fn
109 %{"url" => [%{"href" => href} | _]} = attachment ->
110 name = attachment["name"] || URI.decode(Path.basename(href))
111 href = MediaProxy.url(href)
112 "<a href=\"#{href}\" class='attachment'>#{shortname(name)}</a>"
113
114 _ ->
115 ""
116 end)
117
118 Enum.join([text | attachment_text], "<br>")
119 end
120
121 @doc """
122 Formatting text to plain text.
123 """
124 def format_input(text, mentions, tags, "text/plain") 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)
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") do
139 text
140 |> Formatter.html_escape("text/html")
141 |> String.replace(~r/\r?\n/, "<br>")
142 |> (&{[], &1}).()
143 |> Formatter.add_user_links(mentions)
144 |> Formatter.finalize()
145 end
146
147 @doc """
148 Formatting text to markdown.
149 """
150 def format_input(text, mentions, tags, "text/markdown") do
151 text
152 |> Formatter.mentions_escape(mentions)
153 |> Earmark.as_html!()
154 |> Formatter.html_escape("text/html")
155 |> String.replace(~r/\r?\n/, "")
156 |> (&{[], &1}).()
157 |> Formatter.add_user_links(mentions)
158 |> Formatter.add_hashtag_links(tags)
159 |> Formatter.finalize()
160 end
161
162 def add_tag_links(text, tags) do
163 tags =
164 tags
165 |> Enum.sort_by(fn {tag, _} -> -String.length(tag) end)
166
167 Enum.reduce(tags, text, fn {full, tag}, text ->
168 url = "<a href='#{Web.base_url()}/tag/#{tag}' rel='tag'>##{tag}</a>"
169 String.replace(text, full, url)
170 end)
171 end
172
173 def make_note_data(
174 actor,
175 to,
176 context,
177 content_html,
178 attachments,
179 inReplyTo,
180 tags,
181 cw \\ nil,
182 cc \\ []
183 ) do
184 object = %{
185 "type" => "Note",
186 "to" => to,
187 "cc" => cc,
188 "content" => content_html,
189 "summary" => cw,
190 "context" => context,
191 "attachment" => attachments,
192 "actor" => actor,
193 "tag" => tags |> Enum.map(fn {_, tag} -> tag end) |> Enum.uniq()
194 }
195
196 if inReplyTo do
197 object
198 |> Map.put("inReplyTo", inReplyTo.data["object"]["id"])
199 |> Map.put("inReplyToStatusId", inReplyTo.id)
200 else
201 object
202 end
203 end
204
205 def format_naive_asctime(date) do
206 date |> DateTime.from_naive!("Etc/UTC") |> format_asctime
207 end
208
209 def format_asctime(date) do
210 Strftime.strftime!(date, "%a %b %d %H:%M:%S %z %Y")
211 end
212
213 def date_to_asctime(date) do
214 with {:ok, date, _offset} <- date |> DateTime.from_iso8601() do
215 format_asctime(date)
216 else
217 _e ->
218 ""
219 end
220 end
221
222 def to_masto_date(%NaiveDateTime{} = date) do
223 date
224 |> NaiveDateTime.to_iso8601()
225 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
226 end
227
228 def to_masto_date(date) do
229 try do
230 date
231 |> NaiveDateTime.from_iso8601!()
232 |> NaiveDateTime.to_iso8601()
233 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
234 rescue
235 _e -> ""
236 end
237 end
238
239 defp shortname(name) do
240 if String.length(name) < 30 do
241 name
242 else
243 String.slice(name, 0..30) <> "…"
244 end
245 end
246
247 def confirm_current_password(user, password) do
248 with %User{local: true} = db_user <- Repo.get(User, user.id),
249 true <- Pbkdf2.checkpw(password, db_user.password_hash) do
250 {:ok, db_user}
251 else
252 _ -> {:error, "Invalid password."}
253 end
254 end
255
256 def emoji_from_profile(%{info: _info} = user) do
257 (Formatter.get_emoji(user.bio) ++ Formatter.get_emoji(user.name))
258 |> Enum.map(fn {shortcode, url} ->
259 %{
260 "type" => "Emoji",
261 "icon" => %{"type" => "Image", "url" => "#{Endpoint.url()}#{url}"},
262 "name" => ":#{shortcode}:"
263 }
264 end)
265 end
266 end