1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Chat do
16 Chat keeps a reference to ChatMessage conversations between a user and an recipient. The recipient can be a user (for now) or a group (not implemented yet).
18 It is a helper only, to make it easy to display a list of chats with other people, ordered by last bump. The actual messages are retrieved by querying the recipients of the ChatMessages.
21 @type t :: %__MODULE__{}
22 @primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
25 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
26 field(:recipient, :string)
31 def changeset(struct, params) do
33 |> cast(params, [:user_id, :recipient])
34 |> validate_change(:recipient, fn
35 :recipient, recipient ->
36 case User.get_cached_by_ap_id(recipient) do
37 nil -> [recipient: "must be an existing user"]
41 |> validate_required([:user_id, :recipient])
42 |> unique_constraint(:user_id, name: :chats_user_id_recipient_index)
45 @spec get_by_user_and_id(User.t(), Ecto.UUID.t()) ::
46 {:ok, t()} | {:error, :not_found}
47 def get_by_user_and_id(%User{id: user_id}, id) do
50 where: c.user_id == ^user_id
52 |> Repo.find_resource()
55 @spec get_by_id(Ecto.UUID.t()) :: t() | nil
57 Repo.get(__MODULE__, id)
60 @spec get(Ecto.UUID.t(), String.t()) :: t() | nil
61 def get(user_id, recipient) do
62 Repo.get_by(__MODULE__, user_id: user_id, recipient: recipient)
65 @spec get_or_create(Ecto.UUID.t(), String.t()) ::
66 {:ok, t()} | {:error, Ecto.Changeset.t()}
67 def get_or_create(user_id, recipient) do
69 |> changeset(%{user_id: user_id, recipient: recipient})
71 # Need to set something, otherwise we get nothing back at all
72 on_conflict: [set: [recipient: recipient]],
74 conflict_target: [:user_id, :recipient]
78 @spec bump_or_create(Ecto.UUID.t(), String.t()) ::
79 {:ok, t()} | {:error, Ecto.Changeset.t()}
80 def bump_or_create(user_id, recipient) do
82 |> changeset(%{user_id: user_id, recipient: recipient})
84 on_conflict: [set: [updated_at: NaiveDateTime.utc_now()]],
86 conflict_target: [:user_id, :recipient]
90 @spec for_user_query(Ecto.UUID.t()) :: Ecto.Query.t()
91 def for_user_query(user_id) do
93 where: c.user_id == ^user_id,
94 order_by: [desc: c.updated_at]