migrate to oban 2.0-rc1
[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 @primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
20
21 schema "chats" do
22 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
23 field(:recipient, :string)
24
25 timestamps()
26 end
27
28 def changeset(struct, params) do
29 struct
30 |> cast(params, [:user_id, :recipient])
31 |> validate_change(:recipient, fn
32 :recipient, recipient ->
33 case User.get_cached_by_ap_id(recipient) do
34 nil -> [recipient: "must be an existing user"]
35 _ -> []
36 end
37 end)
38 |> validate_required([:user_id, :recipient])
39 |> unique_constraint(:user_id, name: :chats_user_id_recipient_index)
40 end
41
42 def get_by_id(id) do
43 __MODULE__
44 |> Repo.get(id)
45 end
46
47 def get(user_id, recipient) do
48 __MODULE__
49 |> Repo.get_by(user_id: user_id, recipient: recipient)
50 end
51
52 def get_or_create(user_id, recipient) do
53 %__MODULE__{}
54 |> changeset(%{user_id: user_id, recipient: recipient})
55 |> Repo.insert(
56 # Need to set something, otherwise we get nothing back at all
57 on_conflict: [set: [recipient: recipient]],
58 returning: true,
59 conflict_target: [:user_id, :recipient]
60 )
61 end
62
63 def bump_or_create(user_id, recipient) do
64 %__MODULE__{}
65 |> changeset(%{user_id: user_id, recipient: recipient})
66 |> Repo.insert(
67 on_conflict: [set: [updated_at: NaiveDateTime.utc_now()]],
68 returning: true,
69 conflict_target: [:user_id, :recipient]
70 )
71 end
72 end