Participation: Get for a user.
[akkoma] / lib / conversation.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 do
6 alias Pleroma.Repo
7 alias Pleroma.Conversation.Participation
8 alias Pleroma.User
9 use Ecto.Schema
10 import Ecto.Changeset
11
12 schema "conversations" do
13 # This is the context ap id.
14 field(:ap_id, :string)
15 has_many(:participations, Participation)
16
17 timestamps()
18 end
19
20 def creation_cng(struct, params) do
21 struct
22 |> cast(params, [:ap_id])
23 |> validate_required([:ap_id])
24 |> unique_constraint(:ap_id)
25 end
26
27 def create_for_ap_id(ap_id) do
28 %__MODULE__{}
29 |> creation_cng(%{ap_id: ap_id})
30 |> Repo.insert(
31 on_conflict: [set: [updated_at: NaiveDateTime.utc_now()]],
32 returning: true,
33 conflict_target: :ap_id
34 )
35 end
36
37 def get_for_ap_id(ap_id) do
38 Repo.get_by(__MODULE__, ap_id: ap_id)
39 end
40
41 @doc """
42 This will
43 1. Create a conversation if there isn't one already
44 2. Create a participation for all the people involved who don't have one already
45 3. Bump all relevant participations to 'unread'
46 """
47 def create_or_bump_for(activity) do
48 with true <- Pleroma.Web.ActivityPub.Visibility.is_direct?(activity),
49 "Create" <- activity.data["type"],
50 "Note" <- activity.data["object"]["type"],
51 ap_id when is_binary(ap_id) <- activity.data["object"]["context"] do
52 {:ok, conversation} = create_for_ap_id(ap_id)
53
54 users = User.get_users_from_set(activity.recipients)
55
56 participations =
57 Enum.map(users, fn user ->
58 {:ok, participation} =
59 Participation.create_for_user_and_conversation(user, conversation)
60
61 participation
62 end)
63
64 %{
65 conversation
66 | participations: participations
67 }
68 end
69 end
70 end