userWatchStats.php 29 KB

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