8478fe4ced6565642c864b0a2b88bededfb7882f
[akkoma] / lib / pleroma / stats.ex
1 defmodule Pleroma.Stats do
2 import Ecto.Query
3 alias Pleroma.{User, Repo}
4
5 def start_link do
6 agent = Agent.start_link(fn -> {[], %{}} end, name: __MODULE__)
7 spawn(fn -> schedule_update() end)
8 agent
9 end
10
11 def get_stats do
12 Agent.get(__MODULE__, fn {_, stats} -> stats end)
13 end
14
15 def get_peers do
16 Agent.get(__MODULE__, fn {peers, _} -> peers end)
17 end
18
19 def schedule_update do
20 spawn(fn ->
21 # 1 hour
22 Process.sleep(1000 * 60 * 60 * 1)
23 schedule_update()
24 end)
25
26 update_stats()
27 end
28
29 def update_stats do
30 peers =
31 from(
32 u in Pleroma.User,
33 select: fragment("distinct ?->'host'", u.info),
34 where: u.local != ^true
35 )
36 |> Repo.all()
37
38 domain_count = Enum.count(peers)
39
40 status_query =
41 from(u in User.local_user_query(), select: fragment("sum((?->>'note_count')::int)", u.info))
42
43 status_count = Repo.one(status_query)
44 user_count = Repo.aggregate(User.local_user_query(), :count, :id)
45
46 Agent.update(__MODULE__, fn _ ->
47 {peers, %{domain_count: domain_count, status_count: status_count, user_count: user_count}}
48 end)
49 end
50 end