Merge remote-tracking branch 'remotes/upstream/develop' into 1335-user-api-id-fields...
[akkoma] / lib / pleroma / stats.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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.Repo
8 alias Pleroma.User
9
10 use GenServer
11
12 @interval 1000 * 60 * 60
13
14 def start_link(_) do
15 GenServer.start_link(__MODULE__, initial_data(), name: __MODULE__)
16 end
17
18 def force_update do
19 GenServer.call(__MODULE__, :force_update)
20 end
21
22 def get_stats do
23 %{stats: stats} = GenServer.call(__MODULE__, :get_state)
24
25 stats
26 end
27
28 def get_peers do
29 %{peers: peers} = GenServer.call(__MODULE__, :get_state)
30
31 peers
32 end
33
34 def init(args) do
35 Process.send(self(), :run_update, [])
36 {:ok, args}
37 end
38
39 def handle_call(:force_update, _from, _state) do
40 new_stats = get_stat_data()
41 {:reply, new_stats, new_stats}
42 end
43
44 def handle_call(:get_state, _from, state) do
45 {:reply, state, state}
46 end
47
48 def handle_info(:run_update, _state) do
49 new_stats = get_stat_data()
50
51 Process.send_after(self(), :run_update, @interval)
52 {:noreply, new_stats}
53 end
54
55 defp initial_data do
56 %{peers: [], stats: %{}}
57 end
58
59 defp get_stat_data do
60 peers =
61 from(
62 u in User,
63 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
64 where: u.local != ^true
65 )
66 |> Repo.all()
67 |> Enum.filter(& &1)
68
69 domain_count = Enum.count(peers)
70
71 status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
72
73 user_count = Repo.aggregate(User.Query.build(%{local: true, active: true}), :count, :id)
74
75 %{
76 peers: peers,
77 stats: %{domain_count: domain_count, status_count: status_count, user_count: user_count}
78 }
79 end
80 end