Add /api/v1/followed_tags
[akkoma] / lib / pleroma / web / mastodon_api / controllers / tag_controller.ex
1 defmodule Pleroma.Web.MastodonAPI.TagController do
2 @moduledoc "Hashtag routes for mastodon API"
3 use Pleroma.Web, :controller
4
5 alias Pleroma.User
6 alias Pleroma.Hashtag
7 alias Pleroma.Pagination
8
9 import Pleroma.Web.ControllerHelper,
10 only: [
11 add_link_headers: 2
12 ]
13
14 plug(Pleroma.Web.ApiSpec.CastAndValidate)
15
16 plug(
17 Pleroma.Web.Plugs.OAuthScopesPlug,
18 %{scopes: ["read"]} when action in [:show]
19 )
20
21 plug(
22 Pleroma.Web.Plugs.OAuthScopesPlug,
23 %{scopes: ["read:follows"]} when action in [:show_followed]
24 )
25
26 plug(
27 Pleroma.Web.Plugs.OAuthScopesPlug,
28 %{scopes: ["write:follows"]} when action in [:follow, :unfollow]
29 )
30
31 defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.TagOperation
32
33 def show(conn, %{id: id}) do
34 with %Hashtag{} = hashtag <- Hashtag.get_by_name(id) do
35 render(conn, "show.json", tag: hashtag, for_user: conn.assigns.user)
36 else
37 _ -> conn |> render_error(:not_found, "Hashtag not found")
38 end
39 end
40
41 def follow(conn, %{id: id}) do
42 with %Hashtag{} = hashtag <- Hashtag.get_by_name(id),
43 %User{} = user <- conn.assigns.user,
44 {:ok, _} <-
45 User.follow_hashtag(user, hashtag) do
46 render(conn, "show.json", tag: hashtag, for_user: user)
47 else
48 _ -> render_error(conn, :not_found, "Hashtag not found")
49 end
50 end
51
52 def unfollow(conn, %{id: id}) do
53 with %Hashtag{} = hashtag <- Hashtag.get_by_name(id),
54 %User{} = user <- conn.assigns.user,
55 {:ok, _} <-
56 User.unfollow_hashtag(user, hashtag) do
57 render(conn, "show.json", tag: hashtag, for_user: user)
58 else
59 _ -> render_error(conn, :not_found, "Hashtag not found")
60 end
61 end
62
63 def show_followed(conn, params) do
64 with %{assigns: %{user: %User{} = user}} <- conn do
65 params = Map.put(params, :id_type, :integer)
66
67 hashtags =
68 user
69 |> User.HashtagFollow.followed_hashtags_query()
70 |> Pagination.fetch_paginated(params)
71
72 conn
73 |> add_link_headers(hashtags)
74 |> render("index.json", tags: hashtags, for_user: user)
75 end
76 end
77 end