+ const gamesTitle = page.locator('p.offer-filters__button__title:has-text("Games"), p.offer-filters__button__title:has-text("einlösen")');
+ if (await gamesTitle.count()) {
+ const btn = gamesTitle.first().locator('xpath=ancestor::button[1]');
+ if (await btn.count()) {
+ await btn.click();
+ return;
+ }
+ }
+ // New Luna claims home already shows games list
+ };
+
+ await openGamesTab();
+
+ const locateGamesList = async () => {
+ const selectors = [
+ 'div[data-a-target="offer-list-FGWP_FULL"]', // old layout
+ '[data-testid="offer-list"]',
+ '[data-test-selector="offer-list"]',
+ 'section:has(h2:has-text("Games with Prime"))',
+ 'section:has(h2:has-text("Games"))',
+ ];
+ for (const sel of selectors) {
+ const loc = page.locator(sel).first();
+ if (await loc.count()) return loc;
+ }
+ return null;
+ };
+
+ const games = await locateGamesList();
+ // Load all cards (old and new layout) by scrolling the container or the page
+ if (games) await scrollUntilStable(() => games.evaluate(el => el.scrollHeight).catch(() => 0));
+ await scrollUntilStable(() => page.evaluate(() => globalThis.document?.scrollingElement?.scrollHeight ?? 0));
+
+ const normalizeClaimUrl = url => {
+ if (!url) return { url, key: null };
+ const m = url.match(/(https?:\/\/[^/]+)?(\/claims\/[^?#]+)/);
+ if (!m) return { url, key: url };
+ const path = m[2];
+ const slug = path.split('/')[2];
+ return { url: 'https://luna.amazon.com' + path, key: slug || path };
+ };
+
+ const cards = [];
+ // New layout: direct claim buttons on cards (FGWPOffer) with "Spiel aktivieren"/"Claim"
+ const fgwps = page.locator('[data-a-target="FGWPOffer"]');
+ if (await fgwps.count()) {
+ for (const handle of await fgwps.elementHandles()) {
+ const href = await handle.getAttribute('href');
+ const { url, key } = normalizeClaimUrl(href?.startsWith('/') ? href : href || '');
+ const title =
+ await handle.$eval('p[title], span[title]', el => el.getAttribute('title')).catch(() => null) ||
+ await handle.$eval('p, span', el => el.textContent).catch(() => null) ||
+ key ||
+ 'Unknown title';
+ cards.push({ kind: 'external', title, url, key });
+ }
+ }
+
+ const anchorClaims = page.locator('a[href*="/claims/"][href*="amzn1.pg.item"]');
+ if (await anchorClaims.count()) {
+ const hrefs = [...new Set(await anchorClaims.evaluateAll(anchors => anchors.map(a => a.getAttribute('href')).filter(Boolean)))];
+ for (const href of hrefs) {
+ const { url, key } = normalizeClaimUrl(href);
+ const title = key || await anchorClaims.first().innerText() || 'Unknown title';
+ cards.push({ kind: 'external', title, url, key });
+ }
+ }
+
+ if (!cards.length && games) {
+ const cardLocator = games.locator([
+ '[data-testid="offer-card"]',
+ '[data-test-selector="offer-card"]',
+ '.item-card__action',
+ ].join(','));
+ if (await cardLocator.count() === 0) {
+ console.log('No games found in list.');
+ } else {
+ for (const handle of await cardLocator.elementHandles()) {
+ const text = (await handle.textContent() || '').toLowerCase();
+ if (text.includes('collected')) continue; // skip already claimed
+ const title = await (await handle.$('h3, h4, [data-testid="item-card-title"], [data-test-selector="item-card-title"], .item-card-details__body__primary'))?.innerText() || 'Unknown title';
+ const linkEl = await handle.$('a[href]');
+ let url = linkEl && await linkEl.getAttribute('href');
+ if (url?.startsWith('/')) url = 'https://luna.amazon.com' + url;
+ const { url: normUrl, key } = normalizeClaimUrl(url);
+ const hasLinkClaim = await handle.$('a:has-text("Claim"), a:has-text("Get"), a:has-text("Details")');
+ const hasButtonClaim = await handle.$('button:has-text("Claim"), button:has-text("Get"), button:has-text("Get game"), button:has-text("Play")');
+ const hasGermanCTA = await handle.$(':is(button,p,a):has-text("Spiel aktivieren"), :is(button,p,a):has-text("Spiel holen")');
+ if (hasLinkClaim || hasGermanCTA) cards.push({ kind: 'external', title, url: normUrl, key });
+ else if (hasButtonClaim) cards.push({ kind: 'internal', title, url: normUrl, key, handle });
+ }
+ }
+ }
+
+ // dedup by URL to avoid duplicates from multiple selectors
+ const seenUrl = new Set();
+ const uniq = cards.filter(c => {
+ const key = c.key || c.url || c.title;
+ if (seenUrl.has(key)) return false;
+ seenUrl.add(key);
+ return true;
+ });
+
+ const internal = uniq.filter(c => c.kind == 'internal');
+ const external = uniq.filter(c => c.kind == 'external');
+ // bottom to top: oldest to newest games
+ internal.reverse();
+ external.reverse();
+ const sameOrNewPage = async url => {
+ const isNew = page.url() != url;
+ let p = page;
+ if (isNew) {
+ p = await context.newPage();
+ await p.goto(url, { waitUntil: 'domcontentloaded' });
+ }
+ return [p, isNew];
+ };
+ const skipBasedOnTime = async url => {
+ const [p, isNew] = await sameOrNewPage(url);
+ const dueDateLoc = p.locator('.availability-date .tw-bold, [data-testid="availability-end-date"], [data-test-selector="availability-end-date"]');
+ if (!await dueDateLoc.count()) {
+ if (isNew) await p.close();
+ return false;
+ }
+ const dueDateOrg = await dueDateLoc.first().innerText();
+ const dueDate = new Date(Date.parse(dueDateOrg + ' 17:00'));
+ const daysLeft = (dueDate.getTime() - Date.now()) / 1000 / 60 / 60 / 24;
+ const availabilityText = await p.locator('.availability-date, [data-testid="availability-end-date"], [data-test-selector="availability-end-date"]').first().innerText().catch(() => dueDateOrg);
+ console.log(' ', availabilityText, '->', daysLeft.toFixed(2));
+ if (isNew) await p.close();
+ return daysLeft > cfg.pg_timeLeft;
+ };
+ console.log('\nNumber of free unclaimed games (Prime Gaming):', internal.length);
+ // claim games in internal store
+ for (const card of internal) {
+ await card.handle.scrollIntoViewIfNeeded();
+ const title = card.title;
+ const url = card.url;
+ console.log('Current free game:', chalk.blue(title));
+ if (cfg.pg_timeLeft && url && await skipBasedOnTime(url)) continue;
+ if (cfg.dryrun) continue;
+ if (cfg.interactive) {
+ const confirmed = await confirm();
+ if (!confirmed) continue;
+ }
+ await card.handle.locator('.tw-button:has-text("Claim"), .tw-button:has-text("Get"), button:has-text("Claim"), button:has-text("Get")').first().click();
+ db.data[user][title] ||= { title, time: datetime(), url, store: 'internal' };
+ notify_games.push({ title, status: 'claimed', url });
+ await card.handle.screenshot({ path: screenshot('internal', `${filenamify(title)}.png`) });
+ }
+ console.log('\nNumber of free unclaimed games (external stores):', external.length);
+ // claim games in external/linked stores. Linked: origin.com, epicgames.com; Redeem-key: gog.com, legacygames.com, microsoft
+ const external_info = [];
+ for (const card of external) { // need to get data incl. URLs in this loop and then navigate in another, otherwise .all() would update after coming back and .elementHandles() like above would lead to error due to page navigation: elementHandle.$: Protocol error (Page.adoptNode)
+ const title = card.title;
+ const url = card.url ? card.url.split('?')[0] : undefined;
+ if (!url) continue;
+ external_info.push({ title, url });
+ }
+ const clickCTA = async p => {
+ const candidates = [
+ p.locator('button[data-a-target="buy-box_call-to-action"]').first(),
+ p.locator('[data-a-target="buy-box_call-to-action"]').first(),
+ p.locator('[data-a-target="buy-box"] .tw-button:has-text("Get game")').first(),
+ p.locator('[data-a-target="buy-box"] .tw-button:has-text("Claim")').first(),
+ p.locator('.tw-button:has-text("Complete Claim")').first(),
+ p.locator('[data-a-target="buy-box_call-to-action-text"]').first().locator('xpath=ancestor::button[1]'),
+ p.locator('.tw-button:has-text("Spiel holen"), .tw-button:has-text("Spiel aktivieren")').first(),
+ p.locator('p:has-text("Spiel holen"), p:has-text("Spiel aktivieren")').first().locator('xpath=ancestor::button[1]'),
+ ];
+ for (const c of candidates) {
+ if (await c.count()) {
+ try {
+ await c.waitFor({ state: 'visible', timeout: 5000 });
+ const enabled = await c.isEnabled();
+ if (enabled) await c.click();
+ else {
+ await c.evaluate(el => {
+ el.disabled = false;
+ el.removeAttribute('disabled');
+ el.click();
+ });
+ }
+ return true;
+ } catch {
+ // try next candidate
+ }
+ }
+ }
+ return false;
+ };
+
+ for (const { title, url } of external_info) {
+ console.log('Current free game:', chalk.blue(title)); // , url);
+ const existingStatus = db.data[user]?.[title]?.status;
+ if (existingStatus && !existingStatus.startsWith('failed')) {
+ console.log(` Already recorded as ${existingStatus}, skipping.`);
+ notify_games.push({ title, url, status: 'existed' });
+ continue;
+ }
+ await page.goto(url, { waitUntil: 'domcontentloaded' });
+ await page.waitForSelector('[data-a-target="buy-box"]', { timeout: 10000 }).catch(() => {});
+ if (cfg.debug) await page.pause();
+ let store = 'unknown';
+ const detailLoc = page.locator('[data-a-target="DescriptionItemDetails"], [data-testid="DescriptionItemDetails"]');
+ if (await detailLoc.count()) {
+ const item_text = await detailLoc.first().innerText();
+ const lower = item_text.toLowerCase();
+ const onPos = lower.lastIndexOf(' on ');
+ if (onPos >= 0) store = lower.slice(onPos + 4).replace(/[.!]$/, '');
+ } else if (url.includes('/claims/')) {
+ const slug = url.split('/claims/')[1]?.split('/')[0] || '';
+ if (slug.includes('gog')) store = 'gog.com';
+ else if (slug.includes('epic')) store = 'epic-games';
+ else if (slug.includes('origin')) store = 'origin';
+ else if (slug.includes('xbox') || slug.includes('microsoft')) store = 'microsoft store';
+ else if (slug.includes('legacy')) store = 'legacy games';
+ const lunaPlay = await page.locator('[data-a-target="LunaOffer"], button[data-a-target="LunaOffer"], button:has-text("Spielen")').count();
+ if (store == 'unknown' && lunaPlay) store = 'luna';
+ }
+ console.log(' External store:', store);
+ const notify_game = { title, url };
+ notify_games.push(notify_game); // status is updated below
+ // Already collected? skip
+ const collectedLoc = page.locator('[data-a-target="ClaimStateQuantityAndDateContent"], [data-a-target="ClaimStateClaimCodeContent"]:has-text("Collected"), [data-a-target="ClaimStateVendorContent"], [data-a-target="ClaimStateViewDetailsAndInstructions"]');
+ const collectedText = page.getByText(/You collected this on/i);
+ const collectedEpic = page.getByText(/Sent to your Epic Games Store library/i);
+ const collectedBanner = page.locator('p.tw-c-text-alert-success:has-text("Collected"), p.tw-c-text-alert-success:has-text("Collected this")');
+ const collectedSuccessIcon = page.locator('[data-a-target="ItemCardDetailSuccessStatus"], .claim-state__success-icon');
+ const disabledCTA = page.locator('[data-a-target="buy-box_call-to-action"][disabled], button[disabled]:has-text("Get game")');
+ const collectedAny = await Promise.all([
+ collectedLoc.count(),
+ collectedBanner.count(),
+ collectedText.count(),
+ collectedEpic.count(),
+ collectedSuccessIcon.count(),
+ disabledCTA.count(),
+ ]).then(([a, b, c, d, e, f]) => a + b + c + d + e + f > 0);
+ if (collectedAny) {
+ console.log(' Already collected, skipping.');
+ notify_game.status = 'existed';
+ db.data[user][title] ||= { title, time: datetime(), url, store, status: 'existed' };
+ continue;
+ }
+ // Disabled CTA (e.g., needs linking or not available)
+ if (await disabledCTA.count()) {
+ if (store !== 'epic-games') {
+ console.log(' CTA is disabled, skipping (likely needs linking/not available).');
+ notify_game.status = 'disabled';
+ db.data[user][title] ||= { title, time: datetime(), url, store, status: 'disabled' };
+ continue;
+ } else {
+ console.log(' CTA disabled for epic-games, will still try to link/claim.');
+ }
+ }
+ if (store == 'luna') {
+ console.log(' Luna cloud title detected, skipping code redemption.');
+ notify_game.status = 'luna (play)';
+ db.data[user][title] ||= { title, time: datetime(), url, store: 'luna', status: 'luna (play)' };
+ continue;
+ }
+ if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue;
+ if (cfg.dryrun) continue;
+ if (cfg.interactive) {
+ const confirmed = await confirm();
+ if (!confirmed) continue;
+ }
+ await clickCTA(page);
+ await Promise.any([
+ page.waitForSelector('.thank-you-title:has-text("Success")', { timeout: cfg.timeout }).catch(() => {}),
+ page.waitForSelector('div:has-text("Link game account")', { timeout: cfg.timeout }).catch(() => {}),
+ ]).catch(() => {});
+ db.data[user][title] ||= { title, time: datetime(), url, store };
+ if (await page.locator('div:has-text("Link game account")').count() // epic games store also shows "Link account"
+ || await page.locator('div:has-text("Link account")').count()) {
+ console.error(' Account linking is required to claim this offer!');
+ notify_game.status = `failed: need account linking for ${store}`;
+ db.data[user][title].status = 'failed: need account linking';
+ // await page.pause();
+ // await page.click('[data-a-target="LinkAccountModal"] [data-a-target="LinkAccountButton"]');
+ // login for epic games also needed if already logged in
+ // wait for https://www.epicgames.com/id/authorize?redirect_uri=https%3A%2F%2Fservice.link.amazon.gg...
+ // await page.click('button[aria-label="Allow"]');
+ } else {
+ db.data[user][title].status = 'claimed';
// print code if there is one
const redeem = {
- // 'origin': 'https://www.origin.com/redeem', // TODO still needed or now only via account linking?
+ // 'origin': 'https://www.origin.com/redeem', // kept for legacy flows; current path uses account linking
'gog.com': 'https://www.gog.com/redeem',
+ 'microsoft store': 'https://account.microsoft.com/billing/redeem',
+ xbox: 'https://account.microsoft.com/billing/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');
+ let code;
+ try {
+ // ensure CTA was clicked in case code is behind it
+ await clickCTA(page).catch(() => {});
+ code = await Promise.any([
+ page.inputValue('input[type="text"]'),
+ page.textContent('[data-a-target="ClaimStateClaimCodeContent"]').then(s => s.replace('Your code: ', '')),
+ ]);
+ } catch {
+ console.error(' Could not find claim code on page (timeout). Please check manually.');
+ db.data[user][title].status = 'claimed (code not found)';
+ notify_game.status = 'claimed (code not found)';
+ await page.screenshot({ path: screenshot('external', `${filenamify(title)}_nocode.png`), fullPage: true }).catch(() => {});
+ continue;
}
- console.log(' URL to redeem game:', redeem[store]);
+ console.log(' Code to redeem game:', chalk.blue(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'); // full text: Click here to enter your redemption code.
+ }
+ let redeem_url = redeem[store];
+ if (store == 'gog.com') redeem_url += '/' + code; // to log and notify, but can't use for goto below (captcha)
+ console.log(' URL to redeem game:', redeem_url);
+ db.data[user][title].code = code;
+ let redeem_action = 'redeem';
+ if (cfg.pg_redeem) { // try to redeem keys on external stores
+ console.log(` Trying to redeem ${code} on ${store} (need to be logged in)!`);
+ const page2 = await context.newPage();
+ await page2.goto(redeem[store], { waitUntil: 'domcontentloaded' });
+ if (store == 'gog.com') {
+ await page2.fill('#codeInput', code);
+ const r1 = page2.waitForResponse(r => r.request().method() == 'GET' && r.url().startsWith('https://redeem.gog.com/'));
+ await page2.click('[type="submit"]'); // click Continue
+ const r1t = await (await r1).text();
+ const reason = JSON.parse(r1t).reason;
+ // {"reason":"Invalid or no captcha"}
+ // {"reason":"code_used"}
+ // {"reason":"code_not_found"}
+ if (reason?.includes('captcha')) {
+ redeem_action = 'redeem (got captcha)';
+ console.error(' Got captcha; could not redeem!');
+ } else if (reason == 'code_used') {
+ redeem_action = 'already redeemed';
+ console.log(' Code was already used!');
+ } else if (reason == 'code_not_found') {
+ redeem_action = 'redeem (not found)';
+ console.error(' Code was not found!');
+ } else { // unknown state; keep info log for later analysis
+ redeem_action = 'redeemed?';
+ console.debug(` Response 1: ${r1t}`);
+ const r2 = page2.waitForResponse(r => r.request().method() == 'POST' && r.url().startsWith('https://redeem.gog.com/'));
+ await page2.click('[type="submit"]'); // click Redeem
+ const r2t = await (await r2).text();
+ const reason2 = JSON.parse(r2t).reason;
+ if (r2t == '{}') {
+ redeem_action = 'redeemed';
+ console.log(' Redeemed successfully.');
+ db.data[user][title].status = 'claimed and redeemed';
+ } else if (reason2?.includes('captcha')) {
+ redeem_action = 'redeem (got captcha)';
+ console.error(' Got captcha; could not redeem!');
+ } else {
+ console.debug(` Response 2: ${r2t}`);
+ console.log(' Unknown Response 2 - please report in https://github.com/vogler/free-games-claimer/issues/5');
+ }
+ }
+ } else if (store == 'microsoft store' || store == 'xbox') {
+ console.error(` Redeem on ${store} is experimental!`);
+ if (page2.url().startsWith('https://login.')) {
+ console.error(' Not logged in! Please redeem the code above manually. You can now login in the browser for next time. Waiting for 60s.');
+ await page2.waitForTimeout(60 * 1000);
+ redeem_action = 'redeem (login)';
+ } else {
+ const iframe = page2.frameLocator('#redeem-iframe');
+ const input = iframe.locator('[name=tokenString]');
+ await input.waitFor();
+ await input.fill(code);
+ const r = page2.waitForResponse(r => r.url().startsWith('https://cart.production.store-web.dynamics.com/v1.0/Redeem/PrepareRedeem'));
+ const rt = await (await r).text();
+ const j = JSON.parse(rt);
+ const reason = j?.events?.cart.length && j.events.cart[0]?.data?.reason;
+ if (reason == 'TokenNotFound') {
+ redeem_action = 'redeem (not found)';
+ console.error(' Code was not found!');
+ } else if (j?.productInfos?.length && j.productInfos[0]?.redeemable) {
+ await iframe.locator('button:has-text("Next")').click();
+ await iframe.locator('button:has-text("Confirm")').click();
+ const r = page2.waitForResponse(r => r.url().startsWith('https://cart.production.store-web.dynamics.com/v1.0/Redeem/RedeemToken'));
+ const j = JSON.parse(await (await r).text());
+ if (j?.events?.cart.length && j.events.cart[0]?.data?.reason == 'UserAlreadyOwnsContent') {
+ redeem_action = 'already redeemed';
+ console.error(' error: UserAlreadyOwnsContent');
+ } else { // success path not seen yet; log below if needed
+ redeem_action = 'redeemed';
+ db.data[user][title].status = 'claimed and redeemed?';
+ console.log(' Redeemed successfully? Please report if not in https://github.com/vogler/free-games-claimer/issues/5');
+ }
+ } else { // other responses; keep info log for analysis
+ redeem_action = 'unknown';
+ console.debug(` Response: ${rt}`);
+ console.log(' Redeemed successfully? Please report your Response from above (if it is new) in https://github.com/vogler/free-games-claimer/issues/5');
+ }
+ }
+ } else if (store == 'legacy games') {
+ await page2.fill('[name=coupon_code]', code);
+ await page2.fill('[name=email]', cfg.lg_email);
+ await page2.fill('[name=email_validate]', cfg.lg_email);
+ await page2.uncheck('[name=newsletter_sub]');
+ await page2.click('[type="submit"]');
+ try {
+ await page2.waitForSelector('h2:has-text("Thanks for redeeming")');
+ redeem_action = 'redeemed';
+ db.data[user][title].status = 'claimed and redeemed';
+ } catch (error) {
+ console.error(' Got error', error);
+ redeem_action = 'redeemed?';
+ db.data[user][title].status = 'claimed and redeemed?';
+ console.log(' Redeemed successfully? Please report problems in https://github.com/vogler/free-games-claimer/issues/5');
+ }
+ } else {
+ console.error(` Redeem on ${store} not yet implemented!`);
+ }
+ if (cfg.debug) await page2.pause();
+ await page2.close();
+ }
+ notify_game.status = `${redeem_action} ${code} on ${store}`;
+ } else {
+ notify_game.status = `claimed on ${store}`;
+ db.data[user][title].status = 'claimed';
}
- db.data.claimed.push({ 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);
- run.c_external++;
+ await page.screenshot({ path: screenshot('external', `${filenamify(title)}.png`), fullPage: true });
}
- // await page.pause();
- await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
+ }
+ await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
+ try {
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) {
- console.error(error);
- run.error = error.toString();
-} finally {
- // write out json db
- run.endTime = datetime();
- db.data.runs.push(run);
- await db.write();
+ } catch {
+ // ignore if filter already selected
+ }
- await context.close();
+ if (notify_games.length && games) { // make screenshot of all games if something was claimed and list exists
+ const p = screenshot(`${filenamify(datetime())}.png`);
+ await scrollUntilStable(() => games.locator('.item-card__action').count());
+ const viewportSize = page.viewportSize(); // current viewport size
+ await page.setViewportSize({ ...viewportSize, height: 3000 }); // increase height, otherwise element screenshot is cut off at the top and bottom
+ await games.screenshot({ path: p }); // screenshot of all claimed games
+ }
+
+ // https://github.com/vogler/free-games-claimer/issues/55
+ if (cfg.pg_claimdlc) {
+ console.log('Trying to claim in-game content...');
+ await page.click('button[data-type="InGameLoot"]');
+ const loot = page.locator('div[data-a-target="offer-list-IN_GAME_LOOT"]');
+ await loot.waitFor();
+
+ process.stdout.write('Loading all DLCs on page...');
+ await scrollUntilStable(() => loot.locator('[data-a-target="item-card"]').count());
+
+ console.log('\nNumber of already claimed DLC:', await loot.locator('p:has-text("Collected")').count());
+
+ const cards = await loot.locator('[data-a-target="item-card"]:has(p:text-is("Claim"))').all();
+ console.log('Number of unclaimed DLC:', cards.length);
+ const dlcs = await Promise.all(cards.map(async card => ({
+ game: await card.locator('.item-card-details__body p').innerText(),
+ title: await card.locator('.item-card-details__body__primary').innerText(),
+ url: 'https://gaming.amazon.com' + await card.locator('a').first().getAttribute('href'),
+ })));
+ // console.log(dlcs);
+
+ const dlc_unlinked = {};
+ for (const dlc of dlcs) {
+ const title = `${dlc.game} - ${dlc.title}`;
+ const url = dlc.url;
+ console.log('Current DLC:', title);
+ if (cfg.debug) await page.pause();
+ if (cfg.dryrun) continue;
+ if (cfg.interactive && !await confirm()) continue;
+ db.data[user][title] ||= { title, time: datetime(), store: 'DLC', status: 'failed: need account linking' };
+ const notify_game = { title, url };
+ notify_games.push(notify_game); // status is updated below
+ try {
+ await page.goto(url, { waitUntil: 'domcontentloaded' });
+ // most games have a button 'Get in-game content'
+ // epic-games: Fall Guys: Claim -> Continue -> Go to Epic Games (despite account linked and logged into epic-games) -> not tied to account but via some cookie?
+ const claimOptions = [
+ page.click('.tw-button:has-text("Get in-game content")'),
+ page.click('.tw-button:has-text("Claim your gift")'),
+ (async () => {
+ await page.click('.tw-button:has-text("Claim")');
+ await page.click('button:has-text("Continue")').catch(() => {});
+ })(),
+ ];
+ await Promise.any(claimOptions);
+ try {
+ await page.click('button:has-text("Continue")');
+ } catch {
+ // continue button not always present
+ }
+ const linkAccountButton = page.locator('[data-a-target="LinkAccountButton"]');
+ let unlinked_store;
+ if (await linkAccountButton.count()) {
+ unlinked_store = await linkAccountButton.first().getAttribute('aria-label');
+ console.debug(' LinkAccountButton label:', unlinked_store);
+ const match = unlinked_store?.match(/Link (.*) account/);
+ const extracted = match?.[1];
+ if (extracted) unlinked_store = extracted;
+ } else if (await page.locator('text=Link game account').count()) { // epic-games only?
+ console.error(' Missing account linking (epic-games specific button?):', await page.locator('button[data-a-target="gms-cta"]').innerText()); // track account-linking UI drift
+ unlinked_store = 'epic-games';
+ }
+ if (unlinked_store) {
+ console.error(' Missing account linking:', unlinked_store, url);
+ dlc_unlinked[unlinked_store] ??= [];
+ dlc_unlinked[unlinked_store].push(title);
+ } else {
+ const code = await page.inputValue('input[type="text"]').catch(() => undefined);
+ console.log(' Code to redeem game:', chalk.blue(code));
+ db.data[user][title].code = code;
+ db.data[user][title].status = 'claimed';
+ }
+ } catch (error) {
+ console.error(error);
+ } finally {
+ await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
+ await page.click('button[data-type="InGameLoot"]');
+ }
+ }
+ console.log('DLC: Unlinked accounts:', dlc_unlinked);
+ }
+} catch (error) {
+ process.exitCode ||= 1;
+ console.error('--- Exception:');
+ console.error(error); // .toString()?
+ if (error.message && process.exitCode != 130) notify(`prime-gaming failed: ${error.message.split('\n')[0]}`);
+} finally {
+ await db.write(); // write out json db
+ if (notify_games.length) { // list should only include claimed games
+ notify(`prime-gaming (${user}):
${html_game_list(notify_games)}`);
+ }
}
+if (page.video()) console.log('Recorded video:', await page.video().path());
+await context.close();
diff --git a/sonar-project.properties b/sonar-project.properties
new file mode 100644
index 0000000..677d6b3
--- /dev/null
+++ b/sonar-project.properties
@@ -0,0 +1,9 @@
+sonar.organization=vogler
+sonar.projectKey=vogler_free-games-claimer
+
+# relative paths to source directories. More details and properties are described
+# in https://sonarcloud.io/documentation/project-administration/narrowing-the-focus/
+sonar.sources=.
+
+#Eslint issues
+sonar.eslint.reportPaths = eslint_report.json
diff --git a/src/config.js b/src/config.js
new file mode 100644
index 0000000..a8b1817
--- /dev/null
+++ b/src/config.js
@@ -0,0 +1,53 @@
+import * as dotenv from 'dotenv';
+import { dataDir } from './util.js';
+
+dotenv.config({ path: 'data/config.env' }); // loads env vars from file - will not set vars that are already set, i.e., can overwrite values from file by prefixing, e.g., VAR=VAL node ...
+
+// Options - also see table in README.md
+export const cfg = {
+ debug: process.env.DEBUG == '1' || process.env.PWDEBUG == '1', // runs non-headless and opens https://playwright.dev/docs/inspector
+ debug_network: process.env.DEBUG_NETWORK == '1', // log network requests and responses
+ record: process.env.RECORD == '1', // `recordHar` (network) + `recordVideo`
+ time: process.env.TIME == '1', // log duration of each step
+ dryrun: process.env.DRYRUN == '1', // don't claim anything
+ interactive: process.env.INTERACTIVE == '1', // confirm to claim, default skip
+ show: process.env.SHOW == '1', // run non-headless
+ get headless() {
+ return !this.debug && !this.show;
+ },
+ width: Number(process.env.WIDTH) || 1920, // width of the opened browser
+ height: Number(process.env.HEIGHT) || 1080, // height of the opened browser
+ timeout: (Number(process.env.TIMEOUT) || 60) * 1000, // default timeout for playwright is 30s
+ login_timeout: (Number(process.env.LOGIN_TIMEOUT) || 180) * 1000, // higher timeout for login, will wait twice: prompt + wait for manual login
+ novnc_port: process.env.NOVNC_PORT, // running in docker if set
+ notify: process.env.NOTIFY, // apprise notification services
+ notify_title: process.env.NOTIFY_TITLE, // apprise notification title
+ get dir() { // avoids ReferenceError: Cannot access 'dataDir' before initialization
+ return {
+ browser: process.env.BROWSER_DIR || dataDir('browser'), // for multiple accounts or testing
+ screenshots: process.env.SCREENSHOTS_DIR || dataDir('screenshots'), // set to 0 to disable screenshots
+ };
+ },
+ // auth epic-games
+ eg_email: process.env.EG_EMAIL || process.env.EMAIL,
+ eg_password: process.env.EG_PASSWORD || process.env.PASSWORD,
+ eg_otpkey: process.env.EG_OTPKEY,
+ eg_parentalpin: process.env.EG_PARENTALPIN,
+ // auth prime-gaming
+ pg_email: process.env.PG_EMAIL || process.env.EMAIL,
+ pg_password: process.env.PG_PASSWORD || process.env.PASSWORD,
+ pg_otpkey: process.env.PG_OTPKEY,
+ // auth gog
+ gog_email: process.env.GOG_EMAIL || process.env.EMAIL,
+ gog_password: process.env.GOG_PASSWORD || process.env.PASSWORD,
+ gog_newsletter: process.env.GOG_NEWSLETTER == '1', // do not unsubscribe from newsletter after claiming a game
+ // auth AliExpress
+ ae_email: process.env.AE_EMAIL || process.env.EMAIL,
+ ae_password: process.env.AE_PASSWORD || process.env.PASSWORD,
+ // OTP only via GOG_EMAIL, can't add app...
+ // experimmental
+ pg_redeem: process.env.PG_REDEEM == '1', // prime-gaming: redeem keys on external stores
+ lg_email: process.env.LG_EMAIL || process.env.PG_EMAIL || process.env.EMAIL, // prime-gaming: external: legacy-games: email to use for redeeming
+ pg_claimdlc: process.env.PG_CLAIMDLC == '1', // prime-gaming: claim in-game content
+ pg_timeLeft: Number(process.env.PG_TIMELEFT), // prime-gaming: check time left to claim and skip game if there are more than PG_TIMELEFT days left to claim it
+};
diff --git a/src/migrate.js b/src/migrate.js
new file mode 100644
index 0000000..e28e88d
--- /dev/null
+++ b/src/migrate.js
@@ -0,0 +1,32 @@
+import { existsSync } from 'node:fs';
+import { Low } from 'lowdb';
+import { JSONFile } from 'lowdb/node';
+import { datetime } from './util.js';
+
+const datetime_UTCtoLocalTimezone = async file => {
+ if (!existsSync(file)) return console.error('File does not exist:', file);
+ const db = new Low(new JSONFile(file));
+ await db.read();
+ db.data ||= {};
+ console.log('Migrating', file);
+ for (const user in db.data) {
+ for (const game in db.data[user]) {
+ const time1 = db.data[user][game].time;
+ const time1s = time1.endsWith('Z') ? time1 : time1 + ' UTC';
+ const time2 = datetime(new Date(time1s));
+ console.log([game, time1, time2]);
+ db.data[user][game].time = time2;
+ }
+ }
+ await db.write(); // write out json db
+};
+
+const args = process.argv.slice(2);
+if (args[0] == 'localtime') {
+ const files = args.slice(1);
+ console.log('Will convert UTC datetime to local timezone for', files);
+ files.forEach(datetime_UTCtoLocalTimezone);
+} else {
+ console.log('Usage: node migrate.js
');
diff --git a/src/version.js b/src/version.js
new file mode 100644
index 0000000..f838d8f
--- /dev/null
+++ b/src/version.js
@@ -0,0 +1,41 @@
+import { log } from 'node:console';
+import { execFile } from 'node:child_process';
+
+const gitBin = process.env.GIT_BIN || '/usr/bin/git';
+
+const runGit = (...args) => new Promise((resolve, reject) => {
+ execFile(gitBin, args, { cwd: process.cwd() }, (error, stdout, stderr) => {
+ if (stderr) console.error(`stderr: ${stderr}`);
+ if (error) {
+ console.log(`error: ${error.message}`);
+ if (error.code === 'ENOENT' || error.message.includes('command not found')) {
+ console.info('Install git to check for updates!');
+ }
+ return reject(error);
+ }
+ resolve(stdout.trim());
+ });
+});
+
+let sha, date;
+if (process.env.NOVNC_PORT) {
+ log('Running inside Docker.');
+ ['COMMIT', 'BRANCH', 'NOW'].forEach(v => log(` ${v}:`, process.env[v]));
+ sha = process.env.COMMIT;
+ date = process.env.NOW;
+} else {
+ log('Not running inside Docker.');
+ sha = await runGit('rev-parse', 'HEAD');
+ date = await runGit('show', '-s', '--format=%cD'); // same as format as `date -R` (RFC2822)
+}
+
+const gh = await (await fetch('https://api.github.com/repos/vogler/free-games-claimer/commits/main')).json();
+
+log('Local commit:', sha, new Date(date));
+log('Online commit:', gh.sha, new Date(gh.commit.committer.date));
+
+if (sha == gh.sha) {
+ log('Running the latest version!');
+} else {
+ log('Not running the latest version!');
+}
diff --git a/steam-games.js b/steam-games.js
new file mode 100644
index 0000000..b23fd31
--- /dev/null
+++ b/steam-games.js
@@ -0,0 +1,70 @@
+import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
+import { jsonDb, prompt } from './src/util.js';
+import { cfg } from './src/config.js';
+
+const db = await jsonDb('steam-games.json', {});
+
+const user = cfg.steam_id || await prompt({ message: 'Enter Steam community id ("View my profile", then copy from URL)' });
+
+// using https://github.com/apify/fingerprint-suite worked, but has no launchPersistentContext...
+// from https://github.com/apify/fingerprint-suite/issues/162
+import { FingerprintInjector } from 'fingerprint-injector';
+import { FingerprintGenerator } from 'fingerprint-generator';
+
+const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({
+ devices: ['desktop'],
+ operatingSystems: ['windows'],
+});
+
+const context = await firefox.launchPersistentContext(cfg.dir.browser, {
+ headless: cfg.headless,
+ locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL
+ userAgent: fingerprint.navigator.userAgent,
+ viewport: {
+ width: fingerprint.screen.width,
+ height: fingerprint.screen.height,
+ },
+ extraHTTPHeaders: {
+ 'accept-language': headers['accept-language'],
+ },
+});
+await new FingerprintInjector().attachFingerprintToPlaywright(context, { fingerprint, headers });
+
+context.setDefaultTimeout(cfg.debug ? 0 : cfg.timeout);
+
+const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
+
+try {
+ await page.goto(`https://steamcommunity.com/id/${user}/games?tab=all`);
+ const games = page.locator('div[data-featuretarget="gameslist-root"] > div.Panel > div.Panel > div');
+ await games.last().waitFor();
+ await page.keyboard.press('End');
+ await page.waitForLoadState('networkidle');
+ console.log('All Games:', await games.count());
+ for (const game of await games.all()) {
+ const title = await game.locator('span a').innerText();
+ let time, last, achievements, size;
+ const ltime = game.locator('span:has-text("total played")');
+ if (await ltime.count()) time = (await ltime.first().innerText()).split('\n')[1];
+ const llast = game.locator('span:has-text("last played")');
+ if (await llast.count()) last = (await llast.first().innerText()).split('\n')[1];
+ const lachievements = game.locator('a:has-text("achievements") + span');
+ if (await lachievements.count()) achievements = (await lachievements.first().innerText()).split('\n');
+ const lsize = game.locator('span:has(+ button)');
+ if (await lsize.count()) size = await lsize.first().innerText();
+ const url = await game.locator('a').first().getAttribute('href');
+ const img = await game.locator('img').first().getAttribute('src');
+ const stat = { title, time, last, achievements, size, url, img };
+ console.log(stat);
+ db.data[title] = stat;
+ }
+
+} catch (error) {
+ process.exitCode ||= 1;
+ console.error('--- Exception:');
+ console.error(error); // .toString()?
+} finally {
+ await db.write(); // write out json db
+}
+if (page.video()) console.log('Recorded video:', await page.video().path());
+await context.close();
diff --git a/test/notify.js b/test/notify.js
new file mode 100644
index 0000000..c5709a9
--- /dev/null
+++ b/test/notify.js
@@ -0,0 +1,42 @@
+import { delay, html_game_list, notify } from '../src/util.js';
+import { cfg } from '../src/config.js';
+
+const URL_CLAIM = 'https://gaming.amazon.com/home'; // dummy URL
+
+console.debug('NOTIFY:', cfg.notify);
+
+const scenarios = [
+ {
+ enabled: process.env.TEST_NOTIFY_EPIC === '1',
+ title: 'epic-games',
+ games: [
+ { title: 'Epistory - Typing Chronicles', status: 'claimed', url: URL_CLAIM },
+ ],
+ },
+ {
+ enabled: process.env.TEST_NOTIFY_PG === '1',
+ delayMs: 1000,
+ title: 'prime-gaming',
+ games: [
+ { title: 'Faraway 2: Jungle Escape', status: 'claimed', url: URL_CLAIM },
+ { title: 'Chicken Police - Paint it RED!', status: 'claimed', url: URL_CLAIM },
+ { title: 'Lawn Mowing Simulator', status: 'claimed', url: URL_CLAIM },
+ { title: 'Breathedge', status: 'claimed', url: URL_CLAIM },
+ { title: 'The Evil Within 2', status: `redeem H97S6FB38FA6D09DEA on gog.com`, url: URL_CLAIM },
+ { title: 'Beat Cop', status: `redeem BMKM8558EC55F7B38F on gog.com`, url: URL_CLAIM },
+ { title: 'Dishonored 2', status: `redeem NNEK0987AB20DFBF8F on gog.com`, url: URL_CLAIM },
+ ],
+ },
+ {
+ enabled: process.env.TEST_NOTIFY_GOG === '1',
+ delayMs: 1000,
+ title: 'gog',
+ games: [{ title: 'Haven Park', status: 'claimed', url: URL_CLAIM }],
+ },
+];
+
+for (const scenario of scenarios) {
+ if (!scenario.enabled) continue;
+ if (scenario.delayMs) await delay(scenario.delayMs);
+ await notify(`${scenario.title}:
${html_game_list(scenario.games)}`);
+}
diff --git a/test/sigint-enquirer-raw-keeps-running.js b/test/sigint-enquirer-raw-keeps-running.js
new file mode 100644
index 0000000..ccb3081
--- /dev/null
+++ b/test/sigint-enquirer-raw-keeps-running.js
@@ -0,0 +1,21 @@
+// open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372
+function onRawSIGINT(fn) {
+ const { stdin, stdout } = process;
+ stdin.setRawMode(true);
+ stdin.resume();
+ stdin.on('data', data => {
+ const key = data.toString('utf-8');
+ if (key === '\u0003') { // ctrl + c
+ fn();
+ } else {
+ stdout.write(key);
+ }
+ });
+}
+console.log(1);
+onRawSIGINT(() => {
+ console.log('raw'); process.exit(1);
+});
+console.log(2);
+
+// onRawSIGINT workaround for enquirer keeps the process from exiting here...
diff --git a/test/sigint-enquirer-raw.js b/test/sigint-enquirer-raw.js
new file mode 100644
index 0000000..f9f365c
--- /dev/null
+++ b/test/sigint-enquirer-raw.js
@@ -0,0 +1,18 @@
+// https://github.com/enquirer/enquirer/issues/372
+import { prompt, handleSIGINT } from '../src/util.js';
+
+handleSIGINT();
+
+console.log('hello');
+console.error('hello error');
+try {
+ const first = await prompt(); // SIGINT no longer handled if this is executed
+ const second = await prompt(); // SIGINT no longer handled if this is executed
+ console.log('values:', first, second);
+ setTimeout(() => console.log('timeout 3s'), 3000);
+} catch (e) {
+ process.exitCode ||= 1;
+ console.log('catch. exitCode:', process.exitCode);
+ console.error(e);
+}
+console.log('end. exitCode:', process.exitCode);
diff --git a/test/sigint-enquirer-simple.js b/test/sigint-enquirer-simple.js
new file mode 100644
index 0000000..25f13ee
--- /dev/null
+++ b/test/sigint-enquirer-simple.js
@@ -0,0 +1,20 @@
+// https://github.com/enquirer/enquirer/issues/372
+import Enquirer from 'enquirer';
+const enquirer = new Enquirer();
+
+let interrupted = false;
+process.on('SIGINT', () => {
+ if (interrupted) process.exit();
+ interrupted = true;
+ console.log('SIGINT');
+});
+await enquirer.prompt({
+ type: 'input',
+ name: 'username',
+ message: 'What is your username?',
+});
+await enquirer.prompt({
+ type: 'input',
+ name: 'username',
+ message: 'What is your username 2?',
+});
diff --git a/unrealengine.js b/unrealengine.js
new file mode 100644
index 0000000..6eb7d79
--- /dev/null
+++ b/unrealengine.js
@@ -0,0 +1,223 @@
+import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
+import { authenticator } from 'otplib';
+import path from 'node:path';
+import { writeFileSync } from 'node:fs';
+import { resolve, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js';
+import { cfg } from './src/config.js';
+
+const screenshot = (...a) => resolve(cfg.dir.screenshots, 'unrealengine', ...a);
+
+const URL_CLAIM = 'https://www.unrealengine.com/marketplace/en-US/assets?count=20&sortBy=effectiveDate&sortDir=DESC&start=0&tag=4910';
+const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM;
+
+console.log(datetime(), 'started checking unrealengine');
+
+const db = await jsonDb('unrealengine.json', {});
+
+// https://playwright.dev/docs/auth#multi-factor-authentication
+const context = await firefox.launchPersistentContext(cfg.dir.browser, {
+ headless: cfg.headless,
+ viewport: { width: cfg.width, height: cfg.height },
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36', // Windows UA avoids "device not supported"; update when browser version changes
+ locale: 'en-US', // ignore OS locale to be sure to have english text for locators
+ recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined, // will record a .webm video for each page navigated; without size, video would be scaled down to fit 800x800
+ recordHar: cfg.record ? { path: `data/record/ue-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools
+ handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved
+});
+
+handleSIGINT(context);
+
+await stealth(context);
+
+if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
+
+const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
+await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
+
+const notify_games = [];
+let user;
+
+try {
+ await context.addCookies([{ name: 'OptanonAlertBoxClosed', value: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), domain: '.epicgames.com', path: '/' }]); // Accept cookies to get rid of banner to save space on screen. Set accept time to 5 days ago.
+
+ await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // 'domcontentloaded' faster than default 'load' https://playwright.dev/docs/api/class-page#page-goto
+
+ await page.waitForResponse(r => r.request().method() == 'POST' && r.url().startsWith('https://graphql.unrealengine.com/ue/graphql'));
+
+ while (await page.locator('unrealengine-navigation').getAttribute('isloggedin') != 'true') {
+ console.error('Not signed in anymore. Please login in the browser or here in the terminal.');
+ if (cfg.novnc_port) console.info(`Open http://localhost:${cfg.novnc_port} to login inside the docker container.`);
+ if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
+ console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`);
+ await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' });
+ if (cfg.eg_email && cfg.eg_password) console.info('Using email and password from environment.');
+ else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).');
+ const email = cfg.eg_email || await prompt({ message: 'Enter email' });
+ const password = email && (cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' }));
+ if (email && password) {
+ await page.fill('#email', email);
+ await page.click('button[type="submit"]');
+ await page.fill('#password', password);
+ await page.click('button[type="submit"]');
+ const watchCaptchaDuringLogin = async () => {
+ try {
+ await page.waitForSelector('#h_captcha_challenge_login_prod iframe', { timeout: 15000 });
+ console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
+ notify('unrealengine: got captcha during login. Please check.');
+ } catch {
+ return;
+ }
+ };
+ const watchMfa = async () => {
+ try {
+ await page.waitForURL('**/id/login/mfa**', { timeout: cfg.login_timeout });
+ console.log('Enter the security code to continue - This appears to be a new device, browser or location. A security code has been sent to your email address at ...');
+ const otp = cfg.eg_otpkey && authenticator.generate(cfg.eg_otpkey) || 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
+ await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString());
+ await page.click('button[type="submit"]');
+ } catch {
+ return;
+ }
+ };
+ watchCaptchaDuringLogin();
+ watchMfa();
+ } else {
+ console.log('Waiting for you to login in the browser.');
+ await notify('unrealengine: no longer signed in and not enough options set for automatic login.');
+ if (cfg.headless) {
+ console.log('Run `SHOW=1 node unrealengine` to login in the opened browser.');
+ await context.close(); // finishes potential recording
+ process.exit(1);
+ }
+ }
+ await page.waitForURL('**unrealengine.com/marketplace/**');
+ if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
+ }
+ await page.waitForTimeout(1000);
+ user = await page.locator('unrealengine-navigation').getAttribute('displayname'); // 'null' if !isloggedin
+ console.log(`Signed in as ${user}`);
+ db.data[user] ||= {};
+
+ page.locator('button:has-text("Accept All Cookies")').click().catch(_ => { });
+
+ const ids = [];
+ for (const p of await page.locator('article.asset').all()) {
+ const link = p.locator('h3 a');
+ const title = await link.innerText();
+ const url = 'https://www.unrealengine.com' + await link.getAttribute('href');
+ console.log([title, url]);
+ const id = url.split('/').pop();
+ db.data[user][id] ||= { title, time: datetime(), url, status: 'failed' }; // this will be set on the initial run only!
+ const notify_game = { title, url, status: 'failed' };
+ notify_games.push(notify_game); // status is updated below
+ // if (await p.locator('.btn .add-review-btn').count()) { // did not work
+ if ((await p.getAttribute('class')).includes('asset--owned')) {
+ console.log(' ↳ Already claimed');
+ if (db.data[user][id].status != 'claimed') {
+ db.data[user][id].status = 'existed';
+ notify_game.status = 'existed';
+ }
+ continue;
+ }
+ if (await p.locator('.btn .in-cart').count()) {
+ console.log(' ↳ Already in cart');
+ } else {
+ await p.locator('.btn .add').click();
+ console.log(' ↳ Added to cart');
+ }
+ ids.push(id);
+ }
+ if (ids.length === 0) {
+ console.log('Nothing to claim');
+ } else {
+ await page.waitForTimeout(2000);
+ const price = (await page.locator('.shopping-cart .total .price').innerText()).split(' ');
+ console.log('Price: ', price[1], 'instead of', price[0]);
+ if (price[1] != '0') {
+ const err = 'Price is not 0! Exit! Please report.';
+ console.error(err);
+ notify('unrealengine: ' + err);
+ process.exit(1);
+ }
+ console.log('Click shopping cart');
+ await page.locator('.shopping-cart').click();
+ await page.locator('button.checkout').click();
+ console.log('Click checkout');
+ // maybe: Accept End User License Agreement
+ const acceptEulaIfPresent = async () => {
+ try {
+ await page.locator('[name=accept-label]').check({ timeout: 10000 });
+ console.log('Accept End User License Agreement');
+ await page.locator('span:text-is("Accept")').click(); // otherwise matches 'Accept All Cookies'
+ } catch {
+ return;
+ }
+ };
+ acceptEulaIfPresent();
+ await page.waitForSelector('#webPurchaseContainer iframe');
+ const iframe = page.frameLocator('#webPurchaseContainer iframe');
+
+ if (cfg.debug) await page.pause();
+ if (cfg.dryrun) {
+ console.log('DRYRUN=1 -> Skip order!');
+ throw new Error('DRYRUN=1');
+ }
+
+ console.log('Click Place Order');
+ // Playwright clicked before button was ready to handle event, https://github.com/vogler/free-games-claimer/issues/84#issuecomment-1474346591
+ await iframe.locator('button:has-text("Place Order"):not(:has(.payment-loading--loading))').click({ delay: 11 });
+
+ // I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872
+ const btnAgree = iframe.locator('button:has-text("I Agree")');
+ const acceptIfRequired = async () => {
+ try {
+ await btnAgree.waitFor({ timeout: 10000 });
+ await btnAgree.click();
+ } catch {
+ return;
+ }
+ }; // EU: wait for and click 'I Agree'
+ acceptIfRequired();
+ try {
+ // context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s?
+ const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe');
+ const watchCaptchaChallenge = async () => {
+ try {
+ await captcha.waitFor({ timeout: 10000 });
+ console.error(' Got hcaptcha challenge! Lost trust due to too many login attempts? You can solve the captcha in the browser or get a new IP address.');
+ } catch {
+ return;
+ }
+ }; // may time out if not shown
+ watchCaptchaChallenge();
+ await page.waitForSelector('text=Thank you');
+ for (const id of ids) {
+ db.data[user][id].status = 'claimed';
+ db.data[user][id].time = datetime(); // claimed time overwrites failed/dryrun time
+ }
+ notify_games.forEach(g => g.status == 'failed' && (g.status = 'claimed'));
+ console.log('Claimed successfully!');
+ } catch (e) {
+ console.log(e);
+ console.error(' Failed to claim! To avoid captchas try to get a new IP address.');
+ await page.screenshot({ path: screenshot('failed', `${filenamify(datetime())}.png`), fullPage: true });
+ notify_games.forEach(g => g.status = 'failed');
+ }
+
+ if (notify_games.length) await page.screenshot({ path: screenshot(`${filenamify(datetime())}.png`), fullPage: false }); // fullPage is quite long...
+ console.log('Done');
+ }
+} catch (error) {
+ process.exitCode ||= 1;
+ console.error('--- Exception:');
+ console.error(error); // .toString()?
+ if (error.message && process.exitCode != 130) notify(`unrealengine failed: ${error.message.split('\n')[0]}`);
+} finally {
+ await db.write(); // write out json db
+ if (notify_games.filter(g => g.status != 'existed').length) { // don't notify if all were already claimed
+ notify(`unrealengine (${user}):
${html_game_list(notify_games)}`);
+ }
+}
+if (cfg.debug) writeFileSync(path.resolve(cfg.dir.browser, 'cookies.json'), JSON.stringify(await context.cookies()));
+if (page.video()) console.log('Recorded video:', await page.video().path());
+await context.close();
diff --git a/util.js b/util.js
deleted file mode 100644
index 644382f..0000000
--- a/util.js
+++ /dev/null
@@ -1,77 +0,0 @@
-// https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-// not the same since these will give the absolute paths for this file instead of for the file using them
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-// explicit object instead of Object.fromEntries since the built-in type would loose the keys, better type: https://dev.to/svehla/typescript-object-fromentries-389c
-const dataDir = s => path.resolve(__dirname, 'data', s);
-export const dirs = {
- data: dataDir('.'),
- browser: dataDir('browser'),
- screenshots: dataDir('screenshots'),
-};
-
-import { Low, JSONFile } from 'lowdb';
-export const jsonDb = async file => {
- const db = new Low(new JSONFile(dataDir(file)));
- await db.read();
- return db;
-};
-
-// date and time as UTC (no timezone offset) in nicely readable and sortable format, e.g., 2022-10-06 12:05:27.313
-export const datetime = (d = new Date()) => d.toISOString().replace('T', ' ').replace('Z', '');
-// same as datetime() but for local timezone, e.g., UTC + 2h for the above in DE
-export const datetimeLocal = (d = new Date()) => datetime(new Date(d.getTime() - new Date().getTimezoneOffset() * 60000));
-export const filenamify = s => s.replaceAll(':', '.').replace(/[^a-z0-9 _\-.]/gi, '_'); // alternative: https://www.npmjs.com/package/filenamify - On Unix-like systems, / is reserved. On Windows, <>:"/\|?* along with trailing periods are reserved.
-
-// stealth with playwright: https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212
-const newStealthContext = async (browser, contextOptions = {}, debug = false) => {
- if (!debug) { // only need to fix userAgent in headless mode
- const dummyContext = await browser.newContext();
- const originalUserAgent = await (await dummyContext.newPage()).evaluate(() => navigator.userAgent);
- await dummyContext.close();
- // console.log('originalUserAgent:', originalUserAgent); // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/96.0.4664.110 Safari/537.36
- contextOptions = {
- ...contextOptions,
- userAgent: originalUserAgent.replace("Headless", ""), // HeadlessChrome -> Chrome, TODO needed?
- };
- }
-};
-
-export const stealth = async (context) => {
- // stealth with playwright: https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212
- // https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth/evasions
- const enabledEvasions = [
- 'chrome.app',
- 'chrome.csi',
- 'chrome.loadTimes',
- 'chrome.runtime',
- // 'defaultArgs',
- 'iframe.contentWindow',
- 'media.codecs',
- 'navigator.hardwareConcurrency',
- 'navigator.languages',
- 'navigator.permissions',
- 'navigator.plugins',
- // 'navigator.vendor',
- 'navigator.webdriver',
- 'sourceurl',
- // 'user-agent-override', // doesn't work since playwright has no page.browser()
- 'webgl.vendor',
- 'window.outerdimensions'
- ];
- const stealth = {
- callbacks: [],
- async evaluateOnNewDocument(...args) {
- this.callbacks.push({ cb: args[0], a: args[1] });
- }
- };
- for (const e of enabledEvasions) {
- const evasion = await import(`puppeteer-extra-plugin-stealth/evasions/${e}/index.js`);
- evasion.default().onPageCreated(stealth);
- }
- for (let evasion of stealth.callbacks) {
- await context.addInitScript(evasion.cb, evasion.a);
- }
-};