1 defmodule Pleroma.User do
4 import Ecto.{Changeset, Query}
5 alias Pleroma.{Repo, User, Object, Web, Activity, Notification}
7 alias Pleroma.Web.{OStatus, Websub}
8 alias Pleroma.Web.ActivityPub.{Utils, ActivityPub}
12 field(:email, :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)
21 field(:local, :boolean, default: true)
22 field(:info, :map, default: %{})
23 field(:follower_address, :string)
24 has_many(:notifications, Notification)
29 def avatar_url(user) do
31 %{"url" => [%{"href" => href} | _]} -> href
32 _ -> "#{Web.base_url()}/images/avi.png"
36 def banner_url(user) do
37 case user.info["banner"] do
38 %{"url" => [%{"href" => href} | _]} -> href
39 _ -> "#{Web.base_url()}/images/banner.png"
43 def ap_id(%User{nickname: nickname}) do
44 "#{Web.base_url()}/users/#{nickname}"
47 def ap_followers(%User{} = user) do
48 "#{ap_id(user)}/followers"
51 def follow_changeset(struct, params \\ %{}) do
53 |> cast(params, [:following])
54 |> validate_required([:following])
57 def info_changeset(struct, params \\ %{}) do
59 |> cast(params, [:info])
60 |> validate_required([:info])
63 def user_info(%User{} = user) do
64 oneself = if user.local, do: 1, else: 0
67 following_count: length(user.following) - oneself,
68 note_count: user.info["note_count"] || 0,
69 follower_count: user.info["follower_count"] || 0
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
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)
86 case changes.changes[:info]["source_data"] do
87 %{"followers" => followers} ->
89 |> put_change(:follower_address, followers)
92 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
95 |> put_change(:follower_address, followers)
102 def update_changeset(struct, params \\ %{}) do
104 |> cast(params, [:bio, :name])
105 |> unique_constraint(:nickname)
106 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
107 |> validate_length(:bio, max: 5000)
108 |> validate_length(:name, min: 1, max: 100)
111 def upgrade_changeset(struct, params \\ %{}) do
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)
120 def password_update_changeset(struct, params) do
123 |> cast(params, [:password, :password_confirmation])
124 |> validate_required([:password, :password_confirmation])
125 |> validate_confirmation(:password)
127 if changeset.valid? do
128 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
131 |> put_change(:password_hash, hashed)
137 def reset_password(user, data) do
138 update_and_set_cache(password_update_changeset(user, data))
141 def register_changeset(struct, params \\ %{}) do
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)
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]})
160 |> put_change(:password_hash, hashed)
161 |> put_change(:ap_id, ap_id)
162 |> put_change(:following, [followers])
163 |> put_change(:follower_address, followers)
169 def follow(%User{} = follower, %User{info: info} = followed) do
170 ap_followers = followed.follower_address
172 if following?(follower, followed) or info["deactivated"] do
173 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
175 if !followed.local && follower.local && !ap_enabled?(followed) do
176 Websub.subscribe(follower, followed)
180 [ap_followers | follower.following]
185 |> follow_changeset(%{following: following})
186 |> update_and_set_cache
188 {:ok, _} = update_follower_count(followed)
194 def unfollow(%User{} = follower, %User{} = followed) do
195 ap_followers = followed.follower_address
197 if following?(follower, followed) and follower.ap_id != followed.ap_id do
200 |> List.delete(ap_followers)
204 |> follow_changeset(%{following: following})
205 |> update_and_set_cache
207 {:ok, followed} = update_follower_count(followed)
209 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
211 {:error, "Not subscribed!"}
215 def following?(%User{} = follower, %User{} = followed) do
216 Enum.member?(follower.following, followed.follower_address)
219 def get_by_ap_id(ap_id) do
220 Repo.get_by(User, ap_id: ap_id)
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))
234 def invalidate_cache(user) do
235 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
236 Cachex.del(:user_cache, "nickname:#{user.nickname}")
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)
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)
249 def get_by_nickname(nickname) do
250 Repo.get_by(User, nickname: nickname)
253 def get_by_nickname_or_email(nickname_or_email) do
254 case user = Repo.get_by(User, nickname: nickname_or_email) do
256 nil -> Repo.get_by(User, email: nickname_or_email)
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)
265 def fetch_by_nickname(nickname) do
266 ap_try = ActivityPub.make_user_from_nickname(nickname)
269 {:ok, user} -> {:ok, user}
270 _ -> OStatus.make_user(nickname)
274 def get_or_fetch_by_nickname(nickname) do
275 with %User{} = user <- get_by_nickname(nickname) do
279 with [_nick, _domain] <- String.split(nickname, "@"),
280 {:ok, user} <- fetch_by_nickname(nickname) do
288 def get_followers_query(%User{id: id, follower_address: follower_address}) do
291 where: fragment("? <@ ?", ^[follower_address], u.following),
296 def get_followers(user) do
297 q = get_followers_query(user)
302 def get_friends_query(%User{id: id, following: following}) do
305 where: u.follower_address in ^following,
310 def get_friends(user) do
311 q = get_friends_query(user)
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)
320 cs = info_changeset(user, %{info: new_info})
322 update_and_set_cache(cs)
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)
330 cs = info_changeset(user, %{info: new_info})
332 update_and_set_cache(cs)
335 def update_note_count(%User{} = user) do
339 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
343 note_count = Repo.one(note_count_query)
345 new_info = Map.put(user.info, "note_count", note_count)
347 cs = info_changeset(user, %{info: new_info})
349 update_and_set_cache(cs)
352 def update_follower_count(%User{} = user) do
353 follower_count_query =
356 where: ^user.follower_address in u.following,
357 where: u.id != ^user.id,
361 follower_count = Repo.one(follower_count_query)
363 new_info = Map.put(user.info, "follower_count", follower_count)
365 cs = info_changeset(user, %{info: new_info})
367 update_and_set_cache(cs)
370 def get_notified_from_activity(%Activity{recipients: to}) do
374 where: u.ap_id in ^to,
375 where: u.local == true
381 def get_recipients_from_activity(%Activity{recipients: to}) do
385 where: u.ap_id in ^to,
386 or_where: fragment("? && ?", u.following, ^to)
389 query = from(u in query, where: u.local == true)
394 def search(query, resolve) do
395 # strip the beginning @ off if there is a query
396 query = String.trim_leading(query, "@")
399 User.get_or_fetch_by_nickname(query)
407 "(to_tsvector('english', ?) || to_tsvector('english', ?)) @@ plainto_tsquery('english', ?)",
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)
423 cs = User.info_changeset(user, %{info: new_info})
424 update_and_set_cache(cs)
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)
432 cs = User.info_changeset(user, %{info: new_info})
433 update_and_set_cache(cs)
436 def blocks?(user, %{ap_id: ap_id}) do
437 blocks = user.info["blocks"] || []
438 Enum.member?(blocks, ap_id)
441 def local_user_query() do
442 from(u in User, where: u.local == true)
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)
451 def delete(%User{} = user) do
452 {:ok, user} = User.deactivate(user)
454 # Remove all relationships
455 {:ok, followers} = User.get_followers(user)
458 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
460 {:ok, friends} = User.get_friends(user)
463 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
465 query = from(a in Activity, where: a.actor == ^user.ap_id)
468 |> Enum.each(fn activity ->
469 case activity.data["type"] do
471 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
473 # TODO: Do something with likes, follows, repeats.
482 def get_or_fetch_by_ap_id(ap_id) do
483 if user = get_by_ap_id(ap_id) do
486 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
493 case OStatus.make_user(ap_id) do
495 _ -> {:error, "Could not fetch by AP id"}
502 def public_key_from_info(%{
503 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
506 :public_key.pem_decode(public_key_pem)
508 |> :public_key.pem_entry_decode()
514 def public_key_from_info(%{"magic_key" => magic_key}) do
515 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
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
527 defp blank?(""), do: nil
528 defp blank?(n), do: n
530 def insert_or_update_user(data) do
533 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
535 cs = User.remote_user_creation(data)
536 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
539 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
540 def ap_enabled?(_), do: false
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)
546 get_or_fetch_by_nickname(uri_or_nickname)