Merge remote-tracking branch 'origin/develop' into global-status-expiration
[akkoma] / lib / pleroma / stats.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Stats do
6 import Ecto.Query
7 alias Pleroma.CounterCache
8 alias Pleroma.Repo
9 alias Pleroma.User
10
11 use GenServer
12
13 @init_state %{
14 peers: [],
15 stats: %{
16 domain_count: 0,
17 status_count: 0,
18 user_count: 0
19 }
20 }
21
22 def start_link(_) do
23 GenServer.start_link(
24 __MODULE__,
25 @init_state,
26 name: __MODULE__
27 )
28 end
29
30 @doc "Performs update stats"
31 def force_update do
32 GenServer.call(__MODULE__, :force_update)
33 end
34
35 @doc "Performs collect stats"
36 def do_collect do
37 GenServer.cast(__MODULE__, :run_update)
38 end
39
40 @doc "Returns stats data"
41 @spec get_stats() :: %{domain_count: integer(), status_count: integer(), user_count: integer()}
42 def get_stats do
43 %{stats: stats} = GenServer.call(__MODULE__, :get_state)
44
45 stats
46 end
47
48 @doc "Returns list peers"
49 @spec get_peers() :: list(String.t())
50 def get_peers do
51 %{peers: peers} = GenServer.call(__MODULE__, :get_state)
52
53 peers
54 end
55
56 def init(args) do
57 {:ok, args}
58 end
59
60 def handle_call(:force_update, _from, _state) do
61 new_stats = get_stat_data()
62 {:reply, new_stats, new_stats}
63 end
64
65 def handle_call(:get_state, _from, state) do
66 {:reply, state, state}
67 end
68
69 def handle_cast(:run_update, _state) do
70 new_stats = get_stat_data()
71
72 {:noreply, new_stats}
73 end
74
75 defp get_stat_data do
76 peers =
77 from(
78 u in User,
79 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
80 where: u.local != ^true
81 )
82 |> Repo.all()
83 |> Enum.filter(& &1)
84
85 domain_count = Enum.count(peers)
86
87 status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
88
89 user_count = Repo.aggregate(User.Query.build(%{local: true, active: true}), :count, :id)
90
91 %{
92 peers: peers,
93 stats: %{
94 domain_count: domain_count,
95 status_count: status_count,
96 user_count: user_count
97 }
98 }
99 end
100
101 def get_status_visibility_count do
102 counter_cache =
103 CounterCache.get_as_map([
104 "status_visibility_public",
105 "status_visibility_private",
106 "status_visibility_unlisted",
107 "status_visibility_direct"
108 ])
109
110 %{
111 public: counter_cache["status_visibility_public"] || 0,
112 unlisted: counter_cache["status_visibility_unlisted"] || 0,
113 private: counter_cache["status_visibility_private"] || 0,
114 direct: counter_cache["status_visibility_direct"] || 0
115 }
116 end
117 end