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