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-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.CommonAPI.Utils do
6 require Logger
7 alias Calendar.Strftime
8 alias Comeonin.Pbkdf2
9 alias Pleroma.{Activity, Formatter, Object, Repo}
10 alias Pleroma.User
11 alias Pleroma.Web
12 alias Pleroma.Web.ActivityPub.Utils
13 alias Pleroma.Web.Endpoint
14 alias Pleroma.Web.MediaProxy
15
16 # This is a hack for twidere.
17 def get_by_id_or_ap_id(id) do
18 activity = Repo.get(Activity, id) || Activity.get_create_activity_by_object_ap_id(id)
19
20 activity &&
21 if activity.data["type"] == "Create" do
22 activity
23 else
24 Activity.get_create_activity_by_object_ap_id(activity.data["object"])
25 end
26 end
27
28 def get_replied_to_activity(""), do: nil
29
30 def get_replied_to_activity(id) when not is_nil(id) do
31 Repo.get(Activity, id)
32 end
33
34 def get_replied_to_activity(_), do: nil
35
36 def attachments_from_ids(ids, descs) do
37 Enum.map(ids || [], fn media_id -> do
38 Logger.warn(descs[media_id])
39 Repo.get(Object, media_id).data
40 end
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, _no_links = true), 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 @doc """
123 Formatting text to plain text.
124 """
125 def format_input(text, mentions, tags, "text/plain") do
126 text
127 |> Formatter.html_escape("text/plain")
128 |> String.replace(~r/\r?\n/, "<br>")
129 |> (&{[], &1}).()
130 |> Formatter.add_links()
131 |> Formatter.add_user_links(mentions)
132 |> Formatter.add_hashtag_links(tags)
133 |> Formatter.finalize()
134 end
135
136 @doc """
137 Formatting text to html.
138 """
139 def format_input(text, mentions, _tags, "text/html") do
140 text
141 |> Formatter.html_escape("text/html")
142 |> String.replace(~r/\r?\n/, "<br>")
143 |> (&{[], &1}).()
144 |> Formatter.add_user_links(mentions)
145 |> Formatter.finalize()
146 end
147
148 @doc """
149 Formatting text to markdown.
150 """
151 def format_input(text, mentions, tags, "text/markdown") do
152 text
153 |> Formatter.mentions_escape(mentions)
154 |> Earmark.as_html!()
155 |> Formatter.html_escape("text/html")
156 |> String.replace(~r/\r?\n/, "")
157 |> (&{[], &1}).()
158 |> Formatter.add_user_links(mentions)
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 end