jellystat.php 94 KB

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