userWatchStats.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. <?php
  2. /**
  3. * User Watch Statistics Homepage Plugin
  4. * Provides comprehensive user watching statistics from Plex/Emby/Jellyfin
  5. */
  6. trait HomepageUserWatchStats
  7. {
  8. public function userWatchStatsSettingsArray($infoOnly = false)
  9. {
  10. $homepageInformation = [
  11. 'name' => 'User Watch Statistics',
  12. 'enabled' => strpos('personal', $this->config['license']) !== false,
  13. 'image' => 'plugins/images/homepage/userWatchStats.png',
  14. 'category' => 'Media Server',
  15. 'settingsArray' => __FUNCTION__
  16. ];
  17. if ($infoOnly) {
  18. return $homepageInformation;
  19. }
  20. $homepageSettings = [
  21. 'debug' => true,
  22. 'settings' => [
  23. 'Enable' => [
  24. $this->settingsOption('enable', 'homepageUserWatchStatsEnabled'),
  25. $this->settingsOption('auth', 'homepageUserWatchStatsAuth'),
  26. ],
  27. 'Connection' => [
  28. $this->settingsOption('select', 'homepageUserWatchStatsService', ['label' => 'Media Server', 'options' => [
  29. ['name' => 'Plex (via Tautulli)', 'value' => 'plex'],
  30. ['name' => 'Emby', 'value' => 'emby'],
  31. ['name' => 'Jellyfin', 'value' => 'jellyfin']
  32. ]]),
  33. $this->settingsOption('url', 'homepageUserWatchStatsURL', ['label' => 'Server URL']),
  34. $this->settingsOption('token', 'homepageUserWatchStatsToken', ['label' => 'API Token/Key']),
  35. $this->settingsOption('disable-cert-check', 'homepageUserWatchStatsDisableCertCheck'),
  36. $this->settingsOption('use-custom-certificate', 'homepageUserWatchStatsUseCustomCertificate'),
  37. ],
  38. 'Display Options' => [
  39. $this->settingsOption('number', 'homepageUserWatchStatsRefresh', ['label' => 'Auto-refresh Interval (minutes)', 'min' => 1, 'max' => 60]),
  40. $this->settingsOption('number', 'homepageUserWatchStatsDays', ['label' => 'Statistics Period (days)', 'min' => 1, 'max' => 365]),
  41. $this->settingsOption('switch', 'homepageUserWatchStatsCompactView', ['label' => 'Use Compact View']),
  42. $this->settingsOption('switch', 'homepageUserWatchStatsShowTopUsers', ['label' => 'Show Top Users']),
  43. $this->settingsOption('switch', 'homepageUserWatchStatsShowMostWatched', ['label' => 'Show Most Watched']),
  44. $this->settingsOption('switch', 'homepageUserWatchStatsShowRecentActivity', ['label' => 'Show Recent Activity']),
  45. $this->settingsOption('number', 'homepageUserWatchStatsMaxItems', ['label' => 'Maximum Items to Display', 'min' => 5, 'max' => 50]),
  46. ],
  47. 'Test Connection' => [
  48. $this->settingsOption('blank', null, ['label' => 'Please Save before Testing']),
  49. $this->settingsOption('test', 'userWatchStats'),
  50. ]
  51. ]
  52. ];
  53. return array_merge($homepageInformation, $homepageSettings);
  54. }
  55. public function testConnectionUserWatchStats()
  56. {
  57. if (!$this->homepageItemPermissions($this->userWatchStatsHomepagePermissions('test'), true)) {
  58. return false;
  59. }
  60. $mediaServer = $this->config['homepageUserWatchStatsService'] ?? 'plex';
  61. $url = $this->config['homepageUserWatchStatsURL'] ?? '';
  62. $token = $this->config['homepageUserWatchStatsToken'] ?? '';
  63. if (empty($url) || empty($token)) {
  64. $serverName = ucfirst($mediaServer) . ($mediaServer === 'plex' ? ' (Tautulli)' : '');
  65. $this->setAPIResponse('error', $serverName . ' URL or API key not configured', 500);
  66. return false;
  67. }
  68. // Test the connection based on media server type
  69. try {
  70. $options = $this->requestOptions($url, null, $this->config['homepageUserWatchStatsDisableCertCheck'] ?? false, $this->config['homepageUserWatchStatsUseCustomCertificate'] ?? false);
  71. switch (strtolower($mediaServer)) {
  72. case 'plex':
  73. // Test Tautulli connection
  74. $testUrl = $this->qualifyURL($url) . '/api/v2?apikey=' . $token . '&cmd=get_server_info';
  75. $response = Requests::get($testUrl, [], $options);
  76. if ($response->success) {
  77. $data = json_decode($response->body, true);
  78. if (isset($data['response']['result']) && $data['response']['result'] === 'success') {
  79. $this->setAPIResponse('success', 'Successfully connected to Tautulli', 200);
  80. return true;
  81. }
  82. }
  83. break;
  84. case 'emby':
  85. // Test Emby connection
  86. $testUrl = $this->qualifyURL($url) . '/emby/System/Info?api_key=' . $token;
  87. $response = Requests::get($testUrl, [], $options);
  88. if ($response->success) {
  89. $data = json_decode($response->body, true);
  90. if (isset($data['ServerName'])) {
  91. $this->setAPIResponse('success', 'Successfully connected to Emby server: ' . $data['ServerName'], 200);
  92. return true;
  93. }
  94. }
  95. break;
  96. case 'jellyfin':
  97. // Test Jellyfin connection
  98. $testUrl = $this->qualifyURL($url) . '/System/Info?api_key=' . $token;
  99. $response = Requests::get($testUrl, [], $options);
  100. if ($response->success) {
  101. $data = json_decode($response->body, true);
  102. if (isset($data['ServerName'])) {
  103. $this->setAPIResponse('success', 'Successfully connected to Jellyfin server: ' . $data['ServerName'], 200);
  104. return true;
  105. }
  106. }
  107. break;
  108. }
  109. $this->setAPIResponse('error', 'Connection test failed - invalid response from server', 500);
  110. return false;
  111. } catch (Exception $e) {
  112. $this->setAPIResponse('error', 'Connection test failed: ' . $e->getMessage(), 500);
  113. return false;
  114. }
  115. }
  116. public function userWatchStatsHomepagePermissions($key = null)
  117. {
  118. $permissions = [
  119. 'test' => [
  120. 'enabled' => [
  121. 'homepageUserWatchStatsEnabled',
  122. ],
  123. 'auth' => [
  124. 'homepageUserWatchStatsAuth',
  125. ],
  126. 'not_empty' => [
  127. 'homepageUserWatchStatsURL',
  128. 'homepageUserWatchStatsToken'
  129. ]
  130. ],
  131. 'main' => [
  132. 'enabled' => [
  133. 'homepageUserWatchStatsEnabled'
  134. ],
  135. 'auth' => [
  136. 'homepageUserWatchStatsAuth'
  137. ],
  138. 'not_empty' => [
  139. 'homepageUserWatchStatsURL',
  140. 'homepageUserWatchStatsToken'
  141. ]
  142. ]
  143. ];
  144. return $this->homepageCheckKeyPermissions($key, $permissions);
  145. }
  146. public function homepageOrderUserWatchStats()
  147. {
  148. if ($this->homepageItemPermissions($this->userWatchStatsHomepagePermissions('main'))) {
  149. $refreshInterval = ($this->config['homepageUserWatchStatsRefresh'] ?? 5) * 60000; // Convert minutes to milliseconds
  150. $compactView = ($this->config['homepageUserWatchStatsCompactView'] ?? false) ? 'true' : 'false';
  151. $days = $this->config['homepageUserWatchStatsDays'] ?? 30;
  152. $maxItems = $this->config['homepageUserWatchStatsMaxItems'] ?? 10;
  153. $showTopUsers = ($this->config['homepageUserWatchStatsShowTopUsers'] ?? true) ? 'true' : 'false';
  154. $showMostWatched = ($this->config['homepageUserWatchStatsShowMostWatched'] ?? true) ? 'true' : 'false';
  155. $showRecentActivity = ($this->config['homepageUserWatchStatsShowRecentActivity'] ?? true) ? 'true' : 'false';
  156. return '
  157. <div id="' . __FUNCTION__ . '">
  158. <div class="white-box">
  159. <div class="white-box-header">
  160. <i class="fa fa-bar-chart"></i> User Watch Statistics
  161. <span class="pull-right">
  162. <small id="watchstats-last-update" class="text-muted"></small>
  163. <button class="btn btn-xs btn-primary" onclick="refreshUserWatchStats()" title="Refresh Data">
  164. <i class="fa fa-refresh" id="watchstats-refresh-icon"></i>
  165. </button>
  166. </span>
  167. </div>
  168. <div class="white-box-content">
  169. <div class="row" id="watchstats-content">
  170. <div class="col-lg-12 text-center">
  171. <i class="fa fa-spinner fa-spin"></i> Loading statistics...
  172. </div>
  173. </div>
  174. </div>
  175. </div>
  176. </div>
  177. <script>
  178. var watchStatsRefreshTimer;
  179. var watchStatsLastRefresh = 0;
  180. function refreshUserWatchStats() {
  181. var refreshIcon = $("#watchstats-refresh-icon");
  182. refreshIcon.addClass("fa-spin");
  183. // Show loading state
  184. $("#watchstats-content").html(\'<div class="col-lg-12 text-center"><i class="fa fa-spinner fa-spin"></i> Loading statistics...</div>\');
  185. // Load watch statistics
  186. getUserWatchStatsData()
  187. .always(function() {
  188. refreshIcon.removeClass("fa-spin");
  189. watchStatsLastRefresh = Date.now();
  190. updateWatchStatsLastRefreshTime();
  191. });
  192. }
  193. function updateWatchStatsLastRefreshTime() {
  194. if (watchStatsLastRefresh > 0) {
  195. var ago = Math.floor((Date.now() - watchStatsLastRefresh) / 1000);
  196. var timeText = ago < 60 ? ago + "s ago" : Math.floor(ago / 60) + "m ago";
  197. $("#watchstats-last-update").text("Updated " + timeText);
  198. }
  199. }
  200. function getUserWatchStatsData() {
  201. return organizrAPI2("GET", "api/v2/homepage/userWatchStats")
  202. .done(function(data) {
  203. if (data && data.response && data.response.result === "success" && data.response.data) {
  204. var stats = data.response.data;
  205. var html = "";
  206. // Display statistics period
  207. html += \'<div class="col-lg-12"><h4>Statistics for \' + (stats.period || "30 days") + \'</h4></div>\';
  208. // Show top users if enabled
  209. if (' . $showTopUsers . ' && stats.top_users && stats.top_users.length > 0) {
  210. html += \'<div class="col-lg-6"><h5>Top Users</h5><ul class="list-group">\';
  211. stats.top_users.slice(0, 5).forEach(function(user) {
  212. html += \'<li class="list-group-item">\' + (user.friendly_name || user.username || "Unknown User") + \' - \' + (user.play_count || 0) + \' plays</li>\';
  213. });
  214. html += \'</ul></div>\';
  215. }
  216. // Show most watched if enabled
  217. if (' . $showMostWatched . ' && stats.most_watched && stats.most_watched.length > 0) {
  218. html += \'<div class="col-lg-6"><h5>Most Watched</h5><ul class="list-group">\';
  219. stats.most_watched.slice(0, 5).forEach(function(item) {
  220. html += \'<li class="list-group-item">\' + (item.title || "Unknown Title") + \' - \' + (item.total_plays || 0) + \' plays</li>\';
  221. });
  222. html += \'</ul></div>\';
  223. }
  224. // Show recent activity if enabled
  225. if (' . $showRecentActivity . ' && stats.recent_activity && stats.recent_activity.length > 0) {
  226. html += \'<div class="col-lg-12"><h5>Recent Activity</h5><ul class="list-group">\';
  227. stats.recent_activity.slice(0, 10).forEach(function(activity) {
  228. html += \'<li class="list-group-item">\' + (activity.title || "Unknown Title") + \' - \' + (activity.added_at || "Unknown Date") + \'</li>\';
  229. });
  230. html += \'</ul></div>\';
  231. }
  232. if (html === \'<div class="col-lg-12"><h4>Statistics for \' + (stats.period || "30 days") + \'</h4></div>\') {
  233. html += \'<div class="col-lg-12 text-center text-muted">No statistics available</div>\';
  234. }
  235. $("#watchstats-content").html(html);
  236. } else {
  237. $("#watchstats-content").html(\'<div class="col-lg-12 text-center text-danger">Failed to load statistics</div>\');
  238. }
  239. })
  240. .fail(function(xhr, status, error) {
  241. $("#watchstats-content").html(\'<div class="col-lg-12 text-center text-danger">Error loading statistics</div>\');
  242. });
  243. }
  244. // Auto-refresh setup
  245. var refreshInterval = ' . $refreshInterval . ';
  246. if (refreshInterval > 0) {
  247. watchStatsRefreshTimer = setInterval(function() {
  248. refreshUserWatchStats();
  249. }, refreshInterval);
  250. }
  251. // Update time display every 30 seconds
  252. setInterval(updateWatchStatsLastRefreshTime, 30000);
  253. // Initial load
  254. $(document).ready(function() {
  255. refreshUserWatchStats();
  256. });
  257. // Cleanup timer when page unloads
  258. $(window).on("beforeunload", function() {
  259. if (watchStatsRefreshTimer) {
  260. clearInterval(watchStatsRefreshTimer);
  261. }
  262. });
  263. </script>
  264. ';
  265. }
  266. }
  267. /**
  268. * Main function to get watch statistics
  269. */
  270. public function getUserWatchStats($options = null)
  271. {
  272. if (!$this->homepageItemPermissions($this->userWatchStatsHomepagePermissions('main'), true)) {
  273. return false;
  274. }
  275. try {
  276. $mediaServer = $this->config['homepageUserWatchStatsService'] ?? 'plex';
  277. $days = intval($this->config['homepageUserWatchStatsDays'] ?? 30);
  278. switch (strtolower($mediaServer)) {
  279. case 'plex':
  280. $stats = $this->getPlexWatchStats($days);
  281. break;
  282. case 'emby':
  283. $stats = $this->getEmbyWatchStats($days);
  284. break;
  285. case 'jellyfin':
  286. $stats = $this->getJellyfinWatchStats($days);
  287. break;
  288. default:
  289. $stats = $this->getPlexWatchStats($days);
  290. break;
  291. }
  292. if (isset($stats['error']) && $stats['error']) {
  293. $this->setAPIResponse('error', $stats['message'], 500);
  294. return false;
  295. }
  296. $this->setAPIResponse('success', 'Watch statistics retrieved successfully', 200, $stats);
  297. return true;
  298. } catch (Exception $e) {
  299. $this->writeLog('error', 'User Watch Stats Error: ' . $e->getMessage(), 'SYSTEM');
  300. $this->setAPIResponse('error', 'Failed to retrieve watch statistics: ' . $e->getMessage(), 500);
  301. return false;
  302. }
  303. }
  304. /**
  305. * Get Plex watch statistics via Tautulli API
  306. */
  307. private function getPlexWatchStats($days = 30)
  308. {
  309. $tautulliUrl = $this->config['homepageUserWatchStatsURL'] ?? '';
  310. $tautulliToken = $this->config['homepageUserWatchStatsToken'] ?? '';
  311. if (empty($tautulliUrl) || empty($tautulliToken)) {
  312. return ['error' => true, 'message' => 'Tautulli URL or API key not configured'];
  313. }
  314. $endDate = date('Y-m-d');
  315. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  316. $stats = [
  317. 'period' => "{$days} days",
  318. 'start_date' => $startDate,
  319. 'end_date' => $endDate,
  320. 'most_watched' => $this->getTautulliMostWatched($tautulliUrl, $tautulliToken, $days),
  321. 'least_watched' => $this->getTautulliLeastWatched($tautulliUrl, $tautulliToken, $days),
  322. 'user_stats' => $this->getTautulliUserStats($tautulliUrl, $tautulliToken, $days),
  323. 'recent_activity' => $this->getTautulliRecentActivity($tautulliUrl, $tautulliToken),
  324. 'top_users' => $this->getTautulliTopUsers($tautulliUrl, $tautulliToken, $days)
  325. ];
  326. return $stats;
  327. }
  328. /**
  329. * Get most watched content from Tautulli
  330. */
  331. private function getTautulliMostWatched($url, $token, $days)
  332. {
  333. $endpoint = rtrim($url, '/') . '/api/v2';
  334. $params = [
  335. 'apikey' => $token,
  336. 'cmd' => 'get_home_stats',
  337. 'time_range' => $days,
  338. 'stats_type' => 'plays',
  339. 'stats_count' => 10
  340. ];
  341. $response = $this->guzzle->request('GET', $endpoint, [
  342. 'query' => $params,
  343. 'timeout' => 15,
  344. 'connect_timeout' => 15,
  345. 'http_errors' => false
  346. ]);
  347. if ($response->getStatusCode() === 200) {
  348. $data = json_decode($response->getBody(), true);
  349. return $data['response']['data'] ?? [];
  350. }
  351. return [];
  352. }
  353. /**
  354. * Get user statistics from Tautulli
  355. */
  356. private function getTautulliUserStats($url, $token, $days)
  357. {
  358. $endpoint = rtrim($url, '/') . '/api/v2';
  359. $params = [
  360. 'apikey' => $token,
  361. 'cmd' => 'get_user_watch_time_stats',
  362. 'time_range' => $days
  363. ];
  364. $response = $this->guzzle->request('GET', $endpoint, [
  365. 'query' => $params,
  366. 'timeout' => 15,
  367. 'connect_timeout' => 15,
  368. 'http_errors' => false
  369. ]);
  370. if ($response->getStatusCode() === 200) {
  371. $data = json_decode($response->getBody(), true);
  372. return $data['response']['data'] ?? [];
  373. }
  374. return [];
  375. }
  376. /**
  377. * Get top users from Tautulli
  378. */
  379. private function getTautulliTopUsers($url, $token, $days)
  380. {
  381. $endpoint = rtrim($url, '/') . '/api/v2';
  382. $params = [
  383. 'apikey' => $token,
  384. 'cmd' => 'get_users',
  385. 'length' => 25
  386. ];
  387. $response = $this->guzzle->request('GET', $endpoint, [
  388. 'query' => $params,
  389. 'timeout' => 15,
  390. 'connect_timeout' => 15,
  391. 'http_errors' => false
  392. ]);
  393. if ($response->getStatusCode() === 200) {
  394. $data = json_decode($response->getBody(), true);
  395. $users = $data['response']['data']['data'] ?? [];
  396. // Sort by play count
  397. usort($users, function($a, $b) {
  398. return ($b['play_count'] ?? 0) - ($a['play_count'] ?? 0);
  399. });
  400. return array_slice($users, 0, 10);
  401. }
  402. return [];
  403. }
  404. /**
  405. * Get recent activity from Tautulli
  406. */
  407. private function getTautulliRecentActivity($url, $token)
  408. {
  409. $endpoint = rtrim($url, '/') . '/api/v2';
  410. $params = [
  411. 'apikey' => $token,
  412. 'cmd' => 'get_recently_added',
  413. 'count' => 10
  414. ];
  415. $response = $this->guzzle->request('GET', $endpoint, [
  416. 'query' => $params,
  417. 'timeout' => 15,
  418. 'connect_timeout' => 15,
  419. 'http_errors' => false
  420. ]);
  421. if ($response->getStatusCode() === 200) {
  422. $data = json_decode($response->getBody(), true);
  423. return $data['response']['data']['recently_added'] ?? [];
  424. }
  425. return [];
  426. }
  427. /**
  428. * Get least watched content (inverse of most watched)
  429. */
  430. private function getTautulliLeastWatched($url, $token, $days)
  431. {
  432. $endpoint = rtrim($url, '/') . '/api/v2';
  433. $params = [
  434. 'apikey' => $token,
  435. 'cmd' => 'get_libraries',
  436. ];
  437. $response = $this->guzzle->request('GET', $endpoint, [
  438. 'query' => $params,
  439. 'timeout' => 15,
  440. 'connect_timeout' => 15,
  441. 'http_errors' => false
  442. ]);
  443. if ($response->getStatusCode() === 200) {
  444. $data = json_decode($response->getBody(), true);
  445. $libraries = $data['response']['data'] ?? [];
  446. $leastWatched = [];
  447. foreach ($libraries as $library) {
  448. $libraryStats = $this->getTautulliLibraryStats($url, $token, $library['section_id'], $days);
  449. if (!empty($libraryStats)) {
  450. $leastWatched = array_merge($leastWatched, array_slice($libraryStats, -10));
  451. }
  452. }
  453. return $leastWatched;
  454. }
  455. return [];
  456. }
  457. /**
  458. * Get library statistics for least watched calculation
  459. */
  460. private function getTautulliLibraryStats($url, $token, $sectionId, $days)
  461. {
  462. $endpoint = rtrim($url, '/') . '/api/v2';
  463. $params = [
  464. 'apikey' => $token,
  465. 'cmd' => 'get_library_media_info',
  466. 'section_id' => $sectionId,
  467. 'length' => 50,
  468. 'order_column' => 'play_count',
  469. 'order_dir' => 'asc'
  470. ];
  471. $response = $this->guzzle->request('GET', $endpoint, [
  472. 'query' => $params,
  473. 'timeout' => 15,
  474. 'connect_timeout' => 15,
  475. 'http_errors' => false
  476. ]);
  477. if ($response->getStatusCode() === 200) {
  478. $data = json_decode($response->getBody(), true);
  479. return $data['response']['data']['data'] ?? [];
  480. }
  481. return [];
  482. }
  483. /**
  484. * Get Emby watch statistics
  485. */
  486. private function getEmbyWatchStats($days = 30)
  487. {
  488. $embyUrl = $this->config['homepageUserWatchStatsURL'] ?? '';
  489. $embyToken = $this->config['homepageUserWatchStatsToken'] ?? '';
  490. if (empty($embyUrl) || empty($embyToken)) {
  491. return ['error' => true, 'message' => 'Emby URL or API key not configured'];
  492. }
  493. // Implement Emby-specific statistics gathering
  494. return $this->getGenericMediaServerStats('emby', $embyUrl, $embyToken, $days);
  495. }
  496. /**
  497. * Get Jellyfin watch statistics
  498. */
  499. private function getJellyfinWatchStats($days = 30)
  500. {
  501. $jellyfinUrl = $this->config['homepageUserWatchStatsURL'] ?? '';
  502. $jellyfinToken = $this->config['homepageUserWatchStatsToken'] ?? '';
  503. if (empty($jellyfinUrl) || empty($jellyfinToken)) {
  504. return ['error' => true, 'message' => 'Jellyfin URL or API key not configured'];
  505. }
  506. // Implement Jellyfin-specific statistics gathering
  507. return $this->getGenericMediaServerStats('jellyfin', $jellyfinUrl, $jellyfinToken, $days);
  508. }
  509. /**
  510. * Generic media server stats for Emby/Jellyfin
  511. */
  512. private function getGenericMediaServerStats($type, $url, $token, $days)
  513. {
  514. // Basic structure for now - can be expanded based on Emby/Jellyfin APIs
  515. return [
  516. 'period' => "{$days} days",
  517. 'start_date' => date('Y-m-d', strtotime("-{$days} days")),
  518. 'end_date' => date('Y-m-d'),
  519. 'message' => ucfirst($type) . ' statistics coming soon',
  520. 'most_watched' => [],
  521. 'least_watched' => [],
  522. 'user_stats' => [],
  523. 'recent_activity' => [],
  524. 'top_users' => []
  525. ];
  526. }
  527. /**
  528. * Format duration for display
  529. */
  530. private function formatDuration($seconds)
  531. {
  532. if ($seconds < 3600) {
  533. return gmdate('i:s', $seconds);
  534. } else {
  535. return gmdate('H:i:s', $seconds);
  536. }
  537. }
  538. /**
  539. * Get user avatar URL
  540. */
  541. private function getUserAvatar($userId, $mediaServer = 'plex')
  542. {
  543. switch ($mediaServer) {
  544. case 'plex':
  545. return $this->getPlexUserAvatar($userId);
  546. case 'emby':
  547. return $this->getEmbyUserAvatar($userId);
  548. case 'jellyfin':
  549. return $this->getJellyfinUserAvatar($userId);
  550. default:
  551. return '/plugins/images/organizr/user-bg.png';
  552. }
  553. }
  554. /**
  555. * Get Plex user avatar
  556. */
  557. private function getPlexUserAvatar($userId)
  558. {
  559. $tautulliUrl = $this->config['plexURL'] ?? '';
  560. $tautulliToken = $this->config['plexToken'] ?? '';
  561. if (empty($tautulliUrl) || empty($tautulliToken)) {
  562. return '/plugins/images/organizr/user-bg.png';
  563. }
  564. $endpoint = rtrim($tautulliUrl, '/') . "/api/v2";
  565. $params = [
  566. 'apikey' => $tautulliToken,
  567. 'cmd' => 'get_user_thumb',
  568. 'user_id' => $userId
  569. ];
  570. try {
  571. $response = $this->guzzle->request('GET', $endpoint, [
  572. 'query' => $params,
  573. 'timeout' => 10,
  574. 'connect_timeout' => 10,
  575. 'http_errors' => false
  576. ]);
  577. if ($response->getStatusCode() === 200) {
  578. $data = json_decode($response->getBody(), true);
  579. return $data['response']['data']['thumb'] ?? '/plugins/images/organizr/user-bg.png';
  580. }
  581. } catch (Exception $e) {
  582. // Return default avatar on error
  583. }
  584. return '/plugins/images/organizr/user-bg.png';
  585. }
  586. /**
  587. * Get Emby user avatar
  588. */
  589. private function getEmbyUserAvatar($userId)
  590. {
  591. // Implement Emby avatar logic
  592. return '/plugins/images/organizr/user-bg.png';
  593. }
  594. /**
  595. * Get Jellyfin user avatar
  596. */
  597. private function getJellyfinUserAvatar($userId)
  598. {
  599. // Implement Jellyfin avatar logic
  600. return '/plugins/images/organizr/user-bg.png';
  601. }
  602. }