-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
660 lines (522 loc) · 19.5 KB
/
scripts.js
File metadata and controls
660 lines (522 loc) · 19.5 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
import { config } from './config.js';
const auth0 = window.auth0; // Auth0 will be globally available
// DOM elements
const loading = document.getElementById('loading');
const error = document.getElementById('error');
const errorDetails = document.getElementById('error-details');
const loggedOutSection = document.getElementById('logged-out');
const loggedInSection = document.getElementById('logged-in');
const loginBtn = document.getElementById('login-btn');
const logoutBtn = document.getElementById('logout-btn');
const profileContainer = document.getElementById('profile');
let auth0Client;
// Initialize Auth0 client
async function initAuth0() {
try {
// Validate environment variables
const domain = config.auth0Domain;
const clientId = config.auth0ClientId;
if (!domain || !clientId) {
throw new Error('Auth0 configuration missing. Please check your config.js file for auth0Domain and auth0ClientId');
}
// Normalize and validate Auth0 domain format
let hostname = domain;
try {
// Allow developers to accidentally include protocol, e.g. "https://your-domain.auth0.com"
if (typeof domain === 'string' && (domain.startsWith('http://') || domain.startsWith('https://') || domain.includes('://'))) {
const parsed = new URL(domain);
hostname = parsed.hostname;
}
} catch (e) {
// If URL parsing fails, fall back to the raw domain string
hostname = domain;
}
const allowedAuth0Suffixes = [
'.auth0.com',
'.us.auth0.com',
'.eu.auth0.com',
'.au.auth0.com'
];
const hasValidAuth0Suffix = allowedAuth0Suffixes.some(suffix => typeof hostname === 'string' && hostname.endsWith(suffix));
if (!hasValidAuth0Suffix) {
console.warn('Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com');
}
auth0Client = await window.auth0.createAuth0Client({
domain: domain,
clientId: clientId,
// Persist tokens across pages / reloads and allow refresh tokens
cacheLocation: 'localstorage',
useRefreshTokens: true,
authorizationParams: {
// Redirect back to the same page the user initiated login from
redirect_uri: window.location.origin + window.location.pathname
}
});
// Check if user is returning from login
if (window.location.search.includes('code=') && window.location.search.includes('state=')) {
await handleRedirectCallback();
}
// Update UI based on authentication state
await updateUI();
} catch (err) {
console.error('Auth0 initialization error:', err);
showError(err.message);
}
}
// Handle redirect callback
async function handleRedirectCallback() {
try {
await auth0Client.handleRedirectCallback();
// Clean up the URL to remove query parameters
window.history.replaceState({}, document.title, window.location.pathname);
} catch (err) {
console.error('Redirect callback error:', err);
showError(err.message);
}
}
// Update UI based on authentication state
async function updateUI() {
try {
const isAuthenticated = await auth0Client.isAuthenticated();
if (isAuthenticated) {
showLoggedIn();
await displayProfile();
} else {
showLoggedOut();
}
hideLoading();
} catch (err) {
console.error('UI update error:', err);
showError(err.message);
}
}
// Display user profile
async function displayProfile() {
try {
const user = await auth0Client.getUser();
const placeholderImage = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='50' height='50' viewBox='0 0 50 50'%3E%3Ccircle cx='25' cy='25' r='25' fill='%2363b3ed'/%3E%3Cpath d='M55 50c8.28 0 15-6.72 15-15s-6.72-15-15-15-15 6.72-15 15 6.72 15 15 15zm0 7.5c-10 0-30 5.02-30 15v3.75c0 2.07 1.68 3.75 3.75 3.75h52.5c2.07 0 3.75-1.68 3.75-3.75V72.5c0-9.98-20-15-30-15z' fill='%23fff'/%3E%3C/svg%3E`;
profileContainer.innerHTML = `
<div style="display: flex; align-items: center; gap: 5px;">
<img
src="${user.picture || placeholderImage}"
alt="${user.name || 'User'}"
class="profile-picture"
onerror="this.src='${placeholderImage}'"
/>
<div style="text-align: center;">
<div class="profile-email" style="font-weight: 600; color: #a0aec0;">
${user.email || 'No email provided'}
</div>
</div>
</div>
`;
} catch (err) {
console.error('Error displaying profile:', err);
}
}
// Event handlers
async function login() {
try {
await auth0Client.loginWithRedirect({
authorizationParams: {
redirect_uri: window.location.origin + window.location.pathname
}
});
} catch (err) {
console.error('Login error:', err);
showError(err.message);
}
}
async function logout() {
try {
await auth0Client.logout({
logoutParams: {
returnTo: window.location.origin
}
});
} catch (err) {
console.error('Logout error:', err);
showError(err.message);
}
}
function hideLoading() {
loading.style.display = 'none';
}
function showError(message) {
loading.style.display = 'none';
error.style.display = 'block';
errorDetails.textContent = message;
}
function showLoggedIn() {
loggedOutSection.style.display = 'none';
loggedInSection.style.display = 'flex';
}
function showLoggedOut() {
loggedInSection.style.display = 'none';
loggedOutSection.style.display = 'flex';
}
// Event listeners
loginBtn.addEventListener('click', login);
logoutBtn.addEventListener('click', logout);
// Initialize the app
initAuth0();
const PROXY_BASE = "https://itad-proxy.ivanprokopenkose7en.workers.dev";
let matchingGames = [];
function showHints(hints) {
const hintsContainer = document.querySelector(".search-hints");
hintsContainer.innerHTML = "";
const hintList = hintsContainer.appendChild(document.createElement("ul"));
hints.forEach((hint) => {
const hintEl = hintList.appendChild(document.createElement("li"))
// Store slug-to-ID mapping for later lookup
setCachedData(`slug_${hint.slug}`, hint.id);
// Use clean path-based URLs
hintEl.innerHTML = `<a href="/game/${hint.slug}">${hint.title}</a>`;
});
}
/* STEAM API IMPLEMENTATION (COMMENTED OUT)
async function fetchSteamDescription(appid) {
if (!appid) return null;
try {
// Use CORS proxy for Steam API
const response = await fetch(`https://corsproxy.io/?${encodeURIComponent(`https://store.steampowered.com/api/appdetails?appids=${appid}`)}`);
const data = await response.json();
console.log("Steam description data:", data);
if (data[appid]?.success && (data[appid]?.data?.short_description || data[appid]?.data?.about_the_game)) {
return data[appid].data.about_the_game || data[appid].data.short_description;
}
} catch (error) {
console.error("Error fetching Steam description:", error);
}
return null;
}
*/
// Helper function to strip HTML tags
function stripHTML(html) {
if (!html || !html.includes('<')) return html;
const temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent || temp.innerText || '';
}
// RAWG API implementation for fetching game summary (optimized to use slug first)
async function fetchRAWGDescription(gameName, gameSlug) {
if (!gameName) return null;
try {
const apiKey = config.rawgApiKey;
if (!apiKey) {
console.warn('RAWG API key not configured');
return null;
}
let slugToUse = gameSlug;
// Step 1: Try direct fetch with slug if available
if (gameSlug) {
try {
const detailResponse = await fetch(
`https://api.rawg.io/api/games/${gameSlug}?key=${apiKey}`
);
if (detailResponse.ok) {
const details = await detailResponse.json();
const description = details.description_raw || details.description;
if (description) {
const cleanText = stripHTML(description).trim();
if (cleanText) {
return { text: cleanText, source: 'RAWG' };
}
}
}
} catch (error) {
console.warn('Direct slug fetch failed, falling back to search:', error.message);
}
}
// Step 2: Fallback to search if direct fetch failed or slug not provided
const searchResponse = await fetch(
`https://api.rawg.io/api/games?key=${apiKey}&search=${encodeURIComponent(gameName)}&search_exact=true&page_size=1`
);
if (!searchResponse.ok) {
console.error("RAWG search error:", searchResponse.statusText);
return null;
}
const searchData = await searchResponse.json();
if (searchData.results && searchData.results.length > 0) {
slugToUse = searchData.results[0].slug;
// Fetch full game details by slug
const detailResponse = await fetch(
`https://api.rawg.io/api/games/${slugToUse}?key=${apiKey}`
);
if (!detailResponse.ok) {
console.error("RAWG detail error:", detailResponse.statusText);
return null;
}
const details = await detailResponse.json();
const description = details.description_raw || details.description;
if (description) {
const cleanText = stripHTML(description).trim();
if (cleanText) {
return { text: cleanText, source: 'RAWG' };
}
}
}
} catch (error) {
console.error("Error fetching RAWG description:", error);
}
return null;
}
// Resolve game slug to ID using cache or search API
async function resolveSlugToId(slug) {
// Check cache first
const cacheKey = `slug_${slug}`;
const cachedId = getCachedData(cacheKey);
if (cachedId) {
return cachedId;
}
// If not in cache, search for the game
try {
const response = await fetch(`${PROXY_BASE}?endpoint=/games/search/v1&title=${encodeURIComponent(slug)}`);
const data = await response.json();
if (data && data.length > 0) {
// Find best match by slug
const game = data.find(g => g.slug === slug) || data[0];
setCachedData(cacheKey, game.id);
return game.id;
}
} catch (error) {
console.error('Error resolving slug to ID:', error);
}
return null;
}
// Main function to fetch game description using RAWG only (with aggressive caching)
async function fetchGameDescription(gameInfo) {
if (!gameInfo) return { text: 'Description unavailable', source: null };
// Check cache first (30-day cache since descriptions never change)
const cacheKey = `desc_${gameInfo.slug || gameInfo.title}`;
const cached = getCachedData(cacheKey, CACHE_DURATIONS.description);
if (cached) return cached;
// Fetch from RAWG API (pass both title and slug for optimization)
const result = await fetchRAWGDescription(gameInfo.title, gameInfo.slug);
// Cache the result (even if null/empty to avoid repeated failed requests)
const finalResult = result || { text: 'Description unavailable', source: null };
setCachedData(cacheKey, finalResult, CACHE_DURATIONS.description);
return finalResult;
}
function renderDeals(game, slug) {
const gameList = document.querySelector(".game-list");
document.querySelector(".title").innerText = slug;
game.deals.forEach((deal) => {
const dealDiv = document.createElement("li");
const dealA = document.createElement("a");
dealDiv.classList.add("game-list_deal");
dealA.classList.add("game-list_link");
dealA.href = deal.url;
dealA.target = "_blank";
dealA.innerHTML = `
<div class="game-list_shop">${deal.shop.name}</div>
<div class="game-list_sale">$${deal.price.amount}</div>
<div class="game-list_discount">${deal.cut}%</div>
`;
dealDiv.appendChild(dealA);
gameList.appendChild(dealDiv);
});
}
async function showGameSidebar(gameInfo) {
const sidebar = document.querySelector(".game-sidebar");
sidebar.innerHTML = "";
// Fetch game description from RAWG
const descriptionResult = await fetchGameDescription(gameInfo);
const descriptionText = descriptionResult.text;
const source = descriptionResult.source;
// Determine attribution link
const attributionHTML = source === 'RAWG'
? 'summary by <a target="_blank" href="https://rawg.io/">RAWG</a>'
: 'summary unavailable';
sidebar.innerHTML = `
<div class="game-sidebar_banner">
<img src="${gameInfo.assets.banner400}" alt="${gameInfo.title} Banner">
</div>
<div class="game-sidebar_block">
<ul class="game-sidebar_tags">
${gameInfo.tags.map(tag => `<li class="game-sidebar_tag">${tag}</li>`).join('')}
</ul>
<div class="game-sidebar_description">
${descriptionText}
</div>
<span class="game-sidebar_metacritic">${attributionHTML}</span>
</div>
`;
}
const FULL_CACHE_DURATION = 1000 * 60 * 60 * 24; // 24 hours
const CACHE_DURATION = 1000 * 60 * 5; // 5 minutes (default)
// Granular cache durations for different data types
const CACHE_DURATIONS = {
gameInfo: 1000 * 60 * 60 * 24 * 7, // 7 days - game info rarely changes
prices: 1000 * 60 * 60, // 1 hour - prices change frequently
slugToId: 1000 * 60 * 60 * 24 * 30, // 30 days - slug-to-ID mapping is permanent
search: 1000 * 60 * 5, // 5 minutes - search results are dynamic
description: 1000 * 60 * 60 * 24 * 30 // 30 days - descriptions never change
};
function getCachedData(key, customDuration) {
const cachedItem = localStorage.getItem(key);
if (!cachedItem) return null;
try {
const parsed = JSON.parse(cachedItem);
const duration = customDuration || parsed.duration || CACHE_DURATION;
if (parsed.timestamp + duration < Date.now()) {
localStorage.removeItem(key);
return null;
}
return parsed.data;
} catch (e) {
localStorage.removeItem(key);
return null;
}
}
function clearDayOldStorage() {
Object.keys(localStorage).forEach(key => {
try {
const { timestamp } = JSON.parse(localStorage.getItem(key));
if (timestamp + FULL_CACHE_DURATION < Date.now()) {
localStorage.removeItem(key);
}
} catch (e) {
localStorage.removeItem(key);
}
});
}
function setCachedData(key, data, customDuration) {
const cacheObject = {
data: data,
timestamp: Date.now(),
duration: customDuration || CACHE_DURATION
};
localStorage.setItem(key, JSON.stringify(cacheObject));
}
document.addEventListener("DOMContentLoaded", async () => {
clearDayOldStorage();
// Check if redirected from 404.html (GitHub Pages)
let pathToUse = window.location.pathname;
const redirectPath = sessionStorage.getItem('redirectPath');
if (redirectPath) {
pathToUse = redirectPath;
sessionStorage.removeItem('redirectPath');
history.replaceState(null, '', redirectPath);
}
const pathParts = pathToUse.split('/');
const slug = pathParts[pathParts.length - 1];
if (slug && slug !== 'game' && slug !== 'game.html') {
const appID = await resolveSlugToId(slug);
if (!appID) {
console.error('Could not resolve game slug to ID');
return;
}
const dealsCacheKey = `deals_${appID}`;
const infoCacheKey = `info_${appID}`;
const descCacheKey = `desc_${slug}`;
// ⚡ INSTANT RENDER: Check if we have cached data
const cachedInfo = getCachedData(infoCacheKey, CACHE_DURATIONS.gameInfo);
const cachedDeals = getCachedData(dealsCacheKey, CACHE_DURATIONS.prices);
const cachedDesc = getCachedData(descCacheKey, CACHE_DURATIONS.description);
// If ALL data is cached, render INSTANTLY
if (cachedInfo && cachedDeals && cachedDesc) {
console.log('⚡ Instant render from cache');
showGameSidebar(cachedInfo, cachedDesc);
renderDeals(cachedDeals, cachedInfo.title);
// Optionally fetch fresh data in background (only if cache is older than 1 hour)
const cacheAge = Date.now() - JSON.parse(localStorage.getItem(infoCacheKey))?.timestamp;
if (cacheAge > 1000 * 60 * 60) { // 1 hour
console.log('🔄 Refreshing data in background');
refreshGameDataInBackground(appID, slug);
}
// Don't return - let search bar initialization run below
} else {
// Otherwise, fetch data normally
try {
const gameInfoPromise = fetch(`${PROXY_BASE}?endpoint=/games/info/v2&id=${appID}`)
.then(response => response.json())
.then(info => {
setCachedData(infoCacheKey, info, CACHE_DURATIONS.gameInfo);
return info;
});
const [gameInfo, gamePrices, descriptionResult] = await Promise.all([
gameInfoPromise,
cachedDeals
? Promise.resolve(cachedDeals)
: fetch(`${PROXY_BASE}?endpoint=/games/prices/v3`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([appID])
})
.then(response => response.json())
.then(pricesArray => {
const prices = pricesArray[0];
setCachedData(dealsCacheKey, prices, CACHE_DURATIONS.prices);
return prices;
}),
gameInfoPromise.then(info => fetchGameDescription(info))
]);
console.log("Fetched game data:", { gameInfo, gamePrices, descriptionResult });
showGameSidebar(gameInfo, descriptionResult);
renderDeals(gamePrices, gameInfo.title);
} catch (error) {
console.error("Error fetching game data:", error);
}
} // End else block for cached data check
}
//searching
const searchBar = document.getElementById("searchBar");
if (searchBar) {
searchBar.addEventListener("input", (e) => {
const searchTerm = e.target.value.toLowerCase();
if (searchTerm.length === 0) {
showHints([]);
return;
}
fetch(`${PROXY_BASE}?endpoint=/games/search/v1&title=${encodeURIComponent(searchTerm)}&results=5`)
.then((response) => response.json())
.then((data) => {
matchingGames = data;
const filteredHints = matchingGames.filter((game) =>
game.title.toLowerCase().includes(searchTerm)
);
showHints(filteredHints)
})
.catch((error) => console.error("Error fetching hints:", error));
});
}
});
// Background refresh function (non-blocking)
async function refreshGameDataInBackground(appID, slug) {
try {
const dealsCacheKey = `deals_${appID}`;
const infoCacheKey = `info_${appID}`;
const gameInfoPromise = fetch(`${PROXY_BASE}?endpoint=/games/info/v2&id=${appID}`)
.then(response => response.json())
.then(info => {
setCachedData(infoCacheKey, info, CACHE_DURATIONS.gameInfo);
return info;
});
const [gameInfo, gamePrices, descriptionResult] = await Promise.all([
gameInfoPromise,
fetch(`${PROXY_BASE}?endpoint=/games/prices/v3`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([appID])
})
.then(response => response.json())
.then(pricesArray => {
const prices = pricesArray[0];
setCachedData(dealsCacheKey, prices, CACHE_DURATIONS.prices);
return prices;
}),
gameInfoPromise.then(info => fetchGameDescription(info))
]);
// Update UI with fresh data
showGameSidebar(gameInfo, descriptionResult);
renderDeals(gamePrices, gameInfo.title);
console.log('✅ Background refresh complete');
} catch (error) {
console.error("Error refreshing data:", error);
}
}
/*
1. pass all filter data to url
2. read url parameters and make a fetch request with those parameters(apply default parameters if not provided)
*/