jellystat.php 96 KB

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