total rebase
[anni] / lib / pleroma / announcement_read_relationship.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.AnnouncementReadRelationship do
6   use Ecto.Schema
7
8   import Ecto.Changeset
9
10   alias FlakeId.Ecto.CompatType
11   alias Pleroma.Announcement
12   alias Pleroma.Repo
13   alias Pleroma.User
14
15   @type t :: %__MODULE__{}
16
17   schema "announcement_read_relationships" do
18     belongs_to(:user, User, type: CompatType)
19     belongs_to(:announcement, Announcement, type: CompatType)
20
21     timestamps(updated_at: false)
22   end
23
24   def mark_read(user, announcement) do
25     %__MODULE__{}
26     |> cast(%{user_id: user.id, announcement_id: announcement.id}, [:user_id, :announcement_id])
27     |> validate_required([:user_id, :announcement_id])
28     |> foreign_key_constraint(:user_id)
29     |> foreign_key_constraint(:announcement_id)
30     |> unique_constraint([:user_id, :announcement_id])
31     |> Repo.insert()
32   end
33
34   def mark_unread(user, announcement) do
35     with relationship <- get(user, announcement),
36          {:exists, true} <- {:exists, not is_nil(relationship)},
37          {:ok, _} <- Repo.delete(relationship) do
38       :ok
39     else
40       {:exists, false} ->
41         :ok
42
43       _ ->
44         :error
45     end
46   end
47
48   def get(user, announcement) do
49     Repo.get_by(__MODULE__, user_id: user.id, announcement_id: announcement.id)
50   end
51
52   def exists?(user, announcement) do
53     not is_nil(get(user, announcement))
54   end
55 end