[#1335] Reorganized `users.mutes` as relation to UserMute entity.
[akkoma] / lib / pleroma / user_mute.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.UserMute do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9 import Ecto.Query
10
11 alias Pleroma.Repo
12 alias Pleroma.User
13 alias Pleroma.UserMute
14
15 schema "user_mutes" do
16 belongs_to(:muter, User, type: FlakeId.Ecto.CompatType)
17 belongs_to(:mutee, User, type: FlakeId.Ecto.CompatType)
18
19 timestamps(updated_at: false)
20 end
21
22 def changeset(%UserMute{} = user_mute, params \\ %{}) do
23 user_mute
24 |> cast(params, [:muter_id, :mutee_id])
25 |> validate_required([:muter_id, :mutee_id])
26 |> unique_constraint(:mutee_id, name: :user_mutes_muter_id_mutee_id_index)
27 |> validate_not_self_mute()
28 end
29
30 def exists?(%User{} = muter, %User{} = mutee) do
31 UserMute
32 |> where(muter_id: ^muter.id, mutee_id: ^mutee.id)
33 |> Repo.exists?()
34 end
35
36 def create(%User{} = muter, %User{} = mutee) do
37 %UserMute{}
38 |> changeset(%{muter_id: muter.id, mutee_id: mutee.id})
39 |> Repo.insert(
40 on_conflict: :replace_all_except_primary_key,
41 conflict_target: [:muter_id, :mutee_id]
42 )
43 end
44
45 def delete(%User{} = muter, %User{} = mutee) do
46 attrs = %{muter_id: muter.id, mutee_id: mutee.id}
47
48 case Repo.get_by(UserMute, attrs) do
49 %UserMute{} = existing_record -> Repo.delete(existing_record)
50 nil -> {:ok, nil}
51 end
52 end
53
54 defp validate_not_self_mute(%Ecto.Changeset{} = changeset) do
55 changeset
56 |> validate_change(:mutee_id, fn _, mutee_id ->
57 if mutee_id == get_field(changeset, :muter_id) do
58 [mutee_id: "can't be equal to muter_id"]
59 else
60 []
61 end
62 end)
63 |> validate_change(:muter_id, fn _, muter_id ->
64 if muter_id == get_field(changeset, :mutee_id) do
65 [muter_id: "can't be equal to mutee_id"]
66 else
67 []
68 end
69 end)
70 end
71 end