Speed up follower query.
[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 following_count: length(user.following) - oneself,
67 note_count: user.info["note_count"] || 0,
68 follower_count: user.info["follower_count"] || 0
69 }
70 end
71
72 @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])?)*$/
73 def remote_user_creation(params) do
74 changes = %User{}
75 |> cast(params, [:bio, :name, :ap_id, :nickname, :info, :avatar])
76 |> validate_required([:name, :ap_id, :nickname])
77 |> unique_constraint(:nickname)
78 |> validate_format(:nickname, @email_regex)
79 |> validate_length(:bio, max: 5000)
80 |> validate_length(:name, max: 100)
81 |> put_change(:local, false)
82 if changes.valid? do
83 case changes.changes[:info]["source_data"] do
84 %{"followers" => followers} ->
85 changes
86 |> put_change(:follower_address, followers)
87 _ ->
88 followers = User.ap_followers(%User{nickname: changes.changes[:nickname]})
89 changes
90 |> put_change(:follower_address, followers)
91 end
92 else
93 changes
94 end
95 end
96
97 def update_changeset(struct, params \\ %{}) do
98 struct
99 |> cast(params, [:bio, :name])
100 |> unique_constraint(:nickname)
101 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
102 |> validate_length(:bio, max: 1000)
103 |> validate_length(:name, min: 1, max: 100)
104 end
105
106 def upgrade_changeset(struct, params \\ %{}) do
107 struct
108 |> cast(params, [:bio, :name, :info, :follower_address, :avatar])
109 |> unique_constraint(:nickname)
110 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
111 |> validate_length(:bio, max: 5000)
112 |> validate_length(:name, max: 100)
113 end
114
115 def password_update_changeset(struct, params) do
116 changeset = struct
117 |> cast(params, [:password, :password_confirmation])
118 |> validate_required([:password, :password_confirmation])
119 |> validate_confirmation(:password)
120
121 if changeset.valid? do
122 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
123 changeset
124 |> put_change(:password_hash, hashed)
125 else
126 changeset
127 end
128 end
129
130 def reset_password(user, data) do
131 update_and_set_cache(password_update_changeset(user, data))
132 end
133
134 def register_changeset(struct, params \\ %{}) do
135 changeset = struct
136 |> cast(params, [:bio, :email, :name, :nickname, :password, :password_confirmation])
137 |> validate_required([:email, :name, :nickname, :password, :password_confirmation])
138 |> validate_confirmation(:password)
139 |> unique_constraint(:email)
140 |> unique_constraint(:nickname)
141 |> validate_format(:nickname, ~r/^[a-zA-Z\d]+$/)
142 |> validate_format(:email, @email_regex)
143 |> validate_length(:bio, max: 1000)
144 |> validate_length(:name, min: 1, max: 100)
145
146 if changeset.valid? do
147 hashed = Pbkdf2.hashpwsalt(changeset.changes[:password])
148 ap_id = User.ap_id(%User{nickname: changeset.changes[:nickname]})
149 followers = User.ap_followers(%User{nickname: changeset.changes[:nickname]})
150 changeset
151 |> put_change(:password_hash, hashed)
152 |> put_change(:ap_id, ap_id)
153 |> put_change(:following, [followers])
154 |> put_change(:follower_address, followers)
155 else
156 changeset
157 end
158 end
159
160 def follow(%User{} = follower, %User{info: info} = followed) do
161 ap_followers = followed.follower_address
162
163 if following?(follower, followed) or info["deactivated"] do
164 {:error,
165 "Could not follow user: #{followed.nickname} is already on your list."}
166 else
167 if !followed.local && follower.local && !ap_enabled?(followed) do
168 Websub.subscribe(follower, followed)
169 end
170
171 following = [ap_followers | follower.following]
172 |> Enum.uniq
173
174 follower = follower
175 |> follow_changeset(%{following: following})
176 |> update_and_set_cache
177
178 {:ok, _} = update_follower_count(followed)
179
180 follower
181 end
182 end
183
184 def unfollow(%User{} = follower, %User{} = followed) do
185 ap_followers = followed.follower_address
186 if following?(follower, followed) and follower.ap_id != followed.ap_id do
187 following = follower.following
188 |> List.delete(ap_followers)
189
190 { :ok, follower } = follower
191 |> follow_changeset(%{following: following})
192 |> update_and_set_cache
193
194 {:ok, followed} = update_follower_count(followed)
195
196 {:ok, follower, Utils.fetch_latest_follow(follower, followed)}
197 else
198 {:error, "Not subscribed!"}
199 end
200 end
201
202 def following?(%User{} = follower, %User{} = followed) do
203 Enum.member?(follower.following, followed.follower_address)
204 end
205
206 def get_by_ap_id(ap_id) do
207 Repo.get_by(User, ap_id: ap_id)
208 end
209
210 def update_and_set_cache(changeset) do
211 with {:ok, user} <- Repo.update(changeset) do
212 Cachex.set(:user_cache, "ap_id:#{user.ap_id}", user)
213 Cachex.set(:user_cache, "nickname:#{user.nickname}", user)
214 Cachex.set(:user_cache, "user_info:#{user.id}", user_info(user))
215 {:ok, user}
216 else
217 e -> e
218 end
219 end
220
221 def invalidate_cache(user) do
222 Cachex.del(:user_cache, "ap_id:#{user.ap_id}")
223 Cachex.del(:user_cache, "nickname:#{user.nickname}")
224 end
225
226 def get_cached_by_ap_id(ap_id) do
227 key = "ap_id:#{ap_id}"
228 Cachex.get!(:user_cache, key, fallback: fn(_) -> get_by_ap_id(ap_id) end)
229 end
230
231 def get_cached_by_nickname(nickname) do
232 key = "nickname:#{nickname}"
233 Cachex.get!(:user_cache, key, fallback: fn(_) -> get_or_fetch_by_nickname(nickname) end)
234 end
235
236 def get_by_nickname(nickname) do
237 Repo.get_by(User, nickname: nickname)
238 end
239
240 def get_cached_user_info(user) do
241 key = "user_info:#{user.id}"
242 Cachex.get!(:user_cache, key, fallback: fn(_) -> user_info(user) end)
243 end
244
245 def fetch_by_nickname(nickname) do
246 ap_try = ActivityPub.make_user_from_nickname(nickname)
247
248 case ap_try do
249 {:ok, user} -> {:ok, user}
250 _ -> OStatus.make_user(nickname)
251 end
252 end
253
254 def get_or_fetch_by_nickname(nickname) do
255 with %User{} = user <- get_by_nickname(nickname) do
256 user
257 else _e ->
258 with [_nick, _domain] <- String.split(nickname, "@"),
259 {:ok, user} <- fetch_by_nickname(nickname) do
260 user
261 else _e -> nil
262 end
263 end
264 end
265
266 def get_followers(%User{id: id, follower_address: follower_address}) do
267 q = from u in User,
268 where: fragment("? <@ ?", ^[follower_address], u.following),
269 where: u.id != ^id
270
271 {:ok, Repo.all(q)}
272 end
273
274 def get_friends(%User{id: id, following: following}) do
275 q = from u in User,
276 where: u.follower_address in ^following,
277 where: u.id != ^id
278
279 {:ok, Repo.all(q)}
280 end
281
282 def increase_note_count(%User{} = user) do
283 note_count = (user.info["note_count"] || 0) + 1
284 new_info = Map.put(user.info, "note_count", note_count)
285
286 cs = info_changeset(user, %{info: new_info})
287
288 update_and_set_cache(cs)
289 end
290
291 def update_note_count(%User{} = user) do
292 note_count_query = from a in Object,
293 where: fragment("?->>'actor' = ? and ?->>'type' = 'Note'", a.data, ^user.ap_id, a.data),
294 select: count(a.id)
295
296 note_count = Repo.one(note_count_query)
297
298 new_info = Map.put(user.info, "note_count", note_count)
299
300 cs = info_changeset(user, %{info: new_info})
301
302 update_and_set_cache(cs)
303 end
304
305 def update_follower_count(%User{} = user) do
306 follower_count_query = from u in User,
307 where: ^user.follower_address in u.following,
308 where: u.id != ^user.id,
309 select: count(u.id)
310
311 follower_count = Repo.one(follower_count_query)
312
313 new_info = Map.put(user.info, "follower_count", follower_count)
314
315 cs = info_changeset(user, %{info: new_info})
316
317 update_and_set_cache(cs)
318 end
319
320 def get_notified_from_activity(%Activity{recipients: to}) do
321 query = from u in User,
322 where: u.ap_id in ^to,
323 where: u.local == true
324
325 Repo.all(query)
326 end
327
328 def get_recipients_from_activity(%Activity{recipients: to}) do
329 query = from u in User,
330 where: u.ap_id in ^to,
331 or_where: fragment("? && ?", u.following, ^to)
332
333 query = from u in query,
334 where: u.local == true
335
336 Repo.all(query)
337 end
338
339 def search(query, resolve) do
340 if resolve do
341 User.get_or_fetch_by_nickname(query)
342 end
343 q = from u in User,
344 where: fragment("(to_tsvector('english', ?) || to_tsvector('english', ?)) @@ plainto_tsquery('english', ?)", u.nickname, u.name, ^query),
345 limit: 20
346 Repo.all(q)
347 end
348
349 def block(user, %{ap_id: ap_id}) do
350 blocks = user.info["blocks"] || []
351 new_blocks = Enum.uniq([ap_id | blocks])
352 new_info = Map.put(user.info, "blocks", new_blocks)
353
354 cs = User.info_changeset(user, %{info: new_info})
355 update_and_set_cache(cs)
356 end
357
358 def unblock(user, %{ap_id: ap_id}) do
359 blocks = user.info["blocks"] || []
360 new_blocks = List.delete(blocks, ap_id)
361 new_info = Map.put(user.info, "blocks", new_blocks)
362
363 cs = User.info_changeset(user, %{info: new_info})
364 update_and_set_cache(cs)
365 end
366
367 def blocks?(user, %{ap_id: ap_id}) do
368 blocks = user.info["blocks"] || []
369 Enum.member?(blocks, ap_id)
370 end
371
372 def local_user_query() do
373 from u in User,
374 where: u.local == true
375 end
376
377 def deactivate (%User{} = user) do
378 new_info = Map.put(user.info, "deactivated", true)
379 cs = User.info_changeset(user, %{info: new_info})
380 update_and_set_cache(cs)
381 end
382
383 def delete (%User{} = user) do
384 {:ok, user} = User.deactivate(user)
385
386 # Remove all relationships
387 {:ok, followers } = User.get_followers(user)
388 followers
389 |> Enum.each(fn (follower) -> User.unfollow(follower, user) end)
390
391 {:ok, friends} = User.get_friends(user)
392 friends
393 |> Enum.each(fn (followed) -> User.unfollow(user, followed) end)
394
395 query = from a in Activity,
396 where: a.actor == ^user.ap_id
397
398 Repo.all(query)
399 |> Enum.each(fn (activity) ->
400 case activity.data["type"] do
401 "Create" -> ActivityPub.delete(Object.get_by_ap_id(activity.data["object"]["id"]))
402 _ -> "Doing nothing" # TODO: Do something with likes, follows, repeats.
403 end
404 end)
405
406 :ok
407 end
408
409 def get_or_fetch_by_ap_id(ap_id) do
410 if user = get_by_ap_id(ap_id) do
411 user
412 else
413 ap_try = ActivityPub.make_user_from_ap_id(ap_id)
414
415 case ap_try do
416 {:ok, user} -> user
417 _ ->
418 case OStatus.make_user(ap_id) do
419 {:ok, user} -> user
420 _ -> {:error, "Could not fetch by AP id"}
421 end
422 end
423 end
424 end
425
426 # AP style
427 def public_key_from_info(%{"source_data" => %{"publicKey" => %{"publicKeyPem" => public_key_pem}}}) do
428 key = :public_key.pem_decode(public_key_pem)
429 |> hd()
430 |> :public_key.pem_entry_decode()
431
432 {:ok, key}
433 end
434
435 # OStatus Magic Key
436 def public_key_from_info(%{"magic_key" => magic_key}) do
437 {:ok, Pleroma.Web.Salmon.decode_key(magic_key)}
438 end
439
440 def get_public_key_for_ap_id(ap_id) do
441 with %User{} = user <- get_or_fetch_by_ap_id(ap_id),
442 {:ok, public_key} <- public_key_from_info(user.info) do
443 {:ok, public_key}
444 else
445 _ -> :error
446 end
447 end
448
449 defp blank?(""), do: nil
450 defp blank?(n), do: n
451
452 def insert_or_update_user(data) do
453 data = data
454 |> Map.put(:name, blank?(data[:name]) || data[:nickname])
455 cs = User.remote_user_creation(data)
456 Repo.insert(cs, on_conflict: :replace_all, conflict_target: :nickname)
457 end
458
459 def ap_enabled?(%User{info: info}), do: info["ap_enabled"]
460 def ap_enabled?(_), do: false
461
462 def get_or_fetch(uri_or_nickname) do
463 if String.starts_with?(uri_or_nickname, "http") do
464 get_or_fetch_by_ap_id(uri_or_nickname)
465 else
466 get_or_fetch_by_nickname(uri_or_nickname)
467 end
468 end
469 end