userWatchStats.php 30 KB

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