1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.UserRelationship do
13 alias Pleroma.UserRelationship
15 schema "user_relationships" do
16 belongs_to(:source, User, type: FlakeId.Ecto.CompatType)
17 belongs_to(:target, User, type: FlakeId.Ecto.CompatType)
18 field(:relationship_type, UserRelationshipTypeEnum)
20 timestamps(updated_at: false)
23 for relationship_type <- Keyword.keys(UserRelationshipTypeEnum.__enum_map__()) do
24 # Definitions of `create_block/2`, `create_mute/2` etc.
25 def unquote(:"create_#{relationship_type}")(source, target),
26 do: create(unquote(relationship_type), source, target)
28 # Definitions of `delete_block/2`, `delete_mute/2` etc.
29 def unquote(:"delete_#{relationship_type}")(source, target),
30 do: delete(unquote(relationship_type), source, target)
32 # Definitions of `block_exists?/2`, `mute_exists?/2` etc.
33 def unquote(:"#{relationship_type}_exists?")(source, target),
34 do: exists?(unquote(relationship_type), source, target)
37 def changeset(%UserRelationship{} = user_relationship, params \\ %{}) do
39 |> cast(params, [:relationship_type, :source_id, :target_id])
40 |> validate_required([:relationship_type, :source_id, :target_id])
41 |> unique_constraint(:relationship_type,
42 name: :user_relationships_source_id_relationship_type_target_id_index
44 |> validate_not_self_relationship()
47 def exists?(relationship_type, %User{} = source, %User{} = target) do
49 |> where(relationship_type: ^relationship_type, source_id: ^source.id, target_id: ^target.id)
53 def create(relationship_type, %User{} = source, %User{} = target) do
56 relationship_type: relationship_type,
61 on_conflict: {:replace_all_except, [:id]},
62 conflict_target: [:source_id, :relationship_type, :target_id]
66 def delete(relationship_type, %User{} = source, %User{} = target) do
67 attrs = %{relationship_type: relationship_type, source_id: source.id, target_id: target.id}
69 case Repo.get_by(UserRelationship, attrs) do
70 %UserRelationship{} = existing_record -> Repo.delete(existing_record)
75 defp validate_not_self_relationship(%Ecto.Changeset{} = changeset) do
77 |> validate_change(:target_id, fn _, target_id ->
78 if target_id == get_field(changeset, :source_id) do
79 [target_id: "can't be equal to source_id"]
84 |> validate_change(:source_id, fn _, source_id ->
85 if source_id == get_field(changeset, :target_id) do
86 [source_id: "can't be equal to target_id"]