allow users to disable their own account
[akkoma] / lib / pleroma / web / twitter_api / twitter_api.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
6 alias Pleroma.UserInviteToken
7 alias Pleroma.User
8 alias Pleroma.Activity
9 alias Pleroma.Repo
10 alias Pleroma.Object
11 alias Pleroma.UserEmail
12 alias Pleroma.Mailer
13 alias Pleroma.Web.ActivityPub.ActivityPub
14 alias Pleroma.Web.TwitterAPI.UserView
15 alias Pleroma.Web.CommonAPI
16
17 import Ecto.Query
18
19 def create_status(%User{} = user, %{"status" => _} = data) do
20 CommonAPI.post(user, data)
21 end
22
23 def delete(%User{} = user, id) do
24 with %Activity{data: %{"type" => _type}} <- Activity.get_by_id(id),
25 {:ok, activity} <- CommonAPI.delete(id, user) do
26 {:ok, activity}
27 end
28 end
29
30 def follow(%User{} = follower, params) do
31 with {:ok, %User{} = followed} <- get_user(params),
32 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
33 {:ok, activity} <- ActivityPub.follow(follower, followed),
34 {:ok, follower, followed} <-
35 User.wait_and_refresh(
36 Pleroma.Config.get([:activitypub, :follow_handshake_timeout]),
37 follower,
38 followed
39 ) do
40 {:ok, follower, followed, activity}
41 else
42 err -> err
43 end
44 end
45
46 def unfollow(%User{} = follower, params) do
47 with {:ok, %User{} = unfollowed} <- get_user(params),
48 {:ok, follower, _follow_activity} <- User.unfollow(follower, unfollowed),
49 {:ok, _activity} <- ActivityPub.unfollow(follower, unfollowed) do
50 {:ok, follower, unfollowed}
51 else
52 err -> err
53 end
54 end
55
56 def block(%User{} = blocker, params) do
57 with {:ok, %User{} = blocked} <- get_user(params),
58 {:ok, blocker} <- User.block(blocker, blocked),
59 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
60 {:ok, blocker, blocked}
61 else
62 err -> err
63 end
64 end
65
66 def unblock(%User{} = blocker, params) do
67 with {:ok, %User{} = blocked} <- get_user(params),
68 {:ok, blocker} <- User.unblock(blocker, blocked),
69 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
70 {:ok, blocker, blocked}
71 else
72 err -> err
73 end
74 end
75
76 def repeat(%User{} = user, ap_id_or_id) do
77 with {:ok, _announce, %{data: %{"id" => id}}} <- CommonAPI.repeat(ap_id_or_id, user),
78 %Activity{} = activity <- Activity.get_create_by_object_ap_id(id) do
79 {:ok, activity}
80 end
81 end
82
83 def unrepeat(%User{} = user, ap_id_or_id) do
84 with {:ok, _unannounce, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
85 %Activity{} = activity <- Activity.get_create_by_object_ap_id(id) do
86 {:ok, activity}
87 end
88 end
89
90 def pin(%User{} = user, ap_id_or_id) do
91 CommonAPI.pin(ap_id_or_id, user)
92 end
93
94 def unpin(%User{} = user, ap_id_or_id) do
95 CommonAPI.unpin(ap_id_or_id, user)
96 end
97
98 def fav(%User{} = user, ap_id_or_id) do
99 with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
100 %Activity{} = activity <- Activity.get_create_by_object_ap_id(id) do
101 {:ok, activity}
102 end
103 end
104
105 def unfav(%User{} = user, ap_id_or_id) do
106 with {:ok, _unfav, _fav, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
107 %Activity{} = activity <- Activity.get_create_by_object_ap_id(id) do
108 {:ok, activity}
109 end
110 end
111
112 def upload(%Plug.Upload{} = file, %User{} = user, format \\ "xml") do
113 {:ok, object} = ActivityPub.upload(file, actor: User.ap_id(user))
114
115 url = List.first(object.data["url"])
116 href = url["href"]
117 type = url["mediaType"]
118
119 case format do
120 "xml" ->
121 # Fake this as good as possible...
122 """
123 <?xml version="1.0" encoding="UTF-8"?>
124 <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
125 <mediaid>#{object.id}</mediaid>
126 <media_id>#{object.id}</media_id>
127 <media_id_string>#{object.id}</media_id_string>
128 <media_url>#{href}</media_url>
129 <mediaurl>#{href}</mediaurl>
130 <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
131 </rsp>
132 """
133
134 "json" ->
135 %{
136 media_id: object.id,
137 media_id_string: "#{object.id}}",
138 media_url: href,
139 size: 0
140 }
141 |> Jason.encode!()
142 end
143 end
144
145 def register_user(params) do
146 tokenString = params["token"]
147
148 params = %{
149 nickname: params["nickname"],
150 name: params["fullname"],
151 bio: User.parse_bio(params["bio"]),
152 email: params["email"],
153 password: params["password"],
154 password_confirmation: params["confirm"],
155 captcha_solution: params["captcha_solution"],
156 captcha_token: params["captcha_token"],
157 captcha_answer_data: params["captcha_answer_data"]
158 }
159
160 captcha_enabled = Pleroma.Config.get([Pleroma.Captcha, :enabled])
161 # true if captcha is disabled or enabled and valid, false otherwise
162 captcha_ok =
163 if !captcha_enabled do
164 :ok
165 else
166 Pleroma.Captcha.validate(
167 params[:captcha_token],
168 params[:captcha_solution],
169 params[:captcha_answer_data]
170 )
171 end
172
173 # Captcha invalid
174 if captcha_ok != :ok do
175 {:error, error} = captcha_ok
176 # I have no idea how this error handling works
177 {:error, %{error: Jason.encode!(%{captcha: [error]})}}
178 else
179 registrations_open = Pleroma.Config.get([:instance, :registrations_open])
180
181 # no need to query DB if registration is open
182 token =
183 unless registrations_open || is_nil(tokenString) do
184 Repo.get_by(UserInviteToken, %{token: tokenString})
185 end
186
187 cond do
188 registrations_open || (!is_nil(token) && !token.used) ->
189 changeset = User.register_changeset(%User{}, params)
190
191 with {:ok, user} <- User.register(changeset) do
192 !registrations_open && UserInviteToken.mark_as_used(token.token)
193
194 {:ok, user}
195 else
196 {:error, changeset} ->
197 errors =
198 Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
199 |> Jason.encode!()
200
201 {:error, %{error: errors}}
202 end
203
204 !registrations_open && is_nil(token) ->
205 {:error, "Invalid token"}
206
207 !registrations_open && token.used ->
208 {:error, "Expired token"}
209 end
210 end
211 end
212
213 def password_reset(nickname_or_email) do
214 with true <- is_binary(nickname_or_email),
215 %User{local: true} = user <- User.get_by_nickname_or_email(nickname_or_email),
216 {:ok, token_record} <- Pleroma.PasswordResetToken.create_token(user) do
217 user
218 |> UserEmail.password_reset_email(token_record.token)
219 |> Mailer.deliver_async()
220 else
221 false ->
222 {:error, "bad user identifier"}
223
224 %User{local: false} ->
225 {:error, "remote user"}
226
227 nil ->
228 {:error, "unknown user"}
229 end
230 end
231
232 def get_user(user \\ nil, params) do
233 case params do
234 %{"user_id" => user_id} ->
235 case User.get_cached_by_nickname_or_id(user_id) do
236 nil ->
237 {:error, "No user with such user_id"}
238
239 %User{info: %{disabled: true}} ->
240 {:error, "User has been disabled"}
241
242 user ->
243 {:ok, user}
244 end
245
246 %{"screen_name" => nickname} ->
247 case User.get_by_nickname(nickname) do
248 nil ->
249 {:error, "No user with such screen_name"}
250
251 %User{info: %{disabled: true}} ->
252 {:error, "User has been disabled"}
253
254 user ->
255 {:ok, user}
256 end
257
258 _ ->
259 if user do
260 {:ok, user}
261 else
262 {:error, "You need to specify screen_name or user_id"}
263 end
264 end
265 end
266
267 defp parse_int(string, default)
268
269 defp parse_int(string, default) when is_binary(string) do
270 with {n, _} <- Integer.parse(string) do
271 n
272 else
273 _e -> default
274 end
275 end
276
277 defp parse_int(_, default), do: default
278
279 def search(_user, %{"q" => query} = params) do
280 limit = parse_int(params["rpp"], 20)
281 page = parse_int(params["page"], 1)
282 offset = (page - 1) * limit
283
284 q =
285 from(
286 a in Activity,
287 where: fragment("?->>'type' = 'Create'", a.data),
288 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
289 where:
290 fragment(
291 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
292 a.data,
293 ^query
294 ),
295 limit: ^limit,
296 offset: ^offset,
297 # this one isn't indexed so psql won't take the wrong index.
298 order_by: [desc: :inserted_at]
299 )
300
301 _activities = Repo.all(q)
302 end
303
304 # DEPRECATED mostly, context objects are now created at insertion time.
305 def context_to_conversation_id(context) do
306 with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
307 id
308 else
309 _e ->
310 changeset = Object.context_mapping(context)
311
312 case Repo.insert(changeset) do
313 {:ok, %{id: id}} ->
314 id
315
316 # This should be solved by an upsert, but it seems ecto
317 # has problems accessing the constraint inside the jsonb.
318 {:error, _} ->
319 Object.get_cached_by_ap_id(context).id
320 end
321 end
322 end
323
324 def conversation_id_to_context(id) do
325 with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
326 context
327 else
328 _e ->
329 {:error, "No such conversation"}
330 end
331 end
332
333 def get_external_profile(for_user, uri) do
334 with %User{} = user <- User.get_or_fetch(uri) do
335 {:ok, UserView.render("show.json", %{user: user, for: for_user})}
336 else
337 _e ->
338 {:error, "Couldn't find user"}
339 end
340 end
341 end