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.MessageReference do
7 A reference that builds a relation between an AP chat message that a user can see and whether it has been seen
8 by them, or should be displayed to them. Used to build the chat view that is presented to the user.
20 @primary_key {:id, FlakeId.Ecto.Type, autogenerate: true}
22 schema "chat_message_references" do
23 belongs_to(:object, Object)
24 belongs_to(:chat, Chat, type: FlakeId.Ecto.CompatType)
26 field(:unread, :boolean, default: true)
31 def changeset(struct, params) do
33 |> cast(params, [:object_id, :chat_id, :unread])
34 |> validate_required([:object_id, :chat_id, :unread])
40 |> Repo.preload(:object)
48 def delete_for_object(%{id: object_id}) do
49 from(cr in __MODULE__,
50 where: cr.object_id == ^object_id
55 def for_chat_and_object(%{id: chat_id}, %{id: object_id}) do
57 |> Repo.get_by(chat_id: chat_id, object_id: object_id)
58 |> Repo.preload(:object)
61 def for_chat_query(chat) do
62 from(cr in __MODULE__,
63 where: cr.chat_id == ^chat.id,
64 order_by: [desc: :id],
69 def last_message_for_chat(chat) do
76 def create(chat, object, unread) do
88 def unread_count_for_chat(chat) do
91 |> where([cmr], cmr.unread == true)
92 |> Repo.aggregate(:count)
95 def mark_as_read(cm_ref) do
97 |> changeset(%{unread: false})
101 def set_all_seen_for_chat(chat, last_read_id \\ nil) do
105 |> exclude(:order_by)
107 |> where([cmr], cmr.unread == true)
111 |> where([cmr], cmr.id <= ^last_read_id)
115 |> Repo.update_all(set: [unread: false])