userWatchStats.php 29 KB

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