// main.js const userAgents = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35", ]; function getRandomUserAgent() { return userAgents[Math.floor(Math.random() * userAgents.length)]; } function makeRequest() { var username = document.getElementById('username').value; // Check if the username is blank if (!username.trim()) { // If the username is blank, do nothing return; } var randomUserAgent = getRandomUserAgent(); var url = `https://api.chess.com/pub/player/${username}/games/archives?callback=jsonpCallback&user_agent=${encodeURIComponent(randomUserAgent)}`; var script = document.createElement('script'); script.src = url; window.jsonpCallback = function(data) { // Check if the response has archives if (data && data.archives && Array.isArray(data.archives)) { if (data.archives.length === 0) { alert("No games found for the provided username."); // Optionally, you can provide a message or take other actions } else { const promises = data.archives.map(function(archiveUrl) { // Append '/.pgn' to each individual URL const url = archiveUrl; return makeAsyncRequest(url, getRandomUserAgent()); }); // Use Promise.all to wait for all requests to complete Promise.all(promises) .then(function(results) { // Concatenate the 'pgn' values const concatenatedPgn = results.flatMap(data => data.games.map(game => game.pgn)).join('\n'); // Trigger download downloadFile(username, concatenatedPgn); }) .catch(function(error) { console.error("Error in one or more requests:", error); // Optionally, you can log errors, but no popup is shown }); } } else { // Handle the case where there are no archives or an invalid response alert("Invalid response from the Chess.com API. Please try again."); // Optionally, you can provide a message or take other actions } // Clean up the script element document.head.removeChild(script); }; document.head.appendChild(script); } // Function to trigger download function downloadFile(username, content) { const blob = new Blob([content], { type: 'text/plain' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `${username}.pgn`; a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(a.href); } // Function to make asynchronous requests function makeAsyncRequest(url, userAgent) { return new Promise(function(resolve, reject) { const callbackName = `jsonpCallback_${Date.now()}_${Math.floor(Math.random() * 1000)}`; const script = document.createElement('script'); window[callbackName] = function(data) { document.head.removeChild(script); delete window[callbackName]; resolve(data); }; const callbackUrl = `${url}?callback=${callbackName}&user_agent=${encodeURIComponent(userAgent)}`; script.src = callbackUrl; document.head.appendChild(script); script.onerror = function(error) { document.head.removeChild(script); delete window[callbackName]; reject(error); }; }); }