Return total from pagination + tests
[akkoma] / lib / pleroma / web / mastodon_api / mastodon_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.MastodonAPI.MastodonAPI do
6 import Ecto.Query
7 import Ecto.Changeset
8
9 alias Pleroma.Activity
10 alias Pleroma.Notification
11 alias Pleroma.Pagination
12 alias Pleroma.ScheduledActivity
13 alias Pleroma.User
14 alias Pleroma.Web.CommonAPI
15
16 @spec follow(User.t(), User.t(), map) :: {:ok, User.t()} | {:error, String.t()}
17 def follow(follower, followed, params \\ %{}) do
18 result =
19 if not User.following?(follower, followed) do
20 CommonAPI.follow(follower, followed)
21 else
22 {:ok, follower, followed, nil}
23 end
24
25 with {:ok, follower, _followed, _} <- result do
26 options = cast_params(params)
27
28 case reblogs_visibility(options[:reblogs], result) do
29 {:ok, follower} -> {:ok, follower}
30 _ -> {:ok, follower}
31 end
32 end
33 end
34
35 defp reblogs_visibility(false, {:ok, follower, followed, _}) do
36 CommonAPI.hide_reblogs(follower, followed)
37 end
38
39 defp reblogs_visibility(_, {:ok, follower, followed, _}) do
40 CommonAPI.show_reblogs(follower, followed)
41 end
42
43 @spec get_followers(User.t(), map()) :: list(User.t())
44 def get_followers(user, params \\ %{}) do
45 user
46 |> User.get_followers_query()
47 |> Pagination.fetch_paginated(params)
48 |> Map.get(:items)
49 end
50
51 def get_friends(user, params \\ %{}) do
52 user
53 |> User.get_friends_query()
54 |> Pagination.fetch_paginated(params)
55 |> Map.get(:items)
56 end
57
58 def get_notifications(user, params \\ %{}) do
59 options = cast_params(params)
60
61 user
62 |> Notification.for_user_query(options)
63 |> restrict(:exclude_types, options)
64 |> Pagination.fetch_paginated(params)
65 |> Map.get(:items)
66 end
67
68 def get_scheduled_activities(user, params \\ %{}) do
69 user
70 |> ScheduledActivity.for_user_query()
71 |> Pagination.fetch_paginated(params)
72 |> Map.get(:items)
73 end
74
75 defp cast_params(params) do
76 param_types = %{
77 exclude_types: {:array, :string},
78 reblogs: :boolean,
79 with_muted: :boolean
80 }
81
82 changeset = cast({%{}, param_types}, params, Map.keys(param_types))
83 changeset.changes
84 end
85
86 defp restrict(query, :exclude_types, %{exclude_types: mastodon_types = [_ | _]}) do
87 ap_types =
88 mastodon_types
89 |> Enum.map(&Activity.from_mastodon_notification_type/1)
90 |> Enum.filter(& &1)
91
92 query
93 |> where([q, a], not fragment("? @> ARRAY[?->>'type']::varchar[]", ^ap_types, a.data))
94 end
95
96 defp restrict(query, _, _), do: query
97 end