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