Merge remote-tracking branch 'upstream/develop' into admin-create-users
[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, :read])
26 |> validate_required([:user_id, :conversation_id])
27 end
28
29 def create_for_user_and_conversation(user, conversation, opts \\ []) do
30 read = !!opts[:read]
31
32 %__MODULE__{}
33 |> creation_cng(%{user_id: user.id, conversation_id: conversation.id, read: read})
34 |> Repo.insert(
35 on_conflict: [set: [read: read, updated_at: NaiveDateTime.utc_now()]],
36 returning: true,
37 conflict_target: [:user_id, :conversation_id]
38 )
39 end
40
41 def read_cng(struct, params) do
42 struct
43 |> cast(params, [:read])
44 |> validate_required([:read])
45 end
46
47 def mark_as_read(participation) do
48 participation
49 |> read_cng(%{read: true})
50 |> Repo.update()
51 end
52
53 def mark_as_unread(participation) do
54 participation
55 |> read_cng(%{read: false})
56 |> Repo.update()
57 end
58
59 def for_user(user, params \\ %{}) do
60 from(p in __MODULE__,
61 where: p.user_id == ^user.id,
62 order_by: [desc: p.updated_at]
63 )
64 |> Pleroma.Pagination.fetch_paginated(params)
65 |> Repo.preload(conversation: [:users])
66 end
67
68 def for_user_with_last_activity_id(user, params \\ %{}) do
69 for_user(user, params)
70 |> Enum.map(fn participation ->
71 activity_id =
72 ActivityPub.fetch_latest_activity_id_for_context(participation.conversation.ap_id, %{
73 "user" => user,
74 "blocking_user" => user
75 })
76
77 %{
78 participation
79 | last_activity_id: activity_id
80 }
81 end)
82 end
83 end