make bulk user creation from admin works as a transaction
[akkoma] / lib / pleroma / 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.Conversation
8 alias Pleroma.Repo
9 alias Pleroma.User
10 alias Pleroma.Web.ActivityPub.ActivityPub
11 import Ecto.Changeset
12 import Ecto.Query
13
14 schema "conversation_participations" do
15 belongs_to(:user, User, type: Pleroma.FlakeId)
16 belongs_to(:conversation, Conversation)
17 field(:read, :boolean, default: false)
18 field(:last_activity_id, Pleroma.FlakeId, virtual: true)
19
20 timestamps()
21 end
22
23 def creation_cng(struct, params) do
24 struct
25 |> cast(params, [:user_id, :conversation_id])
26 |> validate_required([:user_id, :conversation_id])
27 end
28
29 def create_for_user_and_conversation(user, conversation) do
30 %__MODULE__{}
31 |> creation_cng(%{user_id: user.id, conversation_id: conversation.id})
32 |> Repo.insert(
33 on_conflict: [set: [read: false, updated_at: NaiveDateTime.utc_now()]],
34 returning: true,
35 conflict_target: [:user_id, :conversation_id]
36 )
37 end
38
39 def read_cng(struct, params) do
40 struct
41 |> cast(params, [:read])
42 |> validate_required([:read])
43 end
44
45 def mark_as_read(participation) do
46 participation
47 |> read_cng(%{read: true})
48 |> Repo.update()
49 end
50
51 def mark_as_unread(participation) do
52 participation
53 |> read_cng(%{read: false})
54 |> Repo.update()
55 end
56
57 def for_user(user, params \\ %{}) do
58 from(p in __MODULE__,
59 where: p.user_id == ^user.id,
60 order_by: [desc: p.updated_at]
61 )
62 |> Pleroma.Pagination.fetch_paginated(params)
63 |> Repo.preload(conversation: [:users])
64 end
65
66 def for_user_with_last_activity_id(user, params \\ %{}) do
67 for_user(user, params)
68 |> Enum.map(fn participation ->
69 activity_id =
70 ActivityPub.fetch_latest_activity_id_for_context(participation.conversation.ap_id, %{
71 "user" => user,
72 "blocking_user" => user
73 })
74
75 %{
76 participation
77 | last_activity_id: activity_id
78 }
79 end)
80 end
81 end