jellystat.php 90 KB

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