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