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(300)
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
90 where: u.is_active == true,
91 where: u.local == false,
92 where: not is_nil(u.nickname),
93 where: not u.invisible
96 user_count = Repo.aggregate(users_query, :count, :id)
97 remote_user_count = Repo.aggregate(remote_users_query, :count, :id)
102 domain_count: domain_count,
103 status_count: status_count || 0,
104 user_count: user_count,
105 remote_user_count: remote_user_count
110 @spec get_status_visibility_count(String.t() | nil) :: map()
111 def get_status_visibility_count(instance \\ nil) do
112 if is_nil(instance) do
113 CounterCache.get_sum()
115 CounterCache.get_by_instance(instance)
120 def handle_continue(:calculate_stats, _) do
121 stats = calculate_stat_data()
123 unless Pleroma.Config.get(:env) == :test do
124 Process.send_after(self(), :run_update, @interval)
131 def handle_call(:force_update, _from, _state) do
132 new_stats = calculate_stat_data()
133 {:reply, new_stats, new_stats}
137 def handle_call(:get_state, _from, state) do
138 {:reply, state, state}
142 def handle_info(:run_update, _) do
143 new_stats = calculate_stat_data()
144 Process.send_after(self(), :run_update, @interval)
145 {:noreply, new_stats}