Merge branch 'account-subscriptions' into 'develop'
[akkoma] / lib / pleroma / thread_mute.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.ThreadMute do
6 use Ecto.Schema
7
8 alias Pleroma.Repo
9 alias Pleroma.ThreadMute
10 alias Pleroma.User
11
12 import Ecto.Changeset
13 import Ecto.Query
14
15 schema "thread_mutes" do
16 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
17 field(:context, :string)
18 end
19
20 def changeset(mute, params \\ %{}) do
21 mute
22 |> cast(params, [:user_id, :context])
23 |> foreign_key_constraint(:user_id)
24 |> unique_constraint(:user_id, name: :unique_index)
25 end
26
27 def query(user_id, context) do
28 user_binary_id = User.binary_id(user_id)
29
30 ThreadMute
31 |> where(user_id: ^user_binary_id)
32 |> where(context: ^context)
33 end
34
35 def muters_query(context) do
36 ThreadMute
37 |> join(:inner, [tm], u in assoc(tm, :user))
38 |> where([tm], tm.context == ^context)
39 |> select([tm, u], u.ap_id)
40 end
41
42 def muter_ap_ids(context, ap_ids \\ nil)
43
44 # Note: applies to fake activities (ActivityPub.Utils.get_notified_from_object/1 etc.)
45 def muter_ap_ids(context, _ap_ids) when is_nil(context), do: []
46
47 def muter_ap_ids(context, ap_ids) do
48 context
49 |> muters_query()
50 |> maybe_filter_on_ap_id(ap_ids)
51 |> Repo.all()
52 end
53
54 defp maybe_filter_on_ap_id(query, ap_ids) when is_list(ap_ids) do
55 where(query, [tm, u], u.ap_id in ^ap_ids)
56 end
57
58 defp maybe_filter_on_ap_id(query, _ap_ids), do: query
59
60 def add_mute(user_id, context) do
61 %ThreadMute{}
62 |> changeset(%{user_id: user_id, context: context})
63 |> Repo.insert()
64 end
65
66 def remove_mute(user_id, context) do
67 query(user_id, context)
68 |> Repo.delete_all()
69 end
70
71 def exists?(user_id, context) do
72 query(user_id, context)
73 |> Repo.exists?()
74 end
75 end