stats.ex 1.72 KB
Newer Older
1
# Pleroma: A lightweight social networking server
kaniini's avatar
kaniini committed
2
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3
4
# SPDX-License-Identifier: AGPL-3.0-only

5
6
defmodule Pleroma.Stats do
  import Ecto.Query
Haelwenn's avatar
Haelwenn committed
7
  alias Pleroma.Repo
8
  alias Pleroma.User
9

10
11
12
  use GenServer

  @interval 1000 * 60 * 60
Steven Fuchs's avatar
Steven Fuchs committed
13
14

  def start_link(_) do
15
16
17
18
19
    GenServer.start_link(__MODULE__, initial_data(), name: __MODULE__)
  end

  def force_update do
    GenServer.call(__MODULE__, :force_update)
20
21
  end

eal's avatar
eal committed
22
  def get_stats do
23
24
25
    %{stats: stats} = GenServer.call(__MODULE__, :get_state)

    stats
eal's avatar
eal committed
26
27
28
  end

  def get_peers do
29
30
31
32
33
34
    %{peers: peers} = GenServer.call(__MODULE__, :get_state)

    peers
  end

  def init(args) do
35
    Process.send(self(), :run_update, [])
36
    {:ok, args}
37
38
  end

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  def handle_call(:force_update, _from, _state) do
    new_stats = get_stat_data()
    {:reply, new_stats, new_stats}
  end

  def handle_call(:get_state, _from, state) do
    {:reply, state, state}
  end

  def handle_info(:run_update, _state) do
    new_stats = get_stat_data()

    Process.send_after(self(), :run_update, @interval)
    {:noreply, new_stats}
  end
lain's avatar
lain committed
54

55
56
  defp initial_data do
    %{peers: [], stats: %{}}
57
58
  end

59
  defp get_stat_data do
lain's avatar
lain committed
60
61
    peers =
      from(
Alexander Strizhakov's avatar
Alexander Strizhakov committed
62
        u in User,
63
        select: fragment("distinct split_part(?, '@', 2)", u.nickname),
lain's avatar
lain committed
64
65
66
        where: u.local != ^true
      )
      |> Repo.all()
67
      |> Enum.filter(& &1)
lain's avatar
lain committed
68

69
    domain_count = Enum.count(peers)
lain's avatar
lain committed
70

71
    status_count = Repo.aggregate(User.Query.build(%{local: true}), :sum, :note_count)
Alexander Strizhakov's avatar
Alexander Strizhakov committed
72
73

    user_count = Repo.aggregate(User.Query.build(%{local: true, active: true}), :count, :id)
lain's avatar
lain committed
74

75
76
77
78
    %{
      peers: peers,
      stats: %{domain_count: domain_count, status_count: status_count, user_count: user_count}
    }
79
80
  end
end