Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into remake-remodel-dms
[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 import Ecto.Changeset
8
9 alias Pleroma.Repo
10 alias Pleroma.User
11
12 @moduledoc """
13 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).
14
15 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.
16 """
17
18 schema "chats" do
19 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
20 field(:recipient, :string)
21 field(:unread, :integer, default: 0, read_after_writes: true)
22
23 timestamps()
24 end
25
26 def creation_cng(struct, params) do
27 struct
28 |> cast(params, [:user_id, :recipient, :unread])
29 |> validate_change(:recipient, fn
30 :recipient, recipient ->
31 case User.get_cached_by_ap_id(recipient) do
32 nil -> [recipient: "must a 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(user_id, recipient) do
41 __MODULE__
42 |> Repo.get_by(user_id: user_id, recipient: recipient)
43 end
44
45 def get_or_create(user_id, recipient) do
46 %__MODULE__{}
47 |> creation_cng(%{user_id: user_id, recipient: recipient})
48 |> Repo.insert(
49 on_conflict: :nothing,
50 returning: true,
51 conflict_target: [:user_id, :recipient]
52 )
53 end
54
55 def bump_or_create(user_id, recipient) do
56 %__MODULE__{}
57 |> creation_cng(%{user_id: user_id, recipient: recipient, unread: 1})
58 |> Repo.insert(
59 on_conflict: [set: [updated_at: NaiveDateTime.utc_now()], inc: [unread: 1]],
60 conflict_target: [:user_id, :recipient]
61 )
62 end
63 end