Merge remote-tracking branch 'origin/develop' into feature/embeddable-posts
[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 def start_link(_) do
14 GenServer.start_link(
15 __MODULE__,
16 nil,
17 name: __MODULE__
18 )
19 end
20
21 @doc "Performs update stats"
22 def force_update do
23 GenServer.call(__MODULE__, :force_update)
24 end
25
26 @doc "Performs collect stats"
27 def do_collect do
28 GenServer.cast(__MODULE__, :run_update)
29 end
30
31 @doc "Returns stats data"
32 @spec get_stats() :: %{domain_count: integer(), status_count: integer(), user_count: integer()}
33 def get_stats do
34 %{stats: stats} = GenServer.call(__MODULE__, :get_state)
35
36 stats
37 end
38
39 @doc "Returns list peers"
40 @spec get_peers() :: list(String.t())
41 def get_peers do
42 %{peers: peers} = GenServer.call(__MODULE__, :get_state)
43
44 peers
45 end
46
47 def init(_args) do
48 {:ok, calculate_stat_data()}
49 end
50
51 def handle_call(:force_update, _from, _state) do
52 new_stats = calculate_stat_data()
53 {:reply, new_stats, new_stats}
54 end
55
56 def handle_call(:get_state, _from, state) do
57 {:reply, state, state}
58 end
59
60 def handle_cast(:run_update, _state) do
61 new_stats = calculate_stat_data()
62
63 {:noreply, new_stats}
64 end
65
66 def calculate_stat_data do
67 peers =
68 from(
69 u in User,
70 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
71 where: u.local != ^true
72 )
73 |> Repo.all()
74 |> Enum.filter(& &1)
75
76 domain_count = Enum.count(peers)
77
78 status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
79
80 users_query =
81 from(u in User,
82 where: u.deactivated != true,
83 where: u.local == true,
84 where: not is_nil(u.nickname),
85 where: not u.invisible
86 )
87
88 user_count = Repo.aggregate(users_query, :count, :id)
89
90 %{
91 peers: peers,
92 stats: %{
93 domain_count: domain_count,
94 status_count: status_count || 0,
95 user_count: user_count
96 }
97 }
98 end
99
100 def get_status_visibility_count do
101 counter_cache =
102 CounterCache.get_as_map([
103 "status_visibility_public",
104 "status_visibility_private",
105 "status_visibility_unlisted",
106 "status_visibility_direct"
107 ])
108
109 %{
110 public: counter_cache["status_visibility_public"] || 0,
111 unlisted: counter_cache["status_visibility_unlisted"] || 0,
112 private: counter_cache["status_visibility_private"] || 0,
113 direct: counter_cache["status_visibility_direct"] || 0
114 }
115 end
116 end