userWatchStats.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. renderWatchStatsData(data.response.data);
  208. } else {
  209. $("#watchstats-content").html("<div class=\"col-lg-12 text-center text-danger\">Failed to load statistics</div>");
  210. }
  211. })
  212. .fail(function(xhr, status, error) {
  213. $("#watchstats-content").html("<div class=\"col-lg-12 text-center text-danger\">Error loading statistics</div>");
  214. });
  215. }
  216. function renderWatchStatsData(stats) {
  217. var html = "";
  218. // Most Watched Content
  219. if (stats.most_watched && stats.most_watched.length > 0) {
  220. html += "<div class=\"col-lg-12\">";
  221. html += "<h5><i class=\"fa fa-star text-warning\"></i> Most Watched Content</h5>";
  222. html += "<div class=\"table-responsive\">";
  223. html += "<table class=\"table table-striped table-condensed\">";
  224. html += "<thead><tr><th>Title</th><th>Type</th><th>Plays</th><th>Runtime</th><th>Year</th></tr></thead>";
  225. html += "<tbody>";
  226. stats.most_watched.slice(0, 10).forEach(function(item) {
  227. html += "<tr>";
  228. html += "<td><strong>" + (item.title || "Unknown Title") + "</strong></td>";
  229. html += "<td>" + (item.type || "Unknown") + "</td>";
  230. html += "<td><span class=\"label label-primary\">" + (item.total_plays || 0) + "</span></td>";
  231. html += "<td>" + (item.runtime || "Unknown") + "</td>";
  232. html += "<td>" + (item.year || "N/A") + "</td>";
  233. html += "</tr>";
  234. });
  235. html += "</tbody></table></div></div>";
  236. }
  237. // User Statistics
  238. if (stats.user_stats && stats.user_stats.length > 0) {
  239. html += "<div class=\"col-lg-12\" style=\"margin-top: 20px;\">";
  240. html += "<h5><i class=\"fa fa-users\"></i> Server Users (" + stats.user_stats.length + " total)</h5>";
  241. html += "<div class=\"row\">";
  242. stats.user_stats.slice(0, 12).forEach(function(user) {
  243. var lastActivity = "Never";
  244. if (user.LastActivityDate && user.LastActivityDate !== "0001-01-01T00:00:00.0000000Z") {
  245. var activityDate = new Date(user.LastActivityDate);
  246. lastActivity = activityDate.toLocaleDateString();
  247. }
  248. var isAdmin = user.Policy && user.Policy.IsAdministrator;
  249. var isDisabled = user.Policy && user.Policy.IsDisabled;
  250. var badgeClass = isAdmin ? "label-success" : (isDisabled ? "label-danger" : "label-info");
  251. var badgeText = isAdmin ? "Admin" : (isDisabled ? "Disabled" : "User");
  252. html += "<div class=\"col-md-4 col-sm-6\" style=\"margin-bottom: 10px;\">";
  253. html += "<div class=\"media\">";
  254. html += "<div class=\"media-left\"><i class=\"fa fa-user fa-2x text-muted\"></i></div>";
  255. html += "<div class=\"media-body\">";
  256. html += "<h6 class=\"media-heading\">" + (user.Name || "Unknown User") + " <span class=\"label " + badgeClass + "\">" + badgeText + "</span></h6>";
  257. html += "<small class=\"text-muted\">Last Activity: " + lastActivity + "</small>";
  258. html += "</div></div></div>";
  259. });
  260. html += "</div></div>";
  261. }
  262. if (!html) {
  263. html = "<div class=\"col-lg-12 text-center text-muted\">";
  264. html += "<i class=\"fa fa-exclamation-circle fa-3x\" style=\"margin-bottom: 10px;\"></i>";
  265. html += "<h4>No statistics available</h4>";
  266. html += "<p>Start watching some content to see statistics here!</p>";
  267. html += "</div>";
  268. }
  269. $("#watchstats-content").html(html);
  270. }
  271. // Auto-refresh setup
  272. var refreshInterval = ' . $refreshInterval . ';
  273. if (refreshInterval > 0) {
  274. watchStatsRefreshTimer = setInterval(function() {
  275. refreshUserWatchStats();
  276. }, refreshInterval);
  277. }
  278. // Update time display every 30 seconds
  279. setInterval(updateWatchStatsLastRefreshTime, 30000);
  280. // Initial load
  281. $(document).ready(function() {
  282. refreshUserWatchStats();
  283. });
  284. // Cleanup timer when page unloads
  285. $(window).on("beforeunload", function() {
  286. if (watchStatsRefreshTimer) {
  287. clearInterval(watchStatsRefreshTimer);
  288. }
  289. });
  290. </script>
  291. ';
  292. }
  293. }
  294. /**
  295. * Main function to get watch statistics
  296. */
  297. public function getUserWatchStats($options = null)
  298. {
  299. if (!$this->homepageItemPermissions($this->userWatchStatsHomepagePermissions('main'), true)) {
  300. $this->setAPIResponse('error', 'User not approved to view this homepage item - check plugin configuration', 401);
  301. return false;
  302. }
  303. try {
  304. $mediaServer = $this->config['homepageUserWatchStatsService'] ?? 'plex';
  305. $days = intval($this->config['homepageUserWatchStatsDays'] ?? 30);
  306. switch (strtolower($mediaServer)) {
  307. case 'plex':
  308. $stats = $this->getPlexWatchStats($days);
  309. break;
  310. case 'emby':
  311. $stats = $this->getEmbyWatchStats($days);
  312. break;
  313. case 'jellyfin':
  314. $stats = $this->getJellyfinWatchStats($days);
  315. break;
  316. default:
  317. $stats = $this->getPlexWatchStats($days);
  318. break;
  319. }
  320. if (isset($stats['error']) && $stats['error']) {
  321. $this->setAPIResponse('error', $stats['message'], 500);
  322. return false;
  323. }
  324. $this->setAPIResponse('success', 'Watch statistics retrieved successfully', 200, $stats);
  325. return true;
  326. } catch (Exception $e) {
  327. $this->setAPIResponse('error', 'Failed to retrieve watch statistics: ' . $e->getMessage(), 500);
  328. return false;
  329. }
  330. }
  331. /**
  332. * Get Emby watch statistics
  333. */
  334. private function getEmbyWatchStats($days = 30)
  335. {
  336. $embyUrl = $this->config['userWatchStatsURL'] ?? '';
  337. $embyToken = $this->config['userWatchStatsApikey'] ?? '';
  338. if (empty($embyUrl) || empty($embyToken)) {
  339. return ['error' => true, 'message' => 'Emby URL or API key not configured'];
  340. }
  341. $endDate = date('Y-m-d');
  342. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  343. $stats = [
  344. 'period' => "{$days} days",
  345. 'start_date' => $startDate,
  346. 'end_date' => $endDate,
  347. 'most_watched' => $this->getEmbyMostWatched($embyUrl, $embyToken, $days),
  348. 'user_stats' => $this->getEmbyUserStats($embyUrl, $embyToken, $days),
  349. 'recent_activity' => $this->getEmbyRecentActivity($embyUrl, $embyToken),
  350. ];
  351. return $stats;
  352. }
  353. /**
  354. * Get most watched content from Emby
  355. */
  356. private function getEmbyMostWatched($url, $token, $days)
  357. {
  358. return $this->getEmbyFallbackMostWatched($url, $token);
  359. }
  360. /**
  361. * Fallback method - calculate most watched by aggregating play counts across all users
  362. */
  363. private function getEmbyFallbackMostWatched($url, $token)
  364. {
  365. // Get all users first
  366. $users = $this->getEmbyUserStats($url, $token, 30);
  367. $playCountsByItem = [];
  368. $itemDetails = [];
  369. // For each user, get their watched items
  370. foreach ($users as $user) {
  371. if (isset($user['Policy']['IsDisabled']) && $user['Policy']['IsDisabled']) {
  372. continue; // Skip disabled users
  373. }
  374. $userId = $user['Id'];
  375. $userWatchedItems = $this->getEmbyUserWatchedContent($url, $token, $userId, 30);
  376. // Aggregate play counts - count each user who has played the item
  377. foreach ($userWatchedItems as $item) {
  378. $itemId = $item['Id'] ?? $item['title']; // Use ID if available, title as fallback
  379. $isPlayed = $item['is_played'] ?? false;
  380. if ($isPlayed) {
  381. // Increment count for each user who has played this item
  382. $playCountsByItem[$itemId] = ($playCountsByItem[$itemId] ?? 0) + 1;
  383. // Store item details (only need to do this once per item)
  384. if (!isset($itemDetails[$itemId])) {
  385. $itemDetails[$itemId] = [
  386. 'title' => $item['title'] ?? 'Unknown Title',
  387. 'runtime' => $item['runtime'] ?? 'Unknown',
  388. 'type' => $item['type'] ?? 'Unknown',
  389. 'year' => $item['year'] ?? null
  390. ];
  391. }
  392. }
  393. }
  394. }
  395. // Sort by total play count (descending)
  396. arsort($playCountsByItem);
  397. // Build most watched array
  398. $mostWatched = [];
  399. $count = 0;
  400. foreach ($playCountsByItem as $itemId => $totalPlays) {
  401. if ($count >= 20) break; // Limit to top 20
  402. $details = $itemDetails[$itemId] ?? [
  403. 'title' => 'Unknown Title',
  404. 'runtime' => 'Unknown',
  405. 'type' => 'Unknown',
  406. 'year' => null
  407. ];
  408. $mostWatched[] = [
  409. 'title' => $details['title'],
  410. 'total_plays' => $totalPlays,
  411. 'runtime' => $details['runtime'],
  412. 'type' => $details['type'],
  413. 'year' => $details['year']
  414. ];
  415. $count++;
  416. }
  417. // If no watched content found, fall back to recent items as last resort
  418. if (empty($mostWatched)) {
  419. return $this->getEmbyRecentItemsFallback($url, $token);
  420. }
  421. return $mostWatched;
  422. }
  423. /**
  424. * Final fallback - recent items when no watch data is available
  425. */
  426. private function getEmbyRecentItemsFallback($url, $token)
  427. {
  428. $apiURL = rtrim($url, '/') . '/emby/Items?api_key=' . $token .
  429. '&Recursive=true&IncludeItemTypes=Movie,Episode&Fields=Name,RunTimeTicks,ProductionYear,DateCreated' .
  430. '&SortBy=DateCreated&SortOrder=Descending&Limit=10';
  431. try {
  432. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  433. $response = Requests::get($apiURL, [], $options);
  434. if ($response->success) {
  435. $data = json_decode($response->body, true);
  436. $items = $data['Items'] ?? [];
  437. $recentItems = [];
  438. foreach ($items as $item) {
  439. $recentItems[] = [
  440. 'title' => $item['Name'] ?? 'Unknown Title',
  441. 'total_plays' => 0, // No play data available
  442. 'runtime' => isset($item['RunTimeTicks']) ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  443. 'type' => $item['Type'] ?? 'Unknown',
  444. 'year' => $item['ProductionYear'] ?? null
  445. ];
  446. }
  447. return $recentItems;
  448. }
  449. } catch (Requests_Exception $e) {
  450. // Nothing we can do at this point
  451. }
  452. return [];
  453. }
  454. /**
  455. * Get watched content for a specific user
  456. */
  457. private function getEmbyUserWatchedContent($url, $token, $userId, $days)
  458. {
  459. $apiURL = rtrim($url, '/') . '/emby/Users/' . $userId . '/Items?api_key=' . $token .
  460. '&Recursive=true&IncludeItemTypes=Movie,Episode&IsPlayed=true&Limit=50' .
  461. '&Fields=Name,PlayCount,UserData,RunTimeTicks,ProductionYear';
  462. try {
  463. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  464. $response = Requests::get($apiURL, [], $options);
  465. if ($response->success) {
  466. $data = json_decode($response->body, true);
  467. $items = $data['Items'] ?? [];
  468. $watchedContent = [];
  469. foreach ($items as $item) {
  470. // Use Played flag instead of PlayCount since Emby may not increment PlayCount properly
  471. if (($item['UserData']['Played'] ?? false)) {
  472. $watchedContent[] = [
  473. 'Id' => $item['Id'] ?? null,
  474. 'title' => $item['Name'] ?? 'Unknown Title',
  475. 'is_played' => true, // Mark as played for our aggregation
  476. 'runtime' => $item['RunTimeTicks'] ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  477. 'type' => $item['Type'] ?? 'Unknown',
  478. 'year' => $item['ProductionYear'] ?? null
  479. ];
  480. }
  481. }
  482. return $watchedContent;
  483. }
  484. } catch (Requests_Exception $e) {
  485. // Nothing we can do
  486. }
  487. return [];
  488. }
  489. /**
  490. * Get user statistics from Emby
  491. */
  492. private function getEmbyUserStats($url, $token, $days)
  493. {
  494. $apiURL = rtrim($url, '/') . '/emby/Users?api_key=' . $token;
  495. try {
  496. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  497. $response = Requests::get($apiURL, [], $options);
  498. if ($response->success) {
  499. $data = json_decode($response->body, true);
  500. return $data ?? [];
  501. }
  502. } catch (Requests_Exception $e) {
  503. // Nothing we can do
  504. }
  505. return [];
  506. }
  507. /**
  508. * Get recent activity from Emby
  509. */
  510. private function getEmbyRecentActivity($url, $token)
  511. {
  512. $apiURL = rtrim($url, '/') . '/emby/Items/Latest?api_key=' . $token . '&Limit=10&Recursive=true&IncludeItemTypes=Movie,Episode';
  513. try {
  514. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  515. $response = Requests::get($apiURL, [], $options);
  516. if ($response->success) {
  517. $data = json_decode($response->body, true);
  518. $recentActivity = [];
  519. foreach ($data as $item) {
  520. $recentActivity[] = [
  521. 'title' => $item['Name'] ?? 'Unknown Title',
  522. 'type' => $item['Type'] ?? 'Unknown',
  523. 'added_at' => $item['DateCreated'] ?? 'Unknown Date',
  524. 'year' => $item['ProductionYear'] ?? null
  525. ];
  526. }
  527. return $recentActivity;
  528. }
  529. } catch (Requests_Exception $e) {
  530. // Nothing we can do
  531. }
  532. return [];
  533. }
  534. /**
  535. * Format duration for display
  536. */
  537. private function formatDuration($seconds)
  538. {
  539. if ($seconds < 3600) {
  540. return gmdate('i:s', $seconds);
  541. } else {
  542. return gmdate('H:i:s', $seconds);
  543. }
  544. }
  545. // Stub functions for other media servers
  546. private function getPlexWatchStats($days = 30) { return ['error' => true, 'message' => 'Plex not implemented yet']; }
  547. private function getJellyfinWatchStats($days = 30) { return ['error' => true, 'message' => 'Jellyfin not implemented yet']; }
  548. }