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