userWatchStats.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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 watch history (Movies & Shows)
  212. if (stats.watch_history && stats.watch_history.length > 0) {
  213. html += \'<div class="col-lg-12"><h5>Watch History</h5><table class="table table-striped table-condensed">\';
  214. html += \'<thead>\';
  215. html += \'<tr>\';
  216. html += \'<th>Title</th>\';
  217. html += \'<th>Type</th>\';
  218. html += \'<th>Play Count</th>\';
  219. html += \'<th>Runtime</th>\';
  220. html += \'</tr>\';
  221. html += \'</thead>\';
  222. html += \'<tbody>\';
  223. stats.watch_history.slice(0, 10).forEach(function(item) {
  224. html += \'<tr>\';
  225. html += \'<td>\' + (item.title || "Unknown Title") + \'</td>\';
  226. html += \'<td>\' + (item.type || "Unknown") + \'</td>\';
  227. html += \'<td>\' + (item.play_count || 0) + \'</td>\';
  228. html += \'<td>\' + (item.runtime || "Unknown") + \'</td>\';
  229. html += \'</tr>\';
  230. });
  231. html += \'</tbody>\';
  232. html += \'</table>\';
  233. html += \'</div>\';
  234. }
  235. // Show user stats (Emby users)
  236. if (stats.user_stats && stats.user_stats.length > 0) {
  237. html += \'<div class="col-lg-12"><h5>Server Users (\' + stats.user_stats.length + \' total)</h5><ul class="list-group">\';
  238. stats.user_stats.slice(0, 10).forEach(function(user) {
  239. var lastActivity = "Never";
  240. if (user.LastActivityDate && user.LastActivityDate !== "0001-01-01T00:00:00.0000000Z") {
  241. var activityDate = new Date(user.LastActivityDate);
  242. lastActivity = activityDate.toLocaleDateString();
  243. }
  244. var isAdmin = user.Policy && user.Policy.IsAdministrator ? " [Admin]" : "";
  245. var isDisabled = user.Policy && user.Policy.IsDisabled ? " [Disabled]" : "";
  246. html += \'<li class="list-group-item">\' + (user.Name || "Unknown User") + isAdmin + isDisabled + \' - Last Activity: \' + lastActivity + \'</li>\';
  247. });
  248. html += \'</ul></div>\';
  249. }
  250. // Show top users if enabled and has data
  251. if (' . $showTopUsers . ' && stats.top_users && stats.top_users.length > 0) {
  252. html += \'<div class="col-lg-6"><h5>Top Users</h5><ul class="list-group">\';
  253. stats.top_users.slice(0, 5).forEach(function(user) {
  254. html += \'<li class="list-group-item">\' + (user.friendly_name || user.username || "Unknown User") + \' - \' + (user.play_count || 0) + \' plays</li>\';
  255. });
  256. html += \'</ul></div>\';
  257. }
  258. // Show most watched if enabled and has data
  259. if (' . $showMostWatched . ' && stats.most_watched && stats.most_watched.length > 0) {
  260. html += \'<div class="col-lg-6"><h5>Most Watched</h5><ul class="list-group">\';
  261. stats.most_watched.slice(0, 5).forEach(function(item) {
  262. html += \'<li class="list-group-item">\' + (item.title || "Unknown Title") + \' - \' + (item.play_count || item.total_plays || 0) + \' plays</li>\';
  263. });
  264. html += \'</ul></div>\';
  265. }
  266. // Show recent activity if enabled and has data
  267. if (' . $showRecentActivity . ' && stats.recent_activity && stats.recent_activity.length > 0) {
  268. html += \'<div class="col-lg-12"><h5>Recent Activity</h5><ul class="list-group">\';
  269. stats.recent_activity.slice(0, 10).forEach(function(activity) {
  270. html += \'<li class="list-group-item">\' + (activity.title || "Unknown Title") + \' - \' + (activity.added_at || "Unknown Date") + \'</li>\';
  271. });
  272. html += \'</ul></div>\';
  273. }
  274. // Check if we have any data to display
  275. var hasUserStats = stats.user_stats && stats.user_stats.length > 0;
  276. var hasTopUsers = stats.top_users && stats.top_users.length > 0;
  277. var hasMostWatched = stats.most_watched && stats.most_watched.length > 0;
  278. var hasRecentActivity = stats.recent_activity && stats.recent_activity.length > 0;
  279. var hasWatchHistory = stats.watch_history && stats.watch_history.length > 0;
  280. if (!hasUserStats && !hasTopUsers && !hasMostWatched && !hasRecentActivity && !hasWatchHistory) {
  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. $this->setAPIResponse('error', 'User not approved to view this homepage item - check plugin configuration', 401);
  322. return false;
  323. }
  324. try {
  325. $mediaServer = $this->config['homepageUserWatchStatsService'] ?? 'plex';
  326. $days = intval($this->config['homepageUserWatchStatsDays'] ?? 30);
  327. switch (strtolower($mediaServer)) {
  328. case 'plex':
  329. $stats = $this->getPlexWatchStats($days);
  330. break;
  331. case 'emby':
  332. $stats = $this->getEmbyWatchStats($days);
  333. break;
  334. case 'jellyfin':
  335. $stats = $this->getJellyfinWatchStats($days);
  336. break;
  337. default:
  338. $stats = $this->getPlexWatchStats($days);
  339. break;
  340. }
  341. if (isset($stats['error']) && $stats['error']) {
  342. $this->setAPIResponse('error', $stats['message'], 500);
  343. return false;
  344. }
  345. $this->setAPIResponse('success', 'Watch statistics retrieved successfully', 200, $stats);
  346. return true;
  347. } catch (Exception $e) {
  348. // User Watch Stats Error: " . $e->getMessage();
  349. $this->setAPIResponse('error', 'Failed to retrieve watch statistics: ' . $e->getMessage(), 500);
  350. return false;
  351. }
  352. }
  353. /**
  354. * Get Plex watch statistics via Tautulli API
  355. */
  356. private function getPlexWatchStats($days = 30)
  357. {
  358. $tautulliUrl = $this->config['userWatchStatsURL'] ?? '';
  359. $tautulliToken = $this->config['userWatchStatsApikey'] ?? '';
  360. if (empty($tautulliUrl) || empty($tautulliToken)) {
  361. return ['error' => true, 'message' => 'Tautulli URL or API key not configured'];
  362. }
  363. $endDate = date('Y-m-d');
  364. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  365. $stats = [
  366. 'period' => "{$days} days",
  367. 'start_date' => $startDate,
  368. 'end_date' => $endDate,
  369. 'most_watched' => $this->getTautulliMostWatched($tautulliUrl, $tautulliToken, $days),
  370. 'least_watched' => $this->getTautulliLeastWatched($tautulliUrl, $tautulliToken, $days),
  371. 'user_stats' => $this->getTautulliUserStats($tautulliUrl, $tautulliToken, $days),
  372. 'recent_activity' => $this->getTautulliRecentActivity($tautulliUrl, $tautulliToken),
  373. 'top_users' => $this->getTautulliTopUsers($tautulliUrl, $tautulliToken, $days)
  374. ];
  375. return $stats;
  376. }
  377. /**
  378. * Get most watched content from Tautulli
  379. */
  380. private function getTautulliMostWatched($url, $token, $days)
  381. {
  382. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_home_stats&time_range=' . $days . '&stats_type=plays&stats_count=10';
  383. try {
  384. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  385. $response = Requests::get($apiURL, [], $options);
  386. if ($response->success) {
  387. $data = json_decode($response->body, true);
  388. return $data['response']['data'] ?? [];
  389. }
  390. } catch (Requests_Exception $e) {
  391. // Tautulli Most Watched Error: " . $e->getMessage();
  392. }
  393. return [];
  394. }
  395. /**
  396. * Get user statistics from Tautulli
  397. */
  398. private function getTautulliUserStats($url, $token, $days)
  399. {
  400. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_user_watch_time_stats&time_range=' . $days;
  401. try {
  402. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  403. $response = Requests::get($apiURL, [], $options);
  404. if ($response->success) {
  405. $data = json_decode($response->body, true);
  406. return $data['response']['data'] ?? [];
  407. }
  408. } catch (Requests_Exception $e) {
  409. // Tautulli User Stats Error: " . $e->getMessage();
  410. }
  411. return [];
  412. }
  413. /**
  414. * Get top users from Tautulli
  415. */
  416. private function getTautulliTopUsers($url, $token, $days)
  417. {
  418. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_users&length=25';
  419. try {
  420. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  421. $response = Requests::get($apiURL, [], $options);
  422. if ($response->success) {
  423. $data = json_decode($response->body, true);
  424. $users = $data['response']['data']['data'] ?? [];
  425. // Sort by play count
  426. usort($users, function($a, $b) {
  427. return ($b['play_count'] ?? 0) - ($a['play_count'] ?? 0);
  428. });
  429. return array_slice($users, 0, 10);
  430. }
  431. } catch (Requests_Exception $e) {
  432. // Tautulli Top Users Error: " . $e->getMessage();
  433. }
  434. return [];
  435. }
  436. /**
  437. * Get recent activity from Tautulli
  438. */
  439. private function getTautulliRecentActivity($url, $token)
  440. {
  441. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_recently_added&count=10';
  442. try {
  443. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  444. $response = Requests::get($apiURL, [], $options);
  445. if ($response->success) {
  446. $data = json_decode($response->body, true);
  447. return $data['response']['data']['recently_added'] ?? [];
  448. }
  449. } catch (Requests_Exception $e) {
  450. // Tautulli Recent Activity Error: " . $e->getMessage();
  451. }
  452. return [];
  453. }
  454. /**
  455. * Get least watched content (inverse of most watched)
  456. */
  457. private function getTautulliLeastWatched($url, $token, $days)
  458. {
  459. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_libraries';
  460. try {
  461. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  462. $response = Requests::get($apiURL, [], $options);
  463. if ($response->success) {
  464. $data = json_decode($response->body, true);
  465. $libraries = $data['response']['data'] ?? [];
  466. $leastWatched = [];
  467. foreach ($libraries as $library) {
  468. $libraryStats = $this->getTautulliLibraryStats($url, $token, $library['section_id'], $days);
  469. if (!empty($libraryStats)) {
  470. $leastWatched = array_merge($leastWatched, array_slice($libraryStats, -10));
  471. }
  472. }
  473. return $leastWatched;
  474. }
  475. } catch (Requests_Exception $e) {
  476. // Tautulli Least Watched Error: " . $e->getMessage();
  477. }
  478. return [];
  479. }
  480. /**
  481. * Get library statistics for least watched calculation
  482. */
  483. private function getTautulliLibraryStats($url, $token, $sectionId, $days)
  484. {
  485. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_library_media_info&section_id=' . $sectionId . '&length=50&order_column=play_count&order_dir=asc';
  486. try {
  487. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  488. $response = Requests::get($apiURL, [], $options);
  489. if ($response->success) {
  490. $data = json_decode($response->body, true);
  491. return $data['response']['data']['data'] ?? [];
  492. }
  493. } catch (Requests_Exception $e) {
  494. // Tautulli Library Stats Error: " . $e->getMessage();
  495. }
  496. return [];
  497. }
  498. /**
  499. * Get Emby watch statistics
  500. */
  501. private function getEmbyWatchStats($days = 30)
  502. {
  503. $embyUrl = $this->config['userWatchStatsURL'] ?? '';
  504. $embyToken = $this->config['userWatchStatsApikey'] ?? '';
  505. if (empty($embyUrl) || empty($embyToken)) {
  506. return ['error' => true, 'message' => 'Emby URL or API key not configured'];
  507. }
  508. $endDate = date('Y-m-d');
  509. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  510. $stats = [
  511. 'period' => "{$days} days",
  512. 'start_date' => $startDate,
  513. 'end_date' => $endDate,
  514. 'most_watched' => $this->getEmbyMostWatched($embyUrl, $embyToken, $days),
  515. 'least_watched' => [], // Emby doesn't have a direct least watched API
  516. 'user_stats' => $this->getEmbyUserStats($embyUrl, $embyToken, $days),
  517. 'recent_activity' => $this->getEmbyRecentActivity($embyUrl, $embyToken),
  518. 'watch_history' => $this->getEmbyWatchHistory($embyUrl, $embyToken, $days),
  519. 'top_users' => $this->getEmbyTopUsers($embyUrl, $embyToken, $days)
  520. ];
  521. return $stats;
  522. }
  523. /**
  524. * Get Jellyfin watch statistics
  525. */
  526. private function getJellyfinWatchStats($days = 30)
  527. {
  528. $jellyfinUrl = $this->config['jellyfinURL'] ?? '';
  529. $jellyfinToken = $this->config['jellyfinToken'] ?? '';
  530. if (empty($jellyfinUrl) || empty($jellyfinToken)) {
  531. return ['error' => true, 'message' => 'Jellyfin URL or API key not configured'];
  532. }
  533. // Implement Jellyfin-specific statistics gathering
  534. return $this->getGenericMediaServerStats('jellyfin', $jellyfinUrl, $jellyfinToken, $days);
  535. }
  536. /**
  537. * Generic media server stats for Emby/Jellyfin
  538. */
  539. private function getGenericMediaServerStats($type, $url, $token, $days)
  540. {
  541. // Basic structure for now - can be expanded based on Emby/Jellyfin APIs
  542. return [
  543. 'period' => "{$days} days",
  544. 'start_date' => date('Y-m-d', strtotime("-{$days} days")),
  545. 'end_date' => date('Y-m-d'),
  546. 'message' => ucfirst($type) . ' statistics coming soon',
  547. 'most_watched' => [],
  548. 'least_watched' => [],
  549. 'user_stats' => [],
  550. 'recent_activity' => [],
  551. 'top_users' => []
  552. ];
  553. }
  554. /**
  555. * Format duration for display
  556. */
  557. private function formatDuration($seconds)
  558. {
  559. if ($seconds < 3600) {
  560. return gmdate('i:s', $seconds);
  561. } else {
  562. return gmdate('H:i:s', $seconds);
  563. }
  564. }
  565. /**
  566. * Get user avatar URL
  567. */
  568. private function getUserAvatar($userId, $mediaServer = 'plex')
  569. {
  570. switch ($mediaServer) {
  571. case 'plex':
  572. return $this->getPlexUserAvatar($userId);
  573. case 'emby':
  574. return $this->getEmbyUserAvatar($userId);
  575. case 'jellyfin':
  576. return $this->getJellyfinUserAvatar($userId);
  577. default:
  578. return '/plugins/images/organizr/user-bg.png';
  579. }
  580. }
  581. /**
  582. * Get Plex user avatar
  583. */
  584. private function getPlexUserAvatar($userId)
  585. {
  586. $tautulliUrl = $this->config['plexURL'] ?? '';
  587. $tautulliToken = $this->config['plexToken'] ?? '';
  588. if (empty($tautulliUrl) || empty($tautulliToken)) {
  589. return '/plugins/images/organizr/user-bg.png';
  590. }
  591. $apiURL = rtrim($tautulliUrl, '/') . '/api/v2?apikey=' . $tautulliToken . '&cmd=get_user_thumb&user_id=' . $userId;
  592. try {
  593. $options = $this->requestOptions($tautulliUrl, null, $this->config['plexDisableCertCheck'] ?? false, $this->config['plexUseCustomCertificate'] ?? false);
  594. $response = Requests::get($apiURL, [], $options);
  595. if ($response->success) {
  596. $data = json_decode($response->body, true);
  597. return $data['response']['data']['thumb'] ?? '/plugins/images/organizr/user-bg.png';
  598. }
  599. } catch (Requests_Exception $e) {
  600. // Tautulli User Avatar Error: " . $e->getMessage();
  601. }
  602. return '/plugins/images/organizr/user-bg.png';
  603. }
  604. /**
  605. * Get most watched content from Emby (server-wide statistics)
  606. */
  607. private function getEmbyMostWatched($url, $token, $days)
  608. {
  609. // Skip activity log approach and go directly to simple media approach
  610. return $this->getEmbySimpleMostWatched($url, $token);
  611. }
  612. /**
  613. * Get most watched content by aggregating play counts across all users
  614. */
  615. private function getEmbySimpleMostWatched($url, $token)
  616. {
  617. // Since user-specific endpoints are not accessible with API key,
  618. // fall back to using the global Items API sorted by DatePlayed
  619. $apiURL = rtrim($url, '/') . '/emby/Items?api_key=' . $token .
  620. '&Recursive=true&IncludeItemTypes=Movie,Episode&Fields=Name,RunTimeTicks,ProductionYear,DatePlayed' .
  621. '&SortBy=DatePlayed&SortOrder=Descending&Limit=20';
  622. try {
  623. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  624. $response = Requests::get($apiURL, [], $options);
  625. if ($response->success) {
  626. $responseBody = $response->body;
  627. // Check if response contains SQLite exception or other error indicators
  628. if (is_string($responseBody) && (
  629. strpos($responseBody, 'SQLiteException') !== false ||
  630. strpos($responseBody, 'error') !== false ||
  631. strpos($responseBody, 'Error') !== false ||
  632. !trim($responseBody) ||
  633. $responseBody === 'null'
  634. )) {
  635. // Fall back to recently created items if DatePlayed sorting fails
  636. return $this->getEmbyFallbackMostWatched($url, $token);
  637. }
  638. $data = json_decode($responseBody, true);
  639. // Check if JSON decode failed or returned invalid data
  640. if ($data === null || !is_array($data) || !isset($data['Items'])) {
  641. return $this->getEmbyFallbackMostWatched($url, $token);
  642. }
  643. $items = $data['Items'] ?? [];
  644. $mostWatched = [];
  645. foreach ($items as $item) {
  646. // Only include items that have been played (DatePlayed exists)
  647. if (!empty($item['DatePlayed'])) {
  648. $mostWatched[] = [
  649. 'title' => $item['Name'] ?? 'Unknown Title',
  650. 'total_plays' => 1, // We can't get actual play count from this API
  651. 'runtime' => isset($item['RunTimeTicks']) ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  652. 'type' => $item['Type'] ?? 'Unknown',
  653. 'year' => $item['ProductionYear'] ?? null
  654. ];
  655. }
  656. }
  657. // If no items with DatePlayed, fall back to recently created
  658. if (empty($mostWatched)) {
  659. return $this->getEmbyFallbackMostWatched($url, $token);
  660. }
  661. return $mostWatched;
  662. } else {
  663. // HTTP request failed, use fallback
  664. return $this->getEmbyFallbackMostWatched($url, $token);
  665. }
  666. } catch (Exception $e) {
  667. // Any exception triggers fallback
  668. return $this->getEmbyFallbackMostWatched($url, $token);
  669. }
  670. // Fallback if we somehow get here
  671. return $this->getEmbyFallbackMostWatched($url, $token);
  672. }
  673. /**
  674. * Fallback method using recently created items when other approaches fail
  675. */
  676. private function getEmbyFallbackMostWatched($url, $token)
  677. {
  678. $apiURL = rtrim($url, '/') . '/emby/Items?api_key=' . $token .
  679. '&Recursive=true&IncludeItemTypes=Movie,Episode&Fields=Name,RunTimeTicks,ProductionYear,DateCreated' .
  680. '&SortBy=DateCreated&SortOrder=Descending&Limit=20';
  681. try {
  682. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  683. $response = Requests::get($apiURL, [], $options);
  684. if ($response->success) {
  685. $data = json_decode($response->body, true);
  686. $items = $data['Items'] ?? [];
  687. $mostWatched = [];
  688. foreach ($items as $item) {
  689. $mostWatched[] = [
  690. 'title' => $item['Name'] ?? 'Unknown Title',
  691. 'total_plays' => 1, // Placeholder since we can't get real play counts
  692. 'runtime' => isset($item['RunTimeTicks']) ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  693. 'type' => $item['Type'] ?? 'Unknown',
  694. 'year' => $item['ProductionYear'] ?? null
  695. ];
  696. }
  697. return $mostWatched;
  698. }
  699. } catch (Requests_Exception $e) {
  700. // Final fallback - empty array
  701. }
  702. return [];
  703. }
  704. /**
  705. * Get total play count for a specific item across all users
  706. */
  707. private function getEmbyItemTotalPlays($url, $token, $itemId)
  708. {
  709. $totalPlays = 0;
  710. $users = $this->getEmbyUserStats($url, $token, 30);
  711. foreach ($users as $user) {
  712. if (isset($user['Policy']['IsDisabled']) && $user['Policy']['IsDisabled']) {
  713. continue;
  714. }
  715. $userId = $user['Id'];
  716. $userItemURL = rtrim($url, '/') . '/emby/Users/' . $userId . '/Items/' . $itemId . '?api_key=' . $token . '&Fields=UserData';
  717. try {
  718. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  719. $response = Requests::get($userItemURL, [], $options);
  720. if ($response->success) {
  721. $itemData = json_decode($response->body, true);
  722. $totalPlays += $itemData['UserData']['PlayCount'] ?? 0;
  723. }
  724. } catch (Requests_Exception $e) {
  725. // Continue with other users if one fails
  726. continue;
  727. }
  728. }
  729. return $totalPlays;
  730. }
  731. /**
  732. * Get watched content for a specific user
  733. */
  734. private function getEmbyUserWatchedContent($url, $token, $userId, $days)
  735. {
  736. $apiURL = rtrim($url, '/') . '/emby/Users/' . $userId . '/Items?api_key=' . $token .
  737. '&Recursive=true&IncludeItemTypes=Movie,Episode&IsPlayed=true&Limit=50' .
  738. '&Fields=Name,PlayCount,UserData,RunTimeTicks,ProductionYear';
  739. try {
  740. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  741. $response = Requests::get($apiURL, [], $options);
  742. if ($response->success) {
  743. $data = json_decode($response->body, true);
  744. $items = $data['Items'] ?? [];
  745. $watchedContent = [];
  746. foreach ($items as $item) {
  747. if (($item['UserData']['PlayCount'] ?? 0) > 0) {
  748. $watchedContent[] = [
  749. 'Id' => $item['Id'] ?? null,
  750. 'title' => $item['Name'] ?? 'Unknown Title',
  751. 'play_count' => $item['UserData']['PlayCount'] ?? 0,
  752. 'runtime' => $item['RunTimeTicks'] ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  753. 'type' => $item['Type'] ?? 'Unknown',
  754. 'year' => $item['ProductionYear'] ?? null
  755. ];
  756. }
  757. }
  758. return $watchedContent;
  759. }
  760. } catch (Requests_Exception $e) {
  761. // Emby User Watched Content Error: " . $e->getMessage();
  762. }
  763. return [];
  764. }
  765. /**
  766. * Get user statistics from Emby
  767. */
  768. private function getEmbyUserStats($url, $token, $days)
  769. {
  770. $apiURL = rtrim($url, '/') . '/emby/Users?api_key=' . $token;
  771. try {
  772. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  773. $response = Requests::get($apiURL, [], $options);
  774. if ($response->success) {
  775. $data = json_decode($response->body, true);
  776. return $data ?? [];
  777. }
  778. } catch (Requests_Exception $e) {
  779. // Emby User Stats Error: " . $e->getMessage();
  780. }
  781. return [];
  782. }
  783. /**
  784. * Get top users from Emby
  785. */
  786. private function getEmbyTopUsers($url, $token, $days)
  787. {
  788. $apiURL = rtrim($url, '/') . '/emby/Users?api_key=' . $token;
  789. try {
  790. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  791. $response = Requests::get($apiURL, [], $options);
  792. if ($response->success) {
  793. $data = json_decode($response->body, true);
  794. $users = $data ?? [];
  795. $topUsers = [];
  796. foreach ($users as $user) {
  797. if (!isset($user['Policy']['IsHidden']) || !$user['Policy']['IsHidden']) {
  798. $topUsers[] = [
  799. 'username' => $user['Name'] ?? 'Unknown User',
  800. 'friendly_name' => $user['Name'] ?? 'Unknown User',
  801. 'play_count' => 0, // Emby doesn't provide direct play count per user
  802. 'last_seen' => $user['LastActivityDate'] ?? null
  803. ];
  804. }
  805. }
  806. return array_slice($topUsers, 0, 10);
  807. }
  808. } catch (Requests_Exception $e) {
  809. // Emby Top Users Error: " . $e->getMessage();
  810. }
  811. return [];
  812. }
  813. /**
  814. * Get recent activity from Emby
  815. */
  816. private function getEmbyRecentActivity($url, $token)
  817. {
  818. $apiURL = rtrim($url, '/') . '/emby/Items/Latest?api_key=' . $token . '&Limit=10&Recursive=true&IncludeItemTypes=Movie,Episode';
  819. try {
  820. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  821. $response = Requests::get($apiURL, [], $options);
  822. if ($response->success) {
  823. $data = json_decode($response->body, true);
  824. $recentActivity = [];
  825. foreach ($data as $item) {
  826. $recentActivity[] = [
  827. 'title' => $item['Name'] ?? 'Unknown Title',
  828. 'type' => $item['Type'] ?? 'Unknown',
  829. 'added_at' => $item['DateCreated'] ?? 'Unknown Date',
  830. 'year' => $item['ProductionYear'] ?? null
  831. ];
  832. }
  833. return $recentActivity;
  834. }
  835. } catch (Requests_Exception $e) {
  836. // Emby Recent Activity Error: " . $e->getMessage();
  837. }
  838. return [];
  839. }
  840. /**
  841. * Get watch history from Emby
  842. */
  843. private function getEmbyWatchHistory($url, $token, $days)
  844. {
  845. // Try without date filter first to see if we get any played content
  846. $apiURL = rtrim($url, '/') . '/emby/UserLibrary/Items?api_key=' . $token .
  847. '&Recursive=true&IncludeItemTypes=Movie,Episode&IsPlayed=true&Limit=20' .
  848. '&Fields=Name,PlayCount,UserData,RunTimeTicks,DateCreated,UserDataLastPlayedDate';
  849. try {
  850. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  851. $response = Requests::get($apiURL, [], $options);
  852. if ($response->success) {
  853. $data = json_decode($response->body, true);
  854. $items = $data['Items'] ?? [];
  855. $watchHistory = [];
  856. foreach ($items as $item) {
  857. $watchHistory[] = [
  858. 'title' => $item['Name'] ?? 'Unknown Title',
  859. 'play_count' => $item['UserData']['PlayCount'] ?? 0,
  860. 'runtime' => $item['RunTimeTicks'] ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  861. 'type' => $item['Type'] ?? 'Unknown',
  862. 'year' => $item['ProductionYear'] ?? null,
  863. 'last_played' => $item['UserData']['LastPlayedDate'] ?? 'Never'
  864. ];
  865. }
  866. return $watchHistory;
  867. }
  868. } catch (Requests_Exception $e) {
  869. // Emby Watch History Error: " . $e->getMessage();
  870. }
  871. return [];
  872. }
  873. /**
  874. * Get Emby user avatar
  875. */
  876. private function getEmbyUserAvatar($userId)
  877. {
  878. // Implement Emby avatar logic
  879. return '/plugins/images/organizr/user-bg.png';
  880. }
  881. /**
  882. * Get Jellyfin user avatar
  883. */
  884. private function getJellyfinUserAvatar($userId)
  885. {
  886. // Implement Jellyfin avatar logic
  887. return '/plugins/images/organizr/user-bg.png';
  888. }
  889. }