|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors |
| 7 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 8 | + */ |
| 9 | + |
| 10 | +namespace OCA\Whiteboard\BackgroundJob; |
| 11 | + |
| 12 | +use OCA\Whiteboard\Service\ConfigService; |
| 13 | +use OCA\Whiteboard\Service\StatsService; |
| 14 | +use OCP\AppFramework\Utility\ITimeFactory; |
| 15 | +use OCP\BackgroundJob\TimedJob; |
| 16 | + |
| 17 | +class WatchActiveUsers extends TimedJob { |
| 18 | + public function __construct( |
| 19 | + ITimeFactory $time, |
| 20 | + protected bool $isCLI, |
| 21 | + protected StatsService $statsService, |
| 22 | + protected ConfigService $configService, |
| 23 | + ) { |
| 24 | + parent::__construct($time); |
| 25 | + $this->setInterval(300); |
| 26 | + } |
| 27 | + |
| 28 | + protected function run($argument) { |
| 29 | + if (!$this->configService->getWhiteboardEnableStatistics()) { |
| 30 | + return; |
| 31 | + } |
| 32 | + $metricsData = $this->getMetricsData(); |
| 33 | + $activeUsers = $metricsData['totalUsers'] ?? 0; |
| 34 | + $this->statsService->insertActiveUsersCount($activeUsers); |
| 35 | + } |
| 36 | + |
| 37 | + private function getMetricsData(): array { |
| 38 | + $serverUrl = $this->configService->getCollabBackendUrl(); |
| 39 | + $metricToken = $this->configService->getCollabBackendMetricsToken(); |
| 40 | + |
| 41 | + if (!$serverUrl || !$metricToken) { |
| 42 | + return []; |
| 43 | + } |
| 44 | + |
| 45 | + $curl = curl_init(); |
| 46 | + curl_setopt($curl, CURLOPT_URL, $serverUrl . '/metrics'); |
| 47 | + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); |
| 48 | + curl_setopt($curl, CURLOPT_HTTPHEADER, [ |
| 49 | + 'Authorization: Bearer ' . $metricToken, |
| 50 | + ]); |
| 51 | + $response = curl_exec($curl); |
| 52 | + curl_close($curl); |
| 53 | + |
| 54 | + $metrics = [ |
| 55 | + 'totalUsers' => 0, |
| 56 | + ]; |
| 57 | + |
| 58 | + if (!is_string($response)) { |
| 59 | + return $metrics; |
| 60 | + } |
| 61 | + |
| 62 | + foreach (explode("\n", $response) as $line) { |
| 63 | + if (strpos($line, 'whiteboard_room_stats{stat="totalUsers"}') === false) { |
| 64 | + continue; |
| 65 | + } |
| 66 | + $parts = explode(' ', $line); |
| 67 | + $metrics['totalUsers'] = (int)$parts[1]; |
| 68 | + } |
| 69 | + |
| 70 | + return $metrics; |
| 71 | + } |
| 72 | +} |
0 commit comments