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