e959fe67738bdc33f2d38238c4495d07a1f9e70d
[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_cached_user_info(user) do
254 key = "user_info:#{user.id}"
255 Cachex.get!(:user_cache, key, fallback: fn _ -> user_info(user) end)
256 end
257
258 def fetch_by_nickname(nickname) do
259 ap_try = ActivityPub.make_user_from_nickname(nickname)
260
261 case ap_try do
262 {:ok, user} -> {:ok, user}
263 _ -> OStatus.make_user(nickname)
264 end
265 end
266
267 def get_or_fetch_by_nickname(nickname) do
268 with %User{} = user <- get_by_nickname(nickname) do
269 user
270 else
271 _e ->
272 with [_nick, _domain] <- String.split(nickname, "@"),
273 {:ok, user} <- fetch_by_nickname(nickname) do
274 user
275 else
276 _e -> nil
277 end
278 end
279 end
280
281 def get_followers_query(%User{id: id, follower_address: follower_address}) do
282 from(
283 u in User,
284 where: fragment("? <@ ?", ^[follower_address], u.following),
285 where: u.id != ^id
286 )
287 end
288
289 def get_followers(user) do
290 q = get_followers_query(user)
291
292 {:ok, Repo.all(q)}
293 end
294
295 def get_friends_query(%User{id: id, following: following}) do
296 from(
297 u in User,
298 where: u.follower_address in ^following,
299 where: u.id != ^id
300 )
301 end
302
303 def get_friends(user) do
304 q = get_friends_query(user)
305
306 {:ok, Repo.all(q)}
307 end
308
309 def increase_note_count(%User{} = user) do
310 note_count = (user.info["note_count"] || 0) + 1
311 new_info = Map.put(user.info, "note_count", note_count)
312
313 cs = info_changeset(user, %{info: new_info})
314
315 update_and_set_cache(cs)
316 end
317
318 def update_note_count(%User{} = user) do
319 note_count_query =
320 from(
321 a in Object,
322 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
323 select: count(a.id)
324 )
325
326 note_count = Repo.one(note_count_query)
327
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_follower_count(%User{} = user) do
336 follower_count_query =
337 from(
338 u in User,
339 where: ^user.follower_address in u.following,
340 where: u.id != ^user.id,
341 select: count(u.id)
342 )
343
344 follower_count = Repo.one(follower_count_query)
345
346 new_info = Map.put(user.info, "follower_count", follower_count)
347
348 cs = info_changeset(user, %{info: new_info})
349
350 update_and_set_cache(cs)
351 end
352
353 def get_notified_from_activity(%Activity{recipients: to}) do
354 query =
355 from(
356 u in User,
357 where: u.ap_id in ^to,
358 where: u.local == true
359 )
360
361 Repo.all(query)
362 end
363
364 def get_recipients_from_activity(%Activity{recipients: to}) do
365 query =
366 from(
367 u in User,
368 where: u.ap_id in ^to,
369 or_where: fragment("? && ?", u.following, ^to)
370 )
371
372 query = from(u in query, where: u.local == true)
373
374 Repo.all(query)
375 end
376
377 def search(query, resolve) do
378 # strip the beginning @ off if there is a query
379 query = String.trim_leading(query, "@")
380
381 if resolve do
382 User.get_or_fetch_by_nickname(query)
383 end
384
385 q =
386 from(
387 u in User,
388 where:
389 fragment(
390 "(to_tsvector('english', ?) || to_tsvector('english', ?)) @@ plainto_tsquery('english', ?)",
391 u.nickname,
392 u.name,
393 ^query
394 ),
395 limit: 20
396 )
397
398 Repo.all(q)
399 end
400
401 def block(user, %{ap_id: ap_id}) do
402 blocks = user.info["blocks"] || []
403 new_blocks = Enum.uniq([ap_id | blocks])
404 new_info = Map.put(user.info, "blocks", new_blocks)
405
406 cs = User.info_changeset(user, %{info: new_info})
407 update_and_set_cache(cs)
408 end
409
410 def unblock(user, %{ap_id: ap_id}) do
411 blocks = user.info["blocks"] || []
412 new_blocks = List.delete(blocks, ap_id)
413 new_info = Map.put(user.info, "blocks", new_blocks)
414
415 cs = User.info_changeset(user, %{info: new_info})
416 update_and_set_cache(cs)
417 end
418
419 def blocks?(user, %{ap_id: ap_id}) do
420 blocks = user.info["blocks"] || []
421 Enum.member?(blocks, ap_id)
422 end
423
424 def local_user_query() do
425 from(u in User, where: u.local == true)
426 end
427
428 def deactivate(%User{} = user) do
429 new_info = Map.put(user.info, "deactivated", true)
430 cs = User.info_changeset(user, %{info: new_info})
431 update_and_set_cache(cs)
432 end
433
434 def delete(%User{} = user) do
435 {:ok, user} = User.deactivate(user)
436
437 # Remove all relationships
438 {:ok, followers} = User.get_followers(user)
439
440 followers
441 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
442
443 {:ok, friends} = User.get_friends(user)
444
445 friends
446 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
447
448 query = from(a in Activity, where: a.actor == ^user.ap_id)
449
450 Repo.all(query)
451 |> Enum.each(fn activity ->
452 case activity.data["type"] do
453 "Create" ->
454 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
455
456 # TODO: Do something with likes, follows, repeats.
457 _ ->
458 "Doing nothing"
459 end
460 end)
461
462 :ok
463 end
464
465 def get_or_fetch_by_ap_id(ap_id) do
466 if user = get_by_ap_id(ap_id) do
467 user
468 else
469 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
470
471 case ap_try do
472 {:ok, user} ->
473 user
474
475 _ ->
476 case OStatus.make_user(ap_id) do
477 {:ok, user} -> user
478 _ -> {:error, "Could not fetch by AP id"}
479 end
480 end
481 end
482 end
483
484 # AP style
485 def public_key_from_info(%{
486 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
487 }) do
488 key =
489 :public_key.pem_decode(public_key_pem)
490 |> hd()
491 |> :public_key.pem_entry_decode()
492
493 {:ok, key}
494 end
495
496 # OStatus Magic Key
497 def public_key_from_info(%{"magic_key" => magic_key}) do
498 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
499 end
500
501 def get_public_key_for_ap_id(ap_id) do
502 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
503 {:ok, public_key} <- public_key_from_info(user.info) do
504 {:ok, public_key}
505 else
506 _ -> :error
507 end
508 end
509
510 defp blank?(""), do: nil
511 defp blank?(n), do: n
512
513 def insert_or_update_user(data) do
514 data =
515 data
516 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
517
518 cs = User.remote_user_creation(data)
519 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
520 end
521
522 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
523 def ap_enabled?(_), do: false
524
525 def get_or_fetch(uri_or_nickname) do
526 if String.starts_with?(uri_or_nickname, "http") do
527 get_or_fetch_by_ap_id(uri_or_nickname)
528 else
529 get_or_fetch_by_nickname(uri_or_nickname)
530 end
531 end
532 end