2020-01-09 12:18:55 -07:00
|
|
|
# Pleroma: A lightweight social networking server
|
2022-02-25 23:11:42 -07:00
|
|
|
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
2020-01-09 12:18:55 -07:00
|
|
|
# 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 16:20:50 -06:00
|
|
|
field(:instance, :string)
|
|
|
|
field(:public, :integer)
|
|
|
|
field(:unlisted, :integer)
|
|
|
|
field(:private, :integer)
|
|
|
|
field(:direct, :integer)
|
2020-01-09 12:18:55 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
def changeset(struct, params) do
|
|
|
|
struct
|
2020-05-08 16:20:50 -06:00
|
|
|
|> cast(params, [:instance, :public, :unlisted, :private, :direct])
|
|
|
|
|> validate_required([:instance])
|
|
|
|
|> unique_constraint(:instance)
|
2020-01-09 12:18:55 -07:00
|
|
|
end
|
|
|
|
|
2020-05-08 16:20:50 -06:00
|
|
|
def get_by_instance(instance) do
|
2020-01-09 12:18:55 -07:00
|
|
|
CounterCache
|
2020-05-08 16:20:50 -06: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
|
2020-01-09 12:18:55 -07:00
|
|
|
end
|
|
|
|
|
2020-05-09 02:59:49 -06:00
|
|
|
def get_sum do
|
2020-05-08 16:20:50 -06:00
|
|
|
CounterCache
|
|
|
|
|> select([c], %{
|
2020-05-10 00:13:24 -06:00
|
|
|
"public" => type(sum(c.public), :integer),
|
|
|
|
"unlisted" => type(sum(c.unlisted), :integer),
|
|
|
|
"private" => type(sum(c.private), :integer),
|
|
|
|
"direct" => type(sum(c.direct), :integer)
|
2020-05-08 16:20:50 -06:00
|
|
|
})
|
|
|
|
|> Repo.one()
|
|
|
|
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
|
|
|
|
)
|
|
|
|
|
2020-01-09 12:18:55 -07:00
|
|
|
%CounterCache{}
|
2020-05-08 16:20:50 -06:00
|
|
|
|> changeset(params)
|
2020-01-09 12:18:55 -07:00
|
|
|
|> Repo.insert(
|
2020-05-08 16:20:50 -06:00
|
|
|
on_conflict: [
|
|
|
|
set: [
|
|
|
|
public: params["public"],
|
|
|
|
private: params["private"],
|
|
|
|
unlisted: params["unlisted"],
|
|
|
|
direct: params["direct"]
|
|
|
|
]
|
|
|
|
],
|
2020-01-09 12:18:55 -07:00
|
|
|
returning: true,
|
2020-05-08 16:20:50 -06:00
|
|
|
conflict_target: :instance
|
2020-01-09 12:18:55 -07:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|