jellystat.php 69 KB

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