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