userWatchStats.php 26 KB

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