userWatchStats.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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', 'homepageUserWatchStatsURL'),
  34. $this->settingsOption('token', 'homepageUserWatchStatsToken'),
  35. $this->settingsOption('disable-cert-check', 'homepageUserWatchStatsDisableCertCheck'),
  36. $this->settingsOption('use-custom-certificate', 'homepageUserWatchStatsUseCustomCertificate'),
  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['homepageUserWatchStatsURL'] ?? '';
  63. $token = $this->config['homepageUserWatchStatsToken'] ?? '';
  64. $disableCert = $this->config['homepageUserWatchStatsDisableCertCheck'] ?? false;
  65. $customCert = $this->config['homepageUserWatchStatsUseCustomCertificate'] ?? 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. 'homepageUserWatchStatsURL',
  131. 'homepageUserWatchStatsToken'
  132. ]
  133. ],
  134. 'main' => [
  135. 'enabled' => [
  136. 'homepageUserWatchStatsEnabled'
  137. ],
  138. 'auth' => [
  139. 'homepageUserWatchStatsAuth'
  140. ],
  141. 'not_empty' => [
  142. 'homepageUserWatchStatsURL',
  143. 'homepageUserWatchStatsToken'
  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['homepageUserWatchStatsURL'] ?? '';
  337. $embyToken = $this->config['homepageUserWatchStatsToken'] ?? '';
  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. // Try multiple approaches to get accurate play counts
  359. // Approach 1: Try to get activity/playback history if available
  360. $historyStats = $this->getEmbyPlaybackHistory($url, $token, $days);
  361. if (!empty($historyStats)) {
  362. return $historyStats;
  363. }
  364. // Approach 2: Fallback to user aggregation method
  365. return $this->getEmbyFallbackMostWatched($url, $token);
  366. }
  367. /**
  368. * Fallback method - calculate most watched by aggregating play counts across all users
  369. */
  370. private function getEmbyFallbackMostWatched($url, $token)
  371. {
  372. // Get all users first
  373. $users = $this->getEmbyUserStats($url, $token, 30);
  374. $playCountsByItem = [];
  375. $itemDetails = [];
  376. // For each user, get their watched items
  377. foreach ($users as $user) {
  378. if (isset($user['Policy']['IsDisabled']) && $user['Policy']['IsDisabled']) {
  379. continue; // Skip disabled users
  380. }
  381. $userId = $user['Id'];
  382. $userWatchedItems = $this->getEmbyUserWatchedContent($url, $token, $userId, 30);
  383. // Aggregate play counts - use actual PlayCount if available, otherwise count as 1 per user
  384. foreach ($userWatchedItems as $item) {
  385. $itemId = $item['Id'] ?? $item['title']; // Use ID if available, title as fallback
  386. $userPlayCount = $item['play_count'] ?? 0; // Get actual play count from this user
  387. if ($userPlayCount > 0) {
  388. // Add this user's play count to the total for this item
  389. $playCountsByItem[$itemId] = ($playCountsByItem[$itemId] ?? 0) + $userPlayCount;
  390. // Store item details (only need to do this once per item)
  391. if (!isset($itemDetails[$itemId])) {
  392. $itemDetails[$itemId] = [
  393. 'title' => $item['title'] ?? 'Unknown Title',
  394. 'runtime' => $item['runtime'] ?? 'Unknown',
  395. 'type' => $item['type'] ?? 'Unknown',
  396. 'year' => $item['year'] ?? null
  397. ];
  398. }
  399. } elseif ($item['is_played'] ?? false) {
  400. // Fallback: if no play count but marked as played, count as 1 for this user
  401. $playCountsByItem[$itemId] = ($playCountsByItem[$itemId] ?? 0) + 1;
  402. // Store item details
  403. if (!isset($itemDetails[$itemId])) {
  404. $itemDetails[$itemId] = [
  405. 'title' => $item['title'] ?? 'Unknown Title',
  406. 'runtime' => $item['runtime'] ?? 'Unknown',
  407. 'type' => $item['type'] ?? 'Unknown',
  408. 'year' => $item['year'] ?? null
  409. ];
  410. }
  411. }
  412. }
  413. }
  414. // Sort by total play count (descending)
  415. arsort($playCountsByItem);
  416. // Build most watched array
  417. $mostWatched = [];
  418. $count = 0;
  419. foreach ($playCountsByItem as $itemId => $totalPlays) {
  420. if ($count >= 20) break; // Limit to top 20
  421. $details = $itemDetails[$itemId] ?? [
  422. 'title' => 'Unknown Title',
  423. 'runtime' => 'Unknown',
  424. 'type' => 'Unknown',
  425. 'year' => null
  426. ];
  427. $mostWatched[] = [
  428. 'title' => $details['title'],
  429. 'total_plays' => $totalPlays,
  430. 'runtime' => $details['runtime'],
  431. 'type' => $details['type'],
  432. 'year' => $details['year']
  433. ];
  434. $count++;
  435. }
  436. // If no watched content found, fall back to recent items as last resort
  437. if (empty($mostWatched)) {
  438. return $this->getEmbyRecentItemsFallback($url, $token);
  439. }
  440. return $mostWatched;
  441. }
  442. /**
  443. * Final fallback - recent items when no watch data is available
  444. */
  445. private function getEmbyRecentItemsFallback($url, $token)
  446. {
  447. $apiURL = rtrim($url, '/') . '/emby/Items?api_key=' . $token .
  448. '&Recursive=true&IncludeItemTypes=Movie,Episode&Fields=Name,RunTimeTicks,ProductionYear,DateCreated' .
  449. '&SortBy=DateCreated&SortOrder=Descending&Limit=10';
  450. try {
  451. $options = $this->requestOptions($url, null, $this->config['homepageUserWatchStatsDisableCertCheck'] ?? false, $this->config['homepageUserWatchStatsUseCustomCertificate'] ?? false);
  452. $response = Requests::get($apiURL, [], $options);
  453. if ($response->success) {
  454. $data = json_decode($response->body, true);
  455. $items = $data['Items'] ?? [];
  456. $recentItems = [];
  457. foreach ($items as $item) {
  458. $recentItems[] = [
  459. 'title' => $item['Name'] ?? 'Unknown Title',
  460. 'total_plays' => 0, // No play data available
  461. 'runtime' => isset($item['RunTimeTicks']) ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  462. 'type' => $item['Type'] ?? 'Unknown',
  463. 'year' => $item['ProductionYear'] ?? null
  464. ];
  465. }
  466. return $recentItems;
  467. }
  468. } catch (Requests_Exception $e) {
  469. // Nothing we can do at this point
  470. }
  471. return [];
  472. }
  473. /**
  474. * Try to get playback history from Emby's activity log
  475. */
  476. private function getEmbyPlaybackHistory($url, $token, $days)
  477. {
  478. // Try to access Emby's activity log for more accurate play statistics
  479. $apiURL = rtrim($url, '/') . '/emby/System/ActivityLog/Entries?api_key=' . $token . '&Limit=1000&HasUserId=true';
  480. try {
  481. $options = $this->requestOptions($url, null, $this->config['homepageUserWatchStatsDisableCertCheck'] ?? false, $this->config['homepageUserWatchStatsUseCustomCertificate'] ?? false);
  482. $response = Requests::get($apiURL, [], $options);
  483. if ($response->success) {
  484. $data = json_decode($response->body, true);
  485. $activities = $data['Items'] ?? [];
  486. $playCountsByItem = [];
  487. $itemDetails = [];
  488. // Filter for playback activities in the last X days
  489. $cutoffDate = time() - ($days * 24 * 60 * 60);
  490. foreach ($activities as $activity) {
  491. if (isset($activity['Type']) && $activity['Type'] === 'PlaybackStart') {
  492. $activityDate = strtotime($activity['Date']);
  493. if ($activityDate >= $cutoffDate && isset($activity['ItemId'])) {
  494. $itemId = $activity['ItemId'];
  495. $playCountsByItem[$itemId] = ($playCountsByItem[$itemId] ?? 0) + 1;
  496. // Store item name if available
  497. if (isset($activity['Name']) && !isset($itemDetails[$itemId])) {
  498. $itemDetails[$itemId] = [
  499. 'title' => $activity['Name'],
  500. 'type' => 'Unknown', // Activity log doesn't have type info
  501. 'runtime' => 'Unknown',
  502. 'year' => null
  503. ];
  504. }
  505. }
  506. }
  507. }
  508. if (!empty($playCountsByItem)) {
  509. // Sort by play count and build result
  510. arsort($playCountsByItem);
  511. $mostWatched = [];
  512. $count = 0;
  513. foreach ($playCountsByItem as $itemId => $totalPlays) {
  514. if ($count >= 20) break;
  515. $details = $itemDetails[$itemId] ?? ['title' => 'Unknown Title', 'type' => 'Unknown', 'runtime' => 'Unknown', 'year' => null];
  516. $mostWatched[] = [
  517. 'title' => $details['title'],
  518. 'total_plays' => $totalPlays,
  519. 'runtime' => $details['runtime'],
  520. 'type' => $details['type'],
  521. 'year' => $details['year']
  522. ];
  523. $count++;
  524. }
  525. return $mostWatched;
  526. }
  527. }
  528. } catch (Requests_Exception $e) {
  529. // Fall through to other methods
  530. }
  531. return [];
  532. }
  533. /**
  534. * Get watched content for a specific user with debugging
  535. */
  536. private function getEmbyUserWatchedContent($url, $token, $userId, $days)
  537. {
  538. // Try to get all items for this user, including play counts
  539. $apiURL = rtrim($url, '/') . '/emby/Users/' . $userId . '/Items?api_key=' . $token .
  540. '&Recursive=true&IncludeItemTypes=Movie,Episode&Limit=200' .
  541. '&Fields=Name,PlayCount,UserData,RunTimeTicks,ProductionYear&SortBy=PlayCount&SortOrder=Descending';
  542. try {
  543. $options = $this->requestOptions($url, null, $this->config['homepageUserWatchStatsDisableCertCheck'] ?? false, $this->config['homepageUserWatchStatsUseCustomCertificate'] ?? false);
  544. $response = Requests::get($apiURL, [], $options);
  545. if ($response->success) {
  546. $data = json_decode($response->body, true);
  547. $items = $data['Items'] ?? [];
  548. $watchedContent = [];
  549. foreach ($items as $item) {
  550. $playCount = $item['UserData']['PlayCount'] ?? 0;
  551. $isPlayed = $item['UserData']['Played'] ?? false;
  552. // Debug: Log some play count data to see what we're getting
  553. // Uncomment these lines temporarily to debug:
  554. // error_log("Emby Item: " . ($item['Name'] ?? 'Unknown') . " - PlayCount: $playCount, Played: " . ($isPlayed ? 'true' : 'false'));
  555. // Include items that have been played OR have a play count > 0
  556. if ($playCount > 0 || $isPlayed) {
  557. $watchedContent[] = [
  558. 'Id' => $item['Id'] ?? null,
  559. 'title' => $item['Name'] ?? 'Unknown Title',
  560. 'play_count' => $playCount, // Use actual play count from UserData
  561. 'is_played' => $isPlayed,
  562. 'runtime' => $item['RunTimeTicks'] ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  563. 'type' => $item['Type'] ?? 'Unknown',
  564. 'year' => $item['ProductionYear'] ?? null
  565. ];
  566. }
  567. }
  568. return $watchedContent;
  569. }
  570. } catch (Requests_Exception $e) {
  571. // Nothing we can do
  572. }
  573. return [];
  574. }
  575. /**
  576. * Get user statistics from Emby
  577. */
  578. private function getEmbyUserStats($url, $token, $days)
  579. {
  580. $apiURL = rtrim($url, '/') . '/emby/Users?api_key=' . $token;
  581. try {
  582. $options = $this->requestOptions($url, null, $this->config['homepageUserWatchStatsDisableCertCheck'] ?? false, $this->config['homepageUserWatchStatsUseCustomCertificate'] ?? false);
  583. $response = Requests::get($apiURL, [], $options);
  584. if ($response->success) {
  585. $data = json_decode($response->body, true);
  586. return $data ?? [];
  587. }
  588. } catch (Requests_Exception $e) {
  589. // Nothing we can do
  590. }
  591. return [];
  592. }
  593. /**
  594. * Get recent activity from Emby
  595. */
  596. private function getEmbyRecentActivity($url, $token)
  597. {
  598. $apiURL = rtrim($url, '/') . '/emby/Items/Latest?api_key=' . $token . '&Limit=10&Recursive=true&IncludeItemTypes=Movie,Episode';
  599. try {
  600. $options = $this->requestOptions($url, null, $this->config['homepageUserWatchStatsDisableCertCheck'] ?? false, $this->config['homepageUserWatchStatsUseCustomCertificate'] ?? false);
  601. $response = Requests::get($apiURL, [], $options);
  602. if ($response->success) {
  603. $data = json_decode($response->body, true);
  604. $recentActivity = [];
  605. foreach ($data as $item) {
  606. $recentActivity[] = [
  607. 'title' => $item['Name'] ?? 'Unknown Title',
  608. 'type' => $item['Type'] ?? 'Unknown',
  609. 'added_at' => $item['DateCreated'] ?? 'Unknown Date',
  610. 'year' => $item['ProductionYear'] ?? null
  611. ];
  612. }
  613. return $recentActivity;
  614. }
  615. } catch (Requests_Exception $e) {
  616. // Nothing we can do
  617. }
  618. return [];
  619. }
  620. /**
  621. * Format duration for display
  622. */
  623. private function formatDuration($seconds)
  624. {
  625. if ($seconds < 3600) {
  626. return gmdate('i:s', $seconds);
  627. } else {
  628. return gmdate('H:i:s', $seconds);
  629. }
  630. }
  631. // Stub functions for other media servers
  632. private function getPlexWatchStats($days = 30) { return ['error' => true, 'message' => 'Plex not implemented yet']; }
  633. private function getJellyfinWatchStats($days = 30) { return ['error' => true, 'message' => 'Jellyfin not implemented yet']; }
  634. }