1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Marker do
15 @timelines ["notifications"]
18 field(:last_read_id, :string, default: "")
19 field(:timeline, :string, default: "")
20 field(:lock_version, :integer, default: 0)
22 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
26 def get_markers(user, timelines \\ []) do
27 Repo.all(get_query(user, timelines))
30 def upsert(%User{} = user, attrs) do
32 |> Map.take(@timelines)
33 |> Enum.reduce(Multi.new(), fn {timeline, timeline_attrs}, multi ->
36 |> get_marker(timeline)
37 |> changeset(timeline_attrs)
39 Multi.insert(multi, timeline, marker,
41 on_conflict: {:replace, [:last_read_id]},
42 conflict_target: [:user_id, :timeline]
48 defp get_marker(user, timeline) do
49 case Repo.find_resource(get_query(user, timeline)) do
50 {:ok, marker} -> %__MODULE__{marker | user: user}
51 _ -> %__MODULE__{timeline: timeline, user_id: user.id}
56 defp changeset(marker, attrs) do
58 |> cast(attrs, [:last_read_id])
59 |> validate_required([:user_id, :timeline, :last_read_id])
60 |> validate_inclusion(:timeline, @timelines)
63 defp by_timeline(query, timeline) do
64 from(m in query, where: m.timeline in ^List.wrap(timeline))
67 defp by_user_id(query, id), do: from(m in query, where: m.user_id == ^id)
69 defp get_query(user, timelines) do
71 |> by_user_id(user.id)
72 |> by_timeline(timelines)