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