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 field(:search_distance, :float, virtual: true)
25 has_many(:notifications, Notification)
30 def avatar_url(user) do
32 %{"url" => [%{"href" => href} | _]} -> href
33 _ -> "#{Web.base_url()}/images/avi.png"
37 def banner_url(user) do
38 case user.info["banner"] do
39 %{"url" => [%{"href" => href} | _]} -> href
40 _ -> "#{Web.base_url()}/images/banner.png"
44 def ap_id(%User{nickname: nickname}) do
45 "#{Web.base_url()}/users/#{nickname}"
48 def ap_followers(%User{} = user) do
49 "#{ap_id(user)}/followers"
52 def follow_changeset(struct, params \\ %{}) do
54 |> cast(params, [:following])
55 |> validate_required([:following])
58 def info_changeset(struct, params \\ %{}) do
60 |> cast(params, [:info])
61 |> validate_required([:info])
64 def user_info(%User{} = user) do
65 oneself = if user.local, do: 1, else: 0
68 following_count: length(user.following) - oneself,
69 note_count: user.info["note_count"] || 0,
70 follower_count: user.info["follower_count"] || 0
74 @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])?)*$/
75 def remote_user_creation(params) do
78 |> cast(params, [:bio, :name, :ap_id, :nickname, :info, :avatar])
79 |> validate_required([:name, :ap_id, :nickname])
80 |> unique_constraint(:nickname)
81 |> validate_format(:nickname, @email_regex)
82 |> validate_length(:bio, max: 5000)
83 |> validate_length(:name, max: 100)
84 |> put_change(:local, false)
87 case changes.changes[:info]["source_data"] do
88 %{"followers" => followers} ->
90 |> put_change(:follower_address, followers)
93 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
96 |> put_change(:follower_address, followers)
103 def update_changeset(struct, params \\ %{}) do
105 |> cast(params, [:bio, :name])
106 |> unique_constraint(:nickname)
107 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
108 |> validate_length(:bio, max: 5000)
109 |> validate_length(:name, min: 1, max: 100)
112 def upgrade_changeset(struct, params \\ %{}) do
114 |> cast(params, [:bio, :name, :info, :follower_address, :avatar])
115 |> unique_constraint(:nickname)
116 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
117 |> validate_length(:bio, max: 5000)
118 |> validate_length(:name, max: 100)
121 def password_update_changeset(struct, params) do
124 |> cast(params, [:password, :password_confirmation])
125 |> validate_required([:password, :password_confirmation])
126 |> validate_confirmation(:password)
128 if changeset.valid? do
129 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
132 |> put_change(:password_hash, hashed)
138 def reset_password(user, data) do
139 update_and_set_cache(password_update_changeset(user, data))
142 def register_changeset(struct, params \\ %{}) do
145 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
146 |> validate_required([:email, :name, :nickname, :password, :password_confirmation])
147 |> validate_confirmation(:password)
148 |> unique_constraint(:email)
149 |> unique_constraint(:nickname)
150 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
151 |> validate_format(:email, @email_regex)
152 |> validate_length(:bio, max: 1000)
153 |> validate_length(:name, min: 1, max: 100)
155 if changeset.valid? do
156 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
157 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
158 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
161 |> put_change(:password_hash, hashed)
162 |> put_change(:ap_id, ap_id)
163 |> put_change(:following, [followers])
164 |> put_change(:follower_address, followers)
170 def follow(%User{} = follower, %User{info: info} = followed) do
171 ap_followers = followed.follower_address
173 if following?(follower, followed) or info["deactivated"] do
174 {:error, "Could not follow user: #{followed.nickname} is already on your list."}
176 if !followed.local && follower.local && !ap_enabled?(followed) do
177 Websub.subscribe(follower, followed)
181 [ap_followers | follower.following]
186 |> follow_changeset(%{following: following})
187 |> update_and_set_cache
189 {:ok, _} = update_follower_count(followed)
195 def unfollow(%User{} = follower, %User{} = followed) do
196 ap_followers = followed.follower_address
198 if following?(follower, followed) and follower.ap_id != followed.ap_id do
201 |> List.delete(ap_followers)
205 |> follow_changeset(%{following: following})
206 |> update_and_set_cache
208 {:ok, followed} = update_follower_count(followed)
210 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
212 {:error, "Not subscribed!"}
216 def following?(%User{} = follower, %User{} = followed) do
217 Enum.member?(follower.following, followed.follower_address)
220 def get_by_ap_id(ap_id) do
221 Repo.get_by(User, ap_id: ap_id)
224 def update_and_set_cache(changeset) do
225 with {:ok, user} <- Repo.update(changeset) do
226 Cachex.set(:user_cache, "ap_id:#{user.ap_id}", user)
227 Cachex.set(:user_cache, "nickname:#{user.nickname}", user)
228 Cachex.set(:user_cache, "user_info:#{user.id}", user_info(user))
235 def invalidate_cache(user) do
236 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
237 Cachex.del(:user_cache, "nickname:#{user.nickname}")
240 def get_cached_by_ap_id(ap_id) do
241 key = "ap_id:#{ap_id}"
242 Cachex.get!(:user_cache, key, fallback: fn _ -> get_by_ap_id(ap_id) end)
245 def get_cached_by_nickname(nickname) do
246 key = "nickname:#{nickname}"
247 Cachex.get!(:user_cache, key, fallback: fn _ -> get_or_fetch_by_nickname(nickname) end)
250 def get_by_nickname(nickname) do
251 Repo.get_by(User, nickname: nickname)
254 def get_by_nickname_or_email(nickname_or_email) do
255 case user = Repo.get_by(User, nickname: nickname_or_email) do
257 nil -> Repo.get_by(User, email: nickname_or_email)
261 def get_cached_user_info(user) do
262 key = "user_info:#{user.id}"
263 Cachex.get!(:user_cache, key, fallback: fn _ -> user_info(user) end)
266 def fetch_by_nickname(nickname) do
267 ap_try = ActivityPub.make_user_from_nickname(nickname)
270 {:ok, user} -> {:ok, user}
271 _ -> OStatus.make_user(nickname)
275 def get_or_fetch_by_nickname(nickname) do
276 with %User{} = user <- get_by_nickname(nickname) do
280 with [_nick, _domain] <- String.split(nickname, "@"),
281 {:ok, user} <- fetch_by_nickname(nickname) do
289 def get_followers_query(%User{id: id, follower_address: follower_address}) do
292 where: fragment("? <@ ?", ^[follower_address], u.following),
297 def get_followers(user) do
298 q = get_followers_query(user)
303 def get_friends_query(%User{id: id, following: following}) do
306 where: u.follower_address in ^following,
311 def get_friends(user) do
312 q = get_friends_query(user)
317 def increase_note_count(%User{} = user) do
318 note_count = (user.info["note_count"] || 0) + 1
319 new_info = Map.put(user.info, "note_count", note_count)
321 cs = info_changeset(user, %{info: new_info})
323 update_and_set_cache(cs)
326 def decrease_note_count(%User{} = user) do
327 note_count = user.info["note_count"] || 0
328 note_count = if note_count <= 0, do: 0, else: note_count - 1
329 new_info = Map.put(user.info, "note_count", note_count)
331 cs = info_changeset(user, %{info: new_info})
333 update_and_set_cache(cs)
336 def update_note_count(%User{} = user) do
340 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
344 note_count = Repo.one(note_count_query)
346 new_info = Map.put(user.info, "note_count", note_count)
348 cs = info_changeset(user, %{info: new_info})
350 update_and_set_cache(cs)
353 def update_follower_count(%User{} = user) do
354 follower_count_query =
357 where: ^user.follower_address in u.following,
358 where: u.id != ^user.id,
362 follower_count = Repo.one(follower_count_query)
364 new_info = Map.put(user.info, "follower_count", follower_count)
366 cs = info_changeset(user, %{info: new_info})
368 update_and_set_cache(cs)
371 def get_notified_from_activity(%Activity{recipients: to}) do
375 where: u.ap_id in ^to,
376 where: u.local == true
382 def get_recipients_from_activity(%Activity{recipients: to}) do
386 where: u.ap_id in ^to,
387 or_where: fragment("? && ?", u.following, ^to)
390 query = from(u in query, where: u.local == true)
395 def search(query, resolve) do
396 # strip the beginning @ off if there is a query
397 query = String.trim_leading(query, "@")
400 User.get_or_fetch_by_nickname(query)
419 s in subquery(inner),
420 order_by: s.search_distance,
427 def block(user, %{ap_id: ap_id}) do
428 blocks = user.info["blocks"] || []
429 new_blocks = Enum.uniq([ap_id | blocks])
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 unblock(user, %{ap_id: ap_id}) do
437 blocks = user.info["blocks"] || []
438 new_blocks = List.delete(blocks, ap_id)
439 new_info = Map.put(user.info, "blocks", new_blocks)
441 cs = User.info_changeset(user, %{info: new_info})
442 update_and_set_cache(cs)
445 def blocks?(user, %{ap_id: ap_id}) do
446 blocks = user.info["blocks"] || []
447 Enum.member?(blocks, ap_id)
450 def local_user_query() do
451 from(u in User, where: u.local == true)
454 def deactivate(%User{} = user) do
455 new_info = Map.put(user.info, "deactivated", true)
456 cs = User.info_changeset(user, %{info: new_info})
457 update_and_set_cache(cs)
460 def delete(%User{} = user) do
461 {:ok, user} = User.deactivate(user)
463 # Remove all relationships
464 {:ok, followers} = User.get_followers(user)
467 |> Enum.each(fn follower -> User.unfollow(follower, user) end)
469 {:ok, friends} = User.get_friends(user)
472 |> Enum.each(fn followed -> User.unfollow(user, followed) end)
474 query = from(a in Activity, where: a.actor == ^user.ap_id)
477 |> Enum.each(fn activity ->
478 case activity.data["type"] do
480 ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
482 # TODO: Do something with likes, follows, repeats.
491 def get_or_fetch_by_ap_id(ap_id) do
492 if user = get_by_ap_id(ap_id) do
495 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
502 case OStatus.make_user(ap_id) do
504 _ -> {:error, "Could not fetch by AP id"}
511 def public_key_from_info(%{
512 "source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}
515 :public_key.pem_decode(public_key_pem)
517 |> :public_key.pem_entry_decode()
523 def public_key_from_info(%{"magic_key" => magic_key}) do
524 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
527 def get_public_key_for_ap_id(ap_id) do
528 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
529 {:ok, public_key} <- public_key_from_info(user.info) do
536 defp blank?(""), do: nil
537 defp blank?(n), do: n
539 def insert_or_update_user(data) do
542 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
544 cs = User.remote_user_creation(data)
545 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
548 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
549 def ap_enabled?(_), do: false
551 def get_or_fetch(uri_or_nickname) do
552 if String.starts_with?(uri_or_nickname, "http") do
553 get_or_fetch_by_ap_id(uri_or_nickname)
555 get_or_fetch_by_nickname(uri_or_nickname)