1
0
Fork 1
mirror of https://akkoma.dev/AkkomaGang/akkoma.git synced 2024-11-18 10:59:17 +00:00
akkoma/lib/pleroma/counter_cache.ex

84 lines
2 KiB
Elixir
Raw Normal View History

# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.CounterCache do
alias Pleroma.CounterCache
alias Pleroma.Repo
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query
schema "counter_cache" do
2020-05-08 23:20:50 +01:00
field(:instance, :string)
field(:public, :integer)
field(:unlisted, :integer)
field(:private, :integer)
field(:direct, :integer)
end
def changeset(struct, params) do
struct
2020-05-08 23:20:50 +01:00
|> cast(params, [:instance, :public, :unlisted, :private, :direct])
|> validate_required([:instance])
|> unique_constraint(:instance)
end
2020-05-08 23:20:50 +01:00
def get_by_instance(instance) do
CounterCache
2020-05-08 23:20:50 +01:00
|> select([c], %{
"public" => c.public,
"unlisted" => c.unlisted,
"private" => c.private,
"direct" => c.direct
})
|> where([c], c.instance == ^instance)
|> Repo.one()
|> case do
nil -> %{"public" => 0, "unlisted" => 0, "private" => 0, "direct" => 0}
val -> val
end
end
2020-05-09 09:30:37 +01:00
def get_sum() do
2020-05-08 23:20:50 +01:00
CounterCache
|> select([c], %{
"public" => sum(c.public),
"unlisted" => sum(c.unlisted),
"private" => sum(c.private),
"direct" => sum(c.direct)
})
|> Repo.one()
2020-05-09 09:30:37 +01:00
|> Enum.map(fn {visibility, dec_count} ->
{visibility, Decimal.to_integer(dec_count)}
end)
|> Enum.into(%{})
2020-05-08 23:20:50 +01:00
end
def set(instance, values) do
params =
Enum.reduce(
["public", "private", "unlisted", "direct"],
%{"instance" => instance},
fn param, acc ->
Map.put_new(acc, param, Map.get(values, param, 0))
end
)
%CounterCache{}
2020-05-08 23:20:50 +01:00
|> changeset(params)
|> Repo.insert(
2020-05-08 23:20:50 +01:00
on_conflict: [
set: [
public: params["public"],
private: params["private"],
unlisted: params["unlisted"],
direct: params["direct"]
]
],
returning: true,
2020-05-08 23:20:50 +01:00
conflict_target: :instance
)
end
end