Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / mastodon_api / mastodon_api.ex
1 defmodule Pleroma.Web.MastodonAPI.MastodonAPI do
2 import Ecto.Query
3 import Ecto.Changeset
4
5 alias Pleroma.Activity
6 alias Pleroma.Notification
7 alias Pleroma.Pagination
8 alias Pleroma.ScheduledActivity
9 alias Pleroma.User
10 alias Pleroma.Web.CommonAPI
11
12 def follow(follower, followed, params \\ %{}) do
13 options = cast_params(params)
14 reblogs = options[:reblogs]
15
16 result =
17 if not User.following?(follower, followed) do
18 CommonAPI.follow(follower, followed)
19 else
20 {:ok, follower, followed, nil}
21 end
22
23 with {:ok, follower, followed, _} <- result do
24 reblogs
25 |> case do
26 false -> CommonAPI.hide_reblogs(follower, followed)
27 _ -> CommonAPI.show_reblogs(follower, followed)
28 end
29 |> case do
30 {:ok, follower} -> {:ok, follower}
31 _ -> {:ok, follower}
32 end
33 end
34 end
35
36 def get_followers(user, params \\ %{}) do
37 user
38 |> User.get_followers_query()
39 |> Pagination.fetch_paginated(params)
40 end
41
42 def get_friends(user, params \\ %{}) do
43 user
44 |> User.get_friends_query()
45 |> Pagination.fetch_paginated(params)
46 end
47
48 def get_notifications(user, params \\ %{}) do
49 options = cast_params(params)
50
51 user
52 |> Notification.for_user_query()
53 |> restrict(:exclude_types, options)
54 |> Pagination.fetch_paginated(params)
55 end
56
57 def get_scheduled_activities(user, params \\ %{}) do
58 user
59 |> ScheduledActivity.for_user_query()
60 |> Pagination.fetch_paginated(params)
61 end
62
63 defp cast_params(params) do
64 param_types = %{
65 exclude_types: {:array, :string},
66 reblogs: :boolean
67 }
68
69 changeset = cast({%{}, param_types}, params, Map.keys(param_types))
70 changeset.changes
71 end
72
73 defp restrict(query, :exclude_types, %{exclude_types: mastodon_types = [_ | _]}) do
74 ap_types =
75 mastodon_types
76 |> Enum.map(&Activity.from_mastodon_notification_type/1)
77 |> Enum.filter(& &1)
78
79 query
80 |> where([q, a], not fragment("? @> ARRAY[?->>'type']::varchar[]", ^ap_types, a.data))
81 end
82
83 defp restrict(query, _, _), do: query
84 end