Merge branch '483_blocks_import_export' into 'develop'
[akkoma] / lib / pleroma / web / twitter_api / twitter_api_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.TwitterAPI.Controller do
6 use Pleroma.Web, :controller
7
8 import Pleroma.Web.ControllerHelper, only: [json_response: 3]
9
10 alias Pleroma.Web.TwitterAPI.{TwitterAPI, UserView, ActivityView, NotificationView}
11 alias Pleroma.Web.CommonAPI
12 alias Pleroma.{Repo, Activity, Object, User, Notification}
13 alias Pleroma.Web.ActivityPub.ActivityPub
14 alias Pleroma.Web.ActivityPub.Utils
15 alias Ecto.Changeset
16
17 require Logger
18
19 plug(:only_if_public_instance when action in [:public_timeline, :public_and_external_timeline])
20 action_fallback(:errors)
21
22 def verify_credentials(%{assigns: %{user: user}} = conn, _params) do
23 token = Phoenix.Token.sign(conn, "user socket", user.id)
24
25 conn
26 |> put_view(UserView)
27 |> render("show.json", %{user: user, token: token})
28 end
29
30 def status_update(%{assigns: %{user: user}} = conn, %{"status" => _} = status_data) do
31 with media_ids <- extract_media_ids(status_data),
32 {:ok, activity} <-
33 TwitterAPI.create_status(user, Map.put(status_data, "media_ids", media_ids)) do
34 conn
35 |> json(ActivityView.render("activity.json", activity: activity, for: user))
36 else
37 _ -> empty_status_reply(conn)
38 end
39 end
40
41 def status_update(conn, _status_data) do
42 empty_status_reply(conn)
43 end
44
45 defp empty_status_reply(conn) do
46 bad_request_reply(conn, "Client must provide a 'status' parameter with a value.")
47 end
48
49 defp extract_media_ids(status_data) do
50 with media_ids when not is_nil(media_ids) <- status_data["media_ids"],
51 split_ids <- String.split(media_ids, ","),
52 clean_ids <- Enum.reject(split_ids, fn id -> String.length(id) == 0 end) do
53 clean_ids
54 else
55 _e -> []
56 end
57 end
58
59 def public_and_external_timeline(%{assigns: %{user: user}} = conn, params) do
60 params =
61 params
62 |> Map.put("type", ["Create", "Announce"])
63 |> Map.put("blocking_user", user)
64
65 activities = ActivityPub.fetch_public_activities(params)
66
67 conn
68 |> put_view(ActivityView)
69 |> render("index.json", %{activities: activities, for: user})
70 end
71
72 def public_timeline(%{assigns: %{user: user}} = conn, params) do
73 params =
74 params
75 |> Map.put("type", ["Create", "Announce"])
76 |> Map.put("local_only", true)
77 |> Map.put("blocking_user", user)
78
79 activities = ActivityPub.fetch_public_activities(params)
80
81 conn
82 |> put_view(ActivityView)
83 |> render("index.json", %{activities: activities, for: user})
84 end
85
86 def friends_timeline(%{assigns: %{user: user}} = conn, params) do
87 params =
88 params
89 |> Map.put("type", ["Create", "Announce", "Follow", "Like"])
90 |> Map.put("blocking_user", user)
91 |> Map.put("user", user)
92
93 activities =
94 ActivityPub.fetch_activities([user.ap_id | user.following], params)
95 |> ActivityPub.contain_timeline(user)
96
97 conn
98 |> put_view(ActivityView)
99 |> render("index.json", %{activities: activities, for: user})
100 end
101
102 def show_user(conn, params) do
103 for_user = conn.assigns.user
104
105 with {:ok, shown} <- TwitterAPI.get_user(params),
106 true <-
107 User.auth_active?(shown) ||
108 (for_user && (for_user.id == shown.id || User.superuser?(for_user))) do
109 params =
110 if for_user do
111 %{user: shown, for: for_user}
112 else
113 %{user: shown}
114 end
115
116 conn
117 |> put_view(UserView)
118 |> render("show.json", params)
119 else
120 {:error, msg} ->
121 bad_request_reply(conn, msg)
122
123 false ->
124 conn
125 |> put_status(404)
126 |> json(%{error: "Unconfirmed user"})
127 end
128 end
129
130 def user_timeline(%{assigns: %{user: user}} = conn, params) do
131 case TwitterAPI.get_user(user, params) do
132 {:ok, target_user} ->
133 # Twitter and ActivityPub use a different name and sense for this parameter.
134 {include_rts, params} = Map.pop(params, "include_rts")
135
136 params =
137 case include_rts do
138 x when x == "false" or x == "0" -> Map.put(params, "exclude_reblogs", "true")
139 _ -> params
140 end
141
142 activities = ActivityPub.fetch_user_activities(target_user, user, params)
143
144 conn
145 |> put_view(ActivityView)
146 |> render("index.json", %{activities: activities, for: user})
147
148 {:error, msg} ->
149 bad_request_reply(conn, msg)
150 end
151 end
152
153 def mentions_timeline(%{assigns: %{user: user}} = conn, params) do
154 params =
155 params
156 |> Map.put("type", ["Create", "Announce", "Follow", "Like"])
157 |> Map.put("blocking_user", user)
158
159 activities = ActivityPub.fetch_activities([user.ap_id], params)
160
161 conn
162 |> put_view(ActivityView)
163 |> render("index.json", %{activities: activities, for: user})
164 end
165
166 def dm_timeline(%{assigns: %{user: user}} = conn, params) do
167 query =
168 ActivityPub.fetch_activities_query(
169 [user.ap_id],
170 Map.merge(params, %{"type" => "Create", "user" => user, visibility: "direct"})
171 )
172
173 activities = Repo.all(query)
174
175 conn
176 |> put_view(ActivityView)
177 |> render("index.json", %{activities: activities, for: user})
178 end
179
180 def notifications(%{assigns: %{user: user}} = conn, params) do
181 notifications = Notification.for_user(user, params)
182
183 conn
184 |> put_view(NotificationView)
185 |> render("notification.json", %{notifications: notifications, for: user})
186 end
187
188 def notifications_read(%{assigns: %{user: user}} = conn, %{"latest_id" => latest_id} = params) do
189 Notification.set_read_up_to(user, latest_id)
190
191 notifications = Notification.for_user(user, params)
192
193 conn
194 |> put_view(NotificationView)
195 |> render("notification.json", %{notifications: notifications, for: user})
196 end
197
198 def notifications_read(%{assigns: %{user: _user}} = conn, _) do
199 bad_request_reply(conn, "You need to specify latest_id")
200 end
201
202 def follow(%{assigns: %{user: user}} = conn, params) do
203 case TwitterAPI.follow(user, params) do
204 {:ok, user, followed, _activity} ->
205 conn
206 |> put_view(UserView)
207 |> render("show.json", %{user: followed, for: user})
208
209 {:error, msg} ->
210 forbidden_json_reply(conn, msg)
211 end
212 end
213
214 def block(%{assigns: %{user: user}} = conn, params) do
215 case TwitterAPI.block(user, params) do
216 {:ok, user, blocked} ->
217 conn
218 |> put_view(UserView)
219 |> render("show.json", %{user: blocked, for: user})
220
221 {:error, msg} ->
222 forbidden_json_reply(conn, msg)
223 end
224 end
225
226 def unblock(%{assigns: %{user: user}} = conn, params) do
227 case TwitterAPI.unblock(user, params) do
228 {:ok, user, blocked} ->
229 conn
230 |> put_view(UserView)
231 |> render("show.json", %{user: blocked, for: user})
232
233 {:error, msg} ->
234 forbidden_json_reply(conn, msg)
235 end
236 end
237
238 def delete_post(%{assigns: %{user: user}} = conn, %{"id" => id}) do
239 with {:ok, activity} <- TwitterAPI.delete(user, id) do
240 conn
241 |> put_view(ActivityView)
242 |> render("activity.json", %{activity: activity, for: user})
243 end
244 end
245
246 def unfollow(%{assigns: %{user: user}} = conn, params) do
247 case TwitterAPI.unfollow(user, params) do
248 {:ok, user, unfollowed} ->
249 conn
250 |> put_view(UserView)
251 |> render("show.json", %{user: unfollowed, for: user})
252
253 {:error, msg} ->
254 forbidden_json_reply(conn, msg)
255 end
256 end
257
258 def fetch_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
259 with %Activity{} = activity <- Repo.get(Activity, id),
260 true <- ActivityPub.visible_for_user?(activity, user) do
261 conn
262 |> put_view(ActivityView)
263 |> render("activity.json", %{activity: activity, for: user})
264 end
265 end
266
267 def fetch_conversation(%{assigns: %{user: user}} = conn, %{"id" => id}) do
268 id = String.to_integer(id)
269
270 with context when is_binary(context) <- TwitterAPI.conversation_id_to_context(id),
271 activities <-
272 ActivityPub.fetch_activities_for_context(context, %{
273 "blocking_user" => user,
274 "user" => user
275 }) do
276 conn
277 |> put_view(ActivityView)
278 |> render("index.json", %{activities: activities, for: user})
279 end
280 end
281
282 @doc """
283 Updates metadata of uploaded media object.
284 Derived from [Twitter API endpoint](https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create).
285 """
286 def update_media(%{assigns: %{user: user}} = conn, %{"media_id" => id} = data) do
287 object = Repo.get(Object, id)
288 description = get_in(data, ["alt_text", "text"]) || data["name"] || data["description"]
289
290 {conn, status, response_body} =
291 cond do
292 !object ->
293 {halt(conn), :not_found, ""}
294
295 !Object.authorize_mutation(object, user) ->
296 {halt(conn), :forbidden, "You can only update your own uploads."}
297
298 !is_binary(description) ->
299 {conn, :not_modified, ""}
300
301 true ->
302 new_data = Map.put(object.data, "name", description)
303
304 {:ok, _} =
305 object
306 |> Object.change(%{data: new_data})
307 |> Repo.update()
308
309 {conn, :no_content, ""}
310 end
311
312 conn
313 |> put_status(status)
314 |> json(response_body)
315 end
316
317 def upload(%{assigns: %{user: user}} = conn, %{"media" => media}) do
318 response = TwitterAPI.upload(media, user)
319
320 conn
321 |> put_resp_content_type("application/atom+xml")
322 |> send_resp(200, response)
323 end
324
325 def upload_json(%{assigns: %{user: user}} = conn, %{"media" => media}) do
326 response = TwitterAPI.upload(media, user, "json")
327
328 conn
329 |> json_reply(200, response)
330 end
331
332 def get_by_id_or_ap_id(id) do
333 activity = Repo.get(Activity, id) || Activity.get_create_activity_by_object_ap_id(id)
334
335 if activity.data["type"] == "Create" do
336 activity
337 else
338 Activity.get_create_activity_by_object_ap_id(activity.data["object"])
339 end
340 end
341
342 def favorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do
343 with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
344 {:ok, activity} <- TwitterAPI.fav(user, id) do
345 conn
346 |> put_view(ActivityView)
347 |> render("activity.json", %{activity: activity, for: user})
348 end
349 end
350
351 def unfavorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do
352 with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
353 {:ok, activity} <- TwitterAPI.unfav(user, id) do
354 conn
355 |> put_view(ActivityView)
356 |> render("activity.json", %{activity: activity, for: user})
357 end
358 end
359
360 def retweet(%{assigns: %{user: user}} = conn, %{"id" => id}) do
361 with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
362 {:ok, activity} <- TwitterAPI.repeat(user, id) do
363 conn
364 |> put_view(ActivityView)
365 |> render("activity.json", %{activity: activity, for: user})
366 end
367 end
368
369 def unretweet(%{assigns: %{user: user}} = conn, %{"id" => id}) do
370 with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
371 {:ok, activity} <- TwitterAPI.unrepeat(user, id) do
372 conn
373 |> put_view(ActivityView)
374 |> render("activity.json", %{activity: activity, for: user})
375 end
376 end
377
378 def register(conn, params) do
379 with {:ok, user} <- TwitterAPI.register_user(params) do
380 conn
381 |> put_view(UserView)
382 |> render("show.json", %{user: user})
383 else
384 {:error, errors} ->
385 conn
386 |> json_reply(400, Jason.encode!(errors))
387 end
388 end
389
390 def password_reset(conn, params) do
391 nickname_or_email = params["email"] || params["nickname"]
392
393 with {:ok, _} <- TwitterAPI.password_reset(nickname_or_email) do
394 json_response(conn, :no_content, "")
395 end
396 end
397
398 def confirm_email(conn, %{"user_id" => uid, "token" => token}) do
399 with %User{} = user <- Repo.get(User, uid),
400 true <- user.local,
401 true <- user.info.confirmation_pending,
402 true <- user.info.confirmation_token == token,
403 info_change <- User.Info.confirmation_changeset(user.info, :confirmed),
404 changeset <- Changeset.change(user) |> Changeset.put_embed(:info, info_change),
405 {:ok, _} <- User.update_and_set_cache(changeset) do
406 conn
407 |> redirect(to: "/")
408 end
409 end
410
411 def resend_confirmation_email(conn, params) do
412 nickname_or_email = params["email"] || params["nickname"]
413
414 with %User{} = user <- User.get_by_nickname_or_email(nickname_or_email),
415 {:ok, _} <- User.try_send_confirmation_email(user) do
416 conn
417 |> json_response(:no_content, "")
418 end
419 end
420
421 def update_avatar(%{assigns: %{user: user}} = conn, params) do
422 {:ok, object} = ActivityPub.upload(params, type: :avatar)
423 change = Changeset.change(user, %{avatar: object.data})
424 {:ok, user} = User.update_and_set_cache(change)
425 CommonAPI.update(user)
426
427 conn
428 |> put_view(UserView)
429 |> render("show.json", %{user: user, for: user})
430 end
431
432 def update_banner(%{assigns: %{user: user}} = conn, params) do
433 with {:ok, object} <- ActivityPub.upload(%{"img" => params["banner"]}, type: :banner),
434 new_info <- %{"banner" => object.data},
435 info_cng <- User.Info.profile_update(user.info, new_info),
436 changeset <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng),
437 {:ok, user} <- User.update_and_set_cache(changeset) do
438 CommonAPI.update(user)
439 %{"url" => [%{"href" => href} | _]} = object.data
440 response = %{url: href} |> Jason.encode!()
441
442 conn
443 |> json_reply(200, response)
444 end
445 end
446
447 def update_background(%{assigns: %{user: user}} = conn, params) do
448 with {:ok, object} <- ActivityPub.upload(params, type: :background),
449 new_info <- %{"background" => object.data},
450 info_cng <- User.Info.profile_update(user.info, new_info),
451 changeset <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng),
452 {:ok, _user} <- User.update_and_set_cache(changeset) do
453 %{"url" => [%{"href" => href} | _]} = object.data
454 response = %{url: href} |> Jason.encode!()
455
456 conn
457 |> json_reply(200, response)
458 end
459 end
460
461 def external_profile(%{assigns: %{user: current_user}} = conn, %{"profileurl" => uri}) do
462 with {:ok, user_map} <- TwitterAPI.get_external_profile(current_user, uri),
463 response <- Jason.encode!(user_map) do
464 conn
465 |> json_reply(200, response)
466 else
467 _e ->
468 conn
469 |> put_status(404)
470 |> json(%{error: "Can't find user"})
471 end
472 end
473
474 def followers(%{assigns: %{user: for_user}} = conn, params) do
475 with {:ok, user} <- TwitterAPI.get_user(for_user, params),
476 {:ok, followers} <- User.get_followers(user) do
477 followers =
478 cond do
479 for_user && user.id == for_user.id -> followers
480 user.info.hide_network -> []
481 true -> followers
482 end
483
484 conn
485 |> put_view(UserView)
486 |> render("index.json", %{users: followers, for: conn.assigns[:user]})
487 else
488 _e -> bad_request_reply(conn, "Can't get followers")
489 end
490 end
491
492 def friends(%{assigns: %{user: for_user}} = conn, params) do
493 with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params),
494 {:ok, friends} <- User.get_friends(user) do
495 friends =
496 cond do
497 for_user && user.id == for_user.id -> friends
498 user.info.hide_network -> []
499 true -> friends
500 end
501
502 conn
503 |> put_view(UserView)
504 |> render("index.json", %{users: friends, for: conn.assigns[:user]})
505 else
506 _e -> bad_request_reply(conn, "Can't get friends")
507 end
508 end
509
510 def blocks(%{assigns: %{user: user}} = conn, _params) do
511 with blocked_users <- User.blocked_users(user) do
512 conn
513 |> put_view(UserView)
514 |> render("index.json", %{users: blocked_users, for: user})
515 end
516 end
517
518 def friend_requests(conn, params) do
519 with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params),
520 {:ok, friend_requests} <- User.get_follow_requests(user) do
521 conn
522 |> put_view(UserView)
523 |> render("index.json", %{users: friend_requests, for: conn.assigns[:user]})
524 else
525 _e -> bad_request_reply(conn, "Can't get friend requests")
526 end
527 end
528
529 def approve_friend_request(conn, %{"user_id" => uid} = _params) do
530 with followed <- conn.assigns[:user],
531 uid when is_number(uid) <- String.to_integer(uid),
532 %User{} = follower <- Repo.get(User, uid),
533 {:ok, follower} <- User.maybe_follow(follower, followed),
534 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
535 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
536 {:ok, _activity} <-
537 ActivityPub.accept(%{
538 to: [follower.ap_id],
539 actor: followed.ap_id,
540 object: follow_activity.data["id"],
541 type: "Accept"
542 }) do
543 conn
544 |> put_view(UserView)
545 |> render("show.json", %{user: follower, for: followed})
546 else
547 e -> bad_request_reply(conn, "Can't approve user: #{inspect(e)}")
548 end
549 end
550
551 def deny_friend_request(conn, %{"user_id" => uid} = _params) do
552 with followed <- conn.assigns[:user],
553 uid when is_number(uid) <- String.to_integer(uid),
554 %User{} = follower <- Repo.get(User, uid),
555 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
556 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
557 {:ok, _activity} <-
558 ActivityPub.reject(%{
559 to: [follower.ap_id],
560 actor: followed.ap_id,
561 object: follow_activity.data["id"],
562 type: "Reject"
563 }) do
564 conn
565 |> put_view(UserView)
566 |> render("show.json", %{user: follower, for: followed})
567 else
568 e -> bad_request_reply(conn, "Can't deny user: #{inspect(e)}")
569 end
570 end
571
572 def friends_ids(%{assigns: %{user: user}} = conn, _params) do
573 with {:ok, friends} <- User.get_friends(user) do
574 ids =
575 friends
576 |> Enum.map(fn x -> x.id end)
577 |> Jason.encode!()
578
579 json(conn, ids)
580 else
581 _e -> bad_request_reply(conn, "Can't get friends")
582 end
583 end
584
585 def empty_array(conn, _params) do
586 json(conn, Jason.encode!([]))
587 end
588
589 def raw_empty_array(conn, _params) do
590 json(conn, [])
591 end
592
593 defp build_info_cng(user, params) do
594 info_params =
595 ["no_rich_text", "locked", "hide_network"]
596 |> Enum.reduce(%{}, fn key, res ->
597 if value = params[key] do
598 Map.put(res, key, value == "true")
599 else
600 res
601 end
602 end)
603
604 info_params =
605 if value = params["default_scope"] do
606 Map.put(info_params, "default_scope", value)
607 else
608 info_params
609 end
610
611 User.Info.profile_update(user.info, info_params)
612 end
613
614 defp parse_profile_bio(user, params) do
615 if bio = params["description"] do
616 Map.put(params, "bio", User.parse_bio(bio, user))
617 else
618 params
619 end
620 end
621
622 def update_profile(%{assigns: %{user: user}} = conn, params) do
623 params = parse_profile_bio(user, params)
624 info_cng = build_info_cng(user, params)
625
626 with changeset <- User.update_changeset(user, params),
627 changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
628 {:ok, user} <- User.update_and_set_cache(changeset) do
629 CommonAPI.update(user)
630
631 conn
632 |> put_view(UserView)
633 |> render("user.json", %{user: user, for: user})
634 else
635 error ->
636 Logger.debug("Can't update user: #{inspect(error)}")
637 bad_request_reply(conn, "Can't update user")
638 end
639 end
640
641 def search(%{assigns: %{user: user}} = conn, %{"q" => _query} = params) do
642 activities = TwitterAPI.search(user, params)
643
644 conn
645 |> put_view(ActivityView)
646 |> render("index.json", %{activities: activities, for: user})
647 end
648
649 def search_user(%{assigns: %{user: user}} = conn, %{"query" => query}) do
650 users = User.search(query, true)
651
652 conn
653 |> put_view(UserView)
654 |> render("index.json", %{users: users, for: user})
655 end
656
657 defp bad_request_reply(conn, error_message) do
658 json = error_json(conn, error_message)
659 json_reply(conn, 400, json)
660 end
661
662 defp json_reply(conn, status, json) do
663 conn
664 |> put_resp_content_type("application/json")
665 |> send_resp(status, json)
666 end
667
668 defp forbidden_json_reply(conn, error_message) do
669 json = error_json(conn, error_message)
670 json_reply(conn, 403, json)
671 end
672
673 def only_if_public_instance(%{assigns: %{user: %User{}}} = conn, _), do: conn
674
675 def only_if_public_instance(conn, _) do
676 if Keyword.get(Application.get_env(:pleroma, :instance), :public) do
677 conn
678 else
679 conn
680 |> forbidden_json_reply("Invalid credentials.")
681 |> halt()
682 end
683 end
684
685 defp error_json(conn, error_message) do
686 %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
687 end
688
689 def errors(conn, {:param_cast, _}) do
690 conn
691 |> put_status(400)
692 |> json("Invalid parameters")
693 end
694
695 def errors(conn, _) do
696 conn
697 |> put_status(500)
698 |> json("Something went wrong")
699 end
700 end