1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Stats do
10 alias Pleroma.CounterCache
14 @interval :timer.seconds(60)
26 {:ok, nil, {:continue, :calculate_stats}}
29 @doc "Performs update stats"
31 GenServer.call(__MODULE__, :force_update)
34 @doc "Returns stats data"
35 @spec get_stats() :: %{
36 domain_count: non_neg_integer(),
37 status_count: non_neg_integer(),
38 user_count: non_neg_integer()
41 %{stats: stats} = GenServer.call(__MODULE__, :get_state)
46 @doc "Returns list peers"
47 @spec get_peers() :: list(String.t())
49 %{peers: peers} = GenServer.call(__MODULE__, :get_state)
54 @spec calculate_stat_data() :: %{
57 domain_count: non_neg_integer(),
58 status_count: non_neg_integer(),
59 user_count: non_neg_integer()
62 def calculate_stat_data do
66 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
67 where: u.local != ^true
72 domain_count = Enum.count(peers)
74 status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
78 where: u.is_active == true,
79 where: u.local == true,
80 where: not is_nil(u.nickname),
81 where: not u.invisible
84 user_count = Repo.aggregate(users_query, :count, :id)
89 domain_count: domain_count,
90 status_count: status_count || 0,
91 user_count: user_count
96 @spec get_status_visibility_count(String.t() | nil) :: map()
97 def get_status_visibility_count(instance \\ nil) do
98 if is_nil(instance) do
99 CounterCache.get_sum()
101 CounterCache.get_by_instance(instance)
106 def handle_continue(:calculate_stats, _) do
107 stats = calculate_stat_data()
109 unless Pleroma.Config.get(:env) == :test do
110 Process.send_after(self(), :run_update, @interval)
117 def handle_call(:force_update, _from, _state) do
118 new_stats = calculate_stat_data()
119 {:reply, new_stats, new_stats}
123 def handle_call(:get_state, _from, state) do
124 {:reply, state, state}
128 def handle_info(:run_update, _) do
129 new_stats = calculate_stat_data()
130 Process.send_after(self(), :run_update, @interval)
131 {:noreply, new_stats}