Chat: creation_cng -> changeset
[akkoma] / lib / pleroma / chat.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Chat do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9
10 alias Pleroma.Repo
11 alias Pleroma.User
12
13 @moduledoc """
14 Chat keeps a reference to ChatMessage conversations between a user and an recipient. The recipient can be a user (for now) or a group (not implemented yet).
15
16 It is a helper only, to make it easy to display a list of chats with other people, ordered by last bump. The actual messages are retrieved by querying the recipients of the ChatMessages.
17 """
18
19 schema "chats" do
20 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
21 field(:recipient, :string)
22
23 timestamps()
24 end
25
26 def changeset(struct, params) do
27 struct
28 |> cast(params, [:user_id, :recipient])
29 |> validate_change(:recipient, fn
30 :recipient, recipient ->
31 case User.get_cached_by_ap_id(recipient) do
32 nil -> [recipient: "must be an existing user"]
33 _ -> []
34 end
35 end)
36 |> validate_required([:user_id, :recipient])
37 |> unique_constraint(:user_id, name: :chats_user_id_recipient_index)
38 end
39
40 def get_by_id(id) do
41 __MODULE__
42 |> Repo.get(id)
43 end
44
45 def get(user_id, recipient) do
46 __MODULE__
47 |> Repo.get_by(user_id: user_id, recipient: recipient)
48 end
49
50 def get_or_create(user_id, recipient) do
51 %__MODULE__{}
52 |> changeset(%{user_id: user_id, recipient: recipient})
53 |> Repo.insert(
54 # Need to set something, otherwise we get nothing back at all
55 on_conflict: [set: [recipient: recipient]],
56 returning: true,
57 conflict_target: [:user_id, :recipient]
58 )
59 end
60
61 def bump_or_create(user_id, recipient) do
62 %__MODULE__{}
63 |> changeset(%{user_id: user_id, recipient: recipient})
64 |> Repo.insert(
65 on_conflict: [set: [updated_at: NaiveDateTime.utc_now()]],
66 conflict_target: [:user_id, :recipient]
67 )
68 end
69 end