logger = $logger; $this->userId = $UserId ?? ''; $this->subscriptionChangeRepository = $subscriptionChangeRepository; $this->episodeActionRepository = $episodeActionRepository; $this->podcastCacheService = $podcastCacheService; } /** * * @NoAdminRequired * @NoCSRFRequired * * @return JSONResponse */ public function metrics(): JSONResponse { $sinceDatetime = (new DateTime)->setTimestamp(0); $subscriptionChanges = $this->subscriptionChangeRepository->findAllSubscribed($sinceDatetime, $this->userId); $episodeActions = $this->episodeActionRepository->findAll(0, $this->userId); $subStats = array(); foreach ($episodeActions as $ep) { $url = $ep->getPodcast(); $stats = $subStats[$url] ?? self::defaultSubscriptionData(); $actionCounts = $stats['actionCounts']; $actionLower = strtolower($ep->getAction()); if (array_key_exists($actionLower, $actionCounts)) { $actionCounts[$actionLower]++; } $stats['actionCounts'] = $actionCounts; if ($actionLower == 'play') { $seconds = $ep->getPosition(); if ($seconds && $seconds != -1) { $stats['listenedSeconds'] += $seconds; } } $subStats[$url] = $stats; } $subscriptions = array_map(function (SubscriptionChangeEntity $sub) use ($subStats) { $url = $sub->getUrl(); $stats = $subStats[$url] ?? self::defaultSubscriptionData(); $sub = [ 'url' => $url ?? '', 'listenedSeconds' => $stats['listenedSeconds'], 'actionCounts' => $stats['actionCounts'], ]; try { $podcast = $this->podcastCacheService->getCachedOrFetchPodcastData($url); $sub['podcast'] = $podcast; } catch (Exception $e) { $sub['podcast'] = null; $this->logger->error("Failed to get podcast data.", [ 'exception' => $e, 'podcastUrl' => $url, ]); } return $sub; }, $subscriptionChanges); return new JSONResponse([ 'subscriptions' => $subscriptions, ]); } private static function defaultSubscriptionData(): array { return [ 'listenedSeconds' => 0, 'actionCounts' => [ 'download' => 0, 'delete' => 0, 'play' => 0, 'new' => 0, 'flattr' => 0, ], ]; } }