e4fb57308749173b211519280f7ed2bb52087b10
[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 def maybe_direct_follow(%User{} = follower, %User{info: info} = followed) do
172 user_info = user_info(followed)
173
174 should_direct_follow =
175 cond do
176 # if the account is locked, don't pre-create the relationship
177 user_info.locked == true ->
178 false
179
180 # if the users are blocking each other, we shouldn't even be here, but check for it anyway
181 User.blocks?(follower, followed) == true or User.blocks?(followed, follower) == true ->
182 false
183
184 # if OStatus, then there is no three-way handshake to follow
185 User.ap_enabled?(followed) != true ->
186 true
187
188 # if there are no other reasons not to, just pre-create the relationship
189 true ->
190 true
191 end
192
193 if should_direct_follow do
194 follow(follower, followed)
195 else
196 follower
197 end
198 end
199
200 def follow(%User{} = follower, %User{info: info} = followed) do
201 ap_followers = followed.follower_address
202
203 if following?(follower, followed) or info["deactivated"] do
204 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
205 else
206 if !followed.local && follower.local && !ap_enabled?(followed) do
207 Websub.subscribe(follower, followed)
208 end
209
210 following =
211 [ap_followers | follower.following]
212 |> Enum.uniq()
213
214 follower =
215 follower
216 |> follow_changeset(%{following: following})
217 |> update_and_set_cache
218
219 {:ok, _} = update_follower_count(followed)
220
221 follower
222 end
223 end
224
225 def unfollow(%User{} = follower, %User{} = followed) do
226 ap_followers = followed.follower_address
227
228 if following?(follower, followed) and follower.ap_id != followed.ap_id do
229 following =
230 follower.following
231 |> List.delete(ap_followers)
232
233 {:ok, follower} =
234 follower
235 |> follow_changeset(%{following: following})
236 |> update_and_set_cache
237
238 {:ok, followed} = update_follower_count(followed)
239
240 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
241 else
242 {:error, "Not subscribed!"}
243 end
244 end
245
246 def following?(%User{} = follower, %User{} = followed) do
247 Enum.member?(follower.following, followed.follower_address)
248 end
249
250 def get_by_ap_id(ap_id) do
251 Repo.get_by(User, ap_id: ap_id)
252 end
253
254 def update_and_set_cache(changeset) do
255 with {:ok, user} <- Repo.update(changeset) do
256 Cachex.put(:user_cache, "ap_id:#{user.ap_id}", user)
257 Cachex.put(:user_cache, "nickname:#{user.nickname}", user)
258 Cachex.put(:user_cache, "user_info:#{user.id}", user_info(user))
259 {:ok, user}
260 else
261 e -> e
262 end
263 end
264
265 def invalidate_cache(user) do
266 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
267 Cachex.del(:user_cache, "nickname:#{user.nickname}")
268 end
269
270 def get_cached_by_ap_id(ap_id) do
271 key = "ap_id:#{ap_id}"
272 Cachex.fetch!(:user_cache, key, fn _ -> get_by_ap_id(ap_id) end)
273 end
274
275 def get_cached_by_nickname(nickname) do
276 key = "nickname:#{nickname}"
277 Cachex.fetch!(:user_cache, key, fn _ -> get_or_fetch_by_nickname(nickname) end)
278 end
279
280 def get_by_nickname(nickname) do
281 Repo.get_by(User, nickname: nickname)
282 end
283
284 def get_by_nickname_or_email(nickname_or_email) do
285 case user = Repo.get_by(User, nickname: nickname_or_email) do
286 %User{} -> user
287 nil -> Repo.get_by(User, email: nickname_or_email)
288 end
289 end
290
291 def get_cached_user_info(user) do
292 key = "user_info:#{user.id}"
293 Cachex.fetch!(:user_cache, key, fn _ -> user_info(user) end)
294 end
295
296 def fetch_by_nickname(nickname) do
297 ap_try = ActivityPub.make_user_from_nickname(nickname)
298
299 case ap_try do
300 {:ok, user} -> {:ok, user}
301 _ -> OStatus.make_user(nickname)
302 end
303 end
304
305 def get_or_fetch_by_nickname(nickname) do
306 with %User{} = user <- get_by_nickname(nickname) do
307 user
308 else
309 _e ->
310 with [_nick, _domain] <- String.split(nickname, "@"),
311 {:ok, user} <- fetch_by_nickname(nickname) do
312 user
313 else
314 _e -> nil
315 end
316 end
317 end
318
319 def get_followers_query(%User{id: id, follower_address: follower_address}) do
320 from(
321 u in User,
322 where: fragment("? <@ ?", ^[follower_address], u.following),
323 where: u.id != ^id
324 )
325 end
326
327 def get_followers(user) do
328 q = get_followers_query(user)
329
330 {:ok, Repo.all(q)}
331 end
332
333 def get_friends_query(%User{id: id, following: following}) do
334 from(
335 u in User,
336 where: u.follower_address in ^following,
337 where: u.id != ^id
338 )
339 end
340
341 def get_friends(user) do
342 q = get_friends_query(user)
343
344 {:ok, Repo.all(q)}
345 end
346
347 def increase_note_count(%User{} = user) do
348 note_count = (user.info["note_count"] || 0) + 1
349 new_info = Map.put(user.info, "note_count", note_count)
350
351 cs = info_changeset(user, %{info: new_info})
352
353 update_and_set_cache(cs)
354 end
355
356 def decrease_note_count(%User{} = user) do
357 note_count = user.info["note_count"] || 0
358 note_count = if note_count <= 0, do: 0, else: note_count - 1
359 new_info = Map.put(user.info, "note_count", note_count)
360
361 cs = info_changeset(user, %{info: new_info})
362
363 update_and_set_cache(cs)
364 end
365
366 def update_note_count(%User{} = user) do
367 note_count_query =
368 from(
369 a in Object,
370 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
371 select: count(a.id)
372 )
373
374 note_count = Repo.one(note_count_query)
375
376 new_info = Map.put(user.info, "note_count", note_count)
377
378 cs = info_changeset(user, %{info: new_info})
379
380 update_and_set_cache(cs)
381 end
382
383 def update_follower_count(%User{} = user) do
384 follower_count_query =
385 from(
386 u in User,
387 where: ^user.follower_address in u.following,
388 where: u.id != ^user.id,
389 select: count(u.id)
390 )
391
392 follower_count = Repo.one(follower_count_query)
393
394 new_info = Map.put(user.info, "follower_count", follower_count)
395
396 cs = info_changeset(user, %{info: new_info})
397
398 update_and_set_cache(cs)
399 end
400
401 def get_notified_from_activity(%Activity{recipients: to}) do
402 query =
403 from(
404 u in User,
405 where: u.ap_id in ^to,
406 where: u.local == true
407 )
408
409 Repo.all(query)
410 end
411
412 def get_recipients_from_activity(%Activity{recipients: to}) do
413 query =
414 from(
415 u in User,
416 where: u.ap_id in ^to,
417 or_where: fragment("? && ?", u.following, ^to)
418 )
419
420 query = from(u in query, where: u.local == true)
421
422 Repo.all(query)
423 end
424
425 def search(query, resolve) do
426 # strip the beginning @ off if there is a query
427 query = String.trim_leading(query, "@")
428
429 if resolve do
430 User.get_or_fetch_by_nickname(query)
431 end
432
433 inner =
434 from(
435 u in User,
436 select_merge: %{
437 search_distance:
438 fragment(
439 "? <-> (? || ?)",
440 ^query,
441 u.nickname,
442 u.name
443 )
444 }
445 )
446
447 q =
448 from(
449 s in subquery(inner),
450 order_by: s.search_distance,
451 limit: 20
452 )
453
454 Repo.all(q)
455 end
456
457 def block(user, %{ap_id: ap_id}) do
458 blocks = user.info["blocks"] || []
459 new_blocks = Enum.uniq([ap_id | blocks])
460 new_info = Map.put(user.info, "blocks", new_blocks)
461
462 cs = User.info_changeset(user, %{info: new_info})
463 update_and_set_cache(cs)
464 end
465
466 def unblock(user, %{ap_id: ap_id}) do
467 blocks = user.info["blocks"] || []
468 new_blocks = List.delete(blocks, ap_id)
469 new_info = Map.put(user.info, "blocks", new_blocks)
470
471 cs = User.info_changeset(user, %{info: new_info})
472 update_and_set_cache(cs)
473 end
474
475 def blocks?(user, %{ap_id: ap_id}) do
476 blocks = user.info["blocks"] || []
477 Enum.member?(blocks, ap_id)
478 end
479
480 def local_user_query() do
481 from(u in User, where: u.local == true)
482 end
483
484 def deactivate(%User{} = user) do
485 new_info = Map.put(user.info, "deactivated", true)
486 cs = User.info_changeset(user, %{info: new_info})
487 update_and_set_cache(cs)
488 end
489
490 def delete(%User{} = user) do
491 {:ok, user} = User.deactivate(user)
492
493 # Remove all relationships
494 {:ok, followers} = User.get_followers(user)
495
496 followers
497 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
498
499 {:ok, friends} = User.get_friends(user)
500
501 friends
502 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
503
504 query = from(a in Activity, where: a.actor == ^user.ap_id)
505
506 Repo.all(query)
507 |> Enum.each(fn activity ->
508 case activity.data["type"] do
509 "Create" ->
510 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
511
512 # TODO: Do something with likes, follows, repeats.
513 _ ->
514 "Doing nothing"
515 end
516 end)
517
518 :ok
519 end
520
521 def get_or_fetch_by_ap_id(ap_id) do
522 if user = get_by_ap_id(ap_id) do
523 user
524 else
525 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
526
527 case ap_try do
528 {:ok, user} ->
529 user
530
531 _ ->
532 case OStatus.make_user(ap_id) do
533 {:ok, user} -> user
534 _ -> {:error, "Could not fetch by AP id"}
535 end
536 end
537 end
538 end
539
540 # AP style
541 def public_key_from_info(%{
542 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
543 }) do
544 key =
545 :public_key.pem_decode(public_key_pem)
546 |> hd()
547 |> :public_key.pem_entry_decode()
548
549 {:ok, key}
550 end
551
552 # OStatus Magic Key
553 def public_key_from_info(%{"magic_key" => magic_key}) do
554 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
555 end
556
557 def get_public_key_for_ap_id(ap_id) do
558 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
559 {:ok, public_key} <- public_key_from_info(user.info) do
560 {:ok, public_key}
561 else
562 _ -> :error
563 end
564 end
565
566 defp blank?(""), do: nil
567 defp blank?(n), do: n
568
569 def insert_or_update_user(data) do
570 data =
571 data
572 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
573
574 cs = User.remote_user_creation(data)
575 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
576 end
577
578 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
579 def ap_enabled?(_), do: false
580
581 def get_or_fetch(uri_or_nickname) do
582 if String.starts_with?(uri_or_nickname, "http") do
583 get_or_fetch_by_ap_id(uri_or_nickname)
584 else
585 get_or_fetch_by_nickname(uri_or_nickname)
586 end
587 end
588 end