gog: login, claim (waiting), unsubscribe newsletter
This commit is contained in:
parent
593677ca19
commit
6305ffd15d
1 changed files with 37 additions and 114 deletions
151
gog.js
151
gog.js
|
|
@ -11,158 +11,81 @@ const debug = process.env.PWDEBUG == '1'; // runs non-headless and opens https:/
|
||||||
const show = process.argv.includes('show', 2);
|
const show = process.argv.includes('show', 2);
|
||||||
const headless = !debug && !show;
|
const headless = !debug && !show;
|
||||||
|
|
||||||
// const URL_LOGIN = 'https://www.amazon.de/ap/signin'; // wrong. needs some session args to be valid?
|
const URL_CLAIM = 'https://www.gog.com/en';
|
||||||
const URL_CLAIM = 'https://gaming.amazon.com/home';
|
const TIMEOUT = 0 * 1000; // 20s, default is 30s
|
||||||
const TIMEOUT = 20 * 1000; // 20s, default is 30s
|
|
||||||
const SCREEN_WIDTH = Number(process.env.SCREEN_WIDTH) || 1280;
|
const SCREEN_WIDTH = Number(process.env.SCREEN_WIDTH) || 1280;
|
||||||
const SCREEN_HEIGHT = Number(process.env.SCREEN_HEIGHT) || 1280;
|
const SCREEN_HEIGHT = Number(process.env.SCREEN_HEIGHT) || 1280;
|
||||||
|
|
||||||
console.log(datetime(), 'started checking prime-gaming');
|
console.log(datetime(), 'started checking gog');
|
||||||
|
|
||||||
const db = await jsonDb('prime-gaming.json');
|
const db = await jsonDb('gog.json');
|
||||||
db.data ||= {};
|
db.data ||= {};
|
||||||
const migrateDb = (user) => {
|
|
||||||
if (user in db.data || !('claimed' in db.data)) return;
|
|
||||||
db.data[user] = {};
|
|
||||||
for (const e of db.data.claimed) {
|
|
||||||
db.data[user][e.title] = e;
|
|
||||||
}
|
|
||||||
delete db.data.claimed;
|
|
||||||
delete db.data.runs;
|
|
||||||
}
|
|
||||||
|
|
||||||
// https://playwright.dev/docs/auth#multi-factor-authentication
|
// https://playwright.dev/docs/auth#multi-factor-authentication
|
||||||
const context = await firefox.launchPersistentContext(dirs.browser, {
|
const context = await firefox.launchPersistentContext(dirs.browser, {
|
||||||
headless,
|
headless,
|
||||||
viewport: { width: SCREEN_WIDTH, height: SCREEN_HEIGHT },
|
viewport: { width: SCREEN_WIDTH, height: SCREEN_HEIGHT },
|
||||||
locale: "en-US", // ignore OS locale to be sure to have english text for locators
|
locale: "en-US", // ignore OS locale to be sure to have english text for locators -> done via /en in URL
|
||||||
});
|
});
|
||||||
|
|
||||||
// TODO test if needed
|
|
||||||
await stealth(context);
|
|
||||||
|
|
||||||
if (!debug) context.setDefaultTimeout(TIMEOUT);
|
if (!debug) context.setDefaultTimeout(TIMEOUT);
|
||||||
|
|
||||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||||
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
await context.addCookies([{name: 'CookieConsent', value: '{stamp:%274oR8MJL+bxVlG6g+kl2we5+suMJ+Tv7I4C5d4k+YY4vrnhCD+P23RQ==%27%2Cnecessary:true%2Cpreferences:true%2Cstatistics:true%2Cmarketing:true%2Cmethod:%27explicit%27%2Cver:1%2Cutc:1672331618201%2Cregion:%27de%27}', domain: 'www.gog.com', path: '/'}]); // to not waste screen space when non-headless
|
||||||
|
|
||||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
||||||
// need to wait for some elements to exist before checking if signed in or accepting cookies:
|
|
||||||
await Promise.any(['button:has-text("Sign in")', '[data-a-target="user-dropdown-first-name-text"]'].map(s => page.waitForSelector(s)));
|
// page.click('#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll').catch(_ => { }); // does not work reliably, solved by setting CookieConsent above
|
||||||
page.click('[aria-label="Cookies usage disclaimer banner"] button:has-text("Accept Cookies")').catch(_ => { }); // to not waste screen space when non-headless, TODO does not work reliably, need to wait for something else first?
|
// await Promise.any([page.waitForSelector('a:has-text("Sign in")', {}), page.waitForSelector('#menuUsername')]);
|
||||||
while (await page.locator('button:has-text("Sign in")').count() > 0) {
|
while (await page.locator('a:has-text("Sign in")').first().isVisible()) {
|
||||||
console.error('Not signed in anymore.');
|
console.error('Not signed in anymore.');
|
||||||
await page.click('button:has-text("Sign in")');
|
await page.click('a:has-text("Sign in")');
|
||||||
|
// it then creates an iframe for the login
|
||||||
|
await page.waitForSelector('#GalaxyAccountsFrameContainer iframe'); // TODO needed?
|
||||||
|
const iframe = page.frameLocator('#GalaxyAccountsFrameContainer iframe');
|
||||||
if (!debug) context.setDefaultTimeout(0); // give user time to log in without timeout
|
if (!debug) context.setDefaultTimeout(0); // give user time to log in without timeout
|
||||||
console.info('Press ESC to skip if you want to login in the browser (not possible in default headless mode).');
|
console.info('Press ESC to skip if you want to login in the browser (not possible in headless mode).');
|
||||||
const email = process.env.EMAIL || await prompt({message: 'Enter email'});
|
const email = process.env.EMAIL || await prompt({message: 'Enter email'});
|
||||||
const password = process.env.PASSWORD || await prompt({type: 'password', message: 'Enter password'});
|
const password = process.env.PASSWORD || await prompt({type: 'password', message: 'Enter password'});
|
||||||
if (email && password) {
|
if (email && password) {
|
||||||
await page.fill('[name=email]', email);
|
iframe.locator('a[href="/logout"]').click().catch(_ => { }); // Click 'Change account' (email from previous login is set in some cookie)
|
||||||
await page.fill('[name=password]', password);
|
await iframe.locator('#login_username').fill(email);
|
||||||
await page.check('[name=rememberMe]');
|
await iframe.locator('#login_password').fill(password);
|
||||||
await page.click('input[type="submit"]');
|
await iframe.locator('#login_login').click();
|
||||||
// handle MFA, but don't await it
|
// handle MFA, but don't await it
|
||||||
page.waitForNavigation({ url: '**/ap/mfa**'}).then(async () => {
|
iframe.locator('form[name=second_step_authentication]').waitFor().then(async () => {
|
||||||
console.log('Two-Step Verification - enter the One Time Password (OTP), e.g. generated by your Authenticator App');
|
console.log('Two-Step Verification - Enter security code');
|
||||||
await page.check('[name=rememberDevice]');
|
console.log(await iframe.locator('.form__description').innerText())
|
||||||
const otp = await prompt({type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!'}); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
const otp = await prompt({type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 4 || 'The code must be 4 digits!'}); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||||
await page.type('input[name=otpCode]', otp.toString());
|
await iframe.locator('#second_step_authentication_token_letter_1').type(otp.toString(), {delay: 10});
|
||||||
await page.click('input[type="submit"]');
|
await iframe.locator('#second_step_authentication_send').click();
|
||||||
|
await page.waitForTimeout(1000); // TODO wait for something else below?
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
if (headless) {
|
if (headless) {
|
||||||
console.log('Please run `node prime-gaming show` to login in the opened browser.');
|
console.log('Please run `node gog show` to login in the opened browser.');
|
||||||
await context.close(); // not needed?
|
await context.close(); // not needed?
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
console.log('Waiting for you to login in the browser.');
|
console.log('Waiting for you to login in the browser.');
|
||||||
}
|
}
|
||||||
await page.waitForNavigation({ url: 'https://gaming.amazon.com/home?signedIn=true' });
|
// await page.waitForNavigation(); // TODO was blocking
|
||||||
if (!debug) context.setDefaultTimeout(TIMEOUT);
|
if (!debug) context.setDefaultTimeout(TIMEOUT);
|
||||||
}
|
}
|
||||||
const user = await page.locator('[data-a-target="user-dropdown-first-name-text"]').first().innerText();
|
const user = await page.locator('#menuUsername').first().innerHTML();
|
||||||
console.log(`Signed in as ${user}`);
|
console.log(`Signed in as ${user}`);
|
||||||
// await page.click('button[aria-label="User dropdown and more options"]');
|
|
||||||
// const twitch = await page.locator('[data-a-target="TwitchDisplayName"]').first().innerText();
|
|
||||||
// console.log(`Twitch user name is ${twitch}`);
|
|
||||||
migrateDb(user); // TODO remove this after some time since it will run fine without and people can still use this commit to adjust their data/prime-gaming.json
|
|
||||||
db.data[user] ||= {};
|
db.data[user] ||= {};
|
||||||
|
|
||||||
await page.click('button[data-type="Game"]');
|
console.log('TODO get title of current game (waiting for next offer)');
|
||||||
const games_sel = 'div[data-a-target="offer-list-FGWP_FULL"]';
|
await page.goto('https://www.gog.com/giveaway/claim');
|
||||||
await page.waitForSelector(games_sel);
|
console.log(await page.innerText('body'));
|
||||||
console.log('Number of already claimed games (total):', await page.locator(`${games_sel} p:has-text("Collected")`).count());
|
|
||||||
const game_sel = `${games_sel} [data-a-target="item-card"]:has-text("Claim game")`;
|
console.log("Unsubscribe from 'Promotions and hot deals' newsletter");
|
||||||
console.log('Number of free unclaimed games (Prime Gaming):', await page.locator(game_sel).count());
|
await page.goto('https://www.gog.com/en/account/settings/subscriptions');
|
||||||
const games = await page.$$(game_sel);
|
await page.locator('li:has-text("Promotions and hot deals") input').uncheck();
|
||||||
// for (let i=1; i<=n; i++) {
|
|
||||||
for (const card of games) {
|
|
||||||
// const card = page.locator(`:nth-match(${game_sel}, ${i})`); // this will reevaluate after games are claimed and index will be wrong
|
|
||||||
// const title = await card.locator('h3').first().innerText();
|
|
||||||
const title = await (await card.$('.item-card-details__body__primary')).innerText();
|
|
||||||
console.log('Current free game:', title);
|
|
||||||
if (process.env.DRYRUN) continue;
|
|
||||||
// const img = await (await card.$('img.tw-image')).getAttribute('src');
|
|
||||||
// console.log('Image:', img);
|
|
||||||
const p = path.resolve(dirs.screenshots, 'prime-gaming', 'internal', `${filenamify(title)}.png`);
|
|
||||||
await card.screenshot({ path: p });
|
|
||||||
await (await card.$('button:has-text("Claim game")')).click();
|
|
||||||
db.data[user][title] ||= { title, time: datetime(), store: 'internal' };
|
|
||||||
// await page.pause();
|
|
||||||
}
|
|
||||||
// claim games in external/linked stores. Linked: origin.com, epicgames.com; Redeem-key: gog.com, legacygames.com, microsoft
|
|
||||||
let n;
|
|
||||||
const game_sel_ext = `${games_sel} [data-a-target="item-card"]:has(p:text-is("Claim"))`;
|
|
||||||
do {
|
|
||||||
n = await page.locator(game_sel_ext).count();
|
|
||||||
console.log('Number of free unclaimed games (external stores):', n);
|
|
||||||
const card = await page.$(game_sel_ext);
|
|
||||||
if (!card) break;
|
|
||||||
const title = await (await card.$('.item-card-details__body__primary')).innerText();
|
|
||||||
console.log('Current free game:', title);
|
|
||||||
if (process.env.DRYRUN) continue;
|
|
||||||
await (await card.$('text=Claim')).click();
|
|
||||||
// await page.waitForNavigation();
|
|
||||||
await Promise.any([page.click('button:has-text("Claim now")'), page.click('button:has-text("Complete Claim")'), page.waitForSelector('div:has-text("Link game account")')]); // waits for navigation
|
|
||||||
const store_text = await (await page.$('[data-a-target="hero-header-subtitle"]')).innerText();
|
|
||||||
// Full game for PC [and MAC] on: gog.com, Origin, Legacy Games, EPIC GAMES, Battle.net
|
|
||||||
// 3 Full PC Games on Legacy Games
|
|
||||||
const store = store_text.toLowerCase().replace(/.* on /, '');
|
|
||||||
console.log(' External store:', store);
|
|
||||||
if (await page.locator('div:has-text("Link game account")').count()) {
|
|
||||||
console.error(' Account linking is required to claim this offer!');
|
|
||||||
} else {
|
|
||||||
// print code if there is one
|
|
||||||
const redeem = {
|
|
||||||
// 'origin': 'https://www.origin.com/redeem', // TODO still needed or now only via account linking?
|
|
||||||
'gog.com': 'https://www.gog.com/redeem',
|
|
||||||
'legacy games': 'https://www.legacygames.com/primedeal',
|
|
||||||
'microsoft games': 'https://redeem.microsoft.com',
|
|
||||||
};
|
|
||||||
let code;
|
|
||||||
if (store in redeem) { // did not work for linked origin: && !await page.locator('div:has-text("Successfully Claimed")').count()
|
|
||||||
code = await page.inputValue('input[type="text"]');
|
|
||||||
console.log(' Code to redeem game:', code);
|
|
||||||
if (store == 'legacy games') { // may be different URL like https://legacygames.com/primeday/puzzleoftheyear/
|
|
||||||
redeem[store] = await (await page.$('li:has-text("Click here") a')).getAttribute('href');
|
|
||||||
}
|
|
||||||
console.log(' URL to redeem game:', redeem[store]);
|
|
||||||
}
|
|
||||||
db.data[user][title] ||= { title, time: datetime(), store, code, url: page.url() };
|
|
||||||
// save screenshot of potential code just in case
|
|
||||||
const p = path.resolve(dirs.screenshots, 'prime-gaming', 'external', `${filenamify(title)}.png`);
|
|
||||||
await page.screenshot({ path: p, fullPage: true });
|
|
||||||
// console.info(' Saved a screenshot of page to', p);
|
|
||||||
}
|
|
||||||
// await page.pause();
|
|
||||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
|
|
||||||
await page.click('button[data-type="Game"]');
|
|
||||||
} while (n);
|
|
||||||
const p = path.resolve(dirs.screenshots, 'prime-gaming', `${filenamify(datetime())}.png`);
|
|
||||||
// await page.screenshot({ path: p, fullPage: true });
|
|
||||||
await page.locator(games_sel).screenshot({ path: p });
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error); // .toString()?
|
console.error(error); // .toString()?
|
||||||
} finally {
|
} finally {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue