jellystat.php 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  1. <?php
  2. /**
  3. * JellyStat Homepage Plugin for Organizr
  4. * Supports both Emby and Jellyfin servers via JellyStat API or embedded interface
  5. */
  6. trait JellyStatHomepageItem
  7. {
  8. public function jellystatSettingsArray($infoOnly = false)
  9. {
  10. $homepageInformation = [
  11. 'name' => 'JellyStat',
  12. 'enabled' => true,
  13. 'image' => 'plugins/images/homepage/jellystat.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', 'homepageJellyStatEnabled'),
  25. $this->settingsOption('auth', 'homepageJellyStatAuth'),
  26. ],
  27. 'Display Mode' => [
  28. $this->settingsOption('select', 'homepageJellyStatDisplayMode', ['label' => 'Display Mode', 'options' => [
  29. ['name' => 'Native Statistics View', 'value' => 'native'],
  30. ['name' => 'Embedded JellyStat Interface', 'value' => 'iframe']
  31. ]]),
  32. ],
  33. 'Connection' => [
  34. $this->settingsOption('url', 'jellyStatURL', ['label' => 'JellyStat URL', 'help' => 'URL to your JellyStat instance']),
  35. $this->settingsOption('url', 'jellyStatInternalURL', ['label' => 'Internal JellyStat URL (optional)', 'help' => 'Internal URL for server-side API calls (e.g., http://192.168.80.77:3000). If not set, uses main URL.']),
  36. $this->settingsOption('token', 'jellyStatApikey', ['label' => 'JellyStat API Key', 'help' => 'API key for JellyStat (required for native mode)']),
  37. $this->settingsOption('disable-cert-check', 'jellyStatDisableCertCheck'),
  38. $this->settingsOption('use-custom-certificate', 'jellyStatUseCustomCertificate'),
  39. ],
  40. 'Native Mode Options' => [
  41. $this->settingsOption('number', 'homepageJellyStatRefresh', ['label' => 'Auto-refresh Interval (minutes)', 'min' => 1, 'max' => 60]),
  42. $this->settingsOption('number', 'homepageJellyStatDays', ['label' => 'Statistics Period (days)', 'min' => 1, 'max' => 365]),
  43. $this->settingsOption('switch', 'homepageJellyStatShowLibraries', ['label' => 'Show Library Statistics']),
  44. $this->settingsOption('switch', 'homepageJellyStatShowUsers', ['label' => 'Show User Statistics']),
  45. $this->settingsOption('switch', 'homepageJellyStatShowMostWatched', ['label' => 'Show Most Watched Content']),
  46. $this->settingsOption('switch', 'homepageJellyStatShowRecentActivity', ['label' => 'Show Recent Activity']),
  47. $this->settingsOption('number', 'homepageJellyStatMaxItems', ['label' => 'Maximum Items to Display', 'min' => 5, 'max' => 50]),
  48. ],
  49. 'Most Watched Content' => [
  50. $this->settingsOption('switch', 'homepageJellyStatShowMostWatchedMovies', ['label' => 'Show Most Watched Movies with Posters']),
  51. $this->settingsOption('switch', 'homepageJellyStatShowMostWatchedShows', ['label' => 'Show Most Watched TV Shows with Posters']),
  52. $this->settingsOption('switch', 'homepageJellyStatShowMostListenedMusic', ['label' => 'Show Most Listened Music with Cover Art']),
  53. $this->settingsOption('number', 'homepageJellyStatMostWatchedCount', ['label' => 'Number of Most Watched Items to Display', 'min' => 1, 'max' => 50]),
  54. ],
  55. 'Iframe Mode Options' => [
  56. $this->settingsOption('number', 'homepageJellyStatIframeHeight', ['label' => 'Iframe Height (pixels)', 'min' => 300, 'max' => 2000]),
  57. $this->settingsOption('switch', 'homepageJellyStatIframeScrolling', ['label' => 'Allow Scrolling in Iframe']),
  58. ],
  59. 'Test Connection' => [
  60. $this->settingsOption('blank', null, ['label' => 'Please Save before Testing']),
  61. $this->settingsOption('test', 'jellystat'),
  62. ]
  63. ]
  64. ];
  65. return array_merge($homepageInformation, $homepageSettings);
  66. }
  67. public function testConnectionJellyStat()
  68. {
  69. if (!$this->homepageItemPermissions($this->jellystatHomepagePermissions('test'), true)) {
  70. return false;
  71. }
  72. $url = $this->config['jellyStatURL'] ?? '';
  73. $token = $this->config['jellyStatApikey'] ?? '';
  74. $disableCert = $this->config['jellyStatDisableCertCheck'] ?? false;
  75. $customCert = $this->config['jellyStatUseCustomCertificate'] ?? false;
  76. if (empty($url)) {
  77. $this->setAPIResponse('error', 'JellyStat URL not configured', 500);
  78. return false;
  79. }
  80. $displayMode = $this->config['homepageJellyStatDisplayMode'] ?? 'native';
  81. if ($displayMode === 'iframe') {
  82. // For iframe mode, just test if the URL is reachable (use main URL for frontend)
  83. try {
  84. $options = $this->requestOptions($url, null, $disableCert, $customCert);
  85. $response = Requests::get($this->qualifyURL($url), [], $options);
  86. if ($response->success) {
  87. $this->setAPIResponse('success', 'Successfully connected to JellyStat', 200);
  88. return true;
  89. } else {
  90. $this->setAPIResponse('error', 'Failed to connect to JellyStat URL', 500);
  91. return false;
  92. }
  93. } catch (Exception $e) {
  94. $this->setAPIResponse('error', 'Connection test failed: ' . $e->getMessage(), 500);
  95. return false;
  96. }
  97. } else {
  98. // For native mode, test API connection
  99. if (empty($token)) {
  100. $this->setAPIResponse('error', 'JellyStat API key not configured for native mode', 500);
  101. return false;
  102. }
  103. try {
  104. // Use internal URL for server-side API calls if configured, otherwise use main URL
  105. $internalUrl = $this->config['jellyStatInternalURL'] ?? '';
  106. $apiUrl = !empty($internalUrl) ? $internalUrl : $url;
  107. $options = $this->requestOptions($apiUrl, null, $disableCert, $customCert);
  108. // Test JellyStat API - use query parameter authentication
  109. $testUrl = $this->qualifyURL($apiUrl) . '/api/getLibraries?apiKey=' . urlencode($token);
  110. $response = Requests::get($testUrl, [], $options);
  111. if ($response->success) {
  112. $data = json_decode($response->body, true);
  113. if (isset($data) && is_array($data) && !isset($data['error'])) {
  114. $this->setAPIResponse('success', 'Successfully connected to JellyStat API', 200);
  115. return true;
  116. }
  117. // Check if there's an error message in the response
  118. if (isset($data['error'])) {
  119. $this->writeLog('error', 'JellyStat API test error: ' . $data['error']);
  120. $this->setAPIResponse('error', 'JellyStat API error: ' . $data['error'], 500);
  121. return false;
  122. }
  123. // Log the actual response for debugging
  124. $this->writeLog('error', 'JellyStat API test: Valid HTTP response but invalid data format. Response: ' . substr($response->body, 0, 500));
  125. }
  126. // Log first endpoint failure details
  127. $firstError = "HTTP {$response->status_code}: " . substr($response->body, 0, 200);
  128. $this->writeLog('error', "JellyStat API test failed on /api/getLibraries: {$firstError}");
  129. // If libraries test failed, the API key is likely invalid
  130. $this->writeLog('error', 'JellyStat API key appears to be invalid or JellyStat API is not responding');
  131. // Try basic connection test to see if JellyStat is even running
  132. $response = Requests::get($this->qualifyURL($apiUrl), [], $options);
  133. if ($response->success) {
  134. $this->setAPIResponse('error', 'JellyStat is reachable but API key is invalid or API endpoints are not responding correctly.', 500);
  135. } else {
  136. $this->setAPIResponse('error', 'Cannot connect to JellyStat URL. Check URL and network connectivity.', 500);
  137. }
  138. return false;
  139. } catch (Exception $e) {
  140. $this->writeLog('error', 'JellyStat API test exception: ' . $e->getMessage());
  141. $this->setAPIResponse('error', 'Connection test failed: ' . $e->getMessage(), 500);
  142. return false;
  143. }
  144. }
  145. }
  146. public function jellystatHomepagePermissions($key = null)
  147. {
  148. $displayMode = $this->config['homepageJellyStatDisplayMode'] ?? 'native';
  149. // For iframe mode, only URL is required; for native mode, both URL and API key are required
  150. $requiredFields = ['jellyStatURL'];
  151. if ($displayMode === 'native') {
  152. $requiredFields[] = 'jellyStatApikey';
  153. }
  154. $permissions = [
  155. 'test' => [
  156. 'enabled' => [
  157. 'homepageJellyStatEnabled',
  158. ],
  159. 'auth' => [
  160. 'homepageJellyStatAuth',
  161. ],
  162. 'not_empty' => $requiredFields
  163. ],
  164. 'main' => [
  165. 'enabled' => [
  166. 'homepageJellyStatEnabled'
  167. ],
  168. 'auth' => [
  169. 'homepageJellyStatAuth'
  170. ],
  171. 'not_empty' => $requiredFields
  172. ]
  173. ];
  174. return $this->homepageCheckKeyPermissions($key, $permissions);
  175. }
  176. public function homepageOrderJellyStat()
  177. {
  178. if ($this->homepageItemPermissions($this->jellystatHomepagePermissions('main'))) {
  179. $displayMode = $this->config['homepageJellyStatDisplayMode'] ?? 'native';
  180. if ($displayMode === 'iframe') {
  181. return $this->renderJellyStatIframe();
  182. } else {
  183. return $this->renderJellyStatNative();
  184. }
  185. }
  186. }
  187. private function renderJellyStatIframe()
  188. {
  189. $url = $this->config['jellyStatURL'] ?? '';
  190. $height = $this->config['homepageJellyStatIframeHeight'] ?? 800;
  191. $scrolling = ($this->config['homepageJellyStatIframeScrolling'] ?? true) ? 'auto' : 'no';
  192. return '
  193. <div id="' . __FUNCTION__ . '">
  194. <div class="white-box">
  195. <div class="white-box-header">
  196. <i class="fa fa-bar-chart"></i> JellyStat Dashboard
  197. </div>
  198. <div class="white-box-content" style="padding: 0;">
  199. <iframe
  200. src="' . htmlspecialchars($this->qualifyURL($url)) . '"
  201. width="100%"
  202. height="' . intval($height) . 'px"
  203. style="border: none; border-radius: 0 0 4px 4px;"
  204. scrolling="' . $scrolling . '"
  205. frameborder="0">
  206. <p>Your browser does not support iframes. Please visit <a href="' . htmlspecialchars($url) . '" target="_blank">JellyStat</a> directly.</p>
  207. </iframe>
  208. </div>
  209. </div>
  210. </div>';
  211. }
  212. private function renderJellyStatNative()
  213. {
  214. $refreshInterval = ($this->config['homepageJellyStatRefresh'] ?? 5) * 60000; // Convert minutes to milliseconds
  215. $days = $this->config['homepageJellyStatDays'] ?? 30;
  216. $maxItems = $this->config['homepageJellyStatMaxItems'] ?? 10;
  217. $showLibraries = ($this->config['homepageJellyStatShowLibraries'] ?? true) ? 'true' : 'false';
  218. $showUsers = ($this->config['homepageJellyStatShowUsers'] ?? true) ? 'true' : 'false';
  219. $showMostWatched = ($this->config['homepageJellyStatShowMostWatched'] ?? true) ? 'true' : 'false';
  220. $showRecentActivity = ($this->config['homepageJellyStatShowRecentActivity'] ?? true) ? 'true' : 'false';
  221. $showMostWatchedMovies = ($this->config['homepageJellyStatShowMostWatchedMovies'] ?? true) ? 'true' : 'false';
  222. $showMostWatchedShows = ($this->config['homepageJellyStatShowMostWatchedShows'] ?? true) ? 'true' : 'false';
  223. $showMostListenedMusic = ($this->config['homepageJellyStatShowMostListenedMusic'] ?? true) ? 'true' : 'false';
  224. $mostWatchedCount = $this->config['homepageJellyStatMostWatchedCount'] ?? 10;
  225. $jellyStatUrl = htmlspecialchars($this->qualifyURL($this->config['jellyStatURL'] ?? ''), ENT_QUOTES, 'UTF-8');
  226. return '
  227. <div id="' . __FUNCTION__ . '" style="background: transparent; border: none; padding: 20px;">
  228. <div style="background: rgba(0,0,0,0.1); border-radius: 10px; padding: 20px; backdrop-filter: blur(10px);">
  229. <div style="margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 15px;">
  230. <h3 style="color: white; margin: 0; display: inline-block;"><i class="fa fa-bar-chart"></i> JellyStat Analytics</h3>
  231. <span class="pull-right">
  232. <small id="jellystat-last-update" style="color: rgba(255,255,255,0.7);"></small>
  233. <button class="btn btn-xs btn-primary" onclick="refreshJellyStatData()" title="Refresh Data" style="margin-left: 10px;">
  234. <i class="fa fa-refresh" id="jellystat-refresh-icon"></i>
  235. </button>
  236. </span>
  237. </div>
  238. <div>
  239. <div class="row" id="jellystat-content">
  240. <div class="col-lg-12 text-center">
  241. <i class="fa fa-spinner fa-spin" style="color: white;"></i> <span style="color: white;">Loading JellyStat data...</span>
  242. </div>
  243. </div>
  244. </div>
  245. </div>
  246. </div>
  247. <script>
  248. var jellyStatRefreshTimer;
  249. var jellyStatLastRefresh = 0;
  250. function refreshJellyStatData() {
  251. var refreshIcon = $("#jellystat-refresh-icon");
  252. refreshIcon.addClass("fa-spin");
  253. // Show loading state
  254. $("#jellystat-content").html("<div class=\"col-lg-12 text-center\"><i class=\"fa fa-spinner fa-spin\"></i> Loading JellyStat data...</div>");
  255. // Load JellyStat data
  256. getJellyStatData()
  257. .always(function() {
  258. refreshIcon.removeClass("fa-spin");
  259. jellyStatLastRefresh = Date.now();
  260. updateJellyStatLastRefreshTime();
  261. });
  262. }
  263. function updateJellyStatLastRefreshTime() {
  264. if (jellyStatLastRefresh > 0) {
  265. var ago = Math.floor((Date.now() - jellyStatLastRefresh) / 1000);
  266. var timeText = ago < 60 ? ago + "s ago" : Math.floor(ago / 60) + "m ago";
  267. $("#jellystat-last-update").text("Updated " + timeText);
  268. }
  269. }
  270. // Helper function to get icon for content type
  271. function getTypeIcon(collectionType) {
  272. switch(collectionType) {
  273. case "movies": return "fa-film";
  274. case "tvshows": return "fa-television";
  275. case "music": return "fa-music";
  276. case "mixed": return "fa-folder-open";
  277. default: return "fa-folder";
  278. }
  279. }
  280. // Helper function to format duration from ticks
  281. function formatJellyStatDuration(ticks) {
  282. if (!ticks || ticks === 0) return "0 min";
  283. // Convert ticks to seconds (ticks are in 100-nanosecond intervals)
  284. var seconds = ticks / 10000000;
  285. if (seconds < 60) {
  286. return Math.round(seconds) + " sec";
  287. } else if (seconds < 3600) {
  288. return Math.round(seconds / 60) + " min";
  289. } else if (seconds < 86400) {
  290. var hours = Math.floor(seconds / 3600);
  291. var minutes = Math.floor((seconds % 3600) / 60);
  292. return hours + "h " + minutes + "m";
  293. } else {
  294. var days = Math.floor(seconds / 86400);
  295. var hours = Math.floor((seconds % 86400) / 3600);
  296. return days + "d " + hours + "h";
  297. }
  298. }
  299. // Helper function to generate poster URLs from JellyStat/Jellyfin
  300. function getPosterUrl(posterPath, itemId, serverId) {
  301. console.log("getPosterUrl called with:", {posterPath, itemId, serverId});
  302. // Use external URL for frontend poster display to avoid mixed content issues
  303. var jellyStatUrl = ' . json_encode($jellyStatUrl) . ';
  304. console.log("JellyStat URL from config:", jellyStatUrl);
  305. if (!posterPath && !itemId) {
  306. console.log("No poster path or item ID provided");
  307. return null;
  308. }
  309. // If we have a poster path, process it
  310. if (posterPath) {
  311. console.log("Processing poster path:", posterPath);
  312. // If its already an absolute URL, use it directly
  313. if (posterPath.indexOf("http://") === 0 || posterPath.indexOf("https://") === 0) {
  314. console.log("Poster path is absolute URL:", posterPath);
  315. return posterPath;
  316. }
  317. // If its a relative path starting with /, prepend the JellyStat URL
  318. if (jellyStatUrl && posterPath.indexOf("/") === 0) {
  319. var fullUrl = jellyStatUrl + posterPath;
  320. console.log("Generated full URL from relative path:", fullUrl);
  321. return fullUrl;
  322. }
  323. }
  324. // If we have itemId, try to generate JellyStat image proxy URL
  325. if (itemId && jellyStatUrl) {
  326. // JellyStat uses /proxy/Items/Images/Primary endpoint
  327. // Format: /proxy/Items/Images/Primary?id={itemId}&fillWidth=200&quality=90
  328. var baseUrl = jellyStatUrl.replace(/\/+$/, ""); // Remove trailing slashes
  329. var apiUrl = baseUrl + "/proxy/Items/Images/Primary?id=" + itemId + "&fillWidth=200&quality=90";
  330. console.log("Generated JellyStat proxy image URL:", apiUrl);
  331. return apiUrl;
  332. }
  333. console.log("No valid poster URL could be generated");
  334. return null;
  335. }
  336. function getJellyStatData() {
  337. return organizrAPI2("GET", "api/v2/homepage/jellystat")
  338. .done(function(data) {
  339. console.log("JellyStat API Response:", data);
  340. if (data && data.response && data.response.result === "success" && data.response.data) {
  341. console.log("JellyStat Data:", data.response.data);
  342. renderJellyStatData(data.response.data);
  343. } else {
  344. console.error("JellyStat API Error:", data);
  345. var errorMsg = "Failed to load JellyStat data";
  346. if (data && data.response && data.response.message) {
  347. errorMsg += ": " + data.response.message;
  348. }
  349. $("#jellystat-content").html("<div class=\"col-lg-12 text-center text-danger\">" + errorMsg + "</div>");
  350. }
  351. })
  352. .fail(function(xhr, status, error) {
  353. console.error("JellyStat API Request Failed:", xhr, status, error);
  354. $("#jellystat-content").html("<div class=\"col-lg-12 text-center text-danger\">Error loading JellyStat data: " + error + "</div>");
  355. });
  356. }
  357. function renderJellyStatData(stats) {
  358. console.log("Rendering JellyStat data:", stats);
  359. var html = "";
  360. // Server Overview - Summary Stats
  361. if (stats.library_totals) {
  362. console.log("Library totals found:", stats.library_totals);
  363. html += "<div class=\"col-lg-12\" style=\"margin-bottom: 20px;\">";
  364. html += "<div class=\"row\">";
  365. // Total Libraries
  366. html += "<div class=\"col-sm-3\">";
  367. html += "<div class=\"small-box bg-blue\">";
  368. html += "<div class=\"inner\">";
  369. html += "<h3>" + (stats.library_totals.total_libraries || 0) + "</h3>";
  370. html += "<p>Libraries</p>";
  371. html += "</div>";
  372. html += "<div class=\"icon\"><i class=\"fa fa-folder\"></i></div>";
  373. html += "</div></div>";
  374. // Total Items
  375. html += "<div class=\"col-sm-3\">";
  376. html += "<div class=\"small-box bg-green\">";
  377. html += "<div class=\"inner\">";
  378. html += "<h3>" + (stats.library_totals.total_items || 0).toLocaleString() + "</h3>";
  379. html += "<p>Total Items</p>";
  380. html += "</div>";
  381. html += "<div class=\"icon\"><i class=\"fa fa-film\"></i></div>";
  382. html += "</div></div>";
  383. // Total Episodes (if any)
  384. if (stats.library_totals.total_episodes > 0) {
  385. html += "<div class=\"col-sm-3\">";
  386. html += "<div class=\"small-box bg-yellow\">";
  387. html += "<div class=\"inner\">";
  388. html += "<h3>" + (stats.library_totals.total_episodes || 0).toLocaleString() + "</h3>";
  389. html += "<p>Episodes</p>";
  390. html += "</div>";
  391. html += "<div class=\"icon\"><i class=\"fa fa-television\"></i></div>";
  392. html += "</div></div>";
  393. }
  394. // Total Play Time
  395. html += "<div class=\"col-sm-3\">";
  396. html += "<div class=\"small-box bg-red\">";
  397. html += "<div class=\"inner\">";
  398. html += "<h3 style=\"font-size: 18px;\">" + (stats.library_totals.total_play_time || "0 min") + "</h3>";
  399. html += "<p>Total Watched</p>";
  400. html += "</div>";
  401. html += "<div class=\"icon\"><i class=\"fa fa-clock-o\"></i></div>";
  402. html += "</div></div>";
  403. html += "</div></div>";
  404. }
  405. // Content Type Breakdown
  406. if (stats.library_totals && stats.library_totals.type_breakdown) {
  407. html += "<div class=\"col-lg-6\">";
  408. html += "<h5><i class=\"fa fa-pie-chart text-primary\"></i> Content Breakdown</h5>";
  409. html += "<div class=\"table-responsive\">";
  410. html += "<table class=\"table table-striped table-condensed\">";
  411. html += "<thead><tr><th>Type</th><th>Libraries</th><th>Items</th><th>Watch Time</th></tr></thead>";
  412. html += "<tbody>";
  413. Object.keys(stats.library_totals.type_breakdown).forEach(function(type) {
  414. var breakdown = stats.library_totals.type_breakdown[type];
  415. var playTimeFormatted = breakdown.play_time > 0 ? formatJellyStatDuration(breakdown.play_time) : "0 min";
  416. html += "<tr>";
  417. html += "<td><strong>" + breakdown.label + "</strong></td>";
  418. html += "<td><strong style=\"color: #5bc0de;\">" + breakdown.count + "</strong></td>";
  419. html += "<td><strong style=\"color: #5cb85c;\">" + breakdown.items.toLocaleString() + "</strong></td>";
  420. html += "<td><small>" + playTimeFormatted + "</small></td>";
  421. html += "</tr>";
  422. });
  423. html += "</tbody></table></div></div>";
  424. }
  425. // Detailed Library Statistics
  426. if (' . $showLibraries . ' && stats.libraries && stats.libraries.length > 0) {
  427. html += "<div class=\"col-lg-6\">";
  428. html += "<h5><i class=\"fa fa-folder text-info\"></i> Library Details</h5>";
  429. html += "<div class=\"table-responsive\">";
  430. html += "<table class=\"table table-striped table-condensed\">";
  431. html += "<thead><tr><th>Library</th><th>Type</th><th>Items</th><th>Watch Time</th></tr></thead>";
  432. html += "<tbody>";
  433. stats.libraries.slice(0, ' . $maxItems . ').forEach(function(lib) {
  434. var typeIcon = getTypeIcon(lib.collection_type);
  435. html += "<tr>";
  436. html += "<td><i class=\"fa " + typeIcon + " text-muted\"></i> <strong>" + (lib.name || "Unknown Library") + "</strong></td>";
  437. html += "<td><small>" + (lib.type || "Unknown") + "</small></td>";
  438. html += "<td><strong style=\"color: #337ab7;\">" + (lib.item_count || 0).toLocaleString() + "</strong>";
  439. // Show additional counts for TV libraries
  440. if (lib.episode_count > 0) {
  441. html += "<br><small class=\"text-muted\">Episodes: <strong style=\"color: #337ab7;\">" + lib.episode_count.toLocaleString() + "</strong></small>";
  442. }
  443. if (lib.season_count > 0) {
  444. html += "<br><small class=\"text-muted\">Seasons: <strong style=\"color: #337ab7;\">" + lib.season_count.toLocaleString() + "</strong></small>";
  445. }
  446. html += "</td>";
  447. html += "<td><small>" + (lib.total_play_time || "0 min") + "</small></td>";
  448. html += "</tr>";
  449. });
  450. html += "</tbody></table></div></div>";
  451. }
  452. // User Statistics
  453. if (' . $showUsers . ' && stats.users && stats.users.length > 0) {
  454. html += "<div class=\"col-lg-6\">";
  455. html += "<h5><i class=\"fa fa-users\"></i> Active Users (" + stats.users.length + " total)</h5>";
  456. html += "<div class=\"row\">";
  457. stats.users.slice(0, 8).forEach(function(user) {
  458. var lastActivity = "Never";
  459. if (user.last_activity && user.last_activity !== "0001-01-01T00:00:00.0000000Z") {
  460. var activityDate = new Date(user.last_activity);
  461. lastActivity = activityDate.toLocaleDateString();
  462. }
  463. var playCount = user.play_count || 0;
  464. html += "<div class=\"col-md-6 col-sm-6\" style=\"margin-bottom: 10px;\">";
  465. html += "<div class=\"media\">";
  466. html += "<div class=\"media-left\"><i class=\"fa fa-user fa-2x text-muted\"></i></div>";
  467. html += "<div class=\"media-body\">";
  468. html += "<h6 class=\"media-heading\">" + (user.name || "Unknown User") + " <strong style=\"color: #5bc0de;\">" + playCount + " plays</strong></h6>";
  469. html += "<small class=\"text-muted\">Last Activity: " + lastActivity + "</small>";
  470. html += "</div></div></div>";
  471. });
  472. html += "</div></div>";
  473. }
  474. // Most Watched Content
  475. if (' . $showMostWatched . ' && stats.most_watched && stats.most_watched.length > 0) {
  476. html += "<div class=\"col-lg-12\" style=\"margin-top: 20px;\">";
  477. html += "<h5><i class=\"fa fa-star text-warning\"></i> Most Watched Content</h5>";
  478. html += "<div class=\"table-responsive\">";
  479. html += "<table class=\"table table-striped table-condensed\">";
  480. html += "<thead><tr><th>Title</th><th>Type</th><th>Plays</th><th>Runtime</th><th>Year</th></tr></thead>";
  481. html += "<tbody>";
  482. stats.most_watched.slice(0, ' . $maxItems . ').forEach(function(item) {
  483. html += "<tr>";
  484. html += "<td><strong>" + (item.title || "Unknown Title") + "</strong></td>";
  485. html += "<td>" + (item.type || "Unknown") + "</td>";
  486. html += "<td><strong style=\"color: #337ab7;\">" + (item.play_count || 0) + "</strong></td>";
  487. html += "<td>" + (item.runtime || "Unknown") + "</td>";
  488. html += "<td>" + (item.year && item.year !== "N/A" ? item.year : "") + "</td>";
  489. html += "</tr>";
  490. });
  491. html += "</tbody></table></div></div>";
  492. }
  493. // Recent Activity
  494. if (' . $showRecentActivity . ' && stats.recent_activity && stats.recent_activity.length > 0) {
  495. html += "<div class=\"col-lg-12\" style=\"margin-top: 20px;\">";
  496. html += "<h5><i class=\"fa fa-clock-o text-success\"></i> Recent Activity</h5>";
  497. html += "<div class=\"table-responsive\">";
  498. html += "<table class=\"table table-striped table-condensed\">";
  499. html += "<thead><tr><th>Date</th><th>User</th><th>Title</th><th>Type</th></tr></thead>";
  500. html += "<tbody>";
  501. stats.recent_activity.slice(0, ' . $maxItems . ').forEach(function(activity) {
  502. var date = new Date(activity.date);
  503. var formattedDate = date.toLocaleDateString() + " " + date.toLocaleTimeString([], {hour: "2-digit", minute:"2-digit"});
  504. html += "<tr>";
  505. html += "<td><small>" + formattedDate + "</small></td>";
  506. html += "<td>" + (activity.user || "Unknown User") + "</td>";
  507. html += "<td><strong>" + (activity.title || "Unknown Title") + "</strong></td>";
  508. html += "<td>" + (activity.type || "Unknown") + "</td>";
  509. html += "</tr>";
  510. });
  511. html += "</tbody></table></div></div>";
  512. }
  513. // Debug data availability
  514. console.log("Full stats object:", stats);
  515. console.log("Movie settings enabled:", ' . $showMostWatchedMovies . ');
  516. console.log("Movies data:", stats.most_watched_movies);
  517. console.log("Shows data:", stats.most_watched_shows);
  518. console.log("Music data:", stats.most_listened_music);
  519. // Most Watched Movies with Posters
  520. if (' . $showMostWatchedMovies . ' && stats.most_watched_movies && stats.most_watched_movies.length > 0) {
  521. console.log("Rendering most watched movies:", stats.most_watched_movies);
  522. html += "<div class=\"col-lg-12\" style=\"margin-top: 30px;\">";
  523. html += "<h5><i class=\"fa fa-film text-primary\"></i> Most Watched Movies</h5>";
  524. html += "<div style=\"margin-top: 15px; overflow-x: auto; overflow-y: hidden; white-space: nowrap; padding-bottom: 10px; scrollbar-width: thin; scrollbar-color: rgba(255,255,255,0.3) transparent;\">";
  525. html += "<style>div::-webkit-scrollbar { height: 8px; } div::-webkit-scrollbar-track { background: rgba(255,255,255,0.1); border-radius: 4px; } div::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.3); border-radius: 4px; } div::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.5); }</style>";
  526. stats.most_watched_movies.forEach(function(movie) {
  527. console.log("Processing movie:", movie);
  528. console.log("Movie poster_path:", movie.poster_path);
  529. console.log("Movie id:", movie.id);
  530. console.log("Movie server_id:", movie.server_id);
  531. var posterUrl = getPosterUrl(movie.poster_path, movie.id, movie.server_id);
  532. console.log("Generated posterUrl:", posterUrl);
  533. var playCount = movie.play_count || 0;
  534. var year = movie.year && movie.year !== "N/A" ? movie.year : "";
  535. var title = movie.title || "Unknown Movie";
  536. html += "<div style=\"display: inline-block; margin: 0 10px 0 0; width: 150px; vertical-align: top;\">";
  537. html += "<div class=\"poster-card jellystat-metadata-trigger\" style=\"position: relative; width: 150px; height: 225px; transition: transform 0.2s ease; cursor: pointer;\" data-title=\"" + title + "\" data-year=\"" + year + "\" data-plays=\"" + playCount + "\" data-type=\"Movie\" data-id=\"movie-" + movie.id + "\">";
  538. // Poster image container
  539. html += "<div class=\"poster-image\" style=\"position: relative; width: 150px; height: 225px; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.3);\">";
  540. // Hover overlay with title and year - initially hidden
  541. html += "<div class=\"poster-overlay\" style=\"position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(transparent, rgba(0,0,0,0.8)); color: white; padding: 20px 10px 10px; opacity: 0; transition: opacity 0.3s ease; pointer-events: none;\">";
  542. html += "<div style=\"font-size: 12px; font-weight: bold; line-height: 1.3; margin-bottom: 4px; text-shadow: 1px 1px 2px rgba(0,0,0,0.9); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;\" title=\"" + title + "\">" + title + "</div>";
  543. if (year && year !== "N/A") {
  544. html += "<small style=\"color: rgba(255,255,255,0.8); text-shadow: 1px 1px 2px rgba(0,0,0,0.9); line-height: 1.2;\">" + year + "</small>";
  545. }
  546. html += "</div>";
  547. if (posterUrl) {
  548. html += "<img src=\"" + posterUrl + "\" alt=\"" + title + "\" style=\"width: 150px; height: 225px; object-fit: cover;\" onerror=\"this.style.display=\"none\"; this.nextElementSibling.style.display=\"flex\";\">";
  549. }
  550. html += "<div class=\"poster-placeholder\" style=\"position: absolute; top: 0; left: 0; width: 150px; height: 225px; display: " + (posterUrl ? "none" : "flex") + "; align-items: center; justify-content: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;\">";
  551. html += "<i class=\"fa fa-film fa-3x\"></i>";
  552. html += "</div>";
  553. // Play count badge
  554. html += "<div class=\"play-count-badge\" style=\"position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.8); color: white; padding: 4px 8px; border-radius: 12px; font-size: 11px; backdrop-filter: blur(4px);\">";
  555. html += "<i class=\"fa fa-play\"></i> " + playCount;
  556. html += "</div>";
  557. html += "</div>";
  558. // Add CSS for hover effect - this will be applied once when the first poster is rendered
  559. if (movie === stats.most_watched_movies[0]) {
  560. html += "<style>";
  561. html += ".poster-card:hover .poster-overlay { opacity: 1 !important; }";
  562. html += ".poster-card:hover { transform: scale(1.05); z-index: 10; }";
  563. html += "</style>";
  564. }
  565. // Add hidden metadata popup div for this movie
  566. html += "<div class=\"movie-" + movie.id + "-metadata-info hidden\"></div>";
  567. html += "<a class=\"movie-" + movie.id + " hidden\" data-toggle=\"modal\" data-target=\"#database\"></a>";
  568. html += "</div></div>";
  569. });
  570. html += "</div></div>";
  571. } else {
  572. console.log("Movies not showing because:");
  573. console.log("- Setting enabled:", ' . $showMostWatchedMovies . ');
  574. console.log("- Has data:", stats.most_watched_movies && stats.most_watched_movies.length > 0);
  575. console.log("- Data:", stats.most_watched_movies);
  576. }
  577. // Most Watched TV Shows with Posters
  578. if (' . $showMostWatchedShows . ' && stats.most_watched_shows && stats.most_watched_shows.length > 0) {
  579. html += "<div class=\"col-lg-12\" style=\"margin-top: 30px;\">";
  580. html += "<h5><i class=\"fa fa-television text-info\"></i> Most Watched TV Shows</h5>";
  581. html += "<div style=\"margin-top: 15px; overflow-x: auto; overflow-y: hidden; white-space: nowrap; padding-bottom: 10px; scrollbar-width: thin; scrollbar-color: rgba(255,255,255,0.3) transparent;\">";
  582. html += "<style>div::-webkit-scrollbar { height: 8px; } div::-webkit-scrollbar-track { background: rgba(255,255,255,0.1); border-radius: 4px; } div::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.3); border-radius: 4px; } div::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.5); }</style>";
  583. stats.most_watched_shows.forEach(function(show) {
  584. var posterUrl = getPosterUrl(show.poster_path, show.id, show.server_id);
  585. var playCount = show.play_count || 0;
  586. var year = show.year && show.year !== "N/A" ? show.year : "";
  587. var title = show.title || "Unknown Show";
  588. html += "<div style=\"display: inline-block; margin: 0 10px 0 0; width: 150px; vertical-align: top;\">";
  589. html += "<div class=\"poster-card jellystat-metadata-trigger\" style=\"position: relative; width: 150px; height: 225px; transition: transform 0.2s ease; cursor: pointer;\" data-title=\"" + title + "\" data-year=\"" + year + "\" data-plays=\"" + playCount + "\" data-type=\"TV Show\" data-id=\"show-" + show.id + "\">";
  590. // Poster image container
  591. html += "<div class=\"poster-image\" style=\"position: relative; width: 150px; height: 225px; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.3);\">";
  592. // Hover overlay with title and year - initially hidden
  593. html += "<div class=\"poster-overlay\" style=\"position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(transparent, rgba(0,0,0,0.8)); color: white; padding: 20px 10px 10px; opacity: 0; transition: opacity 0.3s ease; pointer-events: none;\">";
  594. html += "<div style=\"font-size: 12px; font-weight: bold; line-height: 1.3; margin-bottom: 4px; text-shadow: 1px 1px 2px rgba(0,0,0,0.9); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;\" title=\"" + title + "\">" + title + "</div>";
  595. if (year && year !== "N/A") {
  596. html += "<small style=\"color: rgba(255,255,255,0.8); text-shadow: 1px 1px 2px rgba(0,0,0,0.9); line-height: 1.2;\">" + year + "</small>";
  597. }
  598. html += "</div>";
  599. if (posterUrl) {
  600. html += "<img src=\"" + posterUrl + "\" alt=\"" + title + "\" style=\"width: 150px; height: 225px; object-fit: cover;\" onerror=\"this.style.display=\"none\"; this.nextElementSibling.style.display=\"flex\";\">";
  601. }
  602. html += "<div class=\"poster-placeholder\" style=\"position: absolute; top: 0; left: 0; width: 150px; height: 225px; display: " + (posterUrl ? "none" : "flex") + "; align-items: center; justify-content: center; background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%); color: white;\">";
  603. html += "<i class=\"fa fa-television fa-3x\"></i>";
  604. html += "</div>";
  605. // Play count badge
  606. html += "<div class=\"play-count-badge\" style=\"position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.8); color: white; padding: 4px 8px; border-radius: 12px; font-size: 11px; backdrop-filter: blur(4px);\">";
  607. html += "<i class=\"fa fa-play\"></i> " + playCount;
  608. html += "</div>";
  609. html += "</div>";
  610. // Add CSS for hover effect - this will be applied once when the first poster is rendered
  611. if (show === stats.most_watched_shows[0]) {
  612. html += "<style>";
  613. html += ".poster-card:hover .poster-overlay { opacity: 1 !important; }";
  614. html += ".poster-card:hover { transform: scale(1.05); z-index: 10; }";
  615. html += "</style>";
  616. }
  617. // Add hidden metadata popup div for this show
  618. html += "<div class=\"show-" + show.id + "-metadata-info hidden\"></div>";
  619. html += "<a class=\"show-" + show.id + " hidden\" data-toggle=\"modal\" data-target=\"#database\"></a>";
  620. html += "</div></div>";
  621. });
  622. html += "</div></div>";
  623. }
  624. // Most Listened Music with Cover Art
  625. if (' . $showMostListenedMusic . ' && stats.most_listened_music && stats.most_listened_music.length > 0) {
  626. html += "<div class=\"col-lg-12\" style=\"margin-top: 30px;\">";
  627. html += "<h5><i class=\"fa fa-music text-success\"></i> Most Listened Music</h5>";
  628. html += "<div class=\"row\" style=\"margin-top: 15px;\">";
  629. stats.most_listened_music.forEach(function(music) {
  630. var posterUrl = getPosterUrl(music.poster_path || music.cover_art, music.id, music.server_id);
  631. var playCount = music.play_count || 0;
  632. var artist = music.artist || "Unknown Artist";
  633. var title = music.title || music.album || "Unknown";
  634. html += "<div class=\"col-lg-2 col-md-3 col-sm-4 col-xs-6\" style=\"margin-bottom: 20px;\">";
  635. html += "<div class=\"poster-card\" style=\"position: relative; transition: transform 0.2s ease;\">";
  636. // Cover art
  637. html += "<div class=\"poster-image\" style=\"position: relative; padding-top: 100%; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.3);\">";
  638. if (posterUrl) {
  639. html += "<img src=\"" + posterUrl + "\" alt=\"" + title + "\" style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover;\" onerror=\"this.style.display=\"none\"; this.nextElementSibling.style.display=\"flex\";\">";
  640. }
  641. html += "<div class=\"poster-placeholder\" style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: " + (posterUrl ? "none" : "flex") + "; align-items: center; justify-content: center; background: linear-gradient(135deg, #fd79a8 0%, #e84393 100%); color: white;\">";
  642. html += "<i class=\"fa fa-music fa-3x\"></i>";
  643. html += "</div>";
  644. // Play count badge
  645. html += "<div class=\"play-count-badge\" style=\"position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.8); color: white; padding: 4px 8px; border-radius: 12px; font-size: 11px; backdrop-filter: blur(4px);\">";
  646. html += "<i class=\"fa fa-play\"></i> " + playCount;
  647. html += "</div>";
  648. html += "</div>";
  649. // Music info with transparent background and white text
  650. html += "<div class=\"poster-info\" style=\"padding: 12px 8px; text-align: center;\">";
  651. html += "<h6 style=\"margin: 0 0 4px 0; font-size: 13px; font-weight: bold; line-height: 1.2; height: 32px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.8);\" title=\"" + title + "\">" + title + "</h6>";
  652. html += "<small style=\"color: rgba(255,255,255,0.8); text-shadow: 1px 1px 2px rgba(0,0,0,0.8);\">" + artist + "</small>";
  653. html += "</div>";
  654. html += "</div></div>";
  655. });
  656. html += "</div></div>";
  657. }
  658. if (!html) {
  659. html = "<div class=\"col-lg-12 text-center text-muted\">";
  660. html += "<i class=\"fa fa-exclamation-circle fa-3x\" style=\"margin-bottom: 10px;\"></i>";
  661. html += "<h4>No JellyStat data available</h4>";
  662. html += "<p>Check your JellyStat connection and API configuration.</p>";
  663. html += "</div>";
  664. }
  665. $("#jellystat-content").html(html);
  666. }
  667. // Auto-refresh setup
  668. var refreshInterval = ' . $refreshInterval . ';
  669. if (refreshInterval > 0) {
  670. jellyStatRefreshTimer = setInterval(function() {
  671. refreshJellyStatData();
  672. }, refreshInterval);
  673. }
  674. // Update time display every 30 seconds
  675. setInterval(updateJellyStatLastRefreshTime, 30000);
  676. // Initial load
  677. $(document).ready(function() {
  678. refreshJellyStatData();
  679. });
  680. // Cleanup timer when page unloads
  681. $(window).on("beforeunload", function() {
  682. if (jellyStatRefreshTimer) {
  683. clearInterval(jellyStatRefreshTimer);
  684. }
  685. });
  686. // Add click handler for metadata popups
  687. $(document).on(\'click\', \'.jellystat-metadata-trigger\', function(e) {
  688. e.preventDefault();
  689. e.stopPropagation();
  690. var title = $(this).data(\'title\');
  691. var year = $(this).data(\'year\');
  692. var plays = $(this).data(\'plays\');
  693. var type = $(this).data(\'type\');
  694. var id = $(this).data(\'id\');
  695. if (title && id) {
  696. var metadataHtml = buildJellyStatMetadata(title, year, plays, type);
  697. $(\'.\' + id + \'-metadata-info\').html(metadataHtml);
  698. $(\'.\' + id).trigger(\'click\');
  699. }
  700. });
  701. // Function to build metadata popup HTML
  702. function buildJellyStatMetadata(title, year, plays, type) {
  703. var html = \'<div class="modal-body">\';
  704. html += \'<div class="row">\';
  705. html += \'<div class="col-sm-12">\';
  706. html += \'<h4><strong>\' + title + \'</strong>\';
  707. if (year && year !== \'N/A\' && year !== \'\') {
  708. html += \' (\' + year + \')\';
  709. }
  710. html += \'</h4>\';
  711. html += \'<hr>\';
  712. html += \'<p><strong>Type:</strong> \' + type + \'</p>\';
  713. html += \'<p><strong>Total Plays:</strong> \' + plays + \'</p>\';
  714. html += \'<p><strong>Source:</strong> JellyStat Analytics</p>\';
  715. html += \'<p class="text-muted">This data is collected from JellyStat viewing history and may include plays from all users.</p>\';
  716. html += \'</div>\';
  717. html += \'</div>\';
  718. html += \'</div>\';
  719. return html;
  720. }
  721. </script>
  722. ';
  723. }
  724. /**
  725. * Main function to get JellyStat data
  726. */
  727. public function getJellyStatData($options = null)
  728. {
  729. if (!$this->homepageItemPermissions($this->jellystatHomepagePermissions('main'), true)) {
  730. $this->setAPIResponse('error', 'User not approved to view this homepage item - check plugin configuration', 401);
  731. return false;
  732. }
  733. try {
  734. $url = $this->config['jellyStatURL'] ?? '';
  735. $token = $this->config['jellyStatApikey'] ?? '';
  736. $days = intval($this->config['homepageJellyStatDays'] ?? 30);
  737. if (empty($url) || empty($token)) {
  738. $this->setAPIResponse('error', 'JellyStat URL or API key not configured', 500);
  739. return false;
  740. }
  741. $stats = $this->fetchJellyStatStats($url, $token, $days);
  742. if (isset($stats['error']) && $stats['error']) {
  743. $this->setAPIResponse('error', $stats['message'], 500);
  744. return false;
  745. }
  746. $this->setAPIResponse('success', 'JellyStat data retrieved successfully', 200, $stats);
  747. return true;
  748. } catch (Exception $e) {
  749. $this->setAPIResponse('error', 'Failed to retrieve JellyStat data: ' . $e->getMessage(), 500);
  750. return false;
  751. }
  752. }
  753. /**
  754. * Fetch statistics from JellyStat API
  755. */
  756. private function fetchJellyStatStats($url, $token, $days = 30)
  757. {
  758. $disableCert = $this->config['jellyStatDisableCertCheck'] ?? false;
  759. $customCert = $this->config['jellyStatUseCustomCertificate'] ?? false;
  760. // Use internal URL for server-side API calls if configured, otherwise use main URL
  761. $internalUrl = $this->config['jellyStatInternalURL'] ?? '';
  762. $apiUrl = !empty($internalUrl) ? $internalUrl : $url;
  763. $options = $this->requestOptions($apiUrl, null, $disableCert, $customCert);
  764. $baseUrl = $this->qualifyURL($apiUrl);
  765. $stats = [
  766. 'period' => "{$days} days",
  767. 'libraries' => [],
  768. 'library_totals' => [],
  769. 'server_info' => [],
  770. 'most_watched_movies' => [],
  771. 'most_watched_shows' => [],
  772. 'most_listened_music' => []
  773. ];
  774. $mostWatchedCount = $this->config['homepageJellyStatMostWatchedCount'] ?? 10;
  775. try {
  776. // Get Library Statistics - use query parameter authentication
  777. $librariesUrl = $baseUrl . '/api/getLibraries?apiKey=' . urlencode($token);
  778. $response = Requests::get($librariesUrl, [], $options);
  779. if ($response->success) {
  780. $data = json_decode($response->body, true);
  781. if (is_array($data) && !isset($data['error'])) {
  782. // Process individual libraries
  783. $stats['libraries'] = array_map(function($lib) {
  784. return [
  785. 'name' => $lib['Name'] ?? 'Unknown Library',
  786. 'type' => $this->getCollectionTypeLabel($lib['CollectionType'] ?? 'unknown'),
  787. 'item_count' => $lib['item_count'] ?? 0,
  788. 'season_count' => $lib['season_count'] ?? 0,
  789. 'episode_count' => $lib['episode_count'] ?? 0,
  790. 'total_play_time' => $lib['total_play_time'] ? $this->formatJellyStatDuration($lib['total_play_time']) : '0 min',
  791. 'play_time_raw' => $lib['total_play_time'] ?? 0,
  792. 'collection_type' => $lib['CollectionType'] ?? 'unknown'
  793. ];
  794. }, $data);
  795. // Calculate totals across all libraries
  796. $totalItems = array_sum(array_column($data, 'item_count'));
  797. $totalSeasons = array_sum(array_column($data, 'season_count'));
  798. $totalEpisodes = array_sum(array_column($data, 'episode_count'));
  799. $totalPlayTime = array_sum(array_column($data, 'total_play_time'));
  800. // Calculate library type breakdowns
  801. $typeBreakdown = [];
  802. foreach ($data as $lib) {
  803. $type = $lib['CollectionType'] ?? 'unknown';
  804. if (!isset($typeBreakdown[$type])) {
  805. $typeBreakdown[$type] = [
  806. 'count' => 0,
  807. 'items' => 0,
  808. 'play_time' => 0,
  809. 'label' => $this->getCollectionTypeLabel($type)
  810. ];
  811. }
  812. $typeBreakdown[$type]['count']++;
  813. $typeBreakdown[$type]['items'] += $lib['item_count'] ?? 0;
  814. $typeBreakdown[$type]['play_time'] += $lib['total_play_time'] ?? 0;
  815. }
  816. $stats['library_totals'] = [
  817. 'total_libraries' => count($data),
  818. 'total_items' => $totalItems,
  819. 'total_seasons' => $totalSeasons,
  820. 'total_episodes' => $totalEpisodes,
  821. 'total_play_time' => $this->formatJellyStatDuration($totalPlayTime),
  822. 'total_play_time_raw' => $totalPlayTime,
  823. 'type_breakdown' => $typeBreakdown
  824. ];
  825. // Server information
  826. $stats['server_info'] = [
  827. 'server_id' => $data[0]['ServerId'] ?? 'Unknown',
  828. 'last_updated' => date('c')
  829. ];
  830. }
  831. }
  832. // Get History data and process to extract most watched content
  833. // Calculate the start date based on the configured days period
  834. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  835. // Fetch ALL history data using pagination to ensure complete play counts
  836. $allHistoryResults = $this->fetchAllJellyStatHistory($baseUrl, $token, $startDate, $options);
  837. if (!empty($allHistoryResults)) {
  838. // Process history to get most watched content
  839. $processedData = $this->processJellyStatHistory($allHistoryResults);
  840. // Extract most watched items based on user settings
  841. if ($this->config['homepageJellyStatShowMostWatchedMovies'] ?? false) {
  842. $stats['most_watched_movies'] = array_slice($processedData['movies'], 0, $mostWatchedCount);
  843. }
  844. if ($this->config['homepageJellyStatShowMostWatchedShows'] ?? false) {
  845. $stats['most_watched_shows'] = array_slice($processedData['shows'], 0, $mostWatchedCount);
  846. }
  847. if ($this->config['homepageJellyStatShowMostListenedMusic'] ?? false) {
  848. $stats['most_listened_music'] = array_slice($processedData['music'], 0, $mostWatchedCount);
  849. }
  850. }
  851. } catch (Exception $e) {
  852. return ['error' => true, 'message' => 'Failed to fetch JellyStat data: ' . $e->getMessage()];
  853. }
  854. return $stats;
  855. }
  856. /**
  857. * Fetch all history from JellyStat using pagination
  858. */
  859. private function fetchAllJellyStatHistory($baseUrl, $token, $startDate, $options)
  860. {
  861. $allResults = [];
  862. $page = 1;
  863. $pageSize = 1000; // API page size limit
  864. do {
  865. $historyUrl = $baseUrl . '/api/getHistory?apiKey=' . urlencode($token) .
  866. '&page=' . $page .
  867. '&size=' . $pageSize .
  868. '&startDate=' . urlencode($startDate);
  869. $response = Requests::get($historyUrl, [], $options);
  870. if (!$response->success) {
  871. // Stop if there is an error
  872. break;
  873. }
  874. $data = json_decode($response->body, true);
  875. if (!isset($data['results']) || !is_array($data['results']) || empty($data['results'])) {
  876. // No more results, break the loop
  877. break;
  878. }
  879. $allResults = array_merge($allResults, $data['results']);
  880. $page++;
  881. } while (count($data['results']) == $pageSize);
  882. return $allResults;
  883. }
  884. /**
  885. * Get human-readable label for collection type
  886. */
  887. private function getCollectionTypeLabel($type)
  888. {
  889. $labels = [
  890. 'movies' => 'Movies',
  891. 'tvshows' => 'TV Shows',
  892. 'music' => 'Music',
  893. 'mixed' => 'Mixed Content',
  894. 'unknown' => 'Other'
  895. ];
  896. return $labels[$type] ?? ucfirst($type);
  897. }
  898. /**
  899. * Format bytes to human readable format
  900. */
  901. private function formatBytes($size, $precision = 2)
  902. {
  903. if ($size == 0) return '0 B';
  904. $base = log($size, 1024);
  905. $suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
  906. return round(pow(1024, $base - floor($base)), $precision) . ' ' . $suffixes[floor($base)];
  907. }
  908. /**
  909. * Format duration for display (JellyStat specific)
  910. */
  911. private function formatJellyStatDuration($ticks)
  912. {
  913. if ($ticks == 0) return 'Unknown';
  914. // Convert ticks to seconds (ticks are in 100-nanosecond intervals)
  915. $seconds = $ticks / 10000000;
  916. if ($seconds < 3600) {
  917. return gmdate('i:s', $seconds);
  918. } else {
  919. return gmdate('H:i:s', $seconds);
  920. }
  921. }
  922. /**
  923. * Process JellyStat history data to extract most watched content
  924. */
  925. private function processJellyStatHistory($historyResults)
  926. {
  927. $processed = [
  928. 'movies' => [],
  929. 'shows' => [],
  930. 'music' => []
  931. ];
  932. // Group items by ID and count plays
  933. $itemStats = [];
  934. // Debug: Log sample of first few results to understand data structure
  935. $this->setLoggerChannel('JellyStat')->info('JellyStat History Debug: Processing ' . count($historyResults) . ' history records');
  936. if (count($historyResults) > 0) {
  937. $this->setLoggerChannel('JellyStat')->info('JellyStat Sample Record: ' . json_encode(array_slice($historyResults, 0, 3), JSON_PRETTY_PRINT));
  938. }
  939. foreach ($historyResults as $index => $result) {
  940. // Determine content type based on available data
  941. $contentType = 'unknown';
  942. $itemId = null;
  943. $title = 'Unknown';
  944. $year = null;
  945. $serverId = $result['ServerId'] ?? null;
  946. // Check if it's a TV show (has SeriesName)
  947. if (!empty($result['SeriesName'])) {
  948. $contentType = 'show';
  949. $itemId = $result['SeriesName']; // Use series name as unique identifier
  950. $title = $result['SeriesName'];
  951. // Try to extract year from multiple possible sources for TV shows
  952. // 1. Check for SeriesProductionYear or ProductionYear fields
  953. if (!empty($result['SeriesProductionYear'])) {
  954. $year = (string)$result['SeriesProductionYear'];
  955. } elseif (!empty($result['ProductionYear'])) {
  956. $year = (string)$result['ProductionYear'];
  957. } elseif (!empty($result['PremiereDate'])) {
  958. // Extract year from premiere date
  959. $year = date('Y', strtotime($result['PremiereDate']));
  960. } else {
  961. // 2. Try to extract year from series name (e.g., "Show Name (2019)")
  962. if (preg_match('/\((19|20)\d{2}\)/', $title, $matches)) {
  963. $year = trim($matches[0], '()');
  964. $title = trim(str_replace($matches[0], '', $title));
  965. } elseif (!empty($result['EpisodeName'])) {
  966. // 3. As a last resort, try to extract year from episode name
  967. $episodeTitle = $result['EpisodeName'];
  968. if (preg_match('/\b(19|20)\d{2}\b/', $episodeTitle, $matches)) {
  969. $year = $matches[0];
  970. }
  971. }
  972. }
  973. }
  974. // Check if it's a movie (has NowPlayingItemName but no SeriesName)
  975. elseif (!empty($result['NowPlayingItemName']) && empty($result['SeriesName'])) {
  976. // Determine if it's likely a movie or music based on duration or other hints
  977. $itemName = $result['NowPlayingItemName'];
  978. $duration = $result['PlaybackDuration'] ?? 0;
  979. // If duration is very short (< 10 minutes) and no video streams, likely music
  980. $hasVideo = false;
  981. if (isset($result['MediaStreams']) && is_array($result['MediaStreams'])) {
  982. foreach ($result['MediaStreams'] as $stream) {
  983. if (($stream['Type'] ?? '') === 'Video') {
  984. $hasVideo = true;
  985. break;
  986. }
  987. }
  988. }
  989. if (!$hasVideo || $duration < 600) { // Less than 10 minutes and no video = likely music
  990. $contentType = 'music';
  991. $title = $itemName;
  992. // For music, try to extract artist info
  993. // Music tracks might have format like "Artist - Song" or just "Song"
  994. } else {
  995. $contentType = 'movie';
  996. $title = $itemName;
  997. // Try to extract year from multiple possible sources for movies
  998. // 1. Check for ProductionYear field first
  999. if (!empty($result['ProductionYear'])) {
  1000. $year = (string)$result['ProductionYear'];
  1001. } elseif (!empty($result['PremiereDate'])) {
  1002. // Extract year from premiere date
  1003. $year = date('Y', strtotime($result['PremiereDate']));
  1004. } else {
  1005. // 2. Try to extract year from movie title (e.g., "Movie Title (2019)")
  1006. if (preg_match('/\((19|20)\d{2}\)/', $title, $matches)) {
  1007. $year = trim($matches[0], '()');
  1008. $title = trim(str_replace($matches[0], '', $title));
  1009. }
  1010. }
  1011. }
  1012. $itemId = $result['NowPlayingItemId'] ?? $itemName;
  1013. }
  1014. if ($itemId && $contentType !== 'unknown') {
  1015. $key = $contentType . '_' . $itemId;
  1016. if (!isset($itemStats[$key])) {
  1017. // Extract poster/image information from JellyStat API response
  1018. $posterPath = null;
  1019. $actualItemId = null;
  1020. // Get the actual Jellyfin/Emby item ID for poster generation
  1021. // Note: JellyStat history API doesn't provide poster paths directly,
  1022. // so we'll use item IDs with JellyStat's image proxy API
  1023. if ($contentType === 'movie') {
  1024. // For movies, use the NowPlayingItemId
  1025. $actualItemId = $result['NowPlayingItemId'] ?? null;
  1026. } elseif ($contentType === 'show') {
  1027. // Debug: Log all available IDs for TV shows to understand data structure
  1028. $this->setLoggerChannel('JellyStat')->info("JellyStat TV Show Debug - Series: {$result['SeriesName']}");
  1029. $this->setLoggerChannel('JellyStat')->info("Available IDs: SeriesId=" . ($result['SeriesId'] ?? 'null') .
  1030. ", ShowId=" . ($result['ShowId'] ?? 'null') .
  1031. ", ParentId=" . ($result['ParentId'] ?? 'null') .
  1032. ", NowPlayingItemId=" . ($result['NowPlayingItemId'] ?? 'null'));
  1033. // For TV shows, be more selective about ID selection to ensure we get series posters
  1034. // Priority: SeriesId (if exists) > ShowId > NowPlayingItemId (only if it looks like series) > ParentId
  1035. $actualItemId = null;
  1036. if (!empty($result['SeriesId'])) {
  1037. // SeriesId is the most reliable for series posters
  1038. $actualItemId = $result['SeriesId'];
  1039. $this->setLoggerChannel('JellyStat')->info("Using SeriesId: {$actualItemId}");
  1040. } elseif (!empty($result['ShowId'])) {
  1041. // ShowId is also series-specific
  1042. $actualItemId = $result['ShowId'];
  1043. $this->setLoggerChannel('JellyStat')->info("Using ShowId: {$actualItemId}");
  1044. } elseif (!empty($result['NowPlayingItemId'])) {
  1045. // Try NowPlayingItemId - it might be the series ID if we're looking at series-level data
  1046. $actualItemId = $result['NowPlayingItemId'];
  1047. $this->setLoggerChannel('JellyStat')->info("Using NowPlayingItemId: {$actualItemId}");
  1048. } elseif (!empty($result['ParentId'])) {
  1049. // Last resort: ParentId (might be series, season, or library)
  1050. $actualItemId = $result['ParentId'];
  1051. $this->setLoggerChannel('JellyStat')->info("Using ParentId: {$actualItemId}");
  1052. }
  1053. if (!$actualItemId) {
  1054. $this->setLoggerChannel('JellyStat')->info("No suitable ID found for TV show: {$result['SeriesName']}");
  1055. }
  1056. } elseif ($contentType === 'music') {
  1057. // For music, use NowPlayingItemId (album/track)
  1058. $actualItemId = $result['NowPlayingItemId'] ?? null;
  1059. }
  1060. $itemStats[$key] = [
  1061. 'id' => $actualItemId ?? $itemId, // Use actual item ID if available, fallback to name-based ID
  1062. 'title' => $title,
  1063. 'type' => $contentType,
  1064. 'play_count' => 0,
  1065. 'total_duration' => 0,
  1066. 'year' => $year,
  1067. 'server_id' => $serverId,
  1068. 'poster_path' => $posterPath,
  1069. 'first_played' => $result['ActivityDateInserted'] ?? null,
  1070. 'last_played' => $result['ActivityDateInserted'] ?? null
  1071. ];
  1072. }
  1073. $itemStats[$key]['play_count']++;
  1074. $itemStats[$key]['total_duration'] += $result['PlaybackDuration'] ?? 0;
  1075. // Debug: Log each play count increment
  1076. if ($contentType === 'show') {
  1077. $this->setLoggerChannel('JellyStat')->info("Play count increment for {$title}: now {$itemStats[$key]['play_count']} (Episode: {$result['EpisodeName']}, User: {$result['UserName']}, Date: {$result['ActivityDateInserted']})");
  1078. }
  1079. // Update last played time
  1080. $currentTime = $result['ActivityDateInserted'] ?? null;
  1081. if ($currentTime && (!$itemStats[$key]['last_played'] || $currentTime > $itemStats[$key]['last_played'])) {
  1082. $itemStats[$key]['last_played'] = $currentTime;
  1083. }
  1084. // Update first played time
  1085. if ($currentTime && (!$itemStats[$key]['first_played'] || $currentTime < $itemStats[$key]['first_played'])) {
  1086. $itemStats[$key]['first_played'] = $currentTime;
  1087. }
  1088. }
  1089. }
  1090. // Separate by content type and sort by play count
  1091. foreach ($itemStats as $item) {
  1092. switch ($item['type']) {
  1093. case 'movie':
  1094. $processed['movies'][] = $item;
  1095. break;
  1096. case 'show':
  1097. $processed['shows'][] = $item;
  1098. break;
  1099. case 'music':
  1100. $processed['music'][] = $item;
  1101. break;
  1102. }
  1103. }
  1104. // Sort each category by play count (descending)
  1105. usort($processed['movies'], function($a, $b) {
  1106. return $b['play_count'] - $a['play_count'];
  1107. });
  1108. usort($processed['shows'], function($a, $b) {
  1109. return $b['play_count'] - $a['play_count'];
  1110. });
  1111. usort($processed['music'], function($a, $b) {
  1112. return $b['play_count'] - $a['play_count'];
  1113. });
  1114. return $processed;
  1115. }
  1116. }