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