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