logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

counter_cache.ex (1961B)


  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. defmodule Pleroma.CounterCache do
  5. alias Pleroma.CounterCache
  6. alias Pleroma.Repo
  7. use Ecto.Schema
  8. import Ecto.Changeset
  9. import Ecto.Query
  10. schema "counter_cache" do
  11. field(:instance, :string)
  12. field(:public, :integer)
  13. field(:unlisted, :integer)
  14. field(:private, :integer)
  15. field(:direct, :integer)
  16. end
  17. def changeset(struct, params) do
  18. struct
  19. |> cast(params, [:instance, :public, :unlisted, :private, :direct])
  20. |> validate_required([:instance])
  21. |> unique_constraint(:instance)
  22. end
  23. def get_by_instance(instance) do
  24. CounterCache
  25. |> select([c], %{
  26. "public" => c.public,
  27. "unlisted" => c.unlisted,
  28. "private" => c.private,
  29. "direct" => c.direct
  30. })
  31. |> where([c], c.instance == ^instance)
  32. |> Repo.one()
  33. |> case do
  34. nil -> %{"public" => 0, "unlisted" => 0, "private" => 0, "direct" => 0}
  35. val -> val
  36. end
  37. end
  38. def get_sum do
  39. CounterCache
  40. |> select([c], %{
  41. "public" => type(sum(c.public), :integer),
  42. "unlisted" => type(sum(c.unlisted), :integer),
  43. "private" => type(sum(c.private), :integer),
  44. "direct" => type(sum(c.direct), :integer)
  45. })
  46. |> Repo.one()
  47. end
  48. def set(instance, values) do
  49. params =
  50. Enum.reduce(
  51. ["public", "private", "unlisted", "direct"],
  52. %{"instance" => instance},
  53. fn param, acc ->
  54. Map.put_new(acc, param, Map.get(values, param, 0))
  55. end
  56. )
  57. %CounterCache{}
  58. |> changeset(params)
  59. |> Repo.insert(
  60. on_conflict: [
  61. set: [
  62. public: params["public"],
  63. private: params["private"],
  64. unlisted: params["unlisted"],
  65. direct: params["direct"]
  66. ]
  67. ],
  68. returning: true,
  69. conflict_target: :instance
  70. )
  71. end
  72. end