userWatchStats.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  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. var watchStatsData = null;
  204. var currentSort = { field: 'total_plays', direction: 'desc' };
  205. var currentFilter = 'all';
  206. var currentView = 'table';
  207. function getUserWatchStatsData() {
  208. return organizrAPI2("GET", "api/v2/homepage/userWatchStats")
  209. .done(function(data) {
  210. if (data && data.response && data.response.result === "success" && data.response.data) {
  211. watchStatsData = data.response.data;
  212. renderWatchStatsUI();
  213. } else {
  214. $("#watchstats-content").html('\<div class="col-lg-12 text-center text-danger">Failed to load statistics\</div>\');
  215. }
  216. })
  217. .fail(function(xhr, status, error) {
  218. $("#watchstats-content").html('\<div class="col-lg-12 text-center text-danger">Error loading statistics\</div>\');
  219. });
  220. }
  221. function renderWatchStatsUI() {
  222. if (!watchStatsData) return;
  223. var stats = watchStatsData;
  224. var html = "";
  225. // Header with controls
  226. html += '\<div class="col-lg-12">\'';
  227. html += '\<div class="row">\'';
  228. html += '\<div class="col-md-6">\<h4>Watch Statistics for \' + (stats.period || "30 days") + '\</h4>\</div>\'';
  229. html += '\<div class="col-md-6 text-right">\'';
  230. html += '\<div class="btn-group btn-group-sm" role="group">\'';
  231. html += '\<button type="button" class="btn btn-sm \' + (currentView === "table" ? "btn-primary" : "btn-default") + '\" onclick="switchView(\'table\')">\<i class="fa fa-table">\</i> Table\</button>\'';
  232. html += '\<button type="button" class="btn btn-sm \' + (currentView === "cards" ? "btn-primary" : "btn-default") + '\" onclick="switchView(\'cards\')">\<i class="fa fa-th">\</i> Cards\</button>\'';
  233. html += '\</div>\'';
  234. html += '\</div>\'';
  235. html += '\</div>\'';
  236. html += '\</div>\'';
  237. // Filter and search controls
  238. html += '\<div class="col-lg-12">\'';
  239. html += '\<div class="row" style="margin-bottom: 15px;">\'';
  240. html += '\<div class="col-md-4">\'';
  241. html += '\<select class="form-control input-sm" id="media-filter" onchange="filterMedia(this.value)">\'';
  242. html += '\<option value="all" \' + (currentFilter === "all" ? "selected" : "") + '>All Media\</option>\'';
  243. html += '\<option value="Movie" \' + (currentFilter === "Movie" ? "selected" : "") + '>Movies\</option>\'';
  244. html += '\<option value="Episode" \' + (currentFilter === "Episode" ? "selected" : "") + '>TV Episodes\</option>\'';
  245. html += '\<option value="Series" \' + (currentFilter === "Series" ? "selected" : "") + '>TV Series\</option>\'';
  246. html += '\</select>\'';
  247. html += '\</div>\'';
  248. html += '\<div class="col-md-4">\'';
  249. html += '\<input type="text" class="form-control input-sm" placeholder="Search titles..." id="search-input" oninput="searchMedia(this.value)">\'';
  250. html += '\</div>\'';
  251. html += '\<div class="col-md-4">\'';
  252. html += '\<small class="text-muted" id="results-count">\</small>\'';
  253. html += '\</div>\'';
  254. html += '\</div>\'';
  255. html += '\</div>\'';
  256. // Most Watched Content
  257. if (stats.most_watched && stats.most_watched.length > 0) {
  258. html += renderMostWatchedContent(stats.most_watched);
  259. }
  260. // User Statistics (collapsible)
  261. if (stats.user_stats && stats.user_stats.length > 0) {
  262. html += '\<div class="col-lg-12" style="margin-top: 20px;">\'';
  263. html += '\<div class="panel panel-default">\'';
  264. html += '\<div class="panel-heading">\'';
  265. html += '\<h5 class="panel-title">\'';
  266. html += '\<a data-toggle="collapse" href="#user-stats-panel">\'';
  267. html += '\<i class="fa fa-users">\</i> Server Users (\' + stats.user_stats.length + '\' total) \<i class="fa fa-chevron-down pull-right">\</i>\'';
  268. html += '\</a>\'';
  269. html += '\</h5>\'';
  270. html += '\</div>\'';
  271. html += '\<div id="user-stats-panel" class="panel-collapse collapse">\'';
  272. html += '\<div class="panel-body">\'';
  273. html += '\<div class="row">\'';
  274. stats.user_stats.slice(0, 12).forEach(function(user, index) {
  275. var lastActivity = "Never";
  276. if (user.LastActivityDate && user.LastActivityDate !== "0001-01-01T00:00:00.0000000Z") {
  277. var activityDate = new Date(user.LastActivityDate);
  278. lastActivity = activityDate.toLocaleDateString();
  279. }
  280. var isAdmin = user.Policy && user.Policy.IsAdministrator;
  281. var isDisabled = user.Policy && user.Policy.IsDisabled;
  282. var badgeClass = isAdmin ? "label-success" : (isDisabled ? "label-danger" : "label-info");
  283. var badgeText = isAdmin ? "Admin" : (isDisabled ? "Disabled" : "User");
  284. html += '\<div class="col-md-4 col-sm-6" style="margin-bottom: 10px;">\'';
  285. html += '\<div class="media">\'';
  286. html += '\<div class="media-left">\'';
  287. html += '\<i class="fa fa-user fa-2x text-muted">\</i>\'';
  288. html += '\</div>\'';
  289. html += '\<div class="media-body">\'';
  290. html += '\<h6 class="media-heading">\' + (user.Name || "Unknown User") + '\' \<span class="label \' + badgeClass + '">\' + badgeText + '\</span>\</h6>\'';
  291. html += '\<small class="text-muted">Last Activity: \' + lastActivity + '\</small>\'';
  292. html += '\</div>\'';
  293. html += '\</div>\'';
  294. html += '\</div>\'';
  295. });
  296. html += '\</div>\'';
  297. html += '\</div>\'';
  298. html += '\</div>\'';
  299. html += '\</div>\'';
  300. html += '\</div>\'';
  301. }
  302. // Recent Activity (collapsible)
  303. if (' . $showRecentActivity . ' && stats.recent_activity && stats.recent_activity.length > 0) {
  304. html += '\<div class="col-lg-12">\'';
  305. html += '\<div class="panel panel-default">\'';
  306. html += '\<div class="panel-heading">\'';
  307. html += '\<h5 class="panel-title">\'';
  308. html += '\<a data-toggle="collapse" href="#recent-activity-panel">\'';
  309. html += '\<i class="fa fa-clock-o">\</i> Recent Activity \<i class="fa fa-chevron-down pull-right">\</i>\'';
  310. html += '\</a>\'';
  311. html += '\</h5>\'';
  312. html += '\</div>\'';
  313. html += '\<div id="recent-activity-panel" class="panel-collapse collapse">\'';
  314. html += '\<div class="panel-body">\'';
  315. html += '\<div class="row">\'';
  316. stats.recent_activity.slice(0, 10).forEach(function(activity) {
  317. html += '\<div class="col-md-6" style="margin-bottom: 5px;">\'';
  318. html += '\<i class="fa fa-play-circle text-success">\</i> \' + (activity.title || "Unknown Title");
  319. if (activity.year) html += '\' (\' + activity.year + '\')\'';
  320. html += '\<br>\<small class="text-muted">\' + (activity.added_at || "Unknown Date") + '\</small>\'';
  321. html += '\</div>\'';
  322. });
  323. html += '\</div>\'';
  324. html += '\</div>\'';
  325. html += '\</div>\'';
  326. html += '\</div>\'';
  327. html += '\</div>\'';
  328. }
  329. // Check if we have any data to display
  330. var hasData = (stats.most_watched && stats.most_watched.length > 0) ||
  331. (stats.user_stats && stats.user_stats.length > 0) ||
  332. (stats.recent_activity && stats.recent_activity.length > 0);
  333. if (!hasData) {
  334. html += '\<div class="col-lg-12 text-center text-muted">\'';
  335. html += '\<i class="fa fa-exclamation-circle fa-3x" style="margin-bottom: 10px;">\</i>\'';
  336. html += '\<h4>No statistics available\</h4>\'';
  337. html += '\<p>Start watching some content to see statistics here!\</p>\'';
  338. html += '\</div>\'';
  339. }
  340. $("#watchstats-content").html(html);
  341. }
  342. // Auto-refresh setup
  343. var refreshInterval = ' . $refreshInterval . ';
  344. if (refreshInterval > 0) {
  345. watchStatsRefreshTimer = setInterval(function() {
  346. refreshUserWatchStats();
  347. }, refreshInterval);
  348. }
  349. // Update time display every 30 seconds
  350. setInterval(updateWatchStatsLastRefreshTime, 30000);
  351. // Initial load
  352. $(document).ready(function() {
  353. refreshUserWatchStats();
  354. });
  355. // Cleanup timer when page unloads
  356. $(window).on("beforeunload", function() {
  357. if (watchStatsRefreshTimer) {
  358. clearInterval(watchStatsRefreshTimer);
  359. }
  360. });
  361. function renderMostWatchedContent(items) {
  362. var html = '\<div class="col-lg-12">\'';
  363. html += '\<h5>\<i class="fa fa-star text-warning">\</i> Most Watched Content\</h5>\'';
  364. if (currentView === "table") {
  365. html += renderTableView(items);
  366. } else {
  367. html += renderCardView(items);
  368. }
  369. html += '\</div>\'';
  370. return html;
  371. }
  372. function renderTableView(items) {
  373. var filteredItems = filterAndSortItems(items);
  374. var html = '\<div class="table-responsive">\'';
  375. html += '\<table class="table table-striped table-hover table-condensed">\'';
  376. html += '\<thead>\'';
  377. html += '\<tr>\'';
  378. html += '\<th>\<a href="#" onclick="sortBy(\'title\')" class="text-decoration-none">Title \' + getSortIcon(\'title\') + '\</a>\</th>\'';
  379. html += '\<th>\<a href="#" onclick="sortBy(\'type\')" class="text-decoration-none">Type \' + getSortIcon(\'type\') + '\</a>\</th>\'';
  380. html += '\<th>\<a href="#" onclick="sortBy(\'total_plays\')" class="text-decoration-none">Users \' + getSortIcon(\'total_plays\') + '\</a>\</th>\'';
  381. html += '\<th>\<a href="#" onclick="sortBy(\'runtime\')" class="text-decoration-none">Runtime \' + getSortIcon(\'runtime\') + '\</a>\</th>\'';
  382. html += '\<th>\<a href="#" onclick="sortBy(\'year\')" class="text-decoration-none">Year \' + getSortIcon(\'year\') + '\</a>\</th>\'';
  383. html += '\</tr>\'';
  384. html += '\</thead>\'';
  385. html += '\<tbody>\'';
  386. filteredItems.slice(0, 20).forEach(function(item) {
  387. var typeIcon = getTypeIcon(item.type);
  388. var typeBadge = getTypeBadge(item.type);
  389. html += '\<tr>\'';
  390. html += '\<td>\<strong>\' + (item.title || "Unknown Title") + '\</strong>\</td>\'';
  391. html += '\<td>\' + typeIcon + '\' \' + typeBadge + '\</td>\'';
  392. html += '\<td>\<span class="badge badge-primary">\' + (item.total_plays || 0) + '\</span>\</td>\'';
  393. html += '\<td>\' + (item.runtime || "Unknown") + '\</td>\'';
  394. html += '\<td>\' + (item.year || "N/A") + '\</td>\'';
  395. html += '\</tr>\'';
  396. });
  397. html += '\</tbody>\'';
  398. html += '\</table>\'';
  399. html += '\</div>\'';
  400. updateResultsCount(filteredItems.length);
  401. return html;
  402. }
  403. function renderCardView(items) {
  404. var filteredItems = filterAndSortItems(items);
  405. var html = '\<div class="row">\'';
  406. filteredItems.slice(0, 20).forEach(function(item) {
  407. var typeIcon = getTypeIcon(item.type);
  408. var typeBadge = getTypeBadge(item.type);
  409. html += '\<div class="col-lg-4 col-md-6 col-sm-12" style="margin-bottom: 15px;">\'';
  410. html += '\<div class="panel panel-default">\'';
  411. html += '\<div class="panel-body">\'';
  412. html += '\<div class="media">\'';
  413. html += '\<div class="media-left">\'';
  414. html += '\<div class="text-center" style="width: 60px;">\'';
  415. html += typeIcon + '\<br>\'';
  416. html += '\<span class="badge badge-primary">\' + (item.total_plays || 0) + '\</span>\'';
  417. html += '\</div>\'';
  418. html += '\</div>\'';
  419. html += '\<div class="media-body">\'';
  420. html += '\<h6 class="media-heading">\<strong>\' + (item.title || "Unknown Title") + '\</strong>\</h6>\'';
  421. html += '\<p class="text-muted" style="margin-bottom: 5px;">\'';
  422. html += typeBadge;
  423. if (item.year) html += '\' • \' + item.year;
  424. if (item.runtime && item.runtime !== "Unknown") html += '\' • \' + item.runtime;
  425. html += '\</p>\'';
  426. html += '\</div>\'';
  427. html += '\</div>\'';
  428. html += '\</div>\'';
  429. html += '\</div>\'';
  430. html += '\</div>\'';
  431. });
  432. html += '\</div>\'';
  433. updateResultsCount(filteredItems.length);
  434. return html;
  435. }
  436. function filterAndSortItems(items) {
  437. var filtered = items.filter(function(item) {
  438. // Apply media type filter
  439. if (currentFilter !== "all" && item.type !== currentFilter) {
  440. return false;
  441. }
  442. // Apply search filter
  443. var searchTerm = document.getElementById(\'search-input\') ? document.getElementById(\'search-input\').value.toLowerCase() : "";
  444. if (searchTerm && item.title && item.title.toLowerCase().indexOf(searchTerm) === -1) {
  445. return false;
  446. }
  447. return true;
  448. });
  449. // Sort items
  450. filtered.sort(function(a, b) {
  451. var aVal = a[currentSort.field];
  452. var bVal = b[currentSort.field];
  453. // Handle different data types
  454. if (currentSort.field === \'year\' || currentSort.field === \'total_plays\') {
  455. aVal = parseInt(aVal) || 0;
  456. bVal = parseInt(bVal) || 0;
  457. } else {
  458. aVal = (aVal || "").toString().toLowerCase();
  459. bVal = (bVal || "").toString().toLowerCase();
  460. }
  461. var result = aVal < bVal ? -1 : (aVal > bVal ? 1 : 0);
  462. return currentSort.direction === \'desc\' ? -result : result;
  463. });
  464. return filtered;
  465. }
  466. function getTypeIcon(type) {
  467. switch(type) {
  468. case \'Movie\': return '\<i class="fa fa-film fa-2x text-primary">\</i>\';
  469. case \'Episode\': return '\<i class="fa fa-tv fa-2x text-success">\</i>\';
  470. case \'Series\': return '\<i class="fa fa-television fa-2x text-info">\</i>\';
  471. case \'Audio\': return '\<i class="fa fa-music fa-2x text-warning">\</i>\';
  472. default: return '\<i class="fa fa-play-circle fa-2x text-muted">\</i>\';
  473. }
  474. }
  475. function getTypeBadge(type) {
  476. switch(type) {
  477. case \'Movie\': return '\<span class="label label-primary">Movie\</span>\';
  478. case \'Episode\': return '\<span class="label label-success">TV Episode\</span>\';
  479. case \'Series\': return '\<span class="label label-info">TV Series\</span>\';
  480. case \'Audio\': return '\<span class="label label-warning">Music\</span>\';
  481. default: return '\<span class="label label-default">\' + (type || "Unknown") + '\</span>\';
  482. }
  483. }
  484. function getSortIcon(field) {
  485. if (currentSort.field !== field) {
  486. return '\<i class="fa fa-sort text-muted">\</i>\';
  487. }
  488. return currentSort.direction === \'asc\' ?
  489. '\<i class="fa fa-sort-up text-primary">\</i>\' :
  490. '\<i class="fa fa-sort-down text-primary">\</i>\';
  491. }
  492. function sortBy(field) {
  493. if (currentSort.field === field) {
  494. currentSort.direction = currentSort.direction === \'asc\' ? \'desc\' : \'asc\';
  495. } else {
  496. currentSort.field = field;
  497. currentSort.direction = \'desc\';
  498. }
  499. renderWatchStatsUI();
  500. }
  501. function filterMedia(type) {
  502. currentFilter = type;
  503. renderWatchStatsUI();
  504. }
  505. function searchMedia(term) {
  506. renderWatchStatsUI();
  507. }
  508. function switchView(view) {
  509. currentView = view;
  510. renderWatchStatsUI();
  511. }
  512. function updateResultsCount(count) {
  513. setTimeout(function() {
  514. var countElement = document.getElementById(\'results-count\');
  515. if (countElement) {
  516. countElement.innerHTML = \'Showing \' + count + \' item\' + (count !== 1 ? \'s\' : \'\') + \'\'';
  517. }
  518. }, 100);
  519. }
  520. </script>
  521. ';
  522. }
  523. }
  524. /**
  525. * Main function to get watch statistics
  526. */
  527. public function getUserWatchStats($options = null)
  528. {
  529. if (!$this->homepageItemPermissions($this->userWatchStatsHomepagePermissions('main'), true)) {
  530. $this->setAPIResponse('error', 'User not approved to view this homepage item - check plugin configuration', 401);
  531. return false;
  532. }
  533. try {
  534. $mediaServer = $this->config['homepageUserWatchStatsService'] ?? 'plex';
  535. $days = intval($this->config['homepageUserWatchStatsDays'] ?? 30);
  536. switch (strtolower($mediaServer)) {
  537. case 'plex':
  538. $stats = $this->getPlexWatchStats($days);
  539. break;
  540. case 'emby':
  541. $stats = $this->getEmbyWatchStats($days);
  542. break;
  543. case 'jellyfin':
  544. $stats = $this->getJellyfinWatchStats($days);
  545. break;
  546. default:
  547. $stats = $this->getPlexWatchStats($days);
  548. break;
  549. }
  550. if (isset($stats['error']) && $stats['error']) {
  551. $this->setAPIResponse('error', $stats['message'], 500);
  552. return false;
  553. }
  554. $this->setAPIResponse('success', 'Watch statistics retrieved successfully', 200, $stats);
  555. return true;
  556. } catch (Exception $e) {
  557. // User Watch Stats Error: " . $e->getMessage();
  558. $this->setAPIResponse('error', 'Failed to retrieve watch statistics: ' . $e->getMessage(), 500);
  559. return false;
  560. }
  561. }
  562. /**
  563. * Get Plex watch statistics via Tautulli API
  564. */
  565. private function getPlexWatchStats($days = 30)
  566. {
  567. $tautulliUrl = $this->config['userWatchStatsURL'] ?? '';
  568. $tautulliToken = $this->config['userWatchStatsApikey'] ?? '';
  569. if (empty($tautulliUrl) || empty($tautulliToken)) {
  570. return ['error' => true, 'message' => 'Tautulli URL or API key not configured'];
  571. }
  572. $endDate = date('Y-m-d');
  573. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  574. $stats = [
  575. 'period' => "{$days} days",
  576. 'start_date' => $startDate,
  577. 'end_date' => $endDate,
  578. 'most_watched' => $this->getTautulliMostWatched($tautulliUrl, $tautulliToken, $days),
  579. 'least_watched' => $this->getTautulliLeastWatched($tautulliUrl, $tautulliToken, $days),
  580. 'user_stats' => $this->getTautulliUserStats($tautulliUrl, $tautulliToken, $days),
  581. 'recent_activity' => $this->getTautulliRecentActivity($tautulliUrl, $tautulliToken),
  582. 'top_users' => $this->getTautulliTopUsers($tautulliUrl, $tautulliToken, $days)
  583. ];
  584. return $stats;
  585. }
  586. /**
  587. * Get most watched content from Tautulli
  588. */
  589. private function getTautulliMostWatched($url, $token, $days)
  590. {
  591. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_home_stats&time_range=' . $days . '&stats_type=plays&stats_count=10';
  592. try {
  593. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  594. $response = Requests::get($apiURL, [], $options);
  595. if ($response->success) {
  596. $data = json_decode($response->body, true);
  597. return $data['response']['data'] ?? [];
  598. }
  599. } catch (Requests_Exception $e) {
  600. // Tautulli Most Watched Error: " . $e->getMessage();
  601. }
  602. return [];
  603. }
  604. /**
  605. * Get user statistics from Tautulli
  606. */
  607. private function getTautulliUserStats($url, $token, $days)
  608. {
  609. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_user_watch_time_stats&time_range=' . $days;
  610. try {
  611. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  612. $response = Requests::get($apiURL, [], $options);
  613. if ($response->success) {
  614. $data = json_decode($response->body, true);
  615. return $data['response']['data'] ?? [];
  616. }
  617. } catch (Requests_Exception $e) {
  618. // Tautulli User Stats Error: " . $e->getMessage();
  619. }
  620. return [];
  621. }
  622. /**
  623. * Get top users from Tautulli
  624. */
  625. private function getTautulliTopUsers($url, $token, $days)
  626. {
  627. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_users&length=25';
  628. try {
  629. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  630. $response = Requests::get($apiURL, [], $options);
  631. if ($response->success) {
  632. $data = json_decode($response->body, true);
  633. $users = $data['response']['data']['data'] ?? [];
  634. // Sort by play count
  635. usort($users, function($a, $b) {
  636. return ($b['play_count'] ?? 0) - ($a['play_count'] ?? 0);
  637. });
  638. return array_slice($users, 0, 10);
  639. }
  640. } catch (Requests_Exception $e) {
  641. // Tautulli Top Users Error: " . $e->getMessage();
  642. }
  643. return [];
  644. }
  645. /**
  646. * Get recent activity from Tautulli
  647. */
  648. private function getTautulliRecentActivity($url, $token)
  649. {
  650. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_recently_added&count=10';
  651. try {
  652. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  653. $response = Requests::get($apiURL, [], $options);
  654. if ($response->success) {
  655. $data = json_decode($response->body, true);
  656. return $data['response']['data']['recently_added'] ?? [];
  657. }
  658. } catch (Requests_Exception $e) {
  659. // Tautulli Recent Activity Error: " . $e->getMessage();
  660. }
  661. return [];
  662. }
  663. /**
  664. * Get least watched content (inverse of most watched)
  665. */
  666. private function getTautulliLeastWatched($url, $token, $days)
  667. {
  668. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_libraries';
  669. try {
  670. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  671. $response = Requests::get($apiURL, [], $options);
  672. if ($response->success) {
  673. $data = json_decode($response->body, true);
  674. $libraries = $data['response']['data'] ?? [];
  675. $leastWatched = [];
  676. foreach ($libraries as $library) {
  677. $libraryStats = $this->getTautulliLibraryStats($url, $token, $library['section_id'], $days);
  678. if (!empty($libraryStats)) {
  679. $leastWatched = array_merge($leastWatched, array_slice($libraryStats, -10));
  680. }
  681. }
  682. return $leastWatched;
  683. }
  684. } catch (Requests_Exception $e) {
  685. // Tautulli Least Watched Error: " . $e->getMessage();
  686. }
  687. return [];
  688. }
  689. /**
  690. * Get library statistics for least watched calculation
  691. */
  692. private function getTautulliLibraryStats($url, $token, $sectionId, $days)
  693. {
  694. $apiURL = rtrim($url, '/') . '/api/v2?apikey=' . $token . '&cmd=get_library_media_info&section_id=' . $sectionId . '&length=50&order_column=play_count&order_dir=asc';
  695. try {
  696. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  697. $response = Requests::get($apiURL, [], $options);
  698. if ($response->success) {
  699. $data = json_decode($response->body, true);
  700. return $data['response']['data']['data'] ?? [];
  701. }
  702. } catch (Requests_Exception $e) {
  703. // Tautulli Library Stats Error: " . $e->getMessage();
  704. }
  705. return [];
  706. }
  707. /**
  708. * Get Emby watch statistics
  709. */
  710. private function getEmbyWatchStats($days = 30)
  711. {
  712. $embyUrl = $this->config['userWatchStatsURL'] ?? '';
  713. $embyToken = $this->config['userWatchStatsApikey'] ?? '';
  714. if (empty($embyUrl) || empty($embyToken)) {
  715. return ['error' => true, 'message' => 'Emby URL or API key not configured'];
  716. }
  717. $endDate = date('Y-m-d');
  718. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  719. $stats = [
  720. 'period' => "{$days} days",
  721. 'start_date' => $startDate,
  722. 'end_date' => $endDate,
  723. 'most_watched' => $this->getEmbyMostWatched($embyUrl, $embyToken, $days),
  724. 'least_watched' => [], // Emby doesn't have a direct least watched API
  725. 'user_stats' => $this->getEmbyUserStats($embyUrl, $embyToken, $days),
  726. 'recent_activity' => $this->getEmbyRecentActivity($embyUrl, $embyToken),
  727. 'watch_history' => $this->getEmbyWatchHistory($embyUrl, $embyToken, $days),
  728. 'top_users' => $this->getEmbyTopUsers($embyUrl, $embyToken, $days)
  729. ];
  730. return $stats;
  731. }
  732. /**
  733. * Get Jellyfin watch statistics
  734. */
  735. private function getJellyfinWatchStats($days = 30)
  736. {
  737. $jellyfinUrl = $this->config['jellyfinURL'] ?? '';
  738. $jellyfinToken = $this->config['jellyfinToken'] ?? '';
  739. if (empty($jellyfinUrl) || empty($jellyfinToken)) {
  740. return ['error' => true, 'message' => 'Jellyfin URL or API key not configured'];
  741. }
  742. // Implement Jellyfin-specific statistics gathering
  743. return $this->getGenericMediaServerStats('jellyfin', $jellyfinUrl, $jellyfinToken, $days);
  744. }
  745. /**
  746. * Generic media server stats for Emby/Jellyfin
  747. */
  748. private function getGenericMediaServerStats($type, $url, $token, $days)
  749. {
  750. // Basic structure for now - can be expanded based on Emby/Jellyfin APIs
  751. return [
  752. 'period' => "{$days} days",
  753. 'start_date' => date('Y-m-d', strtotime("-{$days} days")),
  754. 'end_date' => date('Y-m-d'),
  755. 'message' => ucfirst($type) . ' statistics coming soon',
  756. 'most_watched' => [],
  757. 'least_watched' => [],
  758. 'user_stats' => [],
  759. 'recent_activity' => [],
  760. 'top_users' => []
  761. ];
  762. }
  763. /**
  764. * Format duration for display
  765. */
  766. private function formatDuration($seconds)
  767. {
  768. if ($seconds < 3600) {
  769. return gmdate('i:s', $seconds);
  770. } else {
  771. return gmdate('H:i:s', $seconds);
  772. }
  773. }
  774. /**
  775. * Get user avatar URL
  776. */
  777. private function getUserAvatar($userId, $mediaServer = 'plex')
  778. {
  779. switch ($mediaServer) {
  780. case 'plex':
  781. return $this->getPlexUserAvatar($userId);
  782. case 'emby':
  783. return $this->getEmbyUserAvatar($userId);
  784. case 'jellyfin':
  785. return $this->getJellyfinUserAvatar($userId);
  786. default:
  787. return '/plugins/images/organizr/user-bg.png';
  788. }
  789. }
  790. /**
  791. * Get Plex user avatar
  792. */
  793. private function getPlexUserAvatar($userId)
  794. {
  795. $tautulliUrl = $this->config['plexURL'] ?? '';
  796. $tautulliToken = $this->config['plexToken'] ?? '';
  797. if (empty($tautulliUrl) || empty($tautulliToken)) {
  798. return '/plugins/images/organizr/user-bg.png';
  799. }
  800. $apiURL = rtrim($tautulliUrl, '/') . '/api/v2?apikey=' . $tautulliToken . '&cmd=get_user_thumb&user_id=' . $userId;
  801. try {
  802. $options = $this->requestOptions($tautulliUrl, null, $this->config['plexDisableCertCheck'] ?? false, $this->config['plexUseCustomCertificate'] ?? false);
  803. $response = Requests::get($apiURL, [], $options);
  804. if ($response->success) {
  805. $data = json_decode($response->body, true);
  806. return $data['response']['data']['thumb'] ?? '/plugins/images/organizr/user-bg.png';
  807. }
  808. } catch (Requests_Exception $e) {
  809. // Tautulli User Avatar Error: " . $e->getMessage();
  810. }
  811. return '/plugins/images/organizr/user-bg.png';
  812. }
  813. /**
  814. * Get most watched content from Emby (server-wide statistics)
  815. */
  816. private function getEmbyMostWatched($url, $token, $days)
  817. {
  818. // Skip activity log approach and go directly to simple media approach
  819. return $this->getEmbySimpleMostWatched($url, $token);
  820. }
  821. /**
  822. * Get most watched content by aggregating play counts across all users
  823. */
  824. private function getEmbySimpleMostWatched($url, $token)
  825. {
  826. // Since user-specific endpoints are not accessible with API key,
  827. // fall back to using the global Items API sorted by DatePlayed
  828. $apiURL = rtrim($url, '/') . '/emby/Items?api_key=' . $token .
  829. '&Recursive=true&IncludeItemTypes=Movie,Episode&Fields=Name,RunTimeTicks,ProductionYear,DatePlayed' .
  830. '&SortBy=DatePlayed&SortOrder=Descending&Limit=20';
  831. try {
  832. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  833. $response = Requests::get($apiURL, [], $options);
  834. if ($response->success) {
  835. $responseBody = $response->body;
  836. // Check if response contains SQLite exception or other error indicators
  837. if (is_string($responseBody) && (
  838. strpos($responseBody, 'SQLiteException') !== false ||
  839. strpos($responseBody, 'error') !== false ||
  840. strpos($responseBody, 'Error') !== false ||
  841. !trim($responseBody) ||
  842. $responseBody === 'null'
  843. )) {
  844. // Fall back to recently created items if DatePlayed sorting fails
  845. return $this->getEmbyFallbackMostWatched($url, $token);
  846. }
  847. $data = json_decode($responseBody, true);
  848. // Check if JSON decode failed or returned invalid data
  849. if ($data === null || !is_array($data) || !isset($data['Items'])) {
  850. return $this->getEmbyFallbackMostWatched($url, $token);
  851. }
  852. $items = $data['Items'] ?? [];
  853. $mostWatched = [];
  854. foreach ($items as $item) {
  855. // Only include items that have been played (DatePlayed exists)
  856. if (!empty($item['DatePlayed'])) {
  857. $mostWatched[] = [
  858. 'title' => $item['Name'] ?? 'Unknown Title',
  859. 'total_plays' => 1, // We can't get actual play count from this API
  860. 'runtime' => isset($item['RunTimeTicks']) ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  861. 'type' => $item['Type'] ?? 'Unknown',
  862. 'year' => $item['ProductionYear'] ?? null
  863. ];
  864. }
  865. }
  866. // If no items with DatePlayed, fall back to recently created
  867. if (empty($mostWatched)) {
  868. return $this->getEmbyFallbackMostWatched($url, $token);
  869. }
  870. return $mostWatched;
  871. } else {
  872. // HTTP request failed, use fallback
  873. return $this->getEmbyFallbackMostWatched($url, $token);
  874. }
  875. } catch (Exception $e) {
  876. // Any exception triggers fallback
  877. return $this->getEmbyFallbackMostWatched($url, $token);
  878. }
  879. // Fallback if we somehow get here
  880. return $this->getEmbyFallbackMostWatched($url, $token);
  881. }
  882. /**
  883. * Fallback method - calculate most watched by aggregating play counts across all users
  884. */
  885. private function getEmbyFallbackMostWatched($url, $token)
  886. {
  887. // Get all users first
  888. $users = $this->getEmbyUserStats($url, $token, 30);
  889. $playCountsByItem = [];
  890. $itemDetails = [];
  891. // For each user, get their watched items
  892. foreach ($users as $user) {
  893. if (isset($user['Policy']['IsDisabled']) && $user['Policy']['IsDisabled']) {
  894. continue; // Skip disabled users
  895. }
  896. $userId = $user['Id'];
  897. $userWatchedItems = $this->getEmbyUserWatchedContent($url, $token, $userId, 30);
  898. // Aggregate play counts - count each user who has played the item
  899. foreach ($userWatchedItems as $item) {
  900. $itemId = $item['Id'] ?? $item['title']; // Use ID if available, title as fallback
  901. $isPlayed = $item['is_played'] ?? false;
  902. if ($isPlayed) {
  903. // Increment count for each user who has played this item
  904. $playCountsByItem[$itemId] = ($playCountsByItem[$itemId] ?? 0) + 1;
  905. // Store item details (only need to do this once per item)
  906. if (!isset($itemDetails[$itemId])) {
  907. $itemDetails[$itemId] = [
  908. 'title' => $item['title'] ?? 'Unknown Title',
  909. 'runtime' => $item['runtime'] ?? 'Unknown',
  910. 'type' => $item['type'] ?? 'Unknown',
  911. 'year' => $item['year'] ?? null
  912. ];
  913. }
  914. }
  915. }
  916. }
  917. // Sort by total play count (descending)
  918. arsort($playCountsByItem);
  919. // Build most watched array
  920. $mostWatched = [];
  921. $count = 0;
  922. foreach ($playCountsByItem as $itemId => $totalPlays) {
  923. if ($count >= 20) break; // Limit to top 20
  924. $details = $itemDetails[$itemId] ?? [
  925. 'title' => 'Unknown Title',
  926. 'runtime' => 'Unknown',
  927. 'type' => 'Unknown',
  928. 'year' => null
  929. ];
  930. $mostWatched[] = [
  931. 'title' => $details['title'],
  932. 'total_plays' => $totalPlays,
  933. 'runtime' => $details['runtime'],
  934. 'type' => $details['type'],
  935. 'year' => $details['year']
  936. ];
  937. $count++;
  938. }
  939. // If no watched content found, fall back to recent items as last resort
  940. if (empty($mostWatched)) {
  941. return $this->getEmbyRecentItemsFallback($url, $token);
  942. }
  943. return $mostWatched;
  944. }
  945. /**
  946. * Final fallback - recent items when no watch data is available
  947. */
  948. private function getEmbyRecentItemsFallback($url, $token)
  949. {
  950. $apiURL = rtrim($url, '/') . '/emby/Items?api_key=' . $token .
  951. '&Recursive=true&IncludeItemTypes=Movie,Episode&Fields=Name,RunTimeTicks,ProductionYear,DateCreated' .
  952. '&SortBy=DateCreated&SortOrder=Descending&Limit=10';
  953. try {
  954. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  955. $response = Requests::get($apiURL, [], $options);
  956. if ($response->success) {
  957. $data = json_decode($response->body, true);
  958. $items = $data['Items'] ?? [];
  959. $recentItems = [];
  960. foreach ($items as $item) {
  961. $recentItems[] = [
  962. 'title' => $item['Name'] ?? 'Unknown Title',
  963. 'total_plays' => 0, // No play data available
  964. 'runtime' => isset($item['RunTimeTicks']) ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  965. 'type' => $item['Type'] ?? 'Unknown',
  966. 'year' => $item['ProductionYear'] ?? null
  967. ];
  968. }
  969. return $recentItems;
  970. }
  971. } catch (Requests_Exception $e) {
  972. // Nothing we can do at this point
  973. }
  974. return [];
  975. }
  976. /**
  977. * Get total play count for a specific item across all users
  978. */
  979. private function getEmbyItemTotalPlays($url, $token, $itemId)
  980. {
  981. $totalPlays = 0;
  982. $users = $this->getEmbyUserStats($url, $token, 30);
  983. foreach ($users as $user) {
  984. if (isset($user['Policy']['IsDisabled']) && $user['Policy']['IsDisabled']) {
  985. continue;
  986. }
  987. $userId = $user['Id'];
  988. $userItemURL = rtrim($url, '/') . '/emby/Users/' . $userId . '/Items/' . $itemId . '?api_key=' . $token . '&Fields=UserData';
  989. try {
  990. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  991. $response = Requests::get($userItemURL, [], $options);
  992. if ($response->success) {
  993. $itemData = json_decode($response->body, true);
  994. $totalPlays += $itemData['UserData']['PlayCount'] ?? 0;
  995. }
  996. } catch (Requests_Exception $e) {
  997. // Continue with other users if one fails
  998. continue;
  999. }
  1000. }
  1001. return $totalPlays;
  1002. }
  1003. /**
  1004. * Get watched content for a specific user
  1005. */
  1006. private function getEmbyUserWatchedContent($url, $token, $userId, $days)
  1007. {
  1008. $apiURL = rtrim($url, '/') . '/emby/Users/' . $userId . '/Items?api_key=' . $token .
  1009. '&Recursive=true&IncludeItemTypes=Movie,Episode&IsPlayed=true&Limit=50' .
  1010. '&Fields=Name,PlayCount,UserData,RunTimeTicks,ProductionYear';
  1011. try {
  1012. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  1013. $response = Requests::get($apiURL, [], $options);
  1014. if ($response->success) {
  1015. $data = json_decode($response->body, true);
  1016. $items = $data['Items'] ?? [];
  1017. $watchedContent = [];
  1018. foreach ($items as $item) {
  1019. // Use Played flag instead of PlayCount since Emby may not increment PlayCount properly
  1020. if (($item['UserData']['Played'] ?? false)) {
  1021. $watchedContent[] = [
  1022. 'Id' => $item['Id'] ?? null,
  1023. 'title' => $item['Name'] ?? 'Unknown Title',
  1024. 'is_played' => true, // Mark as played for our aggregation
  1025. 'runtime' => $item['RunTimeTicks'] ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  1026. 'type' => $item['Type'] ?? 'Unknown',
  1027. 'year' => $item['ProductionYear'] ?? null
  1028. ];
  1029. }
  1030. }
  1031. return $watchedContent;
  1032. }
  1033. } catch (Requests_Exception $e) {
  1034. // Emby User Watched Content Error: " . $e->getMessage();
  1035. }
  1036. return [];
  1037. }
  1038. /**
  1039. * Get user statistics from Emby
  1040. */
  1041. private function getEmbyUserStats($url, $token, $days)
  1042. {
  1043. $apiURL = rtrim($url, '/') . '/emby/Users?api_key=' . $token;
  1044. try {
  1045. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  1046. $response = Requests::get($apiURL, [], $options);
  1047. if ($response->success) {
  1048. $data = json_decode($response->body, true);
  1049. return $data ?? [];
  1050. }
  1051. } catch (Requests_Exception $e) {
  1052. // Emby User Stats Error: " . $e->getMessage();
  1053. }
  1054. return [];
  1055. }
  1056. /**
  1057. * Get top users from Emby
  1058. */
  1059. private function getEmbyTopUsers($url, $token, $days)
  1060. {
  1061. $apiURL = rtrim($url, '/') . '/emby/Users?api_key=' . $token;
  1062. try {
  1063. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  1064. $response = Requests::get($apiURL, [], $options);
  1065. if ($response->success) {
  1066. $data = json_decode($response->body, true);
  1067. $users = $data ?? [];
  1068. $topUsers = [];
  1069. foreach ($users as $user) {
  1070. if (!isset($user['Policy']['IsHidden']) || !$user['Policy']['IsHidden']) {
  1071. $topUsers[] = [
  1072. 'username' => $user['Name'] ?? 'Unknown User',
  1073. 'friendly_name' => $user['Name'] ?? 'Unknown User',
  1074. 'play_count' => 0, // Emby doesn't provide direct play count per user
  1075. 'last_seen' => $user['LastActivityDate'] ?? null
  1076. ];
  1077. }
  1078. }
  1079. return array_slice($topUsers, 0, 10);
  1080. }
  1081. } catch (Requests_Exception $e) {
  1082. // Emby Top Users Error: " . $e->getMessage();
  1083. }
  1084. return [];
  1085. }
  1086. /**
  1087. * Get recent activity from Emby
  1088. */
  1089. private function getEmbyRecentActivity($url, $token)
  1090. {
  1091. $apiURL = rtrim($url, '/') . '/emby/Items/Latest?api_key=' . $token . '&Limit=10&Recursive=true&IncludeItemTypes=Movie,Episode';
  1092. try {
  1093. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  1094. $response = Requests::get($apiURL, [], $options);
  1095. if ($response->success) {
  1096. $data = json_decode($response->body, true);
  1097. $recentActivity = [];
  1098. foreach ($data as $item) {
  1099. $recentActivity[] = [
  1100. 'title' => $item['Name'] ?? 'Unknown Title',
  1101. 'type' => $item['Type'] ?? 'Unknown',
  1102. 'added_at' => $item['DateCreated'] ?? 'Unknown Date',
  1103. 'year' => $item['ProductionYear'] ?? null
  1104. ];
  1105. }
  1106. return $recentActivity;
  1107. }
  1108. } catch (Requests_Exception $e) {
  1109. // Emby Recent Activity Error: " . $e->getMessage();
  1110. }
  1111. return [];
  1112. }
  1113. /**
  1114. * Get watch history from Emby
  1115. */
  1116. private function getEmbyWatchHistory($url, $token, $days)
  1117. {
  1118. // Try without date filter first to see if we get any played content
  1119. $apiURL = rtrim($url, '/') . '/emby/UserLibrary/Items?api_key=' . $token .
  1120. '&Recursive=true&IncludeItemTypes=Movie,Episode&IsPlayed=true&Limit=20' .
  1121. '&Fields=Name,PlayCount,UserData,RunTimeTicks,DateCreated,UserDataLastPlayedDate';
  1122. try {
  1123. $options = $this->requestOptions($url, null, $this->config['userWatchStatsDisableCertCheck'] ?? false, $this->config['userWatchStatsUseCustomCertificate'] ?? false);
  1124. $response = Requests::get($apiURL, [], $options);
  1125. if ($response->success) {
  1126. $data = json_decode($response->body, true);
  1127. $items = $data['Items'] ?? [];
  1128. $watchHistory = [];
  1129. foreach ($items as $item) {
  1130. $watchHistory[] = [
  1131. 'title' => $item['Name'] ?? 'Unknown Title',
  1132. 'play_count' => $item['UserData']['PlayCount'] ?? 0,
  1133. 'runtime' => $item['RunTimeTicks'] ? $this->formatDuration($item['RunTimeTicks'] / 10000000) : 'Unknown',
  1134. 'type' => $item['Type'] ?? 'Unknown',
  1135. 'year' => $item['ProductionYear'] ?? null,
  1136. 'last_played' => $item['UserData']['LastPlayedDate'] ?? 'Never'
  1137. ];
  1138. }
  1139. return $watchHistory;
  1140. }
  1141. } catch (Requests_Exception $e) {
  1142. // Emby Watch History Error: " . $e->getMessage();
  1143. }
  1144. return [];
  1145. }
  1146. /**
  1147. * Get Emby user avatar
  1148. */
  1149. private function getEmbyUserAvatar($userId)
  1150. {
  1151. // Implement Emby avatar logic
  1152. return '/plugins/images/organizr/user-bg.png';
  1153. }
  1154. /**
  1155. * Get Jellyfin user avatar
  1156. */
  1157. private function getJellyfinUserAvatar($userId)
  1158. {
  1159. // Implement Jellyfin avatar logic
  1160. return '/plugins/images/organizr/user-bg.png';
  1161. }
  1162. }