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.Conversation.Participation do
7 alias Pleroma.Conversation
8 alias Pleroma.Conversation.Participation.RecipientShip
11 alias Pleroma.Web.ActivityPub.ActivityPub
15 schema "conversation_participations" do
16 belongs_to(:user, User, type: Pleroma.FlakeId)
17 belongs_to(:conversation, Conversation)
18 field(:read, :boolean, default: false)
19 field(:last_activity_id, Pleroma.FlakeId, virtual: true)
21 has_many(:recipient_ships, RecipientShip)
22 has_many(:recipients, through: [:recipient_ships, :user])
27 def creation_cng(struct, params) do
29 |> cast(params, [:user_id, :conversation_id, :read])
30 |> validate_required([:user_id, :conversation_id])
33 def create_for_user_and_conversation(user, conversation, opts \\ []) do
37 |> creation_cng(%{user_id: user.id, conversation_id: conversation.id, read: read})
39 on_conflict: [set: [read: read, updated_at: NaiveDateTime.utc_now()]],
41 conflict_target: [:user_id, :conversation_id]
45 def read_cng(struct, params) do
47 |> cast(params, [:read])
48 |> validate_required([:read])
51 def mark_as_read(participation) do
53 |> read_cng(%{read: true})
57 def mark_as_unread(participation) do
59 |> read_cng(%{read: false})
63 def for_user(user, params \\ %{}) do
65 where: p.user_id == ^user.id,
66 order_by: [desc: p.updated_at],
67 preload: [conversation: [:users]]
69 |> Pleroma.Pagination.fetch_paginated(params)
72 def for_user_and_conversation(user, conversation) do
74 where: p.user_id == ^user.id,
75 where: p.conversation_id == ^conversation.id
80 def for_user_with_last_activity_id(user, params \\ %{}) do
81 for_user(user, params)
82 |> Enum.map(fn participation ->
84 ActivityPub.fetch_latest_activity_id_for_context(participation.conversation.ap_id, %{
86 "blocking_user" => user
91 | last_activity_id: activity_id
94 |> Enum.filter(& &1.last_activity_id)
98 def get(nil, _), do: nil
100 def get(id, params) do
102 if preload = params[:preload] do
103 from(p in __MODULE__,
113 def set_recipients(participation, user_ids) do
115 [participation.user_id | user_ids]
118 Repo.transaction(fn ->
120 from(r in RecipientShip,
121 where: r.participation_id == ^participation.id
124 Repo.delete_all(query)
128 where: u.id in ^user_ids
132 RecipientShip.create(users, participation)
136 {:ok, Repo.preload(participation, :recipients, force: true)}