Merge branch 'favicon_tag' 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 update_note_count(%User{} = user) do
326 note_count_query =
327 from(
328 a in Object,
329 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
330 select: count(a.id)
331 )
332
333 note_count = Repo.one(note_count_query)
334
335 new_info = Map.put(user.info, "note_count", note_count)
336
337 cs = info_changeset(user, %{info: new_info})
338
339 update_and_set_cache(cs)
340 end
341
342 def update_follower_count(%User{} = user) do
343 follower_count_query =
344 from(
345 u in User,
346 where: ^user.follower_address in u.following,
347 where: u.id != ^user.id,
348 select: count(u.id)
349 )
350
351 follower_count = Repo.one(follower_count_query)
352
353 new_info = Map.put(user.info, "follower_count", follower_count)
354
355 cs = info_changeset(user, %{info: new_info})
356
357 update_and_set_cache(cs)
358 end
359
360 def get_notified_from_activity(%Activity{recipients: to}) do
361 query =
362 from(
363 u in User,
364 where: u.ap_id in ^to,
365 where: u.local == true
366 )
367
368 Repo.all(query)
369 end
370
371 def get_recipients_from_activity(%Activity{recipients: to}) do
372 query =
373 from(
374 u in User,
375 where: u.ap_id in ^to,
376 or_where: fragment("? && ?", u.following, ^to)
377 )
378
379 query = from(u in query, where: u.local == true)
380
381 Repo.all(query)
382 end
383
384 def search(query, resolve) do
385 # strip the beginning @ off if there is a query
386 query = String.trim_leading(query, "@")
387
388 if resolve do
389 User.get_or_fetch_by_nickname(query)
390 end
391
392 q =
393 from(
394 u in User,
395 where:
396 fragment(
397 "(to_tsvector('english', ?) || to_tsvector('english', ?)) @@ plainto_tsquery('english', ?)",
398 u.nickname,
399 u.name,
400 ^query
401 ),
402 limit: 20
403 )
404
405 Repo.all(q)
406 end
407
408 def block(user, %{ap_id: ap_id}) do
409 blocks = user.info["blocks"] || []
410 new_blocks = Enum.uniq([ap_id | blocks])
411 new_info = Map.put(user.info, "blocks", new_blocks)
412
413 cs = User.info_changeset(user, %{info: new_info})
414 update_and_set_cache(cs)
415 end
416
417 def unblock(user, %{ap_id: ap_id}) do
418 blocks = user.info["blocks"] || []
419 new_blocks = List.delete(blocks, ap_id)
420 new_info = Map.put(user.info, "blocks", new_blocks)
421
422 cs = User.info_changeset(user, %{info: new_info})
423 update_and_set_cache(cs)
424 end
425
426 def blocks?(user, %{ap_id: ap_id}) do
427 blocks = user.info["blocks"] || []
428 Enum.member?(blocks, ap_id)
429 end
430
431 def local_user_query() do
432 from(u in User, where: u.local == true)
433 end
434
435 def deactivate(%User{} = user) do
436 new_info = Map.put(user.info, "deactivated", true)
437 cs = User.info_changeset(user, %{info: new_info})
438 update_and_set_cache(cs)
439 end
440
441 def delete(%User{} = user) do
442 {:ok, user} = User.deactivate(user)
443
444 # Remove all relationships
445 {:ok, followers} = User.get_followers(user)
446
447 followers
448 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
449
450 {:ok, friends} = User.get_friends(user)
451
452 friends
453 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
454
455 query = from(a in Activity, where: a.actor == ^user.ap_id)
456
457 Repo.all(query)
458 |> Enum.each(fn activity ->
459 case activity.data["type"] do
460 "Create" ->
461 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
462
463 # TODO: Do something with likes, follows, repeats.
464 _ ->
465 "Doing nothing"
466 end
467 end)
468
469 :ok
470 end
471
472 def get_or_fetch_by_ap_id(ap_id) do
473 if user = get_by_ap_id(ap_id) do
474 user
475 else
476 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
477
478 case ap_try do
479 {:ok, user} ->
480 user
481
482 _ ->
483 case OStatus.make_user(ap_id) do
484 {:ok, user} -> user
485 _ -> {:error, "Could not fetch by AP id"}
486 end
487 end
488 end
489 end
490
491 # AP style
492 def public_key_from_info(%{
493 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
494 }) do
495 key =
496 :public_key.pem_decode(public_key_pem)
497 |> hd()
498 |> :public_key.pem_entry_decode()
499
500 {:ok, key}
501 end
502
503 # OStatus Magic Key
504 def public_key_from_info(%{"magic_key" => magic_key}) do
505 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
506 end
507
508 def get_public_key_for_ap_id(ap_id) do
509 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
510 {:ok, public_key} <- public_key_from_info(user.info) do
511 {:ok, public_key}
512 else
513 _ -> :error
514 end
515 end
516
517 defp blank?(""), do: nil
518 defp blank?(n), do: n
519
520 def insert_or_update_user(data) do
521 data =
522 data
523 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
524
525 cs = User.remote_user_creation(data)
526 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
527 end
528
529 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
530 def ap_enabled?(_), do: false
531
532 def get_or_fetch(uri_or_nickname) do
533 if String.starts_with?(uri_or_nickname, "http") do
534 get_or_fetch_by_ap_id(uri_or_nickname)
535 else
536 get_or_fetch_by_nickname(uri_or_nickname)
537 end
538 end
539 end