branch
[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 set_reblogs_visibility(options[:reblogs], result)
28 {:ok, follower}
29 end
30 end
31
32 defp set_reblogs_visibility(false, {:ok, follower, followed, _}) do
33 CommonAPI.hide_reblogs(follower, followed)
34 end
35
36 defp set_reblogs_visibility(_, {:ok, follower, followed, _}) do
37 CommonAPI.show_reblogs(follower, followed)
38 end
39
40 @spec get_followers(User.t(), map()) :: list(User.t())
41 def get_followers(user, params \\ %{}) do
42 user
43 |> User.get_followers_query()
44 |> Pagination.fetch_paginated(params)
45 end
46
47 def get_friends(user, params \\ %{}) do
48 user
49 |> User.get_friends_query()
50 |> Pagination.fetch_paginated(params)
51 end
52
53 def get_notifications(user, params \\ %{}) do
54 options = cast_params(params)
55
56 user
57 |> Notification.for_user_query(options)
58 |> restrict(:exclude_types, options)
59 |> Pagination.fetch_paginated(params)
60 end
61
62 def get_scheduled_activities(user, params \\ %{}) do
63 user
64 |> ScheduledActivity.for_user_query()
65 |> Pagination.fetch_paginated(params)
66 end
67
68 defp cast_params(params) do
69 param_types = %{
70 exclude_types: {:array, :string},
71 exclude_visibilities: {:array, :string},
72 reblogs: :boolean,
73 with_muted: :boolean,
74 with_move: :boolean
75 }
76
77 changeset = cast({%{}, param_types}, params, Map.keys(param_types))
78 changeset.changes
79 end
80
81 defp restrict(query, :exclude_types, %{exclude_types: mastodon_types = [_ | _]}) do
82 ap_types =
83 mastodon_types
84 |> Enum.map(&Activity.from_mastodon_notification_type/1)
85 |> Enum.filter(& &1)
86
87 query
88 |> where([q, a], not fragment("? @> ARRAY[?->>'type']::varchar[]", ^ap_types, a.data))
89 end
90
91 defp restrict(query, _, _), do: query
92 end