Remove pl-dark-masto-fe, add preloading for common scripts
[akkoma] / lib / pleroma / user.ex
1 defmodule Pleroma.User do
2 use Ecto.Schema
3
4 import Ecto.{Changeset, Query}
5 alias Pleroma.{Repo, User, Object, Web, Activity, Notification}
6 alias Comeonin.Pbkdf2
7 alias Pleroma.Web.{OStatus, Websub}
8 alias Pleroma.Web.ActivityPub.{Utils, ActivityPub}
9
10 schema "users" do
11 field(:bio, :string)
12 field(:email, :string)
13 field(:name, :string)
14 field(:nickname, :string)
15 field(:password_hash, :string)
16 field(:password, :string, virtual: true)
17 field(:password_confirmation, :string, virtual: true)
18 field(:following, {:array, :string}, default: [])
19 field(:ap_id, :string)
20 field(:avatar, :map)
21 field(:local, :boolean, default: true)
22 field(:info, :map, default: %{})
23 field(:follower_address, :string)
24 has_many(:notifications, Notification)
25
26 timestamps()
27 end
28
29 def avatar_url(user) do
30 case user.avatar do
31 %{"url" => [%{"href" => href} | _]} -> href
32 _ -> "#{Web.base_url()}/images/avi.png"
33 end
34 end
35
36 def banner_url(user) do
37 case user.info["banner"] do
38 %{"url" => [%{"href" => href} | _]} -> href
39 _ -> "#{Web.base_url()}/images/banner.png"
40 end
41 end
42
43 def ap_id(%User{nickname: nickname}) do
44 "#{Web.base_url()}/users/#{nickname}"
45 end
46
47 def ap_followers(%User{} = user) do
48 "#{ap_id(user)}/followers"
49 end
50
51 def follow_changeset(struct, params \\ %{}) do
52 struct
53 |> cast(params, [:following])
54 |> validate_required([:following])
55 end
56
57 def info_changeset(struct, params \\ %{}) do
58 struct
59 |> cast(params, [:info])
60 |> validate_required([:info])
61 end
62
63 def user_info(%User{} = user) do
64 oneself = if user.local, do: 1, else: 0
65
66 %{
67 following_count: length(user.following) - oneself,
68 note_count: user.info["note_count"] || 0,
69 follower_count: user.info["follower_count"] || 0
70 }
71 end
72
73 @email_regex ~r/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
74 def remote_user_creation(params) do
75 changes =
76 %User{}
77 |> cast(params, [:bio, :name, :ap_id, :nickname, :info, :avatar])
78 |> validate_required([:name, :ap_id, :nickname])
79 |> unique_constraint(:nickname)
80 |> validate_format(:nickname, @email_regex)
81 |> validate_length(:bio, max: 5000)
82 |> validate_length(:name, max: 100)
83 |> put_change(:local, false)
84
85 if changes.valid? do
86 case changes.changes[:info]["source_data"] do
87 %{"followers" => followers} ->
88 changes
89 |> put_change(:follower_address, followers)
90
91 _ ->
92 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
93
94 changes
95 |> put_change(:follower_address, followers)
96 end
97 else
98 changes
99 end
100 end
101
102 def update_changeset(struct, params \\ %{}) do
103 struct
104 |> cast(params, [:bio, :name])
105 |> unique_constraint(:nickname)
106 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
107 |> validate_length(:bio, max: 1000)
108 |> validate_length(:name, min: 1, max: 100)
109 end
110
111 def upgrade_changeset(struct, params \\ %{}) do
112 struct
113 |> cast(params, [:bio, :name, :info, :follower_address, :avatar])
114 |> unique_constraint(:nickname)
115 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
116 |> validate_length(:bio, max: 5000)
117 |> validate_length(:name, max: 100)
118 end
119
120 def password_update_changeset(struct, params) do
121 changeset =
122 struct
123 |> cast(params, [:password, :password_confirmation])
124 |> validate_required([:password, :password_confirmation])
125 |> validate_confirmation(:password)
126
127 if changeset.valid? do
128 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
129
130 changeset
131 |> put_change(:password_hash, hashed)
132 else
133 changeset
134 end
135 end
136
137 def reset_password(user, data) do
138 update_and_set_cache(password_update_changeset(user, data))
139 end
140
141 def register_changeset(struct, params \\ %{}) do
142 changeset =
143 struct
144 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
145 |> validate_required([:email, :name, :nickname, :password, :password_confirmation])
146 |> validate_confirmation(:password)
147 |> unique_constraint(:email)
148 |> unique_constraint(:nickname)
149 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
150 |> validate_format(:email, @email_regex)
151 |> validate_length(:bio, max: 1000)
152 |> validate_length(:name, min: 1, max: 100)
153
154 if changeset.valid? do
155 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
156 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
157 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
158
159 changeset
160 |> put_change(:password_hash, hashed)
161 |> put_change(:ap_id, ap_id)
162 |> put_change(:following, [followers])
163 |> put_change(:follower_address, followers)
164 else
165 changeset
166 end
167 end
168
169 def follow(%User{} = follower, %User{info: info} = followed) do
170 ap_followers = followed.follower_address
171
172 if following?(follower, followed) or info["deactivated"] do
173 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
174 else
175 if !followed.local && follower.local && !ap_enabled?(followed) do
176 Websub.subscribe(follower, followed)
177 end
178
179 following =
180 [ap_followers | follower.following]
181 |> Enum.uniq()
182
183 follower =
184 follower
185 |> follow_changeset(%{following: following})
186 |> update_and_set_cache
187
188 {:ok, _} = update_follower_count(followed)
189
190 follower
191 end
192 end
193
194 def unfollow(%User{} = follower, %User{} = followed) do
195 ap_followers = followed.follower_address
196
197 if following?(follower, followed) and follower.ap_id != followed.ap_id do
198 following =
199 follower.following
200 |> List.delete(ap_followers)
201
202 {:ok, follower} =
203 follower
204 |> follow_changeset(%{following: following})
205 |> update_and_set_cache
206
207 {:ok, followed} = update_follower_count(followed)
208
209 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
210 else
211 {:error, "Not subscribed!"}
212 end
213 end
214
215 def following?(%User{} = follower, %User{} = followed) do
216 Enum.member?(follower.following, followed.follower_address)
217 end
218
219 def get_by_ap_id(ap_id) do
220 Repo.get_by(User, ap_id: ap_id)
221 end
222
223 def update_and_set_cache(changeset) do
224 with {:ok, user} <- Repo.update(changeset) do
225 Cachex.set(:user_cache, "ap_id:#{user.ap_id}", user)
226 Cachex.set(:user_cache, "nickname:#{user.nickname}", user)
227 Cachex.set(:user_cache, "user_info:#{user.id}", user_info(user))
228 {:ok, user}
229 else
230 e -> e
231 end
232 end
233
234 def invalidate_cache(user) do
235 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
236 Cachex.del(:user_cache, "nickname:#{user.nickname}")
237 end
238
239 def get_cached_by_ap_id(ap_id) do
240 key = "ap_id:#{ap_id}"
241 Cachex.get!(:user_cache, key, fallback: fn _ -> get_by_ap_id(ap_id) end)
242 end
243
244 def get_cached_by_nickname(nickname) do
245 key = "nickname:#{nickname}"
246 Cachex.get!(:user_cache, key, fallback: fn _ -> get_or_fetch_by_nickname(nickname) end)
247 end
248
249 def get_by_nickname(nickname) do
250 Repo.get_by(User, nickname: nickname)
251 end
252
253 def get_cached_user_info(user) do
254 key = "user_info:#{user.id}"
255 Cachex.get!(:user_cache, key, fallback: fn _ -> user_info(user) end)
256 end
257
258 def fetch_by_nickname(nickname) do
259 ap_try = ActivityPub.make_user_from_nickname(nickname)
260
261 case ap_try do
262 {:ok, user} -> {:ok, user}
263 _ -> OStatus.make_user(nickname)
264 end
265 end
266
267 def get_or_fetch_by_nickname(nickname) do
268 with %User{} = user <- get_by_nickname(nickname) do
269 user
270 else
271 _e ->
272 with [_nick, _domain] <- String.split(nickname, "@"),
273 {:ok, user} <- fetch_by_nickname(nickname) do
274 user
275 else
276 _e -> nil
277 end
278 end
279 end
280
281 def get_followers(%User{id: id, follower_address: follower_address}) do
282 q =
283 from(
284 u in User,
285 where: fragment("? <@ ?", ^[follower_address], u.following),
286 where: u.id != ^id
287 )
288
289 {:ok, Repo.all(q)}
290 end
291
292 def get_friends(%User{id: id, following: following}) do
293 q =
294 from(
295 u in User,
296 where: u.follower_address in ^following,
297 where: u.id != ^id
298 )
299
300 {:ok, Repo.all(q)}
301 end
302
303 def increase_note_count(%User{} = user) do
304 note_count = (user.info["note_count"] || 0) + 1
305 new_info = Map.put(user.info, "note_count", note_count)
306
307 cs = info_changeset(user, %{info: new_info})
308
309 update_and_set_cache(cs)
310 end
311
312 def update_note_count(%User{} = user) do
313 note_count_query =
314 from(
315 a in Object,
316 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
317 select: count(a.id)
318 )
319
320 note_count = Repo.one(note_count_query)
321
322 new_info = Map.put(user.info, "note_count", note_count)
323
324 cs = info_changeset(user, %{info: new_info})
325
326 update_and_set_cache(cs)
327 end
328
329 def update_follower_count(%User{} = user) do
330 follower_count_query =
331 from(
332 u in User,
333 where: ^user.follower_address in u.following,
334 where: u.id != ^user.id,
335 select: count(u.id)
336 )
337
338 follower_count = Repo.one(follower_count_query)
339
340 new_info = Map.put(user.info, "follower_count", follower_count)
341
342 cs = info_changeset(user, %{info: new_info})
343
344 update_and_set_cache(cs)
345 end
346
347 def get_notified_from_activity(%Activity{recipients: to}) do
348 query =
349 from(
350 u in User,
351 where: u.ap_id in ^to,
352 where: u.local == true
353 )
354
355 Repo.all(query)
356 end
357
358 def get_recipients_from_activity(%Activity{recipients: to}) do
359 query =
360 from(
361 u in User,
362 where: u.ap_id in ^to,
363 or_where: fragment("? && ?", u.following, ^to)
364 )
365
366 query = from(u in query, where: u.local == true)
367
368 Repo.all(query)
369 end
370
371 def search(query, resolve) do
372 if resolve do
373 User.get_or_fetch_by_nickname(query)
374 end
375
376 q =
377 from(
378 u in User,
379 where:
380 fragment(
381 "(to_tsvector('english', ?) || to_tsvector('english', ?)) @@ plainto_tsquery('english', ?)",
382 u.nickname,
383 u.name,
384 ^query
385 ),
386 limit: 20
387 )
388
389 Repo.all(q)
390 end
391
392 def block(user, %{ap_id: ap_id}) do
393 blocks = user.info["blocks"] || []
394 new_blocks = Enum.uniq([ap_id | blocks])
395 new_info = Map.put(user.info, "blocks", new_blocks)
396
397 cs = User.info_changeset(user, %{info: new_info})
398 update_and_set_cache(cs)
399 end
400
401 def unblock(user, %{ap_id: ap_id}) do
402 blocks = user.info["blocks"] || []
403 new_blocks = List.delete(blocks, ap_id)
404 new_info = Map.put(user.info, "blocks", new_blocks)
405
406 cs = User.info_changeset(user, %{info: new_info})
407 update_and_set_cache(cs)
408 end
409
410 def blocks?(user, %{ap_id: ap_id}) do
411 blocks = user.info["blocks"] || []
412 Enum.member?(blocks, ap_id)
413 end
414
415 def local_user_query() do
416 from(u in User, where: u.local == true)
417 end
418
419 def deactivate(%User{} = user) do
420 new_info = Map.put(user.info, "deactivated", true)
421 cs = User.info_changeset(user, %{info: new_info})
422 update_and_set_cache(cs)
423 end
424
425 def delete(%User{} = user) do
426 {:ok, user} = User.deactivate(user)
427
428 # Remove all relationships
429 {:ok, followers} = User.get_followers(user)
430
431 followers
432 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
433
434 {:ok, friends} = User.get_friends(user)
435
436 friends
437 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
438
439 query = from(a in Activity, where: a.actor == ^user.ap_id)
440
441 Repo.all(query)
442 |> Enum.each(fn activity ->
443 case activity.data["type"] do
444 "Create" ->
445 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
446
447 # TODO: Do something with likes, follows, repeats.
448 _ ->
449 "Doing nothing"
450 end
451 end)
452
453 :ok
454 end
455
456 def get_or_fetch_by_ap_id(ap_id) do
457 if user = get_by_ap_id(ap_id) do
458 user
459 else
460 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
461
462 case ap_try do
463 {:ok, user} ->
464 user
465
466 _ ->
467 case OStatus.make_user(ap_id) do
468 {:ok, user} -> user
469 _ -> {:error, "Could not fetch by AP id"}
470 end
471 end
472 end
473 end
474
475 # AP style
476 def public_key_from_info(%{
477 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
478 }) do
479 key =
480 :public_key.pem_decode(public_key_pem)
481 |> hd()
482 |> :public_key.pem_entry_decode()
483
484 {:ok, key}
485 end
486
487 # OStatus Magic Key
488 def public_key_from_info(%{"magic_key" => magic_key}) do
489 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
490 end
491
492 def get_public_key_for_ap_id(ap_id) do
493 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
494 {:ok, public_key} <- public_key_from_info(user.info) do
495 {:ok, public_key}
496 else
497 _ -> :error
498 end
499 end
500
501 defp blank?(""), do: nil
502 defp blank?(n), do: n
503
504 def insert_or_update_user(data) do
505 data =
506 data
507 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
508
509 cs = User.remote_user_creation(data)
510 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
511 end
512
513 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
514 def ap_enabled?(_), do: false
515
516 def get_or_fetch(uri_or_nickname) do
517 if String.starts_with?(uri_or_nickname, "http") do
518 get_or_fetch_by_ap_id(uri_or_nickname)
519 else
520 get_or_fetch_by_nickname(uri_or_nickname)
521 end
522 end
523 end