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