1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 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 if Pleroma.Config.get(:env) != :test do
27 {:ok, nil, {:continue, :calculate_stats}}
29 {:ok, calculate_stat_data()}
33 @doc "Performs update stats"
35 GenServer.call(__MODULE__, :force_update)
38 @doc "Returns stats data"
39 @spec get_stats() :: %{
40 domain_count: non_neg_integer(),
41 status_count: non_neg_integer(),
42 user_count: non_neg_integer()
45 %{stats: stats} = GenServer.call(__MODULE__, :get_state)
50 @doc "Returns list peers"
51 @spec get_peers() :: list(String.t())
53 %{peers: peers} = GenServer.call(__MODULE__, :get_state)
58 @spec calculate_stat_data() :: %{
61 domain_count: non_neg_integer(),
62 status_count: non_neg_integer(),
63 user_count: non_neg_integer()
66 def calculate_stat_data do
70 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
71 where: u.local != ^true
76 domain_count = Enum.count(peers)
78 status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
82 where: u.is_active == true,
83 where: u.local == true,
84 where: not is_nil(u.nickname),
85 where: not u.invisible
88 user_count = Repo.aggregate(users_query, :count, :id)
93 domain_count: domain_count,
94 status_count: status_count || 0,
95 user_count: user_count
100 @spec get_status_visibility_count(String.t() | nil) :: map()
101 def get_status_visibility_count(instance \\ nil) do
102 if is_nil(instance) do
103 CounterCache.get_sum()
105 CounterCache.get_by_instance(instance)
110 def handle_continue(:calculate_stats, _) do
111 stats = calculate_stat_data()
113 unless Pleroma.Config.get(:env) == :test do
114 Process.send_after(self(), :run_update, @interval)
121 def handle_call(:force_update, _from, _state) do
122 new_stats = calculate_stat_data()
123 {:reply, new_stats, new_stats}
127 def handle_call(:get_state, _from, state) do
128 {:reply, state, state}
132 def handle_info(:run_update, _) do
133 new_stats = calculate_stat_data()
134 Process.send_after(self(), :run_update, @interval)
135 {:noreply, new_stats}