chesstok-lookup/player_games.js
2023-11-23 02:51:05 -07:00

92 lines
2.7 KiB
JavaScript

// mainScript.js
import userAgents from './userAgents.js';
// Declare the script variable
//
let script;
window.downloadPGN = function() {
const username = document.getElementById('usernameInput').value;
if (!username) {
alert('Please enter a username.');
return;
}
// Create a callback function to handle the JSONP response for archives
const archivesCallback = 'handleArchivesResponse';
window[archivesCallback] = function(data) {
document.head.removeChild(script); // Remove the script element after execution
threddGames(data); // Pass the list of archive URLs to the threaded function
};
// Fetch player archives using JSONP
playerArchives(username, archivesCallback);
};
function getRandomUserAgent() {
return userAgents[Math.floor(Math.random() * userAgents.length)];
}
async function playerArchives(username, callback) {
// Replace 'YOUR_API_KEY' with your Chess.com API key
const url = `https://api.chess.com/pub/player/${username}/games/archives`;
const response = await fetch(url);
const data = await response.json();
window[callback](data.archives);
}
async function playerMonthly(url, callback) {
const user_agent = getRandomUserAgent();
const headers = {
'User-Agent': user_agent,
};
const response = await fetch(url + '/pgn', { headers });
const games = await response.text();
window[callback](games); // Execute the callback function with the PGN data
}
async function threddGames(archiveURLs) {
const gamesList = [];
// Using Promise.all to wait for all threads to complete
await Promise.all(archiveURLs.map(async (url) => {
return new Promise(async (resolve) => {
const monthlyGamesCallback = 'handleMonthlyGamesResponse';
window[monthlyGamesCallback] = function(data) {
handleDownload(data, gamesList, resolve);
};
// Fetch monthly games using JSONP
await playerMonthly(url, monthlyGamesCallback);
});
}));
// Combine and save the games to a file
const pgnDb = gamesList.join('\n\n');
const username = document.getElementById('usernameInput').value;
createDownloadLink(pgnDb, `${username}.pgn`);
}
function handleDownload(data, gamesList, resolve) {
gamesList.push(data);
resolve(); // Resolve the promise to indicate completion of this thread
}
function createDownloadLink(data, filename) {
const blob = new Blob([data], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}