jellystat.php 76 KB

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