use default child_specs
[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 Agent
11
12 def start_link(_) do
13 agent = Agent.start_link(fn -> {[], %{}} end, name: __MODULE__)
14 spawn(fn -> schedule_update() end)
15 agent
16 end
17
18 def get_stats do
19 Agent.get(__MODULE__, fn {_, stats} -> stats end)
20 end
21
22 def get_peers do
23 Agent.get(__MODULE__, fn {peers, _} -> peers end)
24 end
25
26 def schedule_update do
27 spawn(fn ->
28 # 1 hour
29 Process.sleep(1000 * 60 * 60)
30 schedule_update()
31 end)
32
33 update_stats()
34 end
35
36 def update_stats do
37 peers =
38 from(
39 u in User,
40 select: fragment("distinct split_part(?, '@', 2)", u.nickname),
41 where: u.local != ^true
42 )
43 |> Repo.all()
44 |> Enum.filter(& &1)
45
46 domain_count = Enum.count(peers)
47
48 status_query =
49 from(u in User.Query.build(%{local: true}),
50 select: fragment("sum((?->>'note_count')::int)", u.info)
51 )
52
53 status_count = Repo.one(status_query)
54
55 user_count = Repo.aggregate(User.Query.build(%{local: true, active: true}), :count, :id)
56
57 Agent.update(__MODULE__, fn _ ->
58 {peers, %{domain_count: domain_count, status_count: status_count, user_count: user_count}}
59 end)
60 end
61 end