jellystat.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  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. 'metadata' => [
  174. 'enabled' => [
  175. 'homepageJellyStatEnabled'
  176. ],
  177. 'auth' => [
  178. 'homepageJellyStatAuth'
  179. ],
  180. 'not_empty' => [
  181. 'jellyStatURL'
  182. ]
  183. ]
  184. ];
  185. return $this->homepageCheckKeyPermissions($key, $permissions);
  186. }
  187. public function getJellyStatMetadata($array)
  188. {
  189. $this->writeLog('info', 'JellyStat getJellyStatMetadata called with: ' . json_encode($array));
  190. try {
  191. // Use dedicated 'metadata' permission (lighter requirements than 'main')
  192. if (!$this->homepageItemPermissions($this->jellystatHomepagePermissions('metadata'), true)) {
  193. $this->writeLog('error', 'JellyStat metadata: Permission check failed');
  194. $this->setAPIResponse('error', 'Not authorized for JellyStat metadata', 401);
  195. return false;
  196. }
  197. $key = $array['key'] ?? null;
  198. if (!$key) {
  199. $this->writeLog('error', 'JellyStat metadata: No key provided');
  200. $this->setAPIResponse('error', 'JellyStat metadata key is not defined', 422);
  201. return false;
  202. }
  203. // Build minimal, safe metadata payload without external API calls
  204. $title = 'JellyStat Item';
  205. $year = '';
  206. $item = [
  207. 'uid' => (string)$key,
  208. 'title' => $title,
  209. 'type' => 'jellystat',
  210. 'nowPlayingImageURL' => 'plugins/images/homepage/no-np.png',
  211. 'address' => $this->qualifyURL($this->config['jellyStatURL'] ?? ''),
  212. 'tabName' => 'jellystat',
  213. 'openTab' => 'true',
  214. 'metadata' => [
  215. 'guid' => (string)$key,
  216. 'summary' => 'Analytics item from JellyStat. Detailed metadata not available.',
  217. 'rating' => '0',
  218. 'duration' => '0',
  219. 'originallyAvailableAt' => '',
  220. 'year' => $year,
  221. 'tagline' => 'JellyStat Analytics',
  222. 'genres' => [],
  223. 'actors' => []
  224. ]
  225. ];
  226. $api = [];
  227. $api['content'][] = $item;
  228. $this->setAPIResponse('success', null, 200, $api);
  229. return $api;
  230. } catch (\Throwable $e) {
  231. // Fail gracefully with a fallback success response instead of 500
  232. $this->writeLog('error', 'JellyStat metadata exception: ' . $e->getMessage());
  233. $fallback = [
  234. 'uid' => (string)($array['key'] ?? 'unknown'),
  235. 'title' => 'JellyStat Item',
  236. 'type' => 'jellystat',
  237. 'nowPlayingImageURL' => 'plugins/images/homepage/no-np.png',
  238. 'address' => $this->qualifyURL($this->config['jellyStatURL'] ?? ''),
  239. 'tabName' => 'jellystat',
  240. 'openTab' => 'true',
  241. 'metadata' => [
  242. 'guid' => (string)($array['key'] ?? 'unknown'),
  243. 'summary' => 'Analytics item from JellyStat.',
  244. 'rating' => '0',
  245. 'duration' => '0',
  246. 'originallyAvailableAt' => '',
  247. 'year' => '',
  248. 'tagline' => 'JellyStat Analytics',
  249. 'genres' => [],
  250. 'actors' => []
  251. ]
  252. ];
  253. $api = ['content' => [$fallback]];
  254. $this->setAPIResponse('success', null, 200, $api);
  255. return $api;
  256. }
  257. }
  258. public function homepageOrderJellyStat()
  259. {
  260. if ($this->homepageItemPermissions($this->jellystatHomepagePermissions('main'))) {
  261. $displayMode = $this->config['homepageJellyStatDisplayMode'] ?? 'native';
  262. if ($displayMode === 'iframe') {
  263. return $this->renderJellyStatIframe();
  264. } else {
  265. return $this->renderJellyStatNative();
  266. }
  267. }
  268. }
  269. private function renderJellyStatIframe()
  270. {
  271. $url = $this->config['jellyStatURL'] ?? '';
  272. $height = $this->config['homepageJellyStatIframeHeight'] ?? 800;
  273. $scrolling = ($this->config['homepageJellyStatIframeScrolling'] ?? true) ? 'auto' : 'no';
  274. return '
  275. <div id="' . __FUNCTION__ . '">
  276. <div class="white-box">
  277. <div class="white-box-header">
  278. <i class="fa fa-bar-chart"></i> JellyStat Dashboard
  279. </div>
  280. <div class="white-box-content" style="padding: 0;">
  281. <iframe
  282. src="' . htmlspecialchars($this->qualifyURL($url)) . '"
  283. width="100%"
  284. height="' . intval($height) . 'px"
  285. style="border: none; border-radius: 0 0 4px 4px;"
  286. scrolling="' . $scrolling . '"
  287. frameborder="0">
  288. <p>Your browser does not support iframes. Please visit <a href="' . htmlspecialchars($url) . '" target="_blank">JellyStat</a> directly.</p>
  289. </iframe>
  290. </div>
  291. </div>
  292. </div>';
  293. }
  294. private function renderJellyStatNative()
  295. {
  296. $refreshInterval = ($this->config['homepageJellyStatRefresh'] ?? 5) * 60000; // Convert minutes to milliseconds
  297. $days = $this->config['homepageJellyStatDays'] ?? 30;
  298. $maxItems = $this->config['homepageJellyStatMaxItems'] ?? 10;
  299. $showLibraries = ($this->config['homepageJellyStatShowLibraries'] ?? true) ? 'true' : 'false';
  300. $showUsers = ($this->config['homepageJellyStatShowUsers'] ?? true) ? 'true' : 'false';
  301. $showMostWatched = ($this->config['homepageJellyStatShowMostWatched'] ?? true) ? 'true' : 'false';
  302. $showRecentActivity = ($this->config['homepageJellyStatShowRecentActivity'] ?? true) ? 'true' : 'false';
  303. $showMostWatchedMovies = ($this->config['homepageJellyStatShowMostWatchedMovies'] ?? true) ? 'true' : 'false';
  304. $showMostWatchedShows = ($this->config['homepageJellyStatShowMostWatchedShows'] ?? true) ? 'true' : 'false';
  305. $showMostListenedMusic = ($this->config['homepageJellyStatShowMostListenedMusic'] ?? true) ? 'true' : 'false';
  306. $mostWatchedCount = $this->config['homepageJellyStatMostWatchedCount'] ?? 10;
  307. $jellyStatUrl = htmlspecialchars($this->qualifyURL($this->config['jellyStatURL'] ?? ''), ENT_QUOTES, 'UTF-8');
  308. return '
  309. <div id="' . __FUNCTION__ . '" style="background: transparent; border: none; padding: 20px;">
  310. <div style="background: rgba(0,0,0,0.1); border-radius: 10px; padding: 20px; backdrop-filter: blur(10px);">
  311. <div style="margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 15px;">
  312. <h3 style="color: white; margin: 0; display: inline-block;"><i class="fa fa-bar-chart"></i> JellyStat Analytics</h3>
  313. <span class="pull-right">
  314. <small id="jellystat-last-update" style="color: rgba(255,255,255,0.7);"></small>
  315. <button class="btn btn-xs btn-primary" onclick="refreshJellyStatData()" title="Refresh Data" style="margin-left: 10px;">
  316. <i class="fa fa-refresh" id="jellystat-refresh-icon"></i>
  317. </button>
  318. </span>
  319. </div>
  320. <div>
  321. <div class="row" id="jellystat-content">
  322. <div class="col-lg-12 text-center">
  323. <i class="fa fa-spinner fa-spin" style="color: white;"></i> <span style="color: white;">Loading JellyStat data...</span>
  324. </div>
  325. </div>
  326. </div>
  327. </div>
  328. </div>
  329. <script>
  330. var jellyStatRefreshTimer;
  331. var jellyStatLastRefresh = 0;
  332. function refreshJellyStatData() {
  333. var refreshIcon = $("#jellystat-refresh-icon");
  334. refreshIcon.addClass("fa-spin");
  335. // Show loading state
  336. $("#jellystat-content").html("<div class=\"col-lg-12 text-center\"><i class=\"fa fa-spinner fa-spin\"></i> Loading JellyStat data...</div>");
  337. // Load JellyStat data
  338. getJellyStatData()
  339. .always(function() {
  340. refreshIcon.removeClass("fa-spin");
  341. jellyStatLastRefresh = Date.now();
  342. updateJellyStatLastRefreshTime();
  343. });
  344. }
  345. function updateJellyStatLastRefreshTime() {
  346. if (jellyStatLastRefresh > 0) {
  347. var ago = Math.floor((Date.now() - jellyStatLastRefresh) / 1000);
  348. var timeText = ago < 60 ? ago + "s ago" : Math.floor(ago / 60) + "m ago";
  349. $("#jellystat-last-update").text("Updated " + timeText);
  350. }
  351. }
  352. // Helper function to get icon for content type
  353. function getTypeIcon(collectionType) {
  354. switch(collectionType) {
  355. case "movies": return "fa-film";
  356. case "tvshows": return "fa-television";
  357. case "music": return "fa-music";
  358. case "mixed": return "fa-folder-open";
  359. default: return "fa-folder";
  360. }
  361. }
  362. // Helper function to format duration from ticks
  363. function formatJellyStatDuration(ticks) {
  364. if (!ticks || ticks === 0) return "0 min";
  365. // Convert ticks to seconds (ticks are in 100-nanosecond intervals)
  366. var seconds = ticks / 10000000;
  367. if (seconds < 60) {
  368. return Math.round(seconds) + " sec";
  369. } else if (seconds < 3600) {
  370. return Math.round(seconds / 60) + " min";
  371. } else if (seconds < 86400) {
  372. var hours = Math.floor(seconds / 3600);
  373. var minutes = Math.floor((seconds % 3600) / 60);
  374. return hours + "h " + minutes + "m";
  375. } else {
  376. var days = Math.floor(seconds / 86400);
  377. var hours = Math.floor((seconds % 86400) / 3600);
  378. return days + "d " + hours + "h";
  379. }
  380. }
  381. // Helper function to sanitize IDs for use in HTML attributes and CSS selectors
  382. function sanitizeId(id) {
  383. if (!id) return \'jellystat-unknown\';
  384. // Convert to string and replace problematic characters
  385. return String(id)
  386. .replace(/[^a-zA-Z0-9\\-_]/g, \'_\') // Replace special chars with underscores
  387. .replace(/^[0-9]/, \'_\' + String(id).charAt(0)) // Prefix with underscore if starts with number
  388. .toLowerCase();
  389. }
  390. // Helper function to generate poster URLs from JellyStat/Jellyfin
  391. function getPosterUrl(posterPath, itemId, serverId) {
  392. console.log("getPosterUrl called with:", {posterPath, itemId, serverId});
  393. // Use external URL for frontend poster display to avoid mixed content issues
  394. var jellyStatUrl = ' . json_encode($jellyStatUrl) . ';
  395. console.log("JellyStat URL from config:", jellyStatUrl);
  396. if (!posterPath && !itemId) {
  397. console.log("No poster path or item ID provided");
  398. return null;
  399. }
  400. // If we have a poster path, process it
  401. if (posterPath) {
  402. console.log("Processing poster path:", posterPath);
  403. // If its already an absolute URL, use it directly
  404. if (posterPath.indexOf("http://") === 0 || posterPath.indexOf("https://") === 0) {
  405. console.log("Poster path is absolute URL:", posterPath);
  406. return posterPath;
  407. }
  408. // If its a relative path starting with /, prepend the JellyStat URL
  409. if (jellyStatUrl && posterPath.indexOf("/") === 0) {
  410. var fullUrl = jellyStatUrl + posterPath;
  411. console.log("Generated full URL from relative path:", fullUrl);
  412. return fullUrl;
  413. }
  414. }
  415. // If we have itemId, try to generate JellyStat image proxy URL
  416. if (itemId && jellyStatUrl) {
  417. // JellyStat uses /proxy/Items/Images/Primary endpoint
  418. // Format: /proxy/Items/Images/Primary?id={itemId}&fillWidth=200&quality=90
  419. var baseUrl = jellyStatUrl.replace(/\/+$/, ""); // Remove trailing slashes
  420. var apiUrl = baseUrl + "/proxy/Items/Images/Primary?id=" + encodeURIComponent(itemId) + "&fillWidth=200&quality=90";
  421. console.log("Generated JellyStat proxy image URL:", apiUrl);
  422. return apiUrl;
  423. }
  424. console.log("No valid poster URL could be generated");
  425. return null;
  426. }
  427. function getJellyStatData() {
  428. return organizrAPI2("GET", "api/v2/homepage/jellystat")
  429. .done(function(data) {
  430. console.log("JellyStat API Response:", data);
  431. if (data && data.response && data.response.result === "success" && data.response.data) {
  432. console.log("JellyStat Data:", data.response.data);
  433. renderJellyStatData(data.response.data);
  434. } else {
  435. console.error("JellyStat API Error:", data);
  436. var errorMsg = "Failed to load JellyStat data";
  437. if (data && data.response && data.response.message) {
  438. errorMsg += ": " + data.response.message;
  439. }
  440. $("#jellystat-content").html("<div class=\"col-lg-12 text-center text-danger\">" + errorMsg + "</div>");
  441. }
  442. })
  443. .fail(function(xhr, status, error) {
  444. console.error("JellyStat API Request Failed:", xhr, status, error);
  445. $("#jellystat-content").html("<div class=\"col-lg-12 text-center text-danger\">Error loading JellyStat data: " + error + "</div>");
  446. });
  447. }
  448. function renderJellyStatData(stats) {
  449. console.log("Rendering JellyStat data:", stats);
  450. var html = "";
  451. // Server Overview - Summary Stats
  452. if (stats.library_totals) {
  453. console.log("Library totals found:", stats.library_totals);
  454. html += "<div class=\"col-lg-12\" style=\"margin-bottom: 20px;\">";
  455. html += "<div class=\"row\">";
  456. // Total Libraries
  457. html += "<div class=\"col-sm-3\">";
  458. html += "<div class=\"small-box bg-blue\">";
  459. html += "<div class=\"inner\">";
  460. html += "<h3>" + (stats.library_totals.total_libraries || 0) + "</h3>";
  461. html += "<p>Libraries</p>";
  462. html += "</div>";
  463. html += "<div class=\"icon\"><i class=\"fa fa-folder\"></i></div>";
  464. html += "</div></div>";
  465. // Total Items
  466. html += "<div class=\"col-sm-3\">";
  467. html += "<div class=\"small-box bg-green\">";
  468. html += "<div class=\"inner\">";
  469. html += "<h3>" + (stats.library_totals.total_items || 0).toLocaleString() + "</h3>";
  470. html += "<p>Total Items</p>";
  471. html += "</div>";
  472. html += "<div class=\"icon\"><i class=\"fa fa-film\"></i></div>";
  473. html += "</div></div>";
  474. // Total Episodes (if any)
  475. if (stats.library_totals.total_episodes > 0) {
  476. html += "<div class=\"col-sm-3\">";
  477. html += "<div class=\"small-box bg-yellow\">";
  478. html += "<div class=\"inner\">";
  479. html += "<h3>" + (stats.library_totals.total_episodes || 0).toLocaleString() + "</h3>";
  480. html += "<p>Episodes</p>";
  481. html += "</div>";
  482. html += "<div class=\"icon\"><i class=\"fa fa-television\"></i></div>";
  483. html += "</div></div>";
  484. }
  485. // Total Play Time
  486. html += "<div class=\"col-sm-3\">";
  487. html += "<div class=\"small-box bg-red\">";
  488. html += "<div class=\"inner\">";
  489. html += "<h3 style=\"font-size: 18px;\">" + (stats.library_totals.total_play_time || "0 min") + "</h3>";
  490. html += "<p>Total Watched</p>";
  491. html += "</div>";
  492. html += "<div class=\"icon\"><i class=\"fa fa-clock-o\"></i></div>";
  493. html += "</div></div>";
  494. html += "</div></div>";
  495. }
  496. // Content Type Breakdown
  497. if (stats.library_totals && stats.library_totals.type_breakdown) {
  498. html += "<div class=\"col-lg-6\">";
  499. html += "<h5><i class=\"fa fa-pie-chart text-primary\"></i> Content Breakdown</h5>";
  500. html += "<div class=\"table-responsive\">";
  501. html += "<table class=\"table table-striped table-condensed\">";
  502. html += "<thead><tr><th>Type</th><th>Libraries</th><th>Items</th><th>Watch Time</th></tr></thead>";
  503. html += "<tbody>";
  504. Object.keys(stats.library_totals.type_breakdown).forEach(function(type) {
  505. var breakdown = stats.library_totals.type_breakdown[type];
  506. var playTimeFormatted = breakdown.play_time > 0 ? formatJellyStatDuration(breakdown.play_time) : "0 min";
  507. html += "<tr>";
  508. html += "<td><strong>" + breakdown.label + "</strong></td>";
  509. html += "<td><strong style=\"color: #5bc0de;\">" + breakdown.count + "</strong></td>";
  510. html += "<td><strong style=\"color: #5cb85c;\">" + breakdown.items.toLocaleString() + "</strong></td>";
  511. html += "<td><small>" + playTimeFormatted + "</small></td>";
  512. html += "</tr>";
  513. });
  514. html += "</tbody></table></div></div>";
  515. }
  516. // Detailed Library Statistics
  517. if (' . $showLibraries . ' && stats.libraries && stats.libraries.length > 0) {
  518. html += "<div class=\"col-lg-6\">";
  519. html += "<h5><i class=\"fa fa-folder text-info\"></i> Library Details</h5>";
  520. html += "<div class=\"table-responsive\">";
  521. html += "<table class=\"table table-striped table-condensed\">";
  522. html += "<thead><tr><th>Library</th><th>Type</th><th>Items</th><th>Watch Time</th></tr></thead>";
  523. html += "<tbody>";
  524. stats.libraries.slice(0, ' . $maxItems . ').forEach(function(lib) {
  525. var typeIcon = getTypeIcon(lib.collection_type);
  526. html += "<tr>";
  527. html += "<td><i class=\"fa " + typeIcon + " text-muted\"></i> <strong>" + (lib.name || "Unknown Library") + "</strong></td>";
  528. html += "<td><small>" + (lib.type || "Unknown") + "</small></td>";
  529. html += "<td><strong style=\"color: #337ab7;\">" + (lib.item_count || 0).toLocaleString() + "</strong>";
  530. // Show additional counts for TV libraries
  531. if (lib.episode_count > 0) {
  532. html += "<br><small class=\"text-muted\">Episodes: <strong style=\"color: #337ab7;\">" + lib.episode_count.toLocaleString() + "</strong></small>";
  533. }
  534. if (lib.season_count > 0) {
  535. html += "<br><small class=\"text-muted\">Seasons: <strong style=\"color: #337ab7;\">" + lib.season_count.toLocaleString() + "</strong></small>";
  536. }
  537. html += "</td>";
  538. html += "<td><small>" + (lib.total_play_time || "0 min") + "</small></td>";
  539. html += "</tr>";
  540. });
  541. html += "</tbody></table></div></div>";
  542. }
  543. // User Statistics
  544. if (' . $showUsers . ' && stats.users && stats.users.length > 0) {
  545. html += "<div class=\"col-lg-6\">";
  546. html += "<h5><i class=\"fa fa-users\"></i> Active Users (" + stats.users.length + " total)</h5>";
  547. html += "<div class=\"row\">";
  548. stats.users.slice(0, 8).forEach(function(user) {
  549. var lastActivity = "Never";
  550. if (user.last_activity && user.last_activity !== "0001-01-01T00:00:00.0000000Z") {
  551. var activityDate = new Date(user.last_activity);
  552. lastActivity = activityDate.toLocaleDateString();
  553. }
  554. var playCount = user.play_count || 0;
  555. html += "<div class=\"col-md-6 col-sm-6\" style=\"margin-bottom: 10px;\">";
  556. html += "<div class=\"media\">";
  557. html += "<div class=\"media-left\"><i class=\"fa fa-user fa-2x text-muted\"></i></div>";
  558. html += "<div class=\"media-body\">";
  559. html += "<h6 class=\"media-heading\">" + (user.name || "Unknown User") + " <strong style=\"color: #5bc0de;\">" + playCount + " plays</strong></h6>";
  560. html += "<small class=\"text-muted\">Last Activity: " + lastActivity + "</small>";
  561. html += "</div></div></div>";
  562. });
  563. html += "</div></div>";
  564. }
  565. // Most Watched Content
  566. if (' . $showMostWatched . ' && stats.most_watched && stats.most_watched.length > 0) {
  567. html += "<div class=\"col-lg-12\" style=\"margin-top: 20px;\">";
  568. html += "<h5><i class=\"fa fa-star text-warning\"></i> Most Watched Content</h5>";
  569. html += "<div class=\"table-responsive\">";
  570. html += "<table class=\"table table-striped table-condensed\">";
  571. html += "<thead><tr><th>Title</th><th>Type</th><th>Plays</th><th>Runtime</th><th>Year</th></tr></thead>";
  572. html += "<tbody>";
  573. stats.most_watched.slice(0, ' . $maxItems . ').forEach(function(item) {
  574. html += "<tr>";
  575. html += "<td><strong>" + (item.title || "Unknown Title") + "</strong></td>";
  576. html += "<td>" + (item.type || "Unknown") + "</td>";
  577. html += "<td><strong style=\"color: #337ab7;\">" + (item.play_count || 0) + "</strong></td>";
  578. html += "<td>" + (item.runtime || "Unknown") + "</td>";
  579. html += "<td>" + (item.year && item.year !== "N/A" ? item.year : "") + "</td>";
  580. html += "</tr>";
  581. });
  582. html += "</tbody></table></div></div>";
  583. }
  584. // Recent Activity
  585. if (' . $showRecentActivity . ' && stats.recent_activity && stats.recent_activity.length > 0) {
  586. html += "<div class=\"col-lg-12\" style=\"margin-top: 20px;\">";
  587. html += "<h5><i class=\"fa fa-clock-o text-success\"></i> Recent Activity</h5>";
  588. html += "<div class=\"table-responsive\">";
  589. html += "<table class=\"table table-striped table-condensed\">";
  590. html += "<thead><tr><th>Date</th><th>User</th><th>Title</th><th>Type</th></tr></thead>";
  591. html += "<tbody>";
  592. stats.recent_activity.slice(0, ' . $maxItems . ').forEach(function(activity) {
  593. var date = new Date(activity.date);
  594. var formattedDate = date.toLocaleDateString() + " " + date.toLocaleTimeString([], {hour: "2-digit", minute:"2-digit"});
  595. html += "<tr>";
  596. html += "<td><small>" + formattedDate + "</small></td>";
  597. html += "<td>" + (activity.user || "Unknown User") + "</td>";
  598. html += "<td><strong>" + (activity.title || "Unknown Title") + "</strong></td>";
  599. html += "<td>" + (activity.type || "Unknown") + "</td>";
  600. html += "</tr>";
  601. });
  602. html += "</tbody></table></div></div>";
  603. }
  604. // Debug data availability
  605. console.log("Full stats object:", stats);
  606. console.log("Movie settings enabled:", ' . $showMostWatchedMovies . ');
  607. console.log("Movies data:", stats.most_watched_movies);
  608. console.log("Shows data:", stats.most_watched_shows);
  609. console.log("Music data:", stats.most_listened_music);
  610. // Most Watched Movies with Posters
  611. if (' . $showMostWatchedMovies . ' && stats.most_watched_movies && stats.most_watched_movies.length > 0) {
  612. console.log("Rendering most watched movies:", stats.most_watched_movies);
  613. html += "<div class=\"col-lg-12\" style=\"margin-top: 30px;\">";
  614. html += "<h5><i class=\"fa fa-film text-primary\"></i> Most Watched Movies</h5>";
  615. 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;\">";
  616. 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>";
  617. stats.most_watched_movies.forEach(function(movie) {
  618. console.log("Processing movie:", movie);
  619. console.log("Movie poster_path:", movie.poster_path);
  620. console.log("Movie id:", movie.id);
  621. console.log("Movie server_id:", movie.server_id);
  622. var posterUrl = getPosterUrl(movie.poster_path, movie.id, movie.server_id);
  623. console.log("Generated posterUrl:", posterUrl);
  624. var playCount = movie.play_count || 0;
  625. var year = movie.year && movie.year !== "N/A" ? movie.year : "";
  626. var title = movie.title || "Unknown Movie";
  627. // Use sanitized ID for DOM elements but original ID for data attributes
  628. var sanitizedId = sanitizeId(movie.id);
  629. console.log("Using sanitized ID:", sanitizedId, "for original ID:", movie.id);
  630. html += "<div style=\"display: inline-block; margin: 0 10px 0 0; width: 150px; vertical-align: top;\">";
  631. html += "<div class=\"poster-card metadata-get\" style=\"position: relative; width: 150px; height: 225px; transition: transform 0.2s ease; cursor: pointer;\" data-source=\"jellystat\" data-key=\"" + movie.id + "\" data-uid=\"" + sanitizedId + "\">";
  632. // Poster image container
  633. 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);\">";
  634. // Hover overlay with title and year - initially hidden
  635. 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;\">";
  636. 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>";
  637. if (year && year !== "N/A") {
  638. 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>";
  639. }
  640. html += "</div>";
  641. if (posterUrl) {
  642. html += "<img src=\"" + posterUrl + "\" alt=\"" + title + "\" style=\"width: 150px; height: 225px; object-fit: cover;\" onerror=\"this.style.display=\"none\"; this.nextElementSibling.style.display=\"flex\";\">";
  643. }
  644. 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;\">";
  645. html += "<i class=\"fa fa-film fa-3x\"></i>";
  646. html += "</div>";
  647. // Play count badge
  648. 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);\">";
  649. html += "<i class=\"fa fa-play\"></i> " + playCount;
  650. html += "</div>";
  651. html += "</div>";
  652. // Add CSS for hover effect - this will be applied once when the first poster is rendered
  653. if (movie === stats.most_watched_movies[0]) {
  654. html += "<style>";
  655. html += ".poster-card:hover .poster-overlay { opacity: 1 !important; }";
  656. html += ".poster-card:hover { transform: scale(1.05); z-index: 10; }";
  657. html += "</style>";
  658. }
  659. html += "</div>";
  660. // Add metadata popup elements (Organizr style) using sanitized ID
  661. // Include a hidden anchor to trigger Magnific Popup, matching Emby/Jellyfin implementation
  662. html += "<a class=\"inline-popups " + sanitizedId + " hidden\" href=\"#" + sanitizedId + "-metadata-div\" data-effect=\"mfp-zoom-out\"></a>";
  663. html += "<div id=\"" + sanitizedId + "-metadata-div\" class=\"white-popup mfp-with-anim mfp-hide\"">";
  664. html += "<div class=\"col-md-8 col-md-offset-2 " + sanitizedId + "-metadata-info\"></div>";
  665. html += "</div>";
  666. html += "</div>";
  667. });
  668. html += "</div></div>";
  669. } else {
  670. console.log("Movies not showing because:");
  671. console.log("- Setting enabled:", ' . $showMostWatchedMovies . ');
  672. console.log("- Has data:", stats.most_watched_movies && stats.most_watched_movies.length > 0);
  673. console.log("- Data:", stats.most_watched_movies);
  674. }
  675. // Most Watched TV Shows with Posters
  676. if (' . $showMostWatchedShows . ' && stats.most_watched_shows && stats.most_watched_shows.length > 0) {
  677. html += "<div class=\"col-lg-12\" style=\"margin-top: 30px;\">";
  678. html += "<h5><i class=\"fa fa-television text-info\"></i> Most Watched TV Shows</h5>";
  679. 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;\">";
  680. 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>";
  681. stats.most_watched_shows.forEach(function(show) {
  682. var posterUrl = getPosterUrl(show.poster_path, show.id, show.server_id);
  683. var playCount = show.play_count || 0;
  684. var year = show.year && show.year !== "N/A" ? show.year : "";
  685. var title = show.title || "Unknown Show";
  686. // Use sanitized ID for DOM elements but original ID for data attributes
  687. var sanitizedId = sanitizeId(show.id);
  688. console.log("Using sanitized ID:", sanitizedId, "for original ID:", show.id);
  689. html += "<div style=\"display: inline-block; margin: 0 10px 0 0; width: 150px; vertical-align: top;\">";
  690. html += "<div class=\"poster-card metadata-get\" style=\"position: relative; width: 150px; height: 225px; transition: transform 0.2s ease; cursor: pointer;\" data-source=\"jellystat\" data-key=\"" + show.id + "\" data-uid=\"" + sanitizedId + "\">";
  691. // Poster image container
  692. 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);\">";
  693. // Hover overlay with title and year - initially hidden
  694. 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;\">";
  695. 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>";
  696. if (year && year !== "N/A") {
  697. 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>";
  698. }
  699. html += "</div>";
  700. if (posterUrl) {
  701. html += "<img src=\"" + posterUrl + "\" alt=\"" + title + "\" style=\"width: 150px; height: 225px; object-fit: cover;\" onerror=\"this.style.display=\"none\"; this.nextElementSibling.style.display=\"flex\";\">";
  702. }
  703. 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;\">";
  704. html += "<i class=\"fa fa-television fa-3x\"></i>";
  705. html += "</div>";
  706. // Play count badge
  707. 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);\">";
  708. html += "<i class=\"fa fa-play\"></i> " + playCount;
  709. html += "</div>";
  710. html += "</div>";
  711. // Add CSS for hover effect - this will be applied once when the first poster is rendered
  712. if (show === stats.most_watched_shows[0]) {
  713. html += "<style>";
  714. html += ".poster-card:hover .poster-overlay { opacity: 1 !important; }";
  715. html += ".poster-card:hover { transform: scale(1.05); z-index: 10; }";
  716. html += "</style>";
  717. }
  718. html += "</div>";
  719. // Add metadata popup elements (Organizr style) using sanitized ID
  720. // Include a hidden anchor to trigger Magnific Popup, matching Emby/Jellyfin implementation
  721. html += "<a class=\"inline-popups " + sanitizedId + " hidden\" href=\"#" + sanitizedId + "-metadata-div\" data-effect=\"mfp-zoom-out\"></a>";
  722. html += "<div id=\"" + sanitizedId + "-metadata-div\" class=\"white-popup mfp-with-anim mfp-hide\"">";
  723. html += "<div class=\"col-md-8 col-md-offset-2 " + sanitizedId + "-metadata-info\"></div>";
  724. html += "</div>";
  725. html += "</div>";
  726. });
  727. html += "</div></div>";
  728. }
  729. // Most Listened Music with Cover Art
  730. if (' . $showMostListenedMusic . ' && stats.most_listened_music && stats.most_listened_music.length > 0) {
  731. html += "<div class=\"col-lg-12\" style=\"margin-top: 30px;\">";
  732. html += "<h5><i class=\"fa fa-music text-success\"></i> Most Listened Music</h5>";
  733. html += "<div class=\"row\" style=\"margin-top: 15px;\">";
  734. stats.most_listened_music.forEach(function(music) {
  735. var posterUrl = getPosterUrl(music.poster_path || music.cover_art, music.id, music.server_id);
  736. var playCount = music.play_count || 0;
  737. var artist = music.artist || "Unknown Artist";
  738. var title = music.title || music.album || "Unknown";
  739. html += "<div class=\"col-lg-2 col-md-3 col-sm-4 col-xs-6\" style=\"margin-bottom: 20px;\">";
  740. html += "<div class=\"poster-card\" style=\"position: relative; transition: transform 0.2s ease;\">";
  741. // Cover art
  742. 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);\">";
  743. if (posterUrl) {
  744. 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\";\">";
  745. }
  746. 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;\">";
  747. html += "<i class=\"fa fa-music fa-3x\"></i>";
  748. html += "</div>";
  749. // Play count badge
  750. 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);\">";
  751. html += "<i class=\"fa fa-play\"></i> " + playCount;
  752. html += "</div>";
  753. html += "</div>";
  754. // Music info with transparent background and white text
  755. html += "<div class=\"poster-info\" style=\"padding: 12px 8px; text-align: center;\">";
  756. 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>";
  757. html += "<small style=\"color: rgba(255,255,255,0.8); text-shadow: 1px 1px 2px rgba(0,0,0,0.8);\">" + artist + "</small>";
  758. html += "</div>";
  759. html += "</div></div>";
  760. });
  761. html += "</div></div>";
  762. }
  763. if (!html) {
  764. html = "<div class=\"col-lg-12 text-center text-muted\">";
  765. html += "<i class=\"fa fa-exclamation-circle fa-3x\" style=\"margin-bottom: 10px;\"></i>";
  766. html += "<h4>No JellyStat data available</h4>";
  767. html += "<p>Check your JellyStat connection and API configuration.</p>";
  768. html += "</div>";
  769. }
  770. $("#jellystat-content").html(html);
  771. }
  772. // Auto-refresh setup
  773. var refreshInterval = ' . $refreshInterval . ';
  774. if (refreshInterval > 0) {
  775. jellyStatRefreshTimer = setInterval(function() {
  776. refreshJellyStatData();
  777. }, refreshInterval);
  778. }
  779. // Update time display every 30 seconds
  780. setInterval(updateJellyStatLastRefreshTime, 30000);
  781. // Initial load
  782. $(document).ready(function() {
  783. refreshJellyStatData();
  784. });
  785. // Cleanup timer when page unloads
  786. $(window).on("beforeunload", function() {
  787. if (jellyStatRefreshTimer) {
  788. clearInterval(jellyStatRefreshTimer);
  789. }
  790. });
  791. // JellyStat metadata popups are handled by Organizr\'s built-in metadata-get click handler
  792. // The handler will call api/v2/homepage/jellystat/metadata with the data-key value
  793. </script>
  794. ';
  795. }
  796. /**
  797. * Main function to get JellyStat data
  798. */
  799. public function getJellyStatData($options = null)
  800. {
  801. if (!$this->homepageItemPermissions($this->jellystatHomepagePermissions('main'), true)) {
  802. $this->setAPIResponse('error', 'User not approved to view this homepage item - check plugin configuration', 401);
  803. return false;
  804. }
  805. try {
  806. $url = $this->config['jellyStatURL'] ?? '';
  807. $token = $this->config['jellyStatApikey'] ?? '';
  808. $days = intval($this->config['homepageJellyStatDays'] ?? 30);
  809. if (empty($url) || empty($token)) {
  810. $this->setAPIResponse('error', 'JellyStat URL or API key not configured', 500);
  811. return false;
  812. }
  813. $stats = $this->fetchJellyStatStats($url, $token, $days);
  814. if (isset($stats['error']) && $stats['error']) {
  815. $this->setAPIResponse('error', $stats['message'], 500);
  816. return false;
  817. }
  818. $this->setAPIResponse('success', 'JellyStat data retrieved successfully', 200, $stats);
  819. return true;
  820. } catch (Exception $e) {
  821. $this->setAPIResponse('error', 'Failed to retrieve JellyStat data: ' . $e->getMessage(), 500);
  822. return false;
  823. }
  824. }
  825. /**
  826. * Fetch statistics from JellyStat API
  827. */
  828. private function fetchJellyStatStats($url, $token, $days = 30)
  829. {
  830. $disableCert = $this->config['jellyStatDisableCertCheck'] ?? false;
  831. $customCert = $this->config['jellyStatUseCustomCertificate'] ?? false;
  832. // Use internal URL for server-side API calls if configured, otherwise use main URL
  833. $internalUrl = $this->config['jellyStatInternalURL'] ?? '';
  834. $apiUrl = !empty($internalUrl) ? $internalUrl : $url;
  835. $options = $this->requestOptions($apiUrl, null, $disableCert, $customCert);
  836. $baseUrl = $this->qualifyURL($apiUrl);
  837. $stats = [
  838. 'period' => "{$days} days",
  839. 'libraries' => [],
  840. 'library_totals' => [],
  841. 'server_info' => [],
  842. 'most_watched_movies' => [],
  843. 'most_watched_shows' => [],
  844. 'most_listened_music' => []
  845. ];
  846. $mostWatchedCount = $this->config['homepageJellyStatMostWatchedCount'] ?? 10;
  847. try {
  848. // Get Library Statistics - use query parameter authentication
  849. $librariesUrl = $baseUrl . '/api/getLibraries?apiKey=' . urlencode($token);
  850. $response = Requests::get($librariesUrl, [], $options);
  851. if ($response->success) {
  852. $data = json_decode($response->body, true);
  853. if (is_array($data) && !isset($data['error'])) {
  854. // Process individual libraries
  855. $stats['libraries'] = array_map(function($lib) {
  856. return [
  857. 'name' => $lib['Name'] ?? 'Unknown Library',
  858. 'type' => $this->getCollectionTypeLabel($lib['CollectionType'] ?? 'unknown'),
  859. 'item_count' => $lib['item_count'] ?? 0,
  860. 'season_count' => $lib['season_count'] ?? 0,
  861. 'episode_count' => $lib['episode_count'] ?? 0,
  862. 'total_play_time' => $lib['total_play_time'] ? $this->formatJellyStatDuration($lib['total_play_time']) : '0 min',
  863. 'play_time_raw' => $lib['total_play_time'] ?? 0,
  864. 'collection_type' => $lib['CollectionType'] ?? 'unknown'
  865. ];
  866. }, $data);
  867. // Calculate totals across all libraries
  868. $totalItems = array_sum(array_column($data, 'item_count'));
  869. $totalSeasons = array_sum(array_column($data, 'season_count'));
  870. $totalEpisodes = array_sum(array_column($data, 'episode_count'));
  871. $totalPlayTime = array_sum(array_column($data, 'total_play_time'));
  872. // Calculate library type breakdowns
  873. $typeBreakdown = [];
  874. foreach ($data as $lib) {
  875. $type = $lib['CollectionType'] ?? 'unknown';
  876. if (!isset($typeBreakdown[$type])) {
  877. $typeBreakdown[$type] = [
  878. 'count' => 0,
  879. 'items' => 0,
  880. 'play_time' => 0,
  881. 'label' => $this->getCollectionTypeLabel($type)
  882. ];
  883. }
  884. $typeBreakdown[$type]['count']++;
  885. $typeBreakdown[$type]['items'] += $lib['item_count'] ?? 0;
  886. $typeBreakdown[$type]['play_time'] += $lib['total_play_time'] ?? 0;
  887. }
  888. $stats['library_totals'] = [
  889. 'total_libraries' => count($data),
  890. 'total_items' => $totalItems,
  891. 'total_seasons' => $totalSeasons,
  892. 'total_episodes' => $totalEpisodes,
  893. 'total_play_time' => $this->formatJellyStatDuration($totalPlayTime),
  894. 'total_play_time_raw' => $totalPlayTime,
  895. 'type_breakdown' => $typeBreakdown
  896. ];
  897. // Server information
  898. $stats['server_info'] = [
  899. 'server_id' => $data[0]['ServerId'] ?? 'Unknown',
  900. 'last_updated' => date('c')
  901. ];
  902. }
  903. }
  904. // Get History data and process to extract most watched content
  905. // Calculate the start date based on the configured days period
  906. $startDate = date('Y-m-d', strtotime("-{$days} days"));
  907. // Fetch ALL history data using pagination to ensure complete play counts
  908. $allHistoryResults = $this->fetchAllJellyStatHistory($baseUrl, $token, $startDate, $options);
  909. if (!empty($allHistoryResults)) {
  910. // Process history to get most watched content
  911. $processedData = $this->processJellyStatHistory($allHistoryResults);
  912. // Extract most watched items based on user settings
  913. if ($this->config['homepageJellyStatShowMostWatchedMovies'] ?? false) {
  914. $stats['most_watched_movies'] = array_slice($processedData['movies'], 0, $mostWatchedCount);
  915. }
  916. if ($this->config['homepageJellyStatShowMostWatchedShows'] ?? false) {
  917. $stats['most_watched_shows'] = array_slice($processedData['shows'], 0, $mostWatchedCount);
  918. }
  919. if ($this->config['homepageJellyStatShowMostListenedMusic'] ?? false) {
  920. $stats['most_listened_music'] = array_slice($processedData['music'], 0, $mostWatchedCount);
  921. }
  922. }
  923. } catch (Exception $e) {
  924. return ['error' => true, 'message' => 'Failed to fetch JellyStat data: ' . $e->getMessage()];
  925. }
  926. return $stats;
  927. }
  928. /**
  929. * Fetch all history from JellyStat using pagination
  930. */
  931. private function fetchAllJellyStatHistory($baseUrl, $token, $startDate, $options)
  932. {
  933. $allResults = [];
  934. $page = 1;
  935. $pageSize = 1000; // API page size limit
  936. do {
  937. $historyUrl = $baseUrl . '/api/getHistory?apiKey=' . urlencode($token) .
  938. '&page=' . $page .
  939. '&size=' . $pageSize .
  940. '&startDate=' . urlencode($startDate);
  941. $response = Requests::get($historyUrl, [], $options);
  942. if (!$response->success) {
  943. // Stop if there is an error
  944. break;
  945. }
  946. $data = json_decode($response->body, true);
  947. if (!isset($data['results']) || !is_array($data['results']) || empty($data['results'])) {
  948. // No more results, break the loop
  949. break;
  950. }
  951. $allResults = array_merge($allResults, $data['results']);
  952. $page++;
  953. } while (count($data['results']) == $pageSize);
  954. return $allResults;
  955. }
  956. /**
  957. * Generate poster URL from JellyStat API
  958. */
  959. private function getPosterUrl($posterPath, $itemId, $serverId)
  960. {
  961. // Use main URL for poster display (not internal URL)
  962. $jellyStatUrl = $this->qualifyURL($this->config['jellyStatURL'] ?? '');
  963. if (!$jellyStatUrl) {
  964. return null;
  965. }
  966. // If we have a poster path, process it
  967. if ($posterPath) {
  968. // If its already an absolute URL, use it directly
  969. if (strpos($posterPath, 'http://') === 0 || strpos($posterPath, 'https://') === 0) {
  970. return $posterPath;
  971. }
  972. // If its a relative path starting with /, prepend the JellyStat URL
  973. if (strpos($posterPath, '/') === 0) {
  974. return rtrim($jellyStatUrl, '/') . $posterPath;
  975. }
  976. }
  977. // If we have itemId, try to generate JellyStat image proxy URL
  978. if ($itemId) {
  979. // JellyStat uses /proxy/Items/Images/Primary endpoint
  980. // Format: /proxy/Items/Images/Primary?id={itemId}&fillWidth=200&quality=90
  981. $baseUrl = rtrim($jellyStatUrl, '/');
  982. return $baseUrl . '/proxy/Items/Images/Primary?id=' . urlencode($itemId) . '&fillWidth=200&quality=90';
  983. }
  984. return null;
  985. }
  986. /**
  987. * Get human-readable label for collection type
  988. */
  989. private function getCollectionTypeLabel($type)
  990. {
  991. $labels = [
  992. 'movies' => 'Movies',
  993. 'tvshows' => 'TV Shows',
  994. 'music' => 'Music',
  995. 'mixed' => 'Mixed Content',
  996. 'unknown' => 'Other'
  997. ];
  998. return $labels[$type] ?? ucfirst($type);
  999. }
  1000. /**
  1001. * Format bytes to human readable format
  1002. */
  1003. private function formatBytes($size, $precision = 2)
  1004. {
  1005. if ($size == 0) return '0 B';
  1006. $base = log($size, 1024);
  1007. $suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
  1008. return round(pow(1024, $base - floor($base)), $precision) . ' ' . $suffixes[floor($base)];
  1009. }
  1010. /**
  1011. * Format duration for display (JellyStat specific)
  1012. */
  1013. private function formatJellyStatDuration($ticks)
  1014. {
  1015. if ($ticks == 0) return 'Unknown';
  1016. // Convert ticks to seconds (ticks are in 100-nanosecond intervals)
  1017. $seconds = $ticks / 10000000;
  1018. if ($seconds < 3600) {
  1019. return gmdate('i:s', $seconds);
  1020. } else {
  1021. return gmdate('H:i:s', $seconds);
  1022. }
  1023. }
  1024. /**
  1025. * Process JellyStat history data to extract most watched content
  1026. */
  1027. private function processJellyStatHistory($historyResults)
  1028. {
  1029. $processed = [
  1030. 'movies' => [],
  1031. 'shows' => [],
  1032. 'music' => []
  1033. ];
  1034. // Group items by ID and count plays
  1035. $itemStats = [];
  1036. // Debug: Log sample of first few results to understand data structure
  1037. $this->setLoggerChannel('JellyStat')->info('JellyStat History Debug: Processing ' . count($historyResults) . ' history records');
  1038. if (count($historyResults) > 0) {
  1039. $this->setLoggerChannel('JellyStat')->info('JellyStat Sample Record: ' . json_encode(array_slice($historyResults, 0, 3), JSON_PRETTY_PRINT));
  1040. }
  1041. foreach ($historyResults as $index => $result) {
  1042. // Determine content type based on available data
  1043. $contentType = 'unknown';
  1044. $itemId = null;
  1045. $title = 'Unknown';
  1046. $year = null;
  1047. $serverId = $result['ServerId'] ?? null;
  1048. // Check if it's a TV show (has SeriesName)
  1049. if (!empty($result['SeriesName'])) {
  1050. $contentType = 'show';
  1051. $itemId = $result['SeriesName']; // Use series name as unique identifier
  1052. $title = $result['SeriesName'];
  1053. // Try to extract year from multiple possible sources for TV shows
  1054. // 1. Check for SeriesProductionYear or ProductionYear fields
  1055. if (!empty($result['SeriesProductionYear'])) {
  1056. $year = (string)$result['SeriesProductionYear'];
  1057. } elseif (!empty($result['ProductionYear'])) {
  1058. $year = (string)$result['ProductionYear'];
  1059. } elseif (!empty($result['PremiereDate'])) {
  1060. // Extract year from premiere date
  1061. $year = date('Y', strtotime($result['PremiereDate']));
  1062. } else {
  1063. // 2. Try to extract year from series name (e.g., "Show Name (2019)")
  1064. if (preg_match('/\((19|20)\d{2}\)/', $title, $matches)) {
  1065. $year = trim($matches[0], '()');
  1066. $title = trim(str_replace($matches[0], '', $title));
  1067. } elseif (!empty($result['EpisodeName'])) {
  1068. // 3. As a last resort, try to extract year from episode name
  1069. $episodeTitle = $result['EpisodeName'];
  1070. if (preg_match('/\b(19|20)\d{2}\b/', $episodeTitle, $matches)) {
  1071. $year = $matches[0];
  1072. }
  1073. }
  1074. }
  1075. }
  1076. // Check if it's a movie (has NowPlayingItemName but no SeriesName)
  1077. elseif (!empty($result['NowPlayingItemName']) && empty($result['SeriesName'])) {
  1078. // Determine if it's likely a movie or music based on duration or other hints
  1079. $itemName = $result['NowPlayingItemName'];
  1080. $duration = $result['PlaybackDuration'] ?? 0;
  1081. // If duration is very short (< 10 minutes) and no video streams, likely music
  1082. $hasVideo = false;
  1083. if (isset($result['MediaStreams']) && is_array($result['MediaStreams'])) {
  1084. foreach ($result['MediaStreams'] as $stream) {
  1085. if (($stream['Type'] ?? '') === 'Video') {
  1086. $hasVideo = true;
  1087. break;
  1088. }
  1089. }
  1090. }
  1091. if (!$hasVideo || $duration < 600) { // Less than 10 minutes and no video = likely music
  1092. $contentType = 'music';
  1093. $title = $itemName;
  1094. // For music, try to extract artist info
  1095. // Music tracks might have format like "Artist - Song" or just "Song"
  1096. } else {
  1097. $contentType = 'movie';
  1098. $title = $itemName;
  1099. // Try to extract year from multiple possible sources for movies
  1100. // 1. Check for ProductionYear field first
  1101. if (!empty($result['ProductionYear'])) {
  1102. $year = (string)$result['ProductionYear'];
  1103. } elseif (!empty($result['PremiereDate'])) {
  1104. // Extract year from premiere date
  1105. $year = date('Y', strtotime($result['PremiereDate']));
  1106. } else {
  1107. // 2. Try to extract year from movie title (e.g., "Movie Title (2019)")
  1108. if (preg_match('/\((19|20)\d{2}\)/', $title, $matches)) {
  1109. $year = trim($matches[0], '()');
  1110. $title = trim(str_replace($matches[0], '', $title));
  1111. }
  1112. }
  1113. }
  1114. $itemId = $result['NowPlayingItemId'] ?? $itemName;
  1115. }
  1116. if ($itemId && $contentType !== 'unknown') {
  1117. $key = $contentType . '_' . $itemId;
  1118. if (!isset($itemStats[$key])) {
  1119. // Extract poster/image information from JellyStat API response
  1120. $posterPath = null;
  1121. $actualItemId = null;
  1122. // Get the actual Jellyfin/Emby item ID for poster generation
  1123. // Note: JellyStat history API doesn't provide poster paths directly,
  1124. // so we'll use item IDs with JellyStat's image proxy API
  1125. if ($contentType === 'movie') {
  1126. // For movies, use the NowPlayingItemId
  1127. $actualItemId = $result['NowPlayingItemId'] ?? null;
  1128. } elseif ($contentType === 'show') {
  1129. // Debug: Log all available IDs for TV shows to understand data structure
  1130. $this->setLoggerChannel('JellyStat')->info("JellyStat TV Show Debug - Series: {$result['SeriesName']}");
  1131. $this->setLoggerChannel('JellyStat')->info("Available IDs: SeriesId=" . ($result['SeriesId'] ?? 'null') .
  1132. ", ShowId=" . ($result['ShowId'] ?? 'null') .
  1133. ", ParentId=" . ($result['ParentId'] ?? 'null') .
  1134. ", NowPlayingItemId=" . ($result['NowPlayingItemId'] ?? 'null'));
  1135. // For TV shows, be more selective about ID selection to ensure we get series posters
  1136. // Priority: SeriesId (if exists) > ShowId > NowPlayingItemId (only if it looks like series) > ParentId
  1137. $actualItemId = null;
  1138. if (!empty($result['SeriesId'])) {
  1139. // SeriesId is the most reliable for series posters
  1140. $actualItemId = $result['SeriesId'];
  1141. $this->setLoggerChannel('JellyStat')->info("Using SeriesId: {$actualItemId}");
  1142. } elseif (!empty($result['ShowId'])) {
  1143. // ShowId is also series-specific
  1144. $actualItemId = $result['ShowId'];
  1145. $this->setLoggerChannel('JellyStat')->info("Using ShowId: {$actualItemId}");
  1146. } elseif (!empty($result['NowPlayingItemId'])) {
  1147. // Try NowPlayingItemId - it might be the series ID if we're looking at series-level data
  1148. $actualItemId = $result['NowPlayingItemId'];
  1149. $this->setLoggerChannel('JellyStat')->info("Using NowPlayingItemId: {$actualItemId}");
  1150. } elseif (!empty($result['ParentId'])) {
  1151. // Last resort: ParentId (might be series, season, or library)
  1152. $actualItemId = $result['ParentId'];
  1153. $this->setLoggerChannel('JellyStat')->info("Using ParentId: {$actualItemId}");
  1154. }
  1155. if (!$actualItemId) {
  1156. $this->setLoggerChannel('JellyStat')->info("No suitable ID found for TV show: {$result['SeriesName']}");
  1157. }
  1158. } elseif ($contentType === 'music') {
  1159. // For music, use NowPlayingItemId (album/track)
  1160. $actualItemId = $result['NowPlayingItemId'] ?? null;
  1161. }
  1162. $itemStats[$key] = [
  1163. 'id' => $actualItemId ?? $itemId, // Use actual item ID if available, fallback to name-based ID
  1164. 'title' => $title,
  1165. 'type' => $contentType,
  1166. 'play_count' => 0,
  1167. 'total_duration' => 0,
  1168. 'year' => $year,
  1169. 'server_id' => $serverId,
  1170. 'poster_path' => $posterPath,
  1171. 'first_played' => $result['ActivityDateInserted'] ?? null,
  1172. 'last_played' => $result['ActivityDateInserted'] ?? null
  1173. ];
  1174. }
  1175. $itemStats[$key]['play_count']++;
  1176. $itemStats[$key]['total_duration'] += $result['PlaybackDuration'] ?? 0;
  1177. // Debug: Log each play count increment
  1178. if ($contentType === 'show') {
  1179. $this->setLoggerChannel('JellyStat')->info("Play count increment for {$title}: now {$itemStats[$key]['play_count']} (Episode: {$result['EpisodeName']}, User: {$result['UserName']}, Date: {$result['ActivityDateInserted']})");
  1180. }
  1181. // Update last played time
  1182. $currentTime = $result['ActivityDateInserted'] ?? null;
  1183. if ($currentTime && (!$itemStats[$key]['last_played'] || $currentTime > $itemStats[$key]['last_played'])) {
  1184. $itemStats[$key]['last_played'] = $currentTime;
  1185. }
  1186. // Update first played time
  1187. if ($currentTime && (!$itemStats[$key]['first_played'] || $currentTime < $itemStats[$key]['first_played'])) {
  1188. $itemStats[$key]['first_played'] = $currentTime;
  1189. }
  1190. }
  1191. }
  1192. // Separate by content type and sort by play count
  1193. foreach ($itemStats as $item) {
  1194. switch ($item['type']) {
  1195. case 'movie':
  1196. $processed['movies'][] = $item;
  1197. break;
  1198. case 'show':
  1199. $processed['shows'][] = $item;
  1200. break;
  1201. case 'music':
  1202. $processed['music'][] = $item;
  1203. break;
  1204. }
  1205. }
  1206. // Sort each category by play count (descending)
  1207. usort($processed['movies'], function($a, $b) {
  1208. return $b['play_count'] - $a['play_count'];
  1209. });
  1210. usort($processed['shows'], function($a, $b) {
  1211. return $b['play_count'] - $a['play_count'];
  1212. });
  1213. usort($processed['music'], function($a, $b) {
  1214. return $b['play_count'] - $a['play_count'];
  1215. });
  1216. return $processed;
  1217. }
  1218. }