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