userWatchStats.php 27 KB

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