Conversations: Tidying up.
[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 end
64
65 def for_user_with_last_activity_id(user, params \\ %{}) do
66 for_user(user, params)
67 |> Repo.preload(:conversation)
68 |> Enum.map(fn participation ->
69 # TODO: Don't load all those activities, just get the most recent
70 # Involves splitting up the query.
71 activities =
72 ActivityPub.fetch_activities_for_context(participation.conversation.ap_id, %{
73 "user" => user,
74 "blocking_user" => user
75 })
76
77 activity_id =
78 case activities do
79 [activity | _] -> activity.id
80 _ -> nil
81 end
82
83 %{
84 participation
85 | last_activity_id: activity_id
86 }
87 end)
88 end
89 end