23e6409f13af62bd2a46a79f84fcc5793853e1af
[akkoma] / lib / conversation / participation.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.Conversation.Participation do
6 use Ecto.Schema
7 alias Pleroma.User
8 alias Pleroma.Conversation
9 alias Pleroma.Repo
10 import Ecto.Changeset
11 import Ecto.Query
12
13 schema "conversation_participations" do
14 belongs_to(:user, User, type: Pleroma.FlakeId)
15 belongs_to(:conversation, Conversation)
16 field(:read, :boolean, default: false)
17
18 timestamps()
19 end
20
21 def creation_cng(struct, params) do
22 struct
23 |> cast(params, [:user_id, :conversation_id])
24 |> validate_required([:user_id, :conversation_id])
25 end
26
27 def create_for_user_and_conversation(user, conversation) do
28 %__MODULE__{}
29 |> creation_cng(%{user_id: user.id, conversation_id: conversation.id})
30 |> Repo.insert(
31 on_conflict: [set: [read: false, updated_at: NaiveDateTime.utc_now()]],
32 returning: true,
33 conflict_target: [:user_id, :conversation_id]
34 )
35 end
36
37 def read_cng(struct, params) do
38 struct
39 |> cast(params, [:read])
40 |> validate_required([:read])
41 end
42
43 def mark_as_read(participation) do
44 participation
45 |> read_cng(%{read: true})
46 |> Repo.update()
47 end
48
49 def mark_as_unread(participation) do
50 participation
51 |> read_cng(%{read: false})
52 |> Repo.update()
53 end
54
55 def for_user(user, params \\ %{}) do
56 from(p in __MODULE__,
57 where: p.user_id == ^user.id,
58 order_by: [desc: p.updated_at]
59 )
60 |> Pleroma.Pagination.fetch_paginated(params)
61 end
62 end