1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Marker do
12 alias Pleroma.Notification
17 @timelines ["notifications"]
18 @type t :: %__MODULE__{}
21 field(:last_read_id, :string, default: "")
22 field(:timeline, :string, default: "")
23 field(:lock_version, :integer, default: 0)
24 field(:unread_count, :integer, default: 0, virtual: true)
26 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
30 @doc "Gets markers by user and timeline."
31 @spec get_markers(User.t(), list(String)) :: list(t())
32 def get_markers(user, timelines \\ []) do
34 |> get_query(timelines)
35 |> unread_count_query()
39 @spec upsert(User.t(), map()) :: {:ok | :error, any()}
40 def upsert(%User{} = user, attrs) do
42 |> Map.take(@timelines)
43 |> Enum.reduce(Multi.new(), fn {timeline, timeline_attrs}, multi ->
46 |> get_marker(timeline)
47 |> changeset(timeline_attrs)
49 Multi.insert(multi, timeline, marker,
51 on_conflict: {:replace, [:last_read_id]},
52 conflict_target: [:user_id, :timeline]
58 @spec multi_set_last_read_id(Multi.t(), User.t(), String.t()) :: Multi.t()
59 def multi_set_last_read_id(multi, %User{} = user, "notifications") do
61 |> Multi.run(:counters, fn _repo, _changes ->
62 {:ok, %{last_read_id: Repo.one(Notification.last_read_query(user))}}
66 fn %{counters: attrs} ->
67 %Marker{timeline: "notifications", user_id: user.id}
69 |> Ecto.Changeset.change()
72 on_conflict: {:replace, [:last_read_id]},
73 conflict_target: [:user_id, :timeline]
77 def multi_set_last_read_id(multi, _, _), do: multi
79 defp get_marker(user, timeline) do
80 case Repo.find_resource(get_query(user, timeline)) do
81 {:ok, marker} -> %__MODULE__{marker | user: user}
82 _ -> %__MODULE__{timeline: timeline, user_id: user.id}
87 defp changeset(marker, attrs) do
89 |> cast(attrs, [:last_read_id])
90 |> validate_required([:user_id, :timeline, :last_read_id])
91 |> validate_inclusion(:timeline, @timelines)
94 defp by_timeline(query, timeline) do
95 from(m in query, where: m.timeline in ^List.wrap(timeline))
98 defp by_user_id(query, id), do: from(m in query, where: m.user_id == ^id)
100 defp get_query(user, timelines) do
102 |> by_user_id(user.id)
103 |> by_timeline(timelines)
106 defp unread_count_query(query) do
109 left_join: n in "notifications",
110 on: n.user_id == q.user_id and n.seen == false,
113 unread_count: fragment("count(?)", n.id)