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