Repository navigation
Expand file tree
/
Copy pathrating.js
More file actions
272 lines (230 loc) · 8.97 KB
/
Copy pathrating.js
File metadata and controls
272 lines (230 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/**
* Applies rating attributes to media elements and CSS styles to those element6
*/
(function() {
'use strict';
console.log("Jellyfin Rating Script: Loaded.");
// Configuration
const CONFIG = {
targetSelector: '.mediaInfoOfficialRating',
attributeName: 'rating',
fallbackInterval: 1000, // Fallback polling interval
debounceDelay: 100, // Debounce delay for rapid changes
maxRetries: 3,
cssUrl: 'https://cdn.jsdelivr.net/gh/n00bcodr/Jellyfish@main/ratings.css', // URL for the CSS
cssId: 'jellyfin-ratings-style' // ID for the style element to prevent duplicates
};
let observer = null;
let fallbackTimer = null;
let debounceTimer = null;
let processedElements = new WeakSet();
/**
* Injects the custom CSS file into the document's head.
*/
function injectCSS() {
// Check if the CSS has already been injected
if (document.getElementById(CONFIG.cssId)) {
return;
}
try {
const linkElement = document.createElement('link');
linkElement.id = CONFIG.cssId;
linkElement.rel = 'stylesheet';
linkElement.type = 'text/css';
linkElement.href = CONFIG.cssUrl;
document.head.appendChild(linkElement);
console.log("Jellyfin Rating Script: Custom CSS injected successfully.");
} catch (error) {
console.error("Jellyfin Rating Script: Failed to inject CSS.", error);
}
}
/**
* Processes rating elements and applies attributes
*/
function processRatingElements() {
try {
const elements = document.querySelectorAll(CONFIG.targetSelector);
let processedCount = 0;
elements.forEach((element, index) => {
// Skip if already processed and unchanged
if (processedElements.has(element)) {
const currentRating = element.textContent?.trim();
const existingRating = element.getAttribute(CONFIG.attributeName);
if (currentRating === existingRating) {
return;
}
}
const ratingText = element.textContent?.trim();
if (ratingText && ratingText.length > 0) {
// Normalize rating text (remove extra spaces, standardize format)
const normalizedRating = normalizeRating(ratingText);
if (element.getAttribute(CONFIG.attributeName) !== normalizedRating) {
element.setAttribute(CONFIG.attributeName, normalizedRating);
processedElements.add(element);
processedCount++;
// Add accessibility attributes
if (!element.getAttribute('aria-label')) {
element.setAttribute('aria-label', `Content rated ${normalizedRating}`);
}
// Add title for hover tooltip
if (!element.getAttribute('title')) {
element.setAttribute('title', `Rating: ${normalizedRating}`);
}
}
}
});
if (processedCount > 0) {
console.log(`Jellyfin Rating Script: Processed ${processedCount} rating elements.`);
}
} catch (error) {
console.error("Jellyfin Rating Script: Error processing elements:", error);
}
}
/**
* Normalizes rating text for consistent formatting
*/
function normalizeRating(rating) {
if (!rating) return '';
// Remove extra whitespace and normalize
let normalized = rating.replace(/\s+/g, ' ').trim().toUpperCase();
// Handle common variations and standardize formats
const ratingMappings = {
'NOT RATED': 'NR',
'NOT-RATED': 'NR',
'UNRATED': 'NR',
'NO RATING': 'NR',
'APPROVED': 'APPROVED',
'PASSED': 'PASSED'
};
return ratingMappings[normalized] || rating.trim();
}
/**
* Debounced version of processRatingElements
*/
function debouncedProcess() {
if (debounceTimer) {
clearTimeout(debounceTimer);
}
debounceTimer = setTimeout(processRatingElements, CONFIG.debounceDelay);
}
/**
* Sets up MutationObserver for efficient DOM monitoring
*/
function setupMutationObserver() {
if (!window.MutationObserver) {
console.warn("Jellyfin Rating Script: MutationObserver not supported, falling back to polling.");
return false;
}
try {
observer = new MutationObserver((mutations) => {
let shouldProcess = false;
mutations.forEach((mutation) => {
// Check for added nodes
if (mutation.type === 'childList') {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
if (node.matches && node.matches(CONFIG.targetSelector)) {
shouldProcess = true;
} else if (node.querySelector && node.querySelector(CONFIG.targetSelector)) {
shouldProcess = true;
}
}
});
}
// Check for text content changes
if (mutation.type === 'characterData' || mutation.type === 'childList') {
const target = mutation.target;
if (target.nodeType === Node.ELEMENT_NODE &&
(target.matches(CONFIG.targetSelector) || target.closest(CONFIG.targetSelector))) {
shouldProcess = true;
}
}
});
if (shouldProcess) {
debouncedProcess();
}
});
// Start observing
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: false
});
console.log("Jellyfin Rating Script: MutationObserver initialized.");
return true;
} catch (error) {
console.error("Jellyfin Rating Script: Failed to setup MutationObserver:", error);
return false;
}
}
/**
* Sets up fallback polling mechanism
*/
function setupFallbackPolling() {
fallbackTimer = setInterval(processRatingElements, CONFIG.fallbackInterval);
console.log(`Jellyfin Rating Script: Fallback polling started (${CONFIG.fallbackInterval}ms interval).`);
}
/**
* Cleanup function
*/
function cleanup() {
if (observer) {
observer.disconnect();
observer = null;
}
if (fallbackTimer) {
clearInterval(fallbackTimer);
fallbackTimer = null;
}
if (debounceTimer) {
clearTimeout(debounceTimer);
debounceTimer = null;
}
processedElements = new WeakSet();
}
/**
* Initialize the rating system
*/
function initialize() {
// Clean up any existing instances
cleanup();
// Inject the custom CSS
injectCSS();
// Process existing elements immediately
processRatingElements();
// Set up efficient monitoring
setupMutationObserver();
// Always set up fallback polling as backup
setupFallbackPolling();
console.log("Jellyfin Rating Script: Initialization complete.");
}
// Handle page visibility changes to optimize performance
if (typeof document.visibilityState !== 'undefined') {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
// Re-process when page becomes visible
setTimeout(processRatingElements, 100);
}
});
}
// Handle navigation changes (for SPAs)
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
setTimeout(initialize, 500); // Re-initialize after navigation
}
}).observe(document, { subtree: true, childList: true });
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initialize);
} else {
initialize();
}
// Cleanup on page unload
window.addEventListener('beforeunload', cleanup);
// Expose cleanup function globally for manual cleanup if needed
window.jellyfinRatingCleanup = cleanup;
})();