actually rvert those changes
[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: fragment(
408 "? <-> (? || ?)",
409 ^query,
410 u.nickname,
411 u.name
412 )}
413 )
414
415 q = from(s in subquery(inner),
416 order_by: s.search_distance,
417 limit: 20
418 )
419
420 Repo.all(q)
421 end
422
423 def block(user, %{ap_id: ap_id}) do
424 blocks = user.info["blocks"] || []
425 new_blocks = Enum.uniq([ap_id | blocks])
426 new_info = Map.put(user.info, "blocks", new_blocks)
427
428 cs = User.info_changeset(user, %{info: new_info})
429 update_and_set_cache(cs)
430 end
431
432 def unblock(user, %{ap_id: ap_id}) do
433 blocks = user.info["blocks"] || []
434 new_blocks = List.delete(blocks, ap_id)
435 new_info = Map.put(user.info, "blocks", new_blocks)
436
437 cs = User.info_changeset(user, %{info: new_info})
438 update_and_set_cache(cs)
439 end
440
441 def blocks?(user, %{ap_id: ap_id}) do
442 blocks = user.info["blocks"] || []
443 Enum.member?(blocks, ap_id)
444 end
445
446 def local_user_query() do
447 from(u in User, where: u.local == true)
448 end
449
450 def deactivate(%User{} = user) do
451 new_info = Map.put(user.info, "deactivated", true)
452 cs = User.info_changeset(user, %{info: new_info})
453 update_and_set_cache(cs)
454 end
455
456 def delete(%User{} = user) do
457 {:ok, user} = User.deactivate(user)
458
459 # Remove all relationships
460 {:ok, followers} = User.get_followers(user)
461
462 followers
463 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
464
465 {:ok, friends} = User.get_friends(user)
466
467 friends
468 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
469
470 query = from(a in Activity, where: a.actor == ^user.ap_id)
471
472 Repo.all(query)
473 |> Enum.each(fn activity ->
474 case activity.data["type"] do
475 "Create" ->
476 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
477
478 # TODO: Do something with likes, follows, repeats.
479 _ ->
480 "Doing nothing"
481 end
482 end)
483
484 :ok
485 end
486
487 def get_or_fetch_by_ap_id(ap_id) do
488 if user = get_by_ap_id(ap_id) do
489 user
490 else
491 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
492
493 case ap_try do
494 {:ok, user} ->
495 user
496
497 _ ->
498 case OStatus.make_user(ap_id) do
499 {:ok, user} -> user
500 _ -> {:error, "Could not fetch by AP id"}
501 end
502 end
503 end
504 end
505
506 # AP style
507 def public_key_from_info(%{
508 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
509 }) do
510 key =
511 :public_key.pem_decode(public_key_pem)
512 |> hd()
513 |> :public_key.pem_entry_decode()
514
515 {:ok, key}
516 end
517
518 # OStatus Magic Key
519 def public_key_from_info(%{"magic_key" => magic_key}) do
520 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
521 end
522
523 def get_public_key_for_ap_id(ap_id) do
524 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
525 {:ok, public_key} <- public_key_from_info(user.info) do
526 {:ok, public_key}
527 else
528 _ -> :error
529 end
530 end
531
532 defp blank?(""), do: nil
533 defp blank?(n), do: n
534
535 def insert_or_update_user(data) do
536 data =
537 data
538 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
539
540 cs = User.remote_user_creation(data)
541 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
542 end
543
544 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
545 def ap_enabled?(_), do: false
546
547 def get_or_fetch(uri_or_nickname) do
548 if String.starts_with?(uri_or_nickname, "http") do
549 get_or_fetch_by_ap_id(uri_or_nickname)
550 else
551 get_or_fetch_by_nickname(uri_or_nickname)
552 end
553 end
554 end