Merge branch 'feature/send-identifier-on-oauth-error' into 'develop'
[akkoma] / lib / pleroma / web / mastodon_api / controllers / list_controller.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.MastodonAPI.ListController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.User
9 alias Pleroma.Web.MastodonAPI.AccountView
10
11 plug(:list_by_id_and_user when action not in [:index, :create])
12
13 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
14
15 # GET /api/v1/lists
16 def index(%{assigns: %{user: user}} = conn, opts) do
17 lists = Pleroma.List.for_user(user, opts)
18 render(conn, "index.json", lists: lists)
19 end
20
21 # POST /api/v1/lists
22 def create(%{assigns: %{user: user}} = conn, %{"title" => title}) do
23 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
24 render(conn, "show.json", list: list)
25 end
26 end
27
28 # GET /api/v1/lists/:id
29 def show(%{assigns: %{list: list}} = conn, _) do
30 render(conn, "show.json", list: list)
31 end
32
33 # PUT /api/v1/lists/:id
34 def update(%{assigns: %{list: list}} = conn, %{"title" => title}) do
35 with {:ok, list} <- Pleroma.List.rename(list, title) do
36 render(conn, "show.json", list: list)
37 end
38 end
39
40 # DELETE /api/v1/lists/:id
41 def delete(%{assigns: %{list: list}} = conn, _) do
42 with {:ok, _list} <- Pleroma.List.delete(list) do
43 json(conn, %{})
44 end
45 end
46
47 # GET /api/v1/lists/:id/accounts
48 def list_accounts(%{assigns: %{user: user, list: list}} = conn, _) do
49 with {:ok, users} <- Pleroma.List.get_following(list) do
50 conn
51 |> put_view(AccountView)
52 |> render("index.json", for: user, users: users, as: :user)
53 end
54 end
55
56 # POST /api/v1/lists/:id/accounts
57 def add_to_list(%{assigns: %{list: list}} = conn, %{"account_ids" => account_ids}) do
58 Enum.each(account_ids, fn account_id ->
59 with %User{} = followed <- User.get_cached_by_id(account_id) do
60 Pleroma.List.follow(list, followed)
61 end
62 end)
63
64 json(conn, %{})
65 end
66
67 # DELETE /api/v1/lists/:id/accounts
68 def remove_from_list(%{assigns: %{list: list}} = conn, %{"account_ids" => account_ids}) do
69 Enum.each(account_ids, fn account_id ->
70 with %User{} = followed <- User.get_cached_by_id(account_id) do
71 Pleroma.List.unfollow(list, followed)
72 end
73 end)
74
75 json(conn, %{})
76 end
77
78 defp list_by_id_and_user(%{assigns: %{user: user}, params: %{"id" => id}} = conn, _) do
79 case Pleroma.List.get(id, user) do
80 %Pleroma.List{} = list -> assign(conn, :list, list)
81 nil -> conn |> render_error(:not_found, "List not found") |> halt()
82 end
83 end
84 end