├── .gitignore ├── .dockerignore ├── .github ├── renovate.json ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── lint.yml │ ├── sonar.yml │ └── docker.yml ├── jsconfig.json ├── .vscode └── settings.json ├── sonar-project.properties ├── CONTRIBUTING.md ├── test ├── sigint-enquirer-simple.js ├── sigint-enquirer-raw-keeps-running.js ├── sigint-enquirer-raw.js └── notify.js ├── docker-compose.yml ├── src ├── migrate.js ├── version.js ├── config.js └── util.js ├── package.json ├── docker-entrypoint.sh ├── steam-games.js ├── eslint.config.js ├── Dockerfile ├── aliexpress.js ├── gog.js ├── unrealengine.js ├── README.md ├── epic-games.js ├── prime-gaming.js └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | data/ 3 | *.env 4 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | data/ 3 | *.env 4 | 5 | .gitignore 6 | .github/ 7 | 8 | **Dockerfile** 9 | .dockerignore 10 | 11 | -------------------------------------------------------------------------------- /.github/renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "enabled": false, 4 | "extends": [ 5 | "config:recommended" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "checkJs": true, 4 | "target": "es2021", 5 | "module": "NodeNext", 6 | "moduleResolution": "NodeNext", // https://github.com/typicode/lowdb/issues/554 7 | }, 8 | "exclude": ["node_modules", "**/node_modules"] 9 | } 10 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | // https://eslint.style/guide/faq#vs-code 3 | "editor.formatOnSave": true, 4 | "editor.formatOnSaveMode": "modifications", 5 | "editor.codeActionsOnSave": { 6 | "source.fixAll.eslint": "explicit" 7 | }, 8 | "eslint.experimental.useFlatConfig": true, 9 | "eslint.codeActionsOnSave.rules": null, 10 | } 11 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | sonar.organization=vogler 2 | sonar.projectKey=vogler_free-games-claimer 3 | 4 | # relative paths to source directories. More details and properties are described 5 | # in https://sonarcloud.io/documentation/project-administration/narrowing-the-focus/ 6 | sonar.sources=. 7 | 8 | #Eslint issues 9 | sonar.eslint.reportPaths = eslint_report.json 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribute 2 | 3 | ## Building and publishing docker images 4 | Setup the secrets for DOCKERHUB_USERNAME and [DOCKERHUB_TOKEN](https://hub.docker.com/settings/security) in https://github.com/YOUR_USERNAME/free-games-claimer/settings/secrets/actions to be able to run the docker.yml workflows. 5 | 6 | Check if under Workflow Permissions in https://github.com/YOUR_USERNAME/free-games-claimer/settings/actions the radio button is set to "Read and write permissions". In case that's not set the push to ghcr.io will fail. -------------------------------------------------------------------------------- /test/sigint-enquirer-simple.js: -------------------------------------------------------------------------------- 1 | // https://github.com/enquirer/enquirer/issues/372 2 | import Enquirer from 'enquirer'; 3 | const enquirer = new Enquirer(); 4 | 5 | let interrupted = false; 6 | process.on('SIGINT', () => { 7 | if (interrupted) process.exit(); 8 | interrupted = true; 9 | console.log('SIGINT'); 10 | }); 11 | await enquirer.prompt({ 12 | type: 'input', 13 | name: 'username', 14 | message: 'What is your username?', 15 | }); 16 | await enquirer.prompt({ 17 | type: 'input', 18 | name: 'username', 19 | message: 'What is your username 2?', 20 | }); 21 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # start with `docker compose up` 2 | services: 3 | free-games-claimer: 4 | container_name: fgc # is printed in front of every output line 5 | image: ghcr.io/vogler/free-games-claimer # otherwise image name will be free-games-claimer-free-games-claimer 6 | build: . 7 | ports: 8 | # - "5900:5900" # VNC server 9 | - "6080:6080" # noVNC (browser-based VNC client) 10 | volumes: 11 | - fgc:/fgc/data 12 | # command: bash -c "node epic-games; node gog" 13 | environment: 14 | # - EMAIL=foo@bar.org 15 | # - NOTIFY='tgram://...' 16 | -------------------------------------------------------------------------------- /test/sigint-enquirer-raw-keeps-running.js: -------------------------------------------------------------------------------- 1 | // open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372 2 | function onRawSIGINT(fn) { 3 | const { stdin, stdout } = process; 4 | stdin.setRawMode(true); 5 | stdin.resume(); 6 | stdin.on('data', data => { 7 | const key = data.toString('utf-8'); 8 | if (key === '\u0003') { // ctrl + c 9 | fn(); 10 | } else { 11 | stdout.write(key); 12 | } 13 | }); 14 | } 15 | console.log(1) 16 | onRawSIGINT(() => { 17 | console.log('raw'); process.exit(1); 18 | }); 19 | console.log(2) 20 | 21 | // onRawSIGINT workaround for enquirer keeps the process from exiting here... 22 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: vogler # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: fgc # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: vogler # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: vogler # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: ["https://www.buymeacoffee.com/vogler", "https://paypal.me/voglerr"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" 9 | directory: "/" 10 | schedule: 11 | interval: "weekly" 12 | # commit-message: 13 | # prefix: "npm" 14 | # include: "scope" 15 | - package-ecosystem: "docker" 16 | directory: "/" 17 | schedule: 18 | interval: "weekly" 19 | # commit-message: 20 | # prefix: "docker" 21 | # include: "scope" 22 | - package-ecosystem: "github-actions" 23 | directory: "/" 24 | schedule: 25 | interval: "weekly" 26 | # commit-message: 27 | # prefix: "github-actions" 28 | # include: "scope" 29 | -------------------------------------------------------------------------------- /src/migrate.js: -------------------------------------------------------------------------------- 1 | import { existsSync } from 'fs'; 2 | import { Low } from 'lowdb'; 3 | import { JSONFile } from 'lowdb/node'; 4 | import { datetime } from './util.js'; 5 | 6 | const datetime_UTCtoLocalTimezone = async file => { 7 | if (!existsSync(file)) return console.error('File does not exist:', file); 8 | const db = new Low(new JSONFile(file)); 9 | await db.read(); 10 | db.data ||= {}; 11 | console.log('Migrating', file); 12 | for (const user in db.data) { 13 | for (const game in db.data[user]) { 14 | const time1 = db.data[user][game].time; 15 | const time1s = time1.endsWith('Z') ? time1 : time1 + ' UTC'; 16 | const time2 = datetime(new Date(time1s)); 17 | console.log([game, time1, time2]); 18 | db.data[user][game].time = time2; 19 | } 20 | } 21 | // console.log(db.data); 22 | await db.write(); // write out json db 23 | }; 24 | 25 | const args = process.argv.slice(2); 26 | if (args[0] == 'localtime') { 27 | const files = args.slice(1); 28 | console.log('Will convert UTC datetime to local timezone for', files); 29 | files.forEach(datetime_UTCtoLocalTimezone); 30 | } else { 31 | console.log('Usage: node migrate.js '); 32 | console.log(' node migrate.js localtime data/*.json'); 33 | } 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "free-games-claimer", 3 | "version": "1.4.0", 4 | "description": "Automatically claims free games on the Epic Games Store, Amazon Prime Gaming and GOG.", 5 | "homepage": "https://github.com/vogler/free-games-claimer", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/vogler/free-games-claimer.git" 9 | }, 10 | "author": "Ralf Vogler", 11 | "license": "AGPL-3.0-only", 12 | "main": "index.js", 13 | "scripts": { 14 | "docker:build": "docker build . -t ghcr.io/vogler/free-games-claimer", 15 | "docker": "cross-env-shell docker run --rm -it -p 5900:5900 -p 6080:6080 -v \\\"$INIT_CWD/data\\\":/fgc/data --name fgc ghcr.io/vogler/free-games-claimer", 16 | "lint": "npx eslint ." 17 | }, 18 | "type": "module", 19 | "engines": { 20 | "node": ">=17" 21 | }, 22 | "dependencies": { 23 | "chalk": "^5.4.1", 24 | "cross-env": "^7.0.3", 25 | "dotenv": "^16.5.0", 26 | "enquirer": "^2.4.1", 27 | "fingerprint-injector": "^2.1.66", 28 | "lowdb": "^7.0.1", 29 | "otplib": "^12.0.1", 30 | "playwright-firefox": "^1.52.0", 31 | "puppeteer-extra-plugin-stealth": "^2.11.2" 32 | }, 33 | "devDependencies": { 34 | "@stylistic/eslint-plugin-js": "^4.2.0", 35 | "eslint": "^9.26.0" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | # https://github.com/marketplace/actions/super-linter#get-started 2 | name: Lint 3 | 4 | on: # yamllint disable-line rule:truthy 5 | push: null 6 | pull_request: null 7 | 8 | permissions: {} 9 | 10 | jobs: 11 | lint: 12 | name: Lint 13 | runs-on: ubuntu-latest 14 | 15 | permissions: 16 | contents: read 17 | packages: read 18 | # To report GitHub Actions status checks 19 | statuses: write 20 | 21 | steps: 22 | - name: Checkout code 23 | uses: actions/checkout@v4 24 | with: 25 | # super-linter needs the full git history to get the 26 | # list of files that changed across commits 27 | fetch-depth: 0 28 | 29 | - name: Super-linter 30 | uses: super-linter/super-linter/slim@v7.4.0 # x-release-please-version 31 | # TODO need to create problem matchers for each linter? https://github.com/rhysd/actionlint/blob/v1.7.7/docs/usage.md#problem-matchers 32 | env: 33 | # To report GitHub Actions status checks 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | # TODO automatically fix linting issues and commit them for PRs 36 | # fix-lint-issues: # https://github.com/marketplace/actions/super-linter#github-actions-workflow-example-pull-request 37 | -------------------------------------------------------------------------------- /test/sigint-enquirer-raw.js: -------------------------------------------------------------------------------- 1 | // https://github.com/enquirer/enquirer/issues/372 2 | import { prompt, handleSIGINT } from '../src/util.js'; 3 | 4 | // const handleSIGINT = () => process.on('SIGINT', () => { // e.g. when killed by Ctrl-C 5 | // console.log('\nInterrupted by SIGINT. Exit!'); 6 | // process.exitCode = 130; 7 | // }); 8 | handleSIGINT(); 9 | 10 | function onRawSIGINT(fn) { 11 | const { stdin, stdout } = process; 12 | stdin.setRawMode(true); 13 | stdin.resume(); 14 | stdin.on('data', data => { 15 | const key = data.toString('utf-8'); 16 | if (key === '\u0003') { // ctrl + c 17 | fn(); 18 | } else { 19 | stdout.write(key); 20 | } 21 | }); 22 | } 23 | // onRawSIGINT(() => { 24 | // console.log('raw'); process.exit(1); 25 | // }); 26 | 27 | console.log('hello'); 28 | console.error('hello error'); 29 | try { 30 | let i = 'foo'; 31 | i = await prompt(); // SIGINT no longer handled if this is executed 32 | i = await prompt(); // SIGINT no longer handled if this is executed 33 | // handleSIGINT(); 34 | console.log('value:', i); 35 | setTimeout(() => console.log('timeout 3s'), 3000); 36 | } catch (e) { 37 | process.exitCode ||= 1; 38 | console.log('catch. exitCode:', process.exitCode); 39 | console.error(e); 40 | } 41 | console.log('end. exitCode:', process.exitCode); 42 | -------------------------------------------------------------------------------- /.github/workflows/sonar.yml: -------------------------------------------------------------------------------- 1 | name: Sonar 2 | 3 | on: 4 | # Trigger analysis when pushing in main or pull requests, and when creating a pull request. 5 | push: 6 | branches: 7 | - main 8 | pull_request: 9 | types: [opened, synchronize, reopened] 10 | 11 | permissions: 12 | contents: read 13 | 14 | jobs: 15 | sonarcloud: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - 19 | uses: actions/checkout@v4 20 | with: 21 | # Disabling shallow clone is recommended for improving relevancy of reporting. Otherwise sonarcloud will show a warning. 22 | fetch-depth: 0 23 | - 24 | uses: actions/setup-node@v4 25 | with: 26 | cache: 'npm' 27 | - 28 | name: Install dev dependencies which includde ESLint + plugins 29 | run: npm install --only=dev 30 | - 31 | name: Run ESLint 32 | continue-on-error: true 33 | run: npx eslint . -f json -o eslint_report.json 34 | - 35 | name: Fix ESLint paths 36 | run: sed -i 's+/home/runner/work/free-games-claimer/free-games-claimer+/github/workspace+g' eslint_report.json 37 | - 38 | name: SonarCloud Scan 39 | uses: sonarsource/sonarcloud-github-action@master 40 | env: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 43 | -------------------------------------------------------------------------------- /test/notify.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-constant-condition */ 2 | import { delay, html_game_list, notify } from '../src/util.js'; 3 | import { cfg } from '../src/config.js'; 4 | 5 | const URL_CLAIM = 'https://gaming.amazon.com/home'; // dummy URL 6 | 7 | console.debug('NOTIFY:', cfg.notify); 8 | 9 | if (true) { 10 | const notify_games = [ 11 | // { title: 'Kerbal Space Program', status: 'claimed', url: URL_CLAIM }, 12 | // { title: "Shadow Tactics - Aiko's Choice", status: 'claimed', url: URL_CLAIM }, 13 | { title: 'Epistory - Typing Chronicles', status: 'claimed', url: URL_CLAIM }, 14 | ]; 15 | await notify(`epic-games:
${html_game_list(notify_games)}`); 16 | } 17 | 18 | if (false) { 19 | await delay(1000); 20 | const notify_games = [ 21 | { title: 'Faraway 2: Jungle Escape', status: 'claimed', url: URL_CLAIM }, 22 | { title: 'Chicken Police - Paint it RED!', status: 'claimed', url: URL_CLAIM }, 23 | { title: 'Lawn Mowing Simulator', status: 'claimed', url: URL_CLAIM }, 24 | { title: 'Breathedge', status: 'claimed', url: URL_CLAIM }, 25 | { title: 'The Evil Within 2', status: `redeem H97S6FB38FA6D09DEA on gog.com`, url: URL_CLAIM }, 26 | { title: 'Beat Cop', status: `redeem BMKM8558EC55F7B38F on gog.com`, url: URL_CLAIM }, 27 | { title: 'Dishonored 2', status: `redeem NNEK0987AB20DFBF8F on gog.com`, url: URL_CLAIM }, 28 | ]; 29 | notify(`prime-gaming:
${html_game_list(notify_games)}`); 30 | } 31 | 32 | if (false) { 33 | await delay(1000); 34 | const notify_games = [ 35 | { title: 'Haven Park', status: 'claimed', url: URL_CLAIM }, 36 | ]; 37 | notify(`gog:
${html_game_list(notify_games)}`); 38 | } 39 | -------------------------------------------------------------------------------- /src/version.js: -------------------------------------------------------------------------------- 1 | // check if running the latest version 2 | 3 | import { log } from 'console'; 4 | import { exec } from 'child_process'; 5 | 6 | const execp = cmd => new Promise((resolve, reject) => { 7 | exec(cmd, (error, stdout, stderr) => { 8 | if (stderr) console.error(`stderr: ${stderr}`); 9 | // if (stdout) console.log(`stdout: ${stdout}`); 10 | if (error) { 11 | console.log(`error: ${error.message}`); 12 | if (error.message.includes('command not found')) { 13 | console.info('Install git to check for updates!'); 14 | } 15 | return reject(error); 16 | } 17 | resolve(stdout.trim()); 18 | }); 19 | }); 20 | 21 | // const git_main = () => readFileSync('.git/refs/heads/main').toString().trim(); 22 | 23 | let sha, date; 24 | // if (existsSync('/.dockerenv')) { // did not work 25 | if (process.env.NOVNC_PORT) { 26 | log('Running inside Docker.'); 27 | ['COMMIT', 'BRANCH', 'NOW'].forEach(v => log(` ${v}:`, process.env[v])); 28 | sha = process.env.COMMIT; 29 | date = process.env.NOW; 30 | } else { 31 | log('Not running inside Docker.'); 32 | sha = await execp('git rev-parse HEAD'); 33 | date = await execp('git show -s --format=%cD'); // same as format as `date -R` (RFC2822) 34 | // date = await execp('git show -s --format=%ch'); // %ch is same as --date=human (short/relative) 35 | } 36 | 37 | const gh = await (await fetch('https://api.github.com/repos/vogler/free-games-claimer/commits/main', { 38 | // headers: { accept: 'application/vnd.github.VERSION.sha' } 39 | })).json(); 40 | // log(gh); 41 | 42 | log('Local commit:', sha, new Date(date)); 43 | log('Online commit:', gh.sha, new Date(gh.commit.committer.date)); 44 | 45 | // git describe --all --long --dirty 46 | // --> heads/main-0-gdee47d2-dirty 47 | // git describe --tags --long --dirty 48 | // --> v1.7-35-gdee47d2-dirty 49 | 50 | if (sha == gh.sha) { 51 | log('Running the latest version!'); 52 | } else { 53 | log('Not running the latest version!'); 54 | } 55 | -------------------------------------------------------------------------------- /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | name: Build and push Docker image (amd64, arm64 to hub.docker.com and ghcr.io) 2 | 3 | on: 4 | workflow_dispatch: # allows manual trigger 5 | push: # push on branch 6 | branches: [main, dev] 7 | paths: # ignore changes to .md files 8 | - '**' 9 | - '!*.md' 10 | # - '!.github/**' 11 | pull_request: # runs when opened/reopned or when the head branch is updated 12 | 13 | permissions: 14 | contents: read 15 | packages: write 16 | 17 | env: 18 | BRANCH: ${{ github.head_ref || github.ref_name }} # head_ref/base_ref are only set for PRs, for branches ref_name will be used 19 | 20 | jobs: 21 | docker: 22 | runs-on: ubuntu-latest 23 | steps: 24 | - 25 | name: Checkout 26 | uses: actions/checkout@v4 27 | - 28 | name: Set environment variables 29 | run: | 30 | echo "NOW=$(date -R)" >> $GITHUB_ENV # date -Iseconds; date +'%Y-%m-%dT%H:%M:%S' 31 | if [[ "$BRANCH" == "main" ]]; then 32 | echo "IMAGE_TAG=latest" >> $GITHUB_ENV 33 | else 34 | echo "IMAGE_TAG=$BRANCH" >> $GITHUB_ENV 35 | fi 36 | - 37 | name: Set up QEMU 38 | uses: docker/setup-qemu-action@v3 39 | - 40 | name: Set up Docker Buildx 41 | uses: docker/setup-buildx-action@v3 42 | - 43 | name: Login to Docker Hub 44 | uses: docker/login-action@v3 45 | # if: ${{ secrets.DOCKERHUB_USERNAME != '' && secrets.DOCKERHUB_TOKEN != '' }} # does not work: Unrecognized named-value: 'secrets' - https://www.cloudtruth.com/blog/skipping-jobs-in-github-actions-when-secrets-are-unavailable-securely-inject-configuration-secrets-into-github 46 | with: 47 | username: ${{ secrets.DOCKERHUB_USERNAME }} 48 | password: ${{ secrets.DOCKERHUB_TOKEN }} 49 | - 50 | name: Login to GitHub Container Registry 51 | uses: docker/login-action@v3 52 | with: 53 | registry: ghcr.io 54 | username: ${{ github.actor }} # actor is user that opened PR, was repository_owner before 55 | password: ${{ secrets.GITHUB_TOKEN }} 56 | - 57 | name: Build and push 58 | uses: docker/build-push-action@v6 59 | if: ${{ env.IMAGE_TAG != '' }} 60 | with: 61 | context: . 62 | push: ${{ secrets.DOCKERHUB_USERNAME != '' }} 63 | build-args: | 64 | COMMIT=${{ github.sha }} 65 | BRANCH=${{ env.BRANCH }} 66 | NOW=${{ env.NOW }} 67 | platforms: linux/amd64,linux/arm64 68 | tags: | 69 | ${{ secrets.DOCKERHUB_USERNAME }}/free-games-claimer:${{env.IMAGE_TAG}} 70 | ghcr.io/${{ github.actor }}/free-games-claimer:${{env.IMAGE_TAG}} 71 | cache-from: type=gha 72 | cache-to: type=gha,mode=max 73 | -------------------------------------------------------------------------------- /docker-entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eo pipefail # exit on error, error on any fail in pipe (not just last cmd); add -x to print each cmd; see gist bash_strict_mode.md 4 | 5 | echo "Version: https://github.com/vogler/free-games-claimer/tree/${COMMIT}" 6 | [ ! -z $BRANCH ] && [ $BRANCH != "main" ] && echo "Branch: ${BRANCH}" 7 | echo "Build: $NOW" 8 | 9 | # Remove chromium profile lock. 10 | # When running in docker and then killing it, on the next run chromium displayed a dialog to unlock the profile which made the script time out. 11 | # Maybe due to changed hostname of container or due to how the docker container kills playwright - didn't check. 12 | # https://bugs.chromium.org/p/chromium/issues/detail?id=367048 13 | rm -f /fgc/data/browser/SingletonLock 14 | 15 | # Firefox preferences are stored in $BROWSER_DIR/pref.js and can be overridden by a file user.js 16 | # Since this file has to be in the volume (data/browser), we can't do this in Dockerfile. 17 | mkdir -p /fgc/data/browser 18 | # fix for 'Incorrect response' after solving a captcha correctly - https://github.com/vogler/free-games-claimer/issues/261#issuecomment-1868385830 19 | # echo 'user_pref("privacy.resistFingerprinting", true);' > /fgc/data/browser/user.js 20 | cat << EOT > /fgc/data/browser/user.js 21 | user_pref("privacy.resistFingerprinting", true); 22 | // user_pref("privacy.resistFingerprinting.letterboxing", true); 23 | // user_pref("browser.contentblocking.category", "strict"); 24 | // user_pref("webgl.disabled", true); 25 | EOT 26 | # TODO disable session restore message? 27 | 28 | # Remove X server display lock, fix for `docker compose up` which reuses container which made it fail after initial run, https://github.com/vogler/free-games-claimer/issues/31 29 | # echo $DISPLAY 30 | # ls -l /tmp/.X11-unix/ 31 | rm -f /tmp/.X1-lock 32 | 33 | # 6000+SERVERNUM is the TCP port Xvfb is listening on: 34 | # SERVERNUM=$(echo "$DISPLAY" | sed 's/:\([0-9][0-9]*\).*/\1/') 35 | 36 | # Options passed directly to the Xvfb server: 37 | # -ac disables host-based access control mechanisms 38 | # −screen NUM WxHxD creates the screen and sets its width, height, and depth 39 | 40 | export DISPLAY=:1 # need to export this, otherwise playwright complains with 'Looks like you launched a headed browser without having a XServer running.' 41 | Xvfb $DISPLAY -ac -screen 0 "${WIDTH}x${HEIGHT}x${DEPTH}" & 42 | echo "Xvfb display server created screen with resolution ${WIDTH}x${HEIGHT}" 43 | if [ -z "$VNC_PASSWORD" ]; then 44 | pw="-nopw" 45 | pwt="no password!" 46 | else 47 | pw="-passwd $VNC_PASSWORD" 48 | pwt="with password" 49 | fi 50 | x11vnc -display $DISPLAY -forever -shared -rfbport $VNC_PORT -bg $pw 2>/dev/null 1>&2 51 | echo "VNC is running on port $VNC_PORT ($pwt)" 52 | websockify -D --web "/usr/share/novnc/" $NOVNC_PORT "localhost:$VNC_PORT" 2>/dev/null 1>&2 & 53 | echo "noVNC (VNC via browser) is running on http://localhost:$NOVNC_PORT" 54 | echo 55 | exec tini -g -- "$@" # https://github.com/krallin/tini/issues/8 node/playwright respond to signals like ctrl-c, but unsure about zombie processes 56 | -------------------------------------------------------------------------------- /src/config.js: -------------------------------------------------------------------------------- 1 | import * as dotenv from 'dotenv'; 2 | import { dataDir } from './util.js'; 3 | 4 | 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 ... 5 | 6 | // Options - also see table in README.md 7 | export const cfg = { 8 | debug: process.env.DEBUG == '1' || process.env.PWDEBUG == '1', // runs non-headless and opens https://playwright.dev/docs/inspector 9 | debug_network: process.env.DEBUG_NETWORK == '1', // log network requests and responses 10 | record: process.env.RECORD == '1', // `recordHar` (network) + `recordVideo` 11 | time: process.env.TIME == '1', // log duration of each step 12 | dryrun: process.env.DRYRUN == '1', // don't claim anything 13 | interactive: process.env.INTERACTIVE == '1', // confirm to claim, default skip 14 | show: process.env.SHOW == '1', // run non-headless 15 | get headless() { 16 | return !this.debug && !this.show; 17 | }, 18 | width: Number(process.env.WIDTH) || 1920, // width of the opened browser 19 | height: Number(process.env.HEIGHT) || 1080, // height of the opened browser 20 | timeout: (Number(process.env.TIMEOUT) || 60) * 1000, // default timeout for playwright is 30s 21 | login_timeout: (Number(process.env.LOGIN_TIMEOUT) || 180) * 1000, // higher timeout for login, will wait twice: prompt + wait for manual login 22 | novnc_port: process.env.NOVNC_PORT, // running in docker if set 23 | notify: process.env.NOTIFY, // apprise notification services 24 | notify_title: process.env.NOTIFY_TITLE, // apprise notification title 25 | get dir() { // avoids ReferenceError: Cannot access 'dataDir' before initialization 26 | return { 27 | browser: process.env.BROWSER_DIR || dataDir('browser'), // for multiple accounts or testing 28 | screenshots: process.env.SCREENSHOTS_DIR || dataDir('screenshots'), // set to 0 to disable screenshots 29 | }; 30 | }, 31 | // auth epic-games 32 | eg_email: process.env.EG_EMAIL || process.env.EMAIL, 33 | eg_password: process.env.EG_PASSWORD || process.env.PASSWORD, 34 | eg_otpkey: process.env.EG_OTPKEY, 35 | eg_parentalpin: process.env.EG_PARENTALPIN, 36 | // auth prime-gaming 37 | pg_email: process.env.PG_EMAIL || process.env.EMAIL, 38 | pg_password: process.env.PG_PASSWORD || process.env.PASSWORD, 39 | pg_otpkey: process.env.PG_OTPKEY, 40 | // auth gog 41 | gog_email: process.env.GOG_EMAIL || process.env.EMAIL, 42 | gog_password: process.env.GOG_PASSWORD || process.env.PASSWORD, 43 | gog_newsletter: process.env.GOG_NEWSLETTER == '1', // do not unsubscribe from newsletter after claiming a game 44 | // auth AliExpress 45 | ae_email: process.env.AE_EMAIL || process.env.EMAIL, 46 | ae_password: process.env.AE_PASSWORD || process.env.PASSWORD, 47 | // OTP only via GOG_EMAIL, can't add app... 48 | // experimmental 49 | pg_redeem: process.env.PG_REDEEM == '1', // prime-gaming: redeem keys on external stores 50 | lg_email: process.env.LG_EMAIL || process.env.PG_EMAIL || process.env.EMAIL, // prime-gaming: external: legacy-games: email to use for redeeming 51 | pg_claimdlc: process.env.PG_CLAIMDLC == '1', // prime-gaming: claim in-game content 52 | 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 53 | }; 54 | -------------------------------------------------------------------------------- /steam-games.js: -------------------------------------------------------------------------------- 1 | import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra 2 | import { jsonDb, prompt } from './src/util.js'; 3 | import { cfg } from './src/config.js'; 4 | 5 | const db = await jsonDb('steam-games.json', {}); 6 | 7 | const user = cfg.steam_id || await prompt({ message: 'Enter Steam community id ("View my profile", then copy from URL)' }); 8 | 9 | // using https://github.com/apify/fingerprint-suite worked, but has no launchPersistentContext... 10 | // from https://github.com/apify/fingerprint-suite/issues/162 11 | import { FingerprintInjector } from 'fingerprint-injector'; 12 | import { FingerprintGenerator } from 'fingerprint-generator'; 13 | 14 | const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({ 15 | devices: ["desktop"], 16 | operatingSystems: ["windows"], 17 | }); 18 | 19 | const context = await firefox.launchPersistentContext(cfg.dir.browser, { 20 | headless: cfg.headless, 21 | // viewport: { width: cfg.width, height: cfg.height }, 22 | locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL 23 | userAgent: fingerprint.navigator.userAgent, 24 | viewport: { 25 | width: fingerprint.screen.width, 26 | height: fingerprint.screen.height, 27 | }, 28 | extraHTTPHeaders: { 29 | 'accept-language': headers['accept-language'], 30 | }, 31 | }); 32 | // await stealth(context); 33 | await new FingerprintInjector().attachFingerprintToPlaywright(context, { fingerprint, headers }); 34 | 35 | context.setDefaultTimeout(cfg.debug ? 0 : cfg.timeout); 36 | 37 | const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist 38 | 39 | try { 40 | await page.goto(`https://steamcommunity.com/id/${user}/games?tab=all`); 41 | const games = page.locator('div[data-featuretarget="gameslist-root"] > div.Panel > div.Panel > div'); 42 | await games.last().waitFor(); 43 | await page.keyboard.press('End'); 44 | await page.waitForLoadState('networkidle'); 45 | console.log('All Games:', await games.count()); 46 | for (const game of await games.all()) { 47 | const title = await game.locator('span a').innerText(); 48 | let time, last, achievements, size; 49 | const ltime = game.locator('span:has-text("total played")'); 50 | if (await ltime.count()) time = (await ltime.first().innerText()).split('\n')[1]; 51 | const llast = game.locator('span:has-text("last played")'); 52 | if (await llast.count()) last = (await llast.first().innerText()).split('\n')[1]; 53 | const lachievements = game.locator('a:has-text("achievements") + span'); 54 | if (await lachievements.count()) achievements = (await lachievements.first().innerText()).split('\n'); 55 | const lsize = game.locator('span:has(+ button)'); 56 | if (await lsize.count()) size = await lsize.first().innerText(); 57 | const url = await game.locator('a').first().getAttribute('href'); 58 | const img = await game.locator('img').first().getAttribute('src'); 59 | const stat = { title, time, last, achievements, size, url, img }; 60 | console.log(stat); 61 | db.data[title] = stat; 62 | } 63 | 64 | // await page.pause(); 65 | } catch (error) { 66 | process.exitCode ||= 1; 67 | console.error('--- Exception:'); 68 | console.error(error); // .toString()? 69 | } finally { 70 | await db.write(); // write out json db 71 | } 72 | if (page.video()) console.log('Recorded video:', await page.video().path()); 73 | await context.close(); 74 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | // https://eslint.org/docs/latest/use/configure/configuration-files-new 2 | // https://eslint.org/docs/latest/use/configure/migration-guide 3 | import js from '@eslint/js'; 4 | import globals from 'globals'; 5 | import stylistic from '@stylistic/eslint-plugin-js'; 6 | 7 | export default [ 8 | // https://eslint.org/docs/latest/use/configure/configuration-files-new#globally-ignoring-files-with-ignores 9 | // object with just `ignores` applies to all configuration objects 10 | // had `ln -s .gitignore .eslintignore` before, but .eslintignore no longer supported 11 | { 12 | ignores: ['data/**'], 13 | }, 14 | js.configs.recommended, // TODO still needed? 15 | { 16 | // files: ['*.js'], 17 | languageOptions: { 18 | globals: globals.node, 19 | }, 20 | plugins: { 21 | '@stylistic/js': stylistic, 22 | }, 23 | // https://eslint.org/docs/latest/rules/ 24 | // https://eslint.style/packages/js 25 | rules: { 26 | 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], 27 | 'prefer-const': 'error', 28 | '@stylistic/js/array-bracket-newline': ['error', 'consistent'], 29 | '@stylistic/js/array-bracket-spacing': 'error', 30 | '@stylistic/js/array-element-newline': ['error', 'consistent'], 31 | '@stylistic/js/arrow-parens': ['error', 'as-needed'], 32 | '@stylistic/js/arrow-spacing': 'error', 33 | '@stylistic/js/block-spacing': 'error', 34 | '@stylistic/js/brace-style': 'error', 35 | '@stylistic/js/comma-dangle': ['error', 'always-multiline'], 36 | '@stylistic/js/comma-spacing': 'error', 37 | '@stylistic/js/comma-style': 'error', 38 | '@stylistic/js/eol-last': 'error', 39 | '@stylistic/js/func-call-spacing': 'error', 40 | '@stylistic/js/function-paren-newline': ['error', 'consistent'], 41 | '@stylistic/js/implicit-arrow-linebreak': 'error', 42 | '@stylistic/js/indent': ['error', 2], 43 | '@stylistic/js/key-spacing': 'error', 44 | '@stylistic/js/keyword-spacing': 'error', 45 | '@stylistic/js/linebreak-style': 'error', 46 | '@stylistic/js/no-extra-parens': 'error', 47 | '@stylistic/js/no-extra-semi': 'error', 48 | '@stylistic/js/no-mixed-spaces-and-tabs': 'error', 49 | '@stylistic/js/no-multi-spaces': 'error', 50 | '@stylistic/js/no-multiple-empty-lines': 'error', 51 | '@stylistic/js/no-tabs': 'error', 52 | '@stylistic/js/no-trailing-spaces': 'error', 53 | '@stylistic/js/no-whitespace-before-property': 'error', 54 | '@stylistic/js/nonblock-statement-body-position': 'error', 55 | '@stylistic/js/object-curly-newline': 'error', 56 | '@stylistic/js/object-curly-spacing': ['error', 'always'], 57 | '@stylistic/js/object-property-newline': ['error', { allowAllPropertiesOnSameLine: true }], 58 | '@stylistic/js/quote-props': ['error', 'as-needed'], 59 | '@stylistic/js/quotes': ['error', 'single'], 60 | '@stylistic/js/rest-spread-spacing': 'error', 61 | '@stylistic/js/semi': 'error', 62 | '@stylistic/js/semi-spacing': 'error', 63 | '@stylistic/js/semi-style': 'error', 64 | '@stylistic/js/space-before-blocks': 'error', 65 | '@stylistic/js/space-before-function-paren': ['error', { anonymous: 'never', named: 'never', asyncArrow: 'always' }], 66 | '@stylistic/js/space-in-parens': 'error', 67 | '@stylistic/js/space-infix-ops': 'error', 68 | '@stylistic/js/space-unary-ops': 'error', 69 | '@stylistic/js/spaced-comment': 'error', 70 | '@stylistic/js/switch-colon-spacing': 'error', 71 | '@stylistic/js/template-curly-spacing': 'error', 72 | '@stylistic/js/template-tag-spacing': 'error', 73 | '@stylistic/js/wrap-regex': 'error', 74 | }, 75 | }, 76 | ]; 77 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # FROM mcr.microsoft.com/playwright:v1.20.0 2 | # Partially from https://github.com/microsoft/playwright/blob/main/utils/docker/Dockerfile.focal 3 | FROM ubuntu:jammy 4 | 5 | # Configuration variables are at the end! 6 | 7 | # https://github.com/hadolint/hadolint/wiki/DL4006 8 | SHELL ["/bin/bash", "-o", "pipefail", "-c"] 9 | ARG DEBIAN_FRONTEND=noninteractive 10 | 11 | # Install up-to-date node & npm, deps for virtual screen & noVNC, firefox, pip for apprise. 12 | RUN apt-get update \ 13 | && apt-get install --no-install-recommends -y curl ca-certificates gnupg \ 14 | && mkdir -p /etc/apt/keyrings \ 15 | && curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \ 16 | && echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list \ 17 | && apt-get update \ 18 | && apt-get install --no-install-recommends -y \ 19 | nodejs \ 20 | xvfb \ 21 | x11vnc \ 22 | tini \ 23 | novnc websockify \ 24 | dos2unix \ 25 | python3-pip \ 26 | # && npx playwright install-deps firefox \ 27 | && apt-get install --no-install-recommends -y \ 28 | libgtk-3-0 \ 29 | libasound2 \ 30 | libxcomposite1 \ 31 | libpangocairo-1.0-0 \ 32 | libpango-1.0-0 \ 33 | libatk1.0-0 \ 34 | libcairo-gobject2 \ 35 | libcairo2 \ 36 | libgdk-pixbuf-2.0-0 \ 37 | libdbus-glib-1-2 \ 38 | libxcursor1 \ 39 | && apt-get autoremove -y \ 40 | && apt-get clean \ 41 | && rm -rf \ 42 | /tmp/* \ 43 | /usr/share/doc/* \ 44 | /var/cache/* \ 45 | /var/lib/apt/lists/* \ 46 | /var/tmp/* 47 | 48 | # RUN node --version 49 | # RUN npm --version 50 | 51 | RUN ln -s /usr/share/novnc/vnc_auto.html /usr/share/novnc/index.html 52 | RUN pip install apprise 53 | 54 | WORKDIR /fgc 55 | COPY package*.json ./ 56 | 57 | # Playwright installs patched firefox to ~/.cache/ms-playwright/firefox-* 58 | # Requires some system deps to run (see inlined install-deps above). 59 | RUN npm install 60 | # Old: PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD + install firefox (had to be done after `npm install` to get the correct version). Now: playwright-firefox as npm dep and `npm install` will only install that. 61 | # From 1.38 Playwright will no longer install browser automatically for playwright, but apparently still for playwright-firefox: https://github.com/microsoft/playwright/releases/tag/v1.38.0 62 | # RUN npx playwright install firefox 63 | 64 | COPY . . 65 | 66 | # Shell scripts need Linux line endings. On Windows, git might be configured to check out dos/CRLF line endings, so we convert them for those people in case they want to build the image. They could also use --config core.autocrlf=input 67 | RUN dos2unix ./*.sh && chmod +x ./*.sh 68 | COPY docker-entrypoint.sh /usr/local/bin/ 69 | 70 | ARG COMMIT="" 71 | ARG BRANCH="" 72 | ARG NOW="" 73 | ENV COMMIT=${COMMIT} 74 | ENV BRANCH=${BRANCH} 75 | ENV NOW=${NOW} 76 | 77 | LABEL org.opencontainers.image.title="free-games-claimer" \ 78 | org.opencontainers.image.name="free-games-claimer" \ 79 | org.opencontainers.image.description="Automatically claims free games on the Epic Games Store, Amazon Prime Gaming and GOG" \ 80 | org.opencontainers.image.url="https://github.com/vogler/free-games-claimer" \ 81 | org.opencontainers.image.source="https://github.com/vogler/free-games-claimer" \ 82 | org.opencontainers.image.revision=${COMMIT} \ 83 | org.opencontainers.image.ref.name=${BRANCH} \ 84 | org.opencontainers.image.base.name="ubuntu:jammy" \ 85 | org.opencontainers.image.version="latest" 86 | 87 | # Configure VNC via environment variables: 88 | ENV VNC_PORT 5900 89 | ENV NOVNC_PORT 6080 90 | EXPOSE 5900 91 | EXPOSE 6080 92 | 93 | # Configure Xvfb via environment variables: 94 | ENV WIDTH 1920 95 | ENV HEIGHT 1080 96 | ENV DEPTH 24 97 | 98 | # Show browser instead of running headless 99 | ENV SHOW 1 100 | 101 | # Script to setup display server & VNC is always executed. 102 | ENTRYPOINT ["docker-entrypoint.sh"] 103 | # Default command to run. This is replaced by appending own command, e.g. `docker run ... node prime-gaming` to only run this script. 104 | CMD node epic-games; node prime-gaming; node gog 105 | -------------------------------------------------------------------------------- /aliexpress.js: -------------------------------------------------------------------------------- 1 | import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra 2 | import { datetime, filenamify, prompt, handleSIGINT, stealth } from './src/util.js'; 3 | import { cfg } from './src/config.js'; 4 | 5 | // using https://github.com/apify/fingerprint-suite worked, but has no launchPersistentContext... 6 | // from https://github.com/apify/fingerprint-suite/issues/162 7 | import { FingerprintInjector } from 'fingerprint-injector'; 8 | import { FingerprintGenerator } from 'fingerprint-generator'; 9 | 10 | const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({ 11 | devices: ["mobile"], 12 | operatingSystems: ["android"], 13 | }); 14 | 15 | const context = await firefox.launchPersistentContext(cfg.dir.browser, { 16 | headless: cfg.headless, 17 | // viewport: { width: cfg.width, height: cfg.height }, 18 | locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL 19 | 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 20 | recordHar: cfg.record ? { path: `data/record/aliexpress-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools 21 | handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved 22 | userAgent: fingerprint.navigator.userAgent, 23 | viewport: { 24 | width: fingerprint.screen.width, 25 | height: fingerprint.screen.height, 26 | }, 27 | extraHTTPHeaders: { 28 | 'accept-language': headers['accept-language'], 29 | }, 30 | }); 31 | handleSIGINT(context); 32 | // await stealth(context); 33 | await new FingerprintInjector().attachFingerprintToPlaywright(context, { fingerprint, headers }); 34 | 35 | context.setDefaultTimeout(cfg.debug ? 0 : cfg.timeout); 36 | 37 | const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist 38 | 39 | const auth = async (url) => { 40 | console.log('auth', url); 41 | await page.goto(url, { waitUntil: 'domcontentloaded' }); 42 | // redirects to https://login.aliexpress.com/?return_url=https%3A%2F%2Fwww.aliexpress.com%2Fp%2Fcoin-pc-index%2Findex.html 43 | await Promise.any([page.waitForURL(/.*login\.aliexpress.com.*/).then(async () => { 44 | // manual login 45 | console.error('Not logged in! Will wait for 120s for you to login...'); 46 | // await page.waitForTimeout(120*1000); 47 | // or try automated 48 | page.locator('span:has-text("Switch account")').click().catch(_ => {}); // sometimes no longer logged in, but previous user/email is pre-selected -> in this case we want to go back to the classic login 49 | const login = page.locator('.login-container'); 50 | const email = cfg.ae_email || await prompt({ message: 'Enter email' }); 51 | const emailInput = login.locator('input[label="Email or phone number"]'); 52 | await emailInput.fill(email); 53 | await emailInput.blur(); // otherwise Continue button stays disabled 54 | const continueButton = login.locator('button:has-text("Continue")'); 55 | await continueButton.click({ force: true }); // normal click waits for button to no longer be covered by their suggestion menu, so we have to force click somewhere for the menu to close and then click 56 | await continueButton.click(); 57 | const password = email && (cfg.ae_password || await prompt({ type: 'password', message: 'Enter password' })); 58 | await login.locator('input[label="Password"]').fill(password); 59 | await login.locator('button:has-text("Sign in")').click(); 60 | const error = login.locator('.error-text'); 61 | error.waitFor().then(async _ => console.error('Login error:', await error.innerText())); 62 | await page.waitForURL(url); 63 | // await page.addLocatorHandler(page.getByRole('button', { name: 'Accept cookies' }), btn => btn.click()); 64 | page.getByRole('button', { name: 'Accept cookies' }).click().then(_ => console.log('Accepted cookies')).catch(_ => { }); 65 | }), page.locator('#nav-user-account').waitFor()]).catch(_ => {}); 66 | 67 | // await page.locator('#nav-user-account').hover(); 68 | // console.log('Logged in as:', await page.locator('.welcome-name').innerText()); 69 | }; 70 | 71 | // copied URLs from AliExpress app on tablet which has menu for the used webview 72 | const urls = { 73 | // works with desktop view, but stuck at 100% loading in mobile view: 74 | coins: 'https://www.aliexpress.com/p/coin-pc-index/index.html', 75 | // only work with mobile view: 76 | grow: 'https://m.aliexpress.com/p/ae_fruit/index.html', // firefox: stuck at 60% loading, chrome: loads, but canvas 77 | gogo: 'https://m.aliexpress.com/p/gogo-match-cc/index.html', // closes firefox?! 78 | // only show notification to install the app 79 | euro: 'https://m.aliexpress.com/p/european-cup/index.html', // doesn't load 80 | merge: 'https://m.aliexpress.com/p/merge-market/index.html', 81 | }; 82 | 83 | const coins = async () => { 84 | // await auth(urls.coins); 85 | await Promise.any([page.locator('.checkin-button').click(), page.locator('.addcoin').waitFor()]); 86 | console.log('Coins:', await page.locator('.mycoin-content-right-money').innerText()); 87 | console.log('Streak:', await page.locator('.title-box').innerText()); 88 | console.log('Tomorrow:', await page.locator('.addcoin').innerText()); 89 | }; 90 | 91 | const grow = async () => { 92 | await page.pause(); 93 | }; 94 | 95 | const gogo = async () => { 96 | await page.pause(); 97 | }; 98 | 99 | const euro = async () => { 100 | await page.pause(); 101 | }; 102 | 103 | const merge = async () => { 104 | await page.pause(); 105 | }; 106 | 107 | try { 108 | // await coins(); 109 | await [ 110 | // coins, 111 | // grow, 112 | // gogo, 113 | // euro, 114 | merge, 115 | ].reduce((a, f) => a.then(async _ => { await auth(urls[f.name]); await f(); console.log() }), Promise.resolve()); 116 | 117 | // await page.pause(); 118 | } catch (error) { 119 | process.exitCode ||= 1; 120 | console.error('--- Exception:'); 121 | console.error(error); // .toString()? 122 | } 123 | if (page.video()) console.log('Recorded video:', await page.video().path()); 124 | await context.close(); 125 | -------------------------------------------------------------------------------- /src/util.js: -------------------------------------------------------------------------------- 1 | // https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules 2 | import path from 'node:path'; 3 | import { fileURLToPath } from 'node:url'; 4 | // not the same since these will give the absolute paths for this file instead of for the file using them 5 | const __filename = fileURLToPath(import.meta.url); 6 | const __dirname = path.dirname(__filename); 7 | // 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 8 | export const dataDir = s => path.resolve(__dirname, '..', 'data', s); 9 | 10 | // modified path.resolve to return null if first argument is '0', used to disable screenshots 11 | export const resolve = (...a) => a.length && a[0] == '0' ? null : path.resolve(...a); 12 | 13 | // json database 14 | import { JSONFilePreset } from 'lowdb/node'; 15 | export const jsonDb = (file, defaultData) => JSONFilePreset(dataDir(file), defaultData); 16 | 17 | export const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); 18 | // date and time as UTC (no timezone offset) in nicely readable and sortable format, e.g., 2022-10-06 12:05:27.313 19 | export const datetimeUTC = (d = new Date()) => d.toISOString().replace('T', ' ').replace('Z', ''); 20 | // same as datetimeUTC() but for local timezone, e.g., UTC + 2h for the above in DE 21 | export const datetime = (d = new Date()) => datetimeUTC(new Date(d.getTime() - d.getTimezoneOffset() * 60000)); 22 | 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. 23 | 24 | export const handleSIGINT = (context = null) => process.on('SIGINT', async () => { // e.g. when killed by Ctrl-C 25 | console.error('\nInterrupted by SIGINT. Exit!'); // Exception shows where the script was:\n'); // killed before catch in docker... 26 | process.exitCode = 130; // 128+SIGINT to indicate to parent that process was killed 27 | if (context) await context.close(); // in order to save recordings also on SIGINT, we need to disable Playwright's handleSIGINT and close the context ourselves 28 | }); 29 | 30 | export const launchChromium = async options => { 31 | const { chromium } = await import('playwright-chromium'); // stealth plugin needs no outdated playwright-extra 32 | 33 | // https://www.nopecha.com extension source from https://github.com/NopeCHA/NopeCHA/releases/tag/0.1.16 34 | // const ext = path.resolve('nopecha'); // used in Chromium, currently not needed in Firefox 35 | 36 | const context = chromium.launchPersistentContext(cfg.dir.browser, { 37 | // chrome will not work in linux arm64, only chromium 38 | // channel: 'chrome', // https://playwright.dev/docs/browsers#google-chrome--microsoft-edge 39 | args: [ // https://peter.sh/experiments/chromium-command-line-switches 40 | // don't want to see bubble 'Restore pages? Chrome didn't shut down correctly.' 41 | // '--restore-last-session', // does not apply for crash/killed 42 | '--hide-crash-restore-bubble', 43 | // `--disable-extensions-except=${ext}`, 44 | // `--load-extension=${ext}`, 45 | ], 46 | // ignoreDefaultArgs: ['--enable-automation'], // remove default arg that shows the info bar with 'Chrome is being controlled by automated test software.'. Since Chromeium 106 this leads to show another info bar with 'You are using an unsupported command-line flag: --no-sandbox. Stability and security will suffer.'. 47 | ...options, 48 | }); 49 | return context; 50 | }; 51 | 52 | export const stealth = async context => { 53 | // stealth with playwright: https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212 54 | // https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth/evasions 55 | const enabledEvasions = [ 56 | 'chrome.app', 57 | 'chrome.csi', 58 | 'chrome.loadTimes', 59 | 'chrome.runtime', 60 | // 'defaultArgs', 61 | 'iframe.contentWindow', 62 | 'media.codecs', 63 | 'navigator.hardwareConcurrency', 64 | 'navigator.languages', 65 | 'navigator.permissions', 66 | 'navigator.plugins', 67 | // 'navigator.vendor', 68 | 'navigator.webdriver', 69 | 'sourceurl', 70 | // 'user-agent-override', // doesn't work since playwright has no page.browser() 71 | 'webgl.vendor', 72 | 'window.outerdimensions', 73 | ]; 74 | const stealth = { 75 | callbacks: [], 76 | async evaluateOnNewDocument(...args) { 77 | this.callbacks.push({ cb: args[0], a: args[1] }); 78 | }, 79 | }; 80 | for (const e of enabledEvasions) { 81 | const evasion = await import(`puppeteer-extra-plugin-stealth/evasions/${e}/index.js`); 82 | evasion.default().onPageCreated(stealth); 83 | } 84 | for (const evasion of stealth.callbacks) { 85 | await context.addInitScript(evasion.cb, evasion.a); 86 | } 87 | }; 88 | 89 | // used prompts before, but couldn't cancel prompt 90 | // alternative inquirer is big (node_modules 29MB, enquirer 9.7MB, prompts 9.8MB, none 9.4MB) and slower 91 | // open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372 92 | import Enquirer from 'enquirer'; const enquirer = new Enquirer(); 93 | const timeoutPlugin = timeout => enquirer => { // cancel prompt after timeout ms 94 | enquirer.on('prompt', prompt => { 95 | const t = setTimeout(() => { 96 | prompt.hint = () => 'timeout'; 97 | prompt.cancel(); 98 | }, timeout); 99 | prompt.on('submit', _ => clearTimeout(t)); 100 | prompt.on('cancel', _ => clearTimeout(t)); 101 | }); 102 | }; 103 | enquirer.use(timeoutPlugin(cfg.login_timeout)); // TODO may not want to have this timeout for all prompts; better extend Prompt and add a timeout prompt option 104 | // single prompt that just returns the non-empty value instead of an object 105 | // @ts-ignore 106 | export const prompt = o => enquirer.prompt({ name: 'name', type: 'input', message: 'Enter value', ...o }).then(r => r.name).catch(_ => {}); 107 | export const confirm = o => prompt({ type: 'confirm', message: 'Continue?', ...o }); 108 | 109 | // notifications via apprise CLI 110 | import { execFile } from 'child_process'; 111 | import { cfg } from './config.js'; 112 | 113 | export const notify = html => new Promise((resolve, reject) => { 114 | if (!cfg.notify) { 115 | if (cfg.debug) console.debug('notify: NOTIFY is not set!'); 116 | return resolve(); 117 | } 118 | // const cmd = `apprise '${cfg.notify}' ${title} -i html -b '${html}'`; // this had problems if e.g. ' was used in arg; could have `npm i shell-escape`, but instead using safer execFile which takes args as array instead of exec which spawned a shell to execute the command 119 | const args = [cfg.notify, '-i', 'html', '-b', `'${html}'`]; 120 | if (cfg.notify_title) args.push(...['-t', cfg.notify_title]); 121 | if (cfg.debug) console.debug(`apprise ${args.map(a => `'${a}'`).join(' ')}`); // this also doesn't escape, but it's just for info 122 | execFile('apprise', args, (error, stdout, stderr) => { 123 | if (error) { 124 | console.log(`error: ${error.message}`); 125 | if (error.message.includes('command not found')) { 126 | console.info('Run `pip install apprise`. See https://github.com/vogler/free-games-claimer#notifications'); 127 | } 128 | return reject(error); 129 | } 130 | if (stderr) console.error(`stderr: ${stderr}`); 131 | if (stdout) console.log(`stdout: ${stdout}`); 132 | resolve(); 133 | }); 134 | }); 135 | 136 | export const escapeHtml = unsafe => unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll('\'', '''); 137 | 138 | export const html_game_list = games => games.map(g => `- ${escapeHtml(g.title)} (${g.status})`).join('
'); 139 | -------------------------------------------------------------------------------- /gog.js: -------------------------------------------------------------------------------- 1 | import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra 2 | import chalk from 'chalk'; 3 | import { resolve, jsonDb, datetime, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js'; 4 | import { cfg } from './src/config.js'; 5 | 6 | const screenshot = (...a) => resolve(cfg.dir.screenshots, 'gog', ...a); 7 | 8 | const URL_CLAIM = 'https://www.gog.com/en'; 9 | 10 | console.log(datetime(), 'started checking gog'); 11 | 12 | const db = await jsonDb('gog.json', {}); 13 | 14 | if (cfg.width < 1280) { // otherwise 'Sign in' and #menuUsername are hidden (but attached to DOM), see https://github.com/vogler/free-games-claimer/issues/335 15 | console.error(`Window width is set to ${cfg.width} but needs to be at least 1280 for GOG!`); 16 | process.exit(1); 17 | } 18 | 19 | // https://playwright.dev/docs/auth#multi-factor-authentication 20 | const context = await firefox.launchPersistentContext(cfg.dir.browser, { 21 | headless: cfg.headless, 22 | viewport: { width: cfg.width, height: cfg.height }, 23 | locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL 24 | 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 25 | recordHar: cfg.record ? { path: `data/record/gog-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools 26 | handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved 27 | }); 28 | 29 | handleSIGINT(context); 30 | 31 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 32 | 33 | const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist 34 | await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it 35 | // console.debug('userAgent:', await page.evaluate(() => navigator.userAgent)); 36 | 37 | const notify_games = []; 38 | let user; 39 | 40 | try { 41 | 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 42 | 43 | await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever 44 | 45 | // page.click('#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll').catch(_ => { }); // does not work reliably, solved by setting CookieConsent above 46 | const signIn = page.locator('a:has-text("Sign in")').first(); 47 | await Promise.any([signIn.waitFor(), page.waitForSelector('#menuUsername')]); 48 | while (await signIn.isVisible()) { 49 | console.error('Not signed in anymore.'); 50 | await signIn.click(); 51 | // it then creates an iframe for the login 52 | await page.waitForSelector('#GalaxyAccountsFrameContainer iframe'); // TODO needed? 53 | const iframe = page.frameLocator('#GalaxyAccountsFrameContainer iframe'); 54 | if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in 55 | console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`); 56 | if (cfg.gog_email && cfg.gog_password) console.info('Using email and password from environment.'); 57 | else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).'); 58 | const email = cfg.gog_email || await prompt({ message: 'Enter email' }); 59 | const password = email && (cfg.gog_password || await prompt({ type: 'password', message: 'Enter password' })); 60 | if (email && password) { 61 | iframe.locator('a[href="/logout"]').click().catch(_ => { }); // Click 'Change account' (email from previous login is set in some cookie) 62 | await iframe.locator('#login_username').fill(email); 63 | await iframe.locator('#login_password').fill(password); 64 | await iframe.locator('#login_login').click(); 65 | // handle MFA, but don't await it 66 | iframe.locator('form[name=second_step_authentication]').waitFor().then(async () => { 67 | console.log('Two-Step Verification - Enter security code'); 68 | console.log(await iframe.locator('.form__description').innerText()); 69 | 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 70 | await iframe.locator('#second_step_authentication_token_letter_1').pressSequentially(otp.toString(), { delay: 10 }); 71 | await iframe.locator('#second_step_authentication_send').click(); 72 | await page.waitForTimeout(1000); // TODO still needed with wait for username below? 73 | }).catch(_ => { }); 74 | // iframe.locator('iframe[title=reCAPTCHA]').waitFor().then(() => { 75 | // iframe.locator('.g-recaptcha').waitFor().then(() => { 76 | iframe.locator('text=Invalid captcha').waitFor().then(() => { 77 | 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.'); 78 | notify('gog: got captcha during login. Please check.'); 79 | // TODO solve reCAPTCHA? 80 | }).catch(_ => { }); 81 | await page.waitForSelector('#menuUsername'); 82 | } else { 83 | console.log('Waiting for you to login in the browser.'); 84 | await notify('gog: no longer signed in and not enough options set for automatic login.'); 85 | if (cfg.headless) { 86 | console.log('Run `SHOW=1 node gog` to login in the opened browser.'); 87 | await context.close(); 88 | process.exit(1); 89 | } 90 | } 91 | await page.waitForSelector('#menuUsername'); 92 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 93 | } 94 | user = await page.locator('#menuUsername').first().textContent(); // innerText is uppercase due to styling! 95 | console.log(`Signed in as ${user}`); 96 | db.data[user] ||= {}; 97 | 98 | const banner = page.locator('#giveaway'); 99 | if (!await banner.count()) { 100 | console.log('Currently no free giveaway!'); 101 | } else { 102 | const text = await page.locator('.giveaway__content-header').innerText(); 103 | const match_all = text.match(/Claim (.*) and don't miss the|Success! (.*) was added to/); 104 | const title = match_all[1] ? match_all[1] : match_all[2]; 105 | const url = await banner.locator('a').first().getAttribute('href'); 106 | console.log(`Current free game: ${chalk.blue(title)} - ${url}`); 107 | db.data[user][title] ||= { title, time: datetime(), url }; 108 | if (cfg.dryrun) process.exit(1); 109 | // await page.locator('#giveaway:not(.is-loading)').waitFor(); // otherwise screenshot is sometimes with loading indicator instead of game title; #TODO fix, skipped due to timeout, see #240 110 | await banner.screenshot({ path: screenshot(`${filenamify(title)}.png`) }); // overwrites every time - only keep first? 111 | 112 | // await banner.getByRole('button', { name: 'Add to library' }).click(); 113 | // instead of clicking the button, we visit the auto-claim URL which gives as a JSON response which is easier than checking the state of a button 114 | await page.goto('https://www.gog.com/giveaway/claim'); 115 | const response = await page.innerText('body'); 116 | // console.log(response); 117 | // {} // when successfully claimed 118 | // {"message":"Already claimed"} 119 | // {"message":"Unauthorized"} 120 | // {"message":"Giveaway has ended"} 121 | let status; 122 | if (response == '{}') { 123 | status = 'claimed'; 124 | console.log(' Claimed successfully!'); 125 | } else { 126 | const message = JSON.parse(response).message; 127 | if (message == 'Already claimed') { 128 | status = 'existed'; // same status text as for epic-games 129 | console.log(' Already in library! Nothing to claim.'); 130 | } else { 131 | console.log(response); 132 | status = message; 133 | } 134 | } 135 | db.data[user][title].status ||= status; 136 | notify_games.push({ title, url, status }); 137 | 138 | if (status == 'claimed' && !cfg.gog_newsletter) { 139 | console.log('Unsubscribe from \'Promotions and hot deals\' newsletter'); 140 | await page.goto('https://www.gog.com/en/account/settings/subscriptions'); 141 | await page.locator('li:has-text("Marketing communications through Trusted Partners") label').uncheck(); 142 | await page.locator('li:has-text("Promotions and hot deals") label').uncheck(); 143 | } 144 | } 145 | } catch (error) { 146 | process.exitCode ||= 1; 147 | console.error('--- Exception:'); 148 | console.error(error); // .toString()? 149 | if (error.message && process.exitCode != 130) notify(`gog failed: ${error.message.split('\n')[0]}`); 150 | } finally { 151 | await db.write(); // write out json db 152 | if (notify_games.filter(g => g.status != 'existed').length) { // don't notify if all were already claimed 153 | notify(`gog (${user}):
${html_game_list(notify_games)}`); 154 | } 155 | } 156 | if (page.video()) console.log('Recorded video:', await page.video().path()); 157 | await context.close(); 158 | -------------------------------------------------------------------------------- /unrealengine.js: -------------------------------------------------------------------------------- 1 | // TODO This is mostly a copy of epic-games.js 2 | // New assets to claim every first Tuesday of a month. 3 | 4 | import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra 5 | import { authenticator } from 'otplib'; 6 | import path from 'path'; 7 | import { writeFileSync } from 'fs'; 8 | import { resolve, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js'; 9 | import { cfg } from './src/config.js'; 10 | 11 | const screenshot = (...a) => resolve(cfg.dir.screenshots, 'unrealengine', ...a); 12 | 13 | const URL_CLAIM = 'https://www.unrealengine.com/marketplace/en-US/assets?count=20&sortBy=effectiveDate&sortDir=DESC&start=0&tag=4910'; 14 | const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM; 15 | 16 | console.log(datetime(), 'started checking unrealengine'); 17 | 18 | const db = await jsonDb('unrealengine.json', {}); 19 | 20 | // https://playwright.dev/docs/auth#multi-factor-authentication 21 | const context = await firefox.launchPersistentContext(cfg.dir.browser, { 22 | headless: cfg.headless, 23 | viewport: { width: cfg.width, height: cfg.height }, 24 | userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36', // see replace of Headless in util.newStealthContext. TODO Windows UA enough to avoid 'device not supported'? update if browser is updated? 25 | // userAgent for firefox: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:106.0) Gecko/20100101 Firefox/106.0 26 | locale: 'en-US', // ignore OS locale to be sure to have english text for locators 27 | 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 28 | 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 29 | handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved 30 | }); 31 | 32 | handleSIGINT(context); 33 | 34 | await stealth(context); 35 | 36 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 37 | 38 | const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist 39 | await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it 40 | // console.debug('userAgent:', await page.evaluate(() => navigator.userAgent)); 41 | 42 | const notify_games = []; 43 | let user; 44 | 45 | try { 46 | 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. 47 | 48 | await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // 'domcontentloaded' faster than default 'load' https://playwright.dev/docs/api/class-page#page-goto 49 | 50 | await page.waitForResponse(r => r.request().method() == 'POST' && r.url().startsWith('https://graphql.unrealengine.com/ue/graphql')); 51 | 52 | while (await page.locator('unrealengine-navigation').getAttribute('isloggedin') != 'true') { 53 | console.error('Not signed in anymore. Please login in the browser or here in the terminal.'); 54 | if (cfg.novnc_port) console.info(`Open http://localhost:${cfg.novnc_port} to login inside the docker container.`); 55 | if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in 56 | console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`); 57 | await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' }); 58 | if (cfg.eg_email && cfg.eg_password) console.info('Using email and password from environment.'); 59 | else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).'); 60 | const email = cfg.eg_email || await prompt({ message: 'Enter email' }); 61 | const password = email && (cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' })); 62 | if (email && password) { 63 | // await page.click('text=Sign in with Epic Games'); 64 | await page.fill('#email', email); 65 | await page.click('button[type="submit"]'); 66 | await page.fill('#password', password); 67 | await page.click('button[type="submit"]'); 68 | page.waitForSelector('#h_captcha_challenge_login_prod iframe').then(() => { 69 | 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.'); 70 | notify('unrealengine: got captcha during login. Please check.'); 71 | }).catch(_ => { }); 72 | // handle MFA, but don't await it 73 | page.waitForURL('**/id/login/mfa**').then(async () => { 74 | 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 ...'); 75 | // TODO locator for text (email or app?) 76 | 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 77 | await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString()); 78 | await page.click('button[type="submit"]'); 79 | }).catch(_ => { }); 80 | } else { 81 | console.log('Waiting for you to login in the browser.'); 82 | await notify('unrealengine: no longer signed in and not enough options set for automatic login.'); 83 | if (cfg.headless) { 84 | console.log('Run `SHOW=1 node unrealengine` to login in the opened browser.'); 85 | await context.close(); // finishes potential recording 86 | process.exit(1); 87 | } 88 | } 89 | await page.waitForURL('**unrealengine.com/marketplace/**'); 90 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 91 | } 92 | await page.waitForTimeout(1000); 93 | user = await page.locator('unrealengine-navigation').getAttribute('displayname'); // 'null' if !isloggedin 94 | console.log(`Signed in as ${user}`); 95 | db.data[user] ||= {}; 96 | 97 | page.locator('button:has-text("Accept All Cookies")').click().catch(_ => { }); 98 | 99 | const ids = []; 100 | for (const p of await page.locator('article.asset').all()) { 101 | const link = p.locator('h3 a'); 102 | const title = await link.innerText(); 103 | const url = 'https://www.unrealengine.com' + await link.getAttribute('href'); 104 | console.log([title, url]); 105 | const id = url.split('/').pop(); 106 | db.data[user][id] ||= { title, time: datetime(), url, status: 'failed' }; // this will be set on the initial run only! 107 | const notify_game = { title, url, status: 'failed' }; 108 | notify_games.push(notify_game); // status is updated below 109 | // if (await p.locator('.btn .add-review-btn').count()) { // did not work 110 | if ((await p.getAttribute('class')).includes('asset--owned')) { 111 | console.log(' ↳ Already claimed'); 112 | if (db.data[user][id].status != 'claimed') { 113 | db.data[user][id].status = 'existed'; 114 | notify_game.status = 'existed'; 115 | } 116 | continue; 117 | } 118 | if (await p.locator('.btn .in-cart').count()) { 119 | console.log(' ↳ Already in cart'); 120 | } else { 121 | await p.locator('.btn .add').click(); 122 | console.log(' ↳ Added to cart'); 123 | } 124 | ids.push(id); 125 | } 126 | if (!ids.length) { 127 | console.log('Nothing to claim'); 128 | } else { 129 | await page.waitForTimeout(2000); 130 | const price = (await page.locator('.shopping-cart .total .price').innerText()).split(' '); 131 | console.log('Price: ', price[1], 'instead of', price[0]); 132 | if (price[1] != '0') { 133 | const err = 'Price is not 0! Exit! Please report.'; 134 | console.error(err); 135 | notify('unrealengine: ' + err); 136 | process.exit(1); 137 | } 138 | // await page.pause(); 139 | console.log('Click shopping cart'); 140 | await page.locator('.shopping-cart').click(); 141 | // await page.waitForTimeout(2000); 142 | await page.locator('button.checkout').click(); 143 | console.log('Click checkout'); 144 | // maybe: Accept End User License Agreement 145 | page.locator('[name=accept-label]').check().then(() => { 146 | console.log('Accept End User License Agreement'); 147 | page.locator('span:text-is("Accept")').click(); // otherwise matches 'Accept All Cookies' 148 | }).catch(_ => { }); 149 | await page.waitForSelector('#webPurchaseContainer iframe'); // TODO needed? 150 | const iframe = page.frameLocator('#webPurchaseContainer iframe'); 151 | 152 | if (cfg.debug) await page.pause(); 153 | if (cfg.dryrun) { 154 | console.log('DRYRUN=1 -> Skip order!'); 155 | throw new Error('DRYRUN=1'); 156 | } 157 | 158 | console.log('Click Place Order'); 159 | // Playwright clicked before button was ready to handle event, https://github.com/vogler/free-games-claimer/issues/84#issuecomment-1474346591 160 | await iframe.locator('button:has-text("Place Order"):not(:has(.payment-loading--loading))').click({ delay: 11 }); 161 | 162 | // I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872 163 | const btnAgree = iframe.locator('button:has-text("I Agree")'); 164 | btnAgree.waitFor().then(() => btnAgree.click()).catch(_ => { }); // EU: wait for and click 'I Agree' 165 | try { 166 | // context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s? 167 | const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe'); 168 | captcha.waitFor().then(async () => { // don't await, since element may not be shown 169 | // console.info(' Got hcaptcha challenge! NopeCHA extension will likely solve it.') 170 | 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.'); 171 | }).catch(_ => { }); // may time out if not shown 172 | await page.waitForSelector('text=Thank you'); 173 | for (const id of ids) { 174 | db.data[user][id].status = 'claimed'; 175 | db.data[user][id].time = datetime(); // claimed time overwrites failed/dryrun time 176 | } 177 | notify_games.forEach(g => g.status == 'failed' && (g.status = 'claimed')); 178 | console.log('Claimed successfully!'); 179 | // context.setDefaultTimeout(cfg.timeout); 180 | } catch (e) { 181 | console.log(e); 182 | // console.error(' Failed to claim! Try again if NopeCHA timed out. Click the extension to see if you ran out of credits (refill after 24h). To avoid captchas try to get a new IP or set a cookie from https://www.hcaptcha.com/accessibility'); 183 | console.error(' Failed to claim! To avoid captchas try to get a new IP address.'); 184 | await page.screenshot({ path: screenshot('failed', `${filenamify(datetime())}.png`), fullPage: true }); 185 | // db.data[user][id].status = 'failed'; 186 | notify_games.forEach(g => g.status = 'failed'); 187 | } 188 | // notify_game.status = db.data[user][game_id].status; // claimed or failed 189 | 190 | if (notify_games.length) await page.screenshot({ path: screenshot(`${filenamify(datetime())}.png`), fullPage: false }); // fullPage is quite long... 191 | console.log('Done'); 192 | } 193 | } catch (error) { 194 | process.exitCode ||= 1; 195 | console.error('--- Exception:'); 196 | console.error(error); // .toString()? 197 | if (error.message && process.exitCode != 130) notify(`unrealengine failed: ${error.message.split('\n')[0]}`); 198 | } finally { 199 | await db.write(); // write out json db 200 | if (notify_games.filter(g => g.status != 'existed').length) { // don't notify if all were already claimed 201 | notify(`unrealengine (${user}):
${html_game_list(notify_games)}`); 202 | } 203 | } 204 | if (cfg.debug) writeFileSync(path.resolve(cfg.dir.browser, 'cookies.json'), JSON.stringify(await context.cookies())); 205 | if (page.video()) console.log('Recorded video:', await page.video().path()); 206 | await context.close(); 207 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | logo-free-games-claimer 3 |

4 | 5 | [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=vogler_free-games-claimer&metric=code_smells)](https://sonarcloud.io/project/overview?id=vogler_free-games-claimer) 6 | # free-games-claimer 7 | 8 | Claims free games periodically on 9 | - [Epic Games Store](https://www.epicgames.com/store/free-games) 10 | - [Amazon Prime Gaming](https://gaming.amazon.com) 11 | - [GOG](https://www.gog.com) 12 | - [Unreal Engine (Assets)](https://www.unrealengine.com/marketplace/en-US/assets?count=20&sortBy=effectiveDate&sortDir=DESC&start=0&tag=4910) ([experimental](https://github.com/vogler/free-games-claimer/issues/44), same login as Epic Games) 13 | 14 | 15 | Pull requests welcome :) 16 | 17 | ![Telegram Screenshot](https://user-images.githubusercontent.com/493741/214667078-eb5c1877-2bdd-40c1-b94e-4a50d6852c06.png) 18 | 19 | _Works on Windows/macOS/Linux._ 20 | 21 | Raspberry Pi (3, 4, Zero 2): [requires 64-bit OS](https://github.com/vogler/free-games-claimer/issues/3) like Raspberry Pi OS or Ubuntu (Raspbian won't work since it's 32-bit). 22 | 23 | ## How to run 24 | Easy option: [install Docker](https://docs.docker.com/get-docker/) (or [podman](https://podman-desktop.io/)) and run this command in a terminal: 25 | ``` 26 | docker run --rm -it -p 6080:6080 -v fgc:/fgc/data --pull=always ghcr.io/vogler/free-games-claimer 27 | ``` 28 | 29 | _This currently gives you a captcha challenge for epic-games. Until [issue #183](https://github.com/vogler/free-games-claimer/issues/183) is fixed, it is recommended to just run `node epic-games` without docker (see below)._ 30 | 31 | This will run `node epic-games; node prime-gaming; node gog` - if you only want to claim games for one of the stores, you can override the default command by appending e.g. `node epic-games` at the end of the `docker run` command, or if you want several `bash -c "node epic-games.js; node gog.js"`. 32 | Data (including json files with claimed games, codes to redeem, screenshots) is stored in the Docker volume `fgc`. 33 | 34 |
35 | I want to run without Docker or develop locally. 36 | 37 | 1. [Install Node.js](https://nodejs.org/en/download) 38 | 2. Clone/download this repository and `cd` into it in a terminal 39 | 3. Run `npm install` 40 | 4. Run `pip install apprise` (or use [pipx](https://github.com/pypa/pipx) if you have [problems](https://stackoverflow.com/questions/75608323/how-do-i-solve-error-externally-managed-environment-every-time-i-use-pip-3)) to install [apprise](https://github.com/caronc/apprise) if you want notifications 41 | 5. To get updates: `git pull; npm install` 42 | 6. Run `node epic-games`, `node prime-gaming`, `node gog`... 43 | 44 | During `npm install` Playwright will download its Firefox to a cache in home ([doc](https://playwright.dev/docs/browsers#managing-browser-binaries)). 45 | If you are missing some dependencies for the browser on your system, you can use `sudo npx playwright install firefox --with-deps`. 46 | 47 | If you don't want to use Docker for quasi-headless mode, you could run inside a virtual machine, on a server, or you wake your PC at night to avoid being interrupted. 48 |
49 | 50 | ## Usage 51 | All scripts start an automated Firefox instance, either with the browser GUI shown or hidden (*headless mode*). By default, you won't see any browser open on your host system. 52 | 53 | - When running inside Docker, the browser will be shown only inside the container. You can open http://localhost:6080 to interact with the browser running inside the container via noVNC (or use other VNC clients on port 5900). 54 | - When running the scripts outside of Docker, the browser will be hidden by default; you can use `SHOW=1 ...` to show the UI (see options below). 55 | 56 | When running the first time, you have to login for each store you want to claim games on. 57 | You can login indirectly via the terminal or directly in the browser. The scripts will wait until you are successfully logged in. 58 | 59 | There will be prompts in the terminal asking you to enter email, password, and afterwards some OTP (one time password / security code) if you have 2FA/MFA (two-/multi-factor authentication) enabled. If you want to login yourself via the browser, you can press escape in the terminal to skip the prompts. 60 | 61 | After login, the script will continue claiming the current games. If it still waits after you are already logged in, you can restart it (and open an issue). If you run the scripts regularly, you should not have to login again. 62 | 63 | ### Configuration / Options 64 | Options are set via [environment variables](https://kinsta.com/knowledgebase/what-is-an-environment-variable/) which allow for flexible configuration. 65 | 66 | TODO: ~~On the first run, the script will guide you through configuration and save all settings to `data/config.env`. You can edit this file directly or run `node fgc config` to run the configuration assistant again.~~ 67 | 68 | Available options/variables and their default values: 69 | 70 | | Option | Default | Description | 71 | |--------------- |--------- |------------------------------------------------------------------------ | 72 | | SHOW | 1 | Show browser if 1. Default for Docker, not shown when running outside. | 73 | | WIDTH | 1280 | Width of the opened browser (and of screen for VNC in Docker). | 74 | | HEIGHT | 1280 | Height of the opened browser (and of screen for VNC in Docker). | 75 | | VNC_PASSWORD | | VNC password for Docker. No password used by default! | 76 | | NOTIFY | | Notification services to use (Pushover, Slack, Telegram...), see below. [Apprise](https://github.com/caronc/apprise) | 77 | | NOTIFY_TITLE | | Optional title for notifications, e.g. for Pushover. | 78 | | BROWSER_DIR | data/browser | Directory for browser profile, e.g. for multiple accounts. | 79 | | TIMEOUT | 60 | Timeout for any page action. Should be fine even on slow machines. | 80 | | LOGIN_TIMEOUT | 180 | Timeout for login in seconds. Will wait twice (prompt + manual login). | 81 | | EMAIL | | Default email for any login. | 82 | | PASSWORD | | Default password for any login. | 83 | | EG_EMAIL | | Epic Games email for login. Overrides EMAIL. | 84 | | EG_PASSWORD | | Epic Games password for login. Overrides PASSWORD. | 85 | | EG_OTPKEY | | Epic Games MFA OTP key. | 86 | | EG_PARENTALPIN | | Epic Games Parental Controls PIN. | 87 | | PG_EMAIL | | Prime Gaming email for login. Overrides EMAIL. | 88 | | PG_PASSWORD | | Prime Gaming password for login. Overrides PASSWORD. | 89 | | PG_OTPKEY | | Prime Gaming MFA OTP key. | 90 | | PG_REDEEM | 0 | Prime Gaming: try to redeem keys on external stores ([experimental](https://github.com/vogler/free-games-claimer/issues/5)). | 91 | | PG_CLAIMDLC | 0 | Prime Gaming: try to claim DLCs ([experimental](https://github.com/vogler/free-games-claimer/issues/55)). | 92 | | GOG_EMAIL | | GOG email for login. Overrides EMAIL. | 93 | | GOG_PASSWORD | | GOG password for login. Overrides PASSWORD. | 94 | | GOG_NEWSLETTER | 0 | Do not unsubscribe from newsletter after claiming a game if 1. | 95 | | LG_EMAIL | | Legacy Games: email to use for redeeming (if not set, defaults to PG_EMAIL) | 96 | 97 | See `src/config.js` for all options. 98 | 99 | #### How to set options 100 | You can add options directly in the command or put them in a file to load. 101 | 102 | ##### Docker 103 | You can pass variables using `-e VAR=VAL`, for example `docker run -e EMAIL=foo@bar.baz -e NOTIFY='tgram://bottoken/ChatID' ...` or using `--env-file fgc.env` where `fgc.env` is a file on your host system (see [docs](https://docs.docker.com/engine/reference/commandline/run/#env)). You can also `docker cp` your configuration file to `/fgc/data/config.env` in the `fgc` volume to store it with the rest of the data instead of on the host ([example](https://github.com/moby/moby/issues/25245#issuecomment-365980572)). 104 | If you are using [docker compose](https://docs.docker.com/compose/environment-variables/) (or Portainer etc.), you can put options in the `environment:` section. 105 | 106 | ##### Without Docker 107 | On Linux/macOS you can prefix the variables you want to set, for example `EMAIL=foo@bar.baz SHOW=1 node epic-games` will show the browser and skip asking you for your login email. On Windows you have to use `set`, [example](https://github.com/vogler/free-games-claimer/issues/314). 108 | You can also put options in `data/config.env` which will be loaded by [dotenv](https://github.com/motdotla/dotenv). 109 | 110 | ### Notifications 111 | The scripts will try to send notifications for successfully claimed games and any errors like needing to log in or encountered captchas (should not happen). 112 | 113 | [apprise](https://github.com/caronc/apprise) is used for notifications and offers many services including Pushover, Slack, Telegram, SMS, Email, desktop and custom notifications. 114 | You just need to set `NOTIFY` to the notification services you want to use, e.g. `NOTIFY='mailto://myemail:mypass@gmail.com' 'pbul://o.gn5kj6nfhv736I7jC3cj3QLRiyhgl98b'` - refer to their list of services and [examples](https://github.com/caronc/apprise#command-line-usage). 115 | 116 | ### Automatic login, two-factor authentication 117 | If you set the options for email, password and OTP key, there will be no prompts and logins should happen automatically. This is optional since all stores should stay logged in since cookies are refreshed. 118 | To get the OTP key, it is easiest to follow the store's guide for adding an authenticator app. You should also scan the shown QR code with your favorite app to have an alternative method for 2FA. 119 | 120 | - **Epic Games**: visit [password & security](https://www.epicgames.com/account/password), enable 'third-party authenticator app', copy the 'Manual Entry Key' and use it to set `EG_OTPKEY`. 121 | - **Prime Gaming**: visit Amazon 'Your Account › Login & security', 2-step verification › Manage › Add new app › Can't scan the barcode, copy the bold key and use it to set `PG_OTPKEY` 122 | - **GOG**: only offers OTP via email 123 | 124 | 125 | Beware that storing passwords and OTP keys as clear text may be a security risk. Use a unique/generated password! TODO: maybe at least offer to base64 encode for storage. 126 | 127 | ### Epic Games Store 128 | Run `node epic-games` (locally or in Docker). 129 | 130 | ### Amazon Prime Gaming 131 | Run `node prime-gaming` (locally or in Docker). 132 | 133 | Claiming the Amazon Games works out-of-the-box, however, for games on external stores you need to either link your account or redeem a key. 134 | 135 | - Stores that require account linking: Epic Games, Battle.net, Origin. 136 | - Stores that require redeeming a key: GOG.com, Microsoft Games, Legacy Games. 137 | 138 | Keys and URLs are printed to the console, included in notifications and saved in `data/prime-gaming.json`. A screenshot of the page with the key is also saved to `data/screenshots`. 139 | [TODO](https://github.com/vogler/free-games-claimer/issues/5): ~~redeem keys on external stores.~~ 140 | 141 | 142 | 143 | 144 | ### Run periodically 145 | #### How often? 146 | Epic Games usually has two free games *every week*, before Christmas every day. 147 | Prime Gaming has new games *every month* or more often during Prime days. 148 | GOG usually has one new game every couples of weeks. 149 | Unreal Engine has new assets to claim *every first Tuesday of a month*. 150 | 151 | 152 | It is safe to run the scripts every day. 153 | 154 | #### How to schedule? 155 | The container/scripts will claim currently available games and then exit. 156 | If you want it to run regularly, you have to schedule the runs yourself: 157 | 158 | - Linux/macOS: `crontab -e` ([example](https://github.com/vogler/free-games-claimer/discussions/56)) 159 | - macOS: [launchd](https://stackoverflow.com/questions/132955/how-do-i-set-a-task-to-run-every-so-often) 160 | - Windows: [task scheduler](https://active-directory-wp.com/docs/Usage/How_to_add_a_cron_job_on_Windows/Scheduled_tasks_and_cron_jobs_on_Windows/index.html) ([example](https://github.com/vogler/free-games-claimer/wiki/%5BHowTo%5D-Schedule-runs-on-Windows)), [other options](https://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron), or just put the command in a `.bat` file in Autostart if you restart often... 161 | - any OS: use a process manager like [pm2](https://pm2.keymetrics.io/docs/usage/restart-strategies/) 162 | - Docker Compose `command: bash -c "node epic-games; node prime-gaming; node gog; echo sleeping; sleep 1d"` additionally add `restart: unless-stopped` to it. 163 | 164 | TODO: ~~add some server-mode where the script just keeps running and claims games e.g. every day.~~ 165 | 166 | ### Problems? 167 | 168 | Check the open [issues](https://github.com/vogler/free-games-claimer/issues) and comment there or open a new issue. 169 | 170 | If you're a developer, you can use `PWDEBUG=1 ...` to [inspect](https://playwright.dev/docs/inspector) which opens a debugger where you can step through the script. 171 | 172 | 173 | ## History/DevLog 174 |
175 | Click to expand 176 | 177 | Tried [epicgames-freebies-claimer](https://github.com/Revadike/epicgames-freebies-claimer), but had problems since epicgames introduced hcaptcha (see [issue](https://github.com/Revadike/epicgames-freebies-claimer/issues/172)). 178 | 179 | Played around with puppeteer before, now trying newer https://playwright.dev which is pretty similar. 180 | Playwright Inspector and `codegen` to generate scripts are nice, but failed to generate the right code for clicking a button in an iframe. 181 | 182 | Added [main.spec.ts](https://github.com/vogler/epicgames-claimer/commit/e5ce7916ab6329cfc7134677c4d89c2b3fa3ba97#diff-d18d03e9c407a20e05fbf03cbd6f9299857740544fb6b50d6a70b9c6fbc35831) which was the test script generated by `npx playwright codegen` with manual fix for clicking buttons in the created iframe. Can be executed by `npx playwright test`. The test runner has options `--debug` and `--timeout` and can execute typescript which is nice. However, this only worked up to the button 'I Agree', and then showed an hcaptcha. 183 | 184 | Added [main.captcha.js](https://github.com/vogler/epicgames-claimer/commit/e5ce7916ab6329cfc7134677c4d89c2b3fa3ba97#diff-d18d03e9c407a20e05fbf03cbd6f9299857740544fb6b50d6a70b9c6fbc35831) which uses beta of `playwright-extra@next` and `@extra/recaptcha@next` (from [comment on puppeteer-extra](https://github.com/berstend/puppeteer-extra/pull/303#issuecomment-775277480)). 185 | However, `playwright-extra` seems to be old and missing `:has-text` selector (fixed [here](https://github.com/vogler/epicgames-claimer/commit/ba97a0e840b65f4476cca18e28d8461b0c703420)) and `page.frameLocator`, so the script did not run without adjustments. 186 | Also, solving via [2captcha](https://2captcha.com?from=13225256) is a paid service which takes time and may be unreliable. 187 | 188 | 189 | Added [main.stealth.js](https://github.com/vogler/epicgames-claimer/commit/64d0ba8ce71baec3947d1b64acd567befcb39340#diff-f70d3bd29df4a343f11062a97063953173491ce30fe34f69a0fc52517adbf342) which uses the stealth plugin without `playwright-extra` wrapper but up-to-date `playwright` (from [comment](https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212)). 190 | The listed evasions are enough to not show an hcaptcha. Script claimed game successfully in non-headless mode. 191 | 192 | Removed `main.captcha.js`. 193 | Using Playwright Test (`main.spec.ts`) instead of Library (`main.stealth.js`) has the advantage of free CLI like `--debug` and `--timeout`. 194 | 195 | 196 | Button selectors should preferably use text in order to be more stable against changes in the DOM. 197 | 198 | Renamed repository from epicgames-claimer to free-games-claimer since a script for Amazon Prime Gaming was also added. Removed all old scripts in favor of just `epic-games.js` and `prime-gaming.js`. 199 | 200 | epic games: `headless` mode gets hcaptcha challenge. More details/references in [issue](https://github.com/vogler/free-games-claimer/issues/2). 201 | 202 | https://github.com/vogler/free-games-claimer/pull/11 introduced a Dockerfile for running non-headless inside the container via xvfb which makes it headless for the host running the container. 203 | 204 | v1.0 Standalone scripts node epic-games and node prime-gaming using Chromium. 205 | 206 | Changed to Firefox for all scripts since Chromium led to captchas. Claiming then also worked in headless mode without Docker. 207 | 208 | Added options via env vars, configurable in `data/config.env`. 209 | 210 | Added OTP generation via otplib for automatic login, even with 2FA. 211 | 212 | Added notifications via [apprise](https://github.com/caronc/apprise). 213 |
214 | 215 | [![Star History Chart](https://api.star-history.com/svg?repos=vogler/free-games-claimer&type=Date)](https://star-history.com/#vogler/free-games-claimer&Date) 216 | 217 | 218 | ![Alt](https://repobeats.axiom.co/api/embed/a1c5e6e420d90e0d6b34c1285e92a69a44138faa.svg "Repobeats analytics image") 219 | 220 | --- 221 | 222 | Logo with smaller aspect ratio (for Telegram bot etc.): 👾 - [emojipedia](https://emojipedia.org/alien-monster/) 223 | 224 | ![logo-fgc](https://user-images.githubusercontent.com/493741/214589922-093d6557-6393-421c-b577-da58ff3671bc.png) 225 | -------------------------------------------------------------------------------- /epic-games.js: -------------------------------------------------------------------------------- 1 | import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra 2 | import { authenticator } from 'otplib'; 3 | import chalk from 'chalk'; 4 | import path from 'path'; 5 | import { existsSync, writeFileSync, appendFileSync } from 'fs'; 6 | import { resolve, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js'; 7 | import { cfg } from './src/config.js'; 8 | 9 | const screenshot = (...a) => resolve(cfg.dir.screenshots, 'epic-games', ...a); 10 | 11 | const URL_CLAIM = 'https://store.epicgames.com/en-US/free-games'; 12 | const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM; 13 | 14 | console.log(datetime(), 'started checking epic-games'); 15 | 16 | const db = await jsonDb('epic-games.json', {}); 17 | 18 | if (cfg.time) console.time('startup'); 19 | 20 | const browserPrefs = path.join(cfg.dir.browser, 'prefs.js'); 21 | if (existsSync(browserPrefs)) { 22 | console.log('Adding webgl.disabled to', browserPrefs); 23 | appendFileSync(browserPrefs, 'user_pref("webgl.disabled", true);'); // apparently Firefox removes duplicates (and sorts), so no problem appending every time 24 | } else { 25 | console.log(browserPrefs, 'does not exist yet, will patch it on next run. Restart the script if you get a captcha.'); 26 | } 27 | 28 | // https://playwright.dev/docs/auth#multi-factor-authentication 29 | const context = await firefox.launchPersistentContext(cfg.dir.browser, { 30 | headless: cfg.headless, 31 | viewport: { width: cfg.width, height: cfg.height }, 32 | userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0', // see replace of Headless in util.newStealthContext. TODO Windows UA enough to avoid 'device not supported'? update if browser is updated? 33 | // userAgent firefox (macOS): Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:106.0) Gecko/20100101 Firefox/106.0 34 | // userAgent firefox (docker): Mozilla/5.0 (X11; Linux aarch64; rv:109.0) Gecko/20100101 Firefox/115.0 35 | locale: 'en-US', // ignore OS locale to be sure to have english text for locators 36 | 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 37 | recordHar: cfg.record ? { path: `data/record/eg-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools 38 | handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved 39 | // user settings for firefox have to be put in $BROWSER_DIR/user.js 40 | args: [ // https://wiki.mozilla.org/Firefox/CommandLineOptions 41 | // '-kiosk', 42 | ], 43 | }); 44 | 45 | handleSIGINT(context); 46 | 47 | // Without stealth plugin, the website shows an hcaptcha on login with username/password and in the last step of claiming a game. It may have other heuristics like unsuccessful logins as well. After <6h (TBD) it resets to no captcha again. Getting a new IP also resets. 48 | await stealth(context); 49 | 50 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 51 | 52 | const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist 53 | await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it 54 | 55 | // some debug info about the page (screen dimensions, user agent, platform) 56 | // eslint-disable-next-line no-undef 57 | if (cfg.debug) console.debug(await page.evaluate(() => [(({ width, height, availWidth, availHeight }) => ({ width, height, availWidth, availHeight }))(window.screen), navigator.userAgent, navigator.platform, navigator.vendor])); // deconstruct screen needed since `window.screen` prints {}, `window.screen.toString()` '[object Screen]', and can't use some pick function without defining it on `page` 58 | if (cfg.debug_network) { 59 | // const filter = _ => true; 60 | const filter = r => r.url().includes('store.epicgames.com'); 61 | page.on('request', request => filter(request) && console.log('>>', request.method(), request.url())); 62 | page.on('response', response => filter(response) && console.log('<<', response.status(), response.url())); 63 | } 64 | 65 | const notify_games = []; 66 | let user; 67 | 68 | try { 69 | await context.addCookies([ 70 | { 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. 71 | { name: 'HasAcceptedAgeGates', value: 'USK:9007199254740991,general:18,EPIC SUGGESTED RATING:18', domain: 'store.epicgames.com', path: '/' }, // gets rid of 'To continue, please provide your date of birth', https://github.com/vogler/free-games-claimer/issues/275, USK number doesn't seem to matter, cookie from 'Fallout 3: Game of the Year Edition' 72 | ]); 73 | 74 | await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // 'domcontentloaded' faster than default 'load' https://playwright.dev/docs/api/class-page#page-goto 75 | 76 | if (cfg.time) console.timeEnd('startup'); 77 | if (cfg.time) console.time('login'); 78 | 79 | // page.click('button:has-text("Accept All Cookies")').catch(_ => { }); // Not needed anymore since we set the cookie above. Clicking this did not always work since the message was animated in too slowly. 80 | 81 | while (await page.locator('egs-navigation').getAttribute('isloggedin') != 'true') { 82 | console.error('Not signed in anymore. Please login in the browser or here in the terminal.'); 83 | if (cfg.novnc_port) console.info(`Open http://localhost:${cfg.novnc_port} to login inside the docker container.`); 84 | if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in 85 | console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`); 86 | await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' }); 87 | if (cfg.eg_email && cfg.eg_password) console.info('Using email and password from environment.'); 88 | else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).'); 89 | const notifyBrowserLogin = async () => { 90 | console.log('Waiting for you to login in the browser.'); 91 | await notify('epic-games: no longer signed in and not enough options set for automatic login.'); 92 | if (cfg.headless) { 93 | console.log('Run `SHOW=1 node epic-games` to login in the opened browser.'); 94 | await context.close(); // finishes potential recording 95 | process.exit(1); 96 | } 97 | }; 98 | const email = cfg.eg_email || await prompt({ message: 'Enter email' }); 99 | if (!email) await notifyBrowserLogin(); 100 | else { 101 | // await page.click('text=Sign in with Epic Games'); 102 | page.waitForSelector('.h_captcha_challenge iframe').then(async () => { 103 | 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.'); 104 | await notify('epic-games: got captcha during login. Please check.'); 105 | }).catch(_ => { }); 106 | page.waitForSelector('p:has-text("Incorrect response.")').then(async () => { 107 | console.error('Incorrect response for captcha!'); 108 | }).catch(_ => { }); 109 | await page.fill('#email', email); 110 | // await page.click('button[type="submit"]'); login was split in two steps for some time, now email and password are on the same form again 111 | const password = email && (cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' })); 112 | if (!password) await notifyBrowserLogin(); 113 | else { 114 | await page.fill('#password', password); 115 | await page.click('button[type="submit"]'); 116 | } 117 | const error = page.locator('#form-error-message'); 118 | error.waitFor().then(async () => { 119 | console.error('Login error:', await error.innerText()); 120 | console.log('Please login in the browser!'); 121 | }).catch(_ => { }); 122 | // handle MFA, but don't await it 123 | page.waitForURL('**/id/login/mfa**').then(async () => { 124 | 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 ...'); 125 | // TODO locator for text (email or app?) 126 | 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 127 | await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString()); 128 | await page.click('button[type="submit"]'); 129 | }).catch(_ => { }); 130 | } 131 | await page.waitForURL(URL_CLAIM); 132 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 133 | } 134 | user = await page.locator('egs-navigation').getAttribute('displayname'); // 'null' if !isloggedin 135 | console.log(`Signed in as ${user}`); 136 | db.data[user] ||= {}; 137 | if (cfg.time) console.timeEnd('login'); 138 | if (cfg.time) console.time('claim all games'); 139 | 140 | // Detect free games 141 | const game_loc = page.locator('a:has(span:text-is("Free Now"))'); 142 | await game_loc.last().waitFor().catch(_ => { 143 | // rarely there are no free games available -> catch Timeout 144 | // TODO would be better to wait for alternative like 'coming soon' instead of waiting for timeout 145 | // see https://github.com/vogler/free-games-claimer/issues/210#issuecomment-1727420943 146 | console.error('Seems like currently there are no free games available in your region...'); 147 | // urls below should then be an empty list 148 | }); 149 | // clicking on `game_sel` sometimes led to a 404, see https://github.com/vogler/free-games-claimer/issues/25 150 | // debug showed that in those cases the href was still correct, so we `goto` the urls instead of clicking. 151 | // Alternative: parse the json loaded to build the page https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions 152 | // i.e. filter data.Catalog.searchStore.elements for .promotions.promotionalOffers being set and build URL with .catalogNs.mappings[0].pageSlug or .urlSlug if not set to some wrong id like it was the case for spirit-of-the-north-f58a66 - this is also what's done here: https://github.com/claabs/epicgames-freegames-node/blob/938a9653ffd08b8284ea32cf01ac8727d25c5d4c/src/puppet/free-games.ts#L138-L213 153 | const urlSlugs = await Promise.all((await game_loc.elementHandles()).map(a => a.getAttribute('href'))); 154 | const urls = urlSlugs.map(s => 'https://store.epicgames.com' + s); 155 | console.log('Free games:', urls); 156 | 157 | for (const url of urls) { 158 | if (cfg.time) console.time('claim game'); 159 | await page.goto(url); // , { waitUntil: 'domcontentloaded' }); 160 | const purchaseBtn = page.locator('button[data-testid="purchase-cta-button"] >> :has-text("e"), :has-text("i")').first(); // when loading, the button text is empty -> need to wait for some text {'get', 'in library', 'requires base game'} -> just wait for e or i to not be too specific; :text-matches("\w+") somehow didn't work - https://github.com/vogler/free-games-claimer/issues/375 161 | await purchaseBtn.waitFor(); 162 | const btnText = (await purchaseBtn.innerText()).toLowerCase(); // barrier to block until page is loaded 163 | 164 | // click Continue if 'This game contains mature content recommended only for ages 18+' 165 | if (await page.locator('button:has-text("Continue")').count() > 0) { 166 | console.log(' This game contains mature content recommended only for ages 18+'); 167 | if (await page.locator('[data-testid="AgeSelect"]').count()) { 168 | console.error(' Got "To continue, please provide your date of birth" - This shouldn\'t happen due to cookie set above. Please report to https://github.com/vogler/free-games-claimer/issues/275'); 169 | await page.locator('#month_toggle').click(); 170 | await page.locator('#month_menu li:has-text("01")').click(); 171 | await page.locator('#day_toggle').click(); 172 | await page.locator('#day_menu li:has-text("01")').click(); 173 | await page.locator('#year_toggle').click(); 174 | await page.locator('#year_menu li:has-text("1987")').click(); 175 | } 176 | await page.click('button:has-text("Continue")', { delay: 111 }); 177 | await page.waitForTimeout(2000); 178 | } 179 | 180 | let title; 181 | let bundle_includes; 182 | if (await page.locator('span:text-is("About Bundle")').count()) { 183 | title = (await page.locator('span:has-text("Buy"):left-of([data-testid="purchase-cta-button"])').first().innerText()).replace('Buy ', ''); 184 | // h1 first didn't exist for bundles but now it does... However h1 would e.g. be 'Fallout® Classic Collection' instead of 'Fallout Classic Collection' 185 | try { 186 | bundle_includes = await Promise.all((await page.locator('.product-card-top-row h5').all()).map(b => b.innerText())); 187 | } catch (e) { 188 | console.error('Failed to get "Bundle Includes":', e); 189 | } 190 | } else { 191 | title = await page.locator('h1').first().innerText(); 192 | } 193 | const game_id = page.url().split('/').pop(); 194 | const existedInDb = db.data[user][game_id]; 195 | db.data[user][game_id] ||= { title, time: datetime(), url: page.url() }; // this will be set on the initial run only! 196 | console.log('Current free game:', chalk.blue(title)); 197 | if (bundle_includes) console.log(' This bundle includes:', bundle_includes); 198 | const notify_game = { title, url, status: 'failed' }; 199 | notify_games.push(notify_game); // status is updated below 200 | 201 | if (btnText == 'in library') { 202 | console.log(' Already in library! Nothing to claim.'); 203 | if (!existedInDb) await notify(`Game already in library: ${url}`); 204 | notify_game.status = 'existed'; 205 | db.data[user][game_id].status ||= 'existed'; // does not overwrite claimed or failed 206 | if (db.data[user][game_id].status.startsWith('failed')) db.data[user][game_id].status = 'manual'; // was failed but now it's claimed 207 | } else if (btnText == 'requires base game') { 208 | console.log(' Requires base game! Nothing to claim.'); 209 | notify_game.status = 'requires base game'; 210 | db.data[user][game_id].status ||= 'failed:requires-base-game'; 211 | // TODO claim base game if it is free 212 | const baseUrl = 'https://store.epicgames.com' + await page.locator('a:has-text("Overview")').getAttribute('href'); 213 | console.log(' Base game:', baseUrl); 214 | // await page.click('a:has-text("Overview")'); 215 | // TODO handle this via function call for base game above since this will never terminate if DRYRUN=1 216 | urls.push(baseUrl); // add base game to the list of games to claim 217 | urls.push(url); // add add-on itself again 218 | } else { // GET 219 | console.log(' Not in library yet! Click', btnText); 220 | await purchaseBtn.click({ delay: 11 }); // got stuck here without delay (or mouse move), see #75, 1ms was also enough 221 | 222 | // click Continue if 'Device not supported. This product is not compatible with your current device.' - avoided by Windows userAgent? 223 | page.click('button:has-text("Continue")').catch(_ => { }); // needed since change from Chromium to Firefox? 224 | 225 | // click 'Yes, buy now' if 'This edition contains something you already have. Still interested?' 226 | page.click('button:has-text("Yes, buy now")').catch(_ => { }); 227 | 228 | // Accept End User License Agreement (only needed once) 229 | page.locator(':has-text("end user license agreement")').waitFor().then(async () => { 230 | console.log(' Accept End User License Agreement (only needed once)'); 231 | console.log(page.innerHTML); 232 | console.log('Please report the HTML above here: https://github.com/vogler/free-games-claimer/issues/371'); 233 | await page.locator('input#agree').check(); // TODO Bundle: got stuck here; likely unrelated to bundle and locator just changed: https://github.com/vogler/free-games-claimer/issues/371 234 | await page.locator('button:has-text("Accept")').click(); 235 | }).catch(_ => { }); 236 | 237 | // it then creates an iframe for the purchase 238 | await page.waitForSelector('#webPurchaseContainer iframe'); // TODO needed? 239 | const iframe = page.frameLocator('#webPurchaseContainer iframe'); 240 | // skip game if unavailable in region, https://github.com/vogler/free-games-claimer/issues/46 TODO check games for account's region 241 | if (await iframe.locator(':has-text("unavailable in your region")').count() > 0) { 242 | console.error(' This product is unavailable in your region!'); 243 | db.data[user][game_id].status = notify_game.status = 'unavailable-in-region'; 244 | if (cfg.time) console.timeEnd('claim game'); 245 | continue; 246 | } 247 | 248 | iframe.locator('.payment-pin-code').waitFor().then(async () => { 249 | if (!cfg.eg_parentalpin) { 250 | console.error(' EG_PARENTALPIN not set. Need to enter Parental Control PIN manually.'); 251 | notify('epic-games: EG_PARENTALPIN not set. Need to enter Parental Control PIN manually.'); 252 | } 253 | await iframe.locator('input.payment-pin-code__input').first().pressSequentially(cfg.eg_parentalpin); 254 | await iframe.locator('button:has-text("Continue")').click({ delay: 11 }); 255 | }).catch(_ => { }); 256 | 257 | if (cfg.debug) await page.pause(); 258 | if (cfg.dryrun) { 259 | console.log(' DRYRUN=1 -> Skip order!'); 260 | notify_game.status = 'skipped'; 261 | if (cfg.time) console.timeEnd('claim game'); 262 | continue; 263 | } 264 | 265 | // Playwright clicked before button was ready to handle event, https://github.com/vogler/free-games-claimer/issues/84#issuecomment-1474346591 266 | await iframe.locator('button:has-text("Place Order"):not(:has(.payment-loading--loading))').click({ delay: 11 }); 267 | 268 | // I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872 269 | const btnAgree = iframe.locator('button:has-text("I Accept")'); 270 | btnAgree.waitFor().then(() => btnAgree.click()).catch(_ => { }); // EU: wait for and click 'I Agree' 271 | try { 272 | // context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s? 273 | const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe'); 274 | captcha.waitFor().then(async () => { // don't await, since element may not be shown 275 | // console.info(' Got hcaptcha challenge! NopeCHA extension will likely solve it.') 276 | 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.'); 277 | // await notify(`epic-games: got captcha challenge right before claim of ${title}. Use VNC to solve it manually.`); // TODO not all apprise services understand HTML: https://github.com/vogler/free-games-claimer/pull/417 278 | await notify(`epic-games: got captcha challenge for.\nGame link: ${url}`); 279 | // TODO could even create purchase URL, see https://github.com/vogler/free-games-claimer/pull/130 280 | // await page.waitForTimeout(2000); 281 | // const p = path.resolve(cfg.dir.screenshots, 'epic-games', 'captcha', `${filenamify(datetime())}.png`); 282 | // await captcha.screenshot({ path: p }); 283 | // console.info(' Saved a screenshot of hcaptcha challenge to', p); 284 | // console.error(' Got hcaptcha challenge. To avoid it, get a link from https://www.hcaptcha.com/accessibility'); // TODO save this link in config and visit it daily to set accessibility cookie to avoid captcha challenge? 285 | }).catch(_ => { }); // may time out if not shown 286 | iframe.locator('.payment__errors:has-text("Failed to challenge captcha, please try again later.")').waitFor().then(async () => { 287 | console.error(' Failed to challenge captcha, please try again later.'); 288 | await notify('epic-games: failed to challenge captcha. Please check.'); 289 | }).catch(_ => { }); 290 | await page.locator('text=Thanks for your order!').waitFor({ state: 'attached' }); // TODO Bundle: got stuck here, but normal game now as well 291 | db.data[user][game_id].status = 'claimed'; 292 | db.data[user][game_id].time = datetime(); // claimed time overwrites failed/dryrun time 293 | console.log(' Claimed successfully!'); 294 | // context.setDefaultTimeout(cfg.timeout); 295 | } catch (e) { 296 | console.log(e); 297 | // console.error(' Failed to claim! Try again if NopeCHA timed out. Click the extension to see if you ran out of credits (refill after 24h). To avoid captchas try to get a new IP or set a cookie from https://www.hcaptcha.com/accessibility'); 298 | console.error(' Failed to claim! To avoid captchas try to get a new IP address.'); 299 | const p = screenshot('failed', `${game_id}_${filenamify(datetime())}.png`); 300 | await page.screenshot({ path: p, fullPage: true }); 301 | db.data[user][game_id].status = 'failed'; 302 | } 303 | notify_game.status = db.data[user][game_id].status; // claimed or failed 304 | 305 | const p = screenshot(`${game_id}.png`); 306 | if (!existsSync(p)) await page.screenshot({ path: p, fullPage: false }); // fullPage is quite long... 307 | } 308 | if (cfg.time) console.timeEnd('claim game'); 309 | } 310 | if (cfg.time) console.timeEnd('claim all games'); 311 | } catch (error) { 312 | process.exitCode ||= 1; 313 | console.error('--- Exception:'); 314 | console.error(error); // .toString()? 315 | if (error.message && process.exitCode != 130) notify(`epic-games failed: ${error.message.split('\n')[0]}`); 316 | } finally { 317 | await db.write(); // write out json db 318 | if (notify_games.filter(g => g.status == 'claimed' || g.status == 'failed').length) { // don't notify if all have status 'existed', 'manual', 'requires base game', 'unavailable-in-region', 'skipped' 319 | notify(`epic-games (${user}):
${html_game_list(notify_games)}`); 320 | } 321 | } 322 | if (cfg.debug) writeFileSync(path.resolve(cfg.dir.browser, 'cookies.json'), JSON.stringify(await context.cookies())); 323 | if (page.video()) console.log('Recorded video:', await page.video().path()); 324 | await context.close(); 325 | -------------------------------------------------------------------------------- /prime-gaming.js: -------------------------------------------------------------------------------- 1 | import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra 2 | import { authenticator } from 'otplib'; 3 | import chalk from 'chalk'; 4 | import { resolve, jsonDb, datetime, stealth, filenamify, prompt, confirm, notify, html_game_list, handleSIGINT } from './src/util.js'; 5 | import { cfg } from './src/config.js'; 6 | 7 | const screenshot = (...a) => resolve(cfg.dir.screenshots, 'prime-gaming', ...a); 8 | 9 | // const URL_LOGIN = 'https://www.amazon.de/ap/signin'; // wrong. needs some session args to be valid? 10 | const URL_CLAIM = 'https://gaming.amazon.com/home'; 11 | 12 | console.log(datetime(), 'started checking prime-gaming'); 13 | 14 | const db = await jsonDb('prime-gaming.json', {}); 15 | 16 | // https://playwright.dev/docs/auth#multi-factor-authentication 17 | const context = await firefox.launchPersistentContext(cfg.dir.browser, { 18 | headless: cfg.headless, 19 | viewport: { width: cfg.width, height: cfg.height }, 20 | locale: 'en-US', // ignore OS locale to be sure to have english text for locators 21 | 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 22 | recordHar: cfg.record ? { path: `data/record/pg-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools 23 | handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved 24 | }); 25 | 26 | handleSIGINT(context); 27 | 28 | // TODO test if needed 29 | await stealth(context); 30 | 31 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 32 | 33 | const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist 34 | await page.setViewportSize({ width: cfg.width, height: cfg.height }); // TODO workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it 35 | // console.debug('userAgent:', await page.evaluate(() => navigator.userAgent)); 36 | 37 | const notify_games = []; 38 | let user; 39 | 40 | try { 41 | await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever 42 | // need to wait for some elements to exist before checking if signed in or accepting cookies: 43 | await Promise.any(['button:has-text("Sign in")', '[data-a-target="user-dropdown-first-name-text"]'].map(s => page.waitForSelector(s))); 44 | 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? 45 | while (await page.locator('button:has-text("Sign in")').count() > 0) { 46 | console.error('Not signed in anymore.'); 47 | await page.click('button:has-text("Sign in")'); 48 | if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in 49 | console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`); 50 | if (cfg.pg_email && cfg.pg_password) console.info('Using email and password from environment.'); 51 | else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).'); 52 | const email = cfg.pg_email || await prompt({ message: 'Enter email' }); 53 | const password = email && (cfg.pg_password || await prompt({ type: 'password', message: 'Enter password' })); 54 | if (email && password) { 55 | await page.fill('[name=email]', email); 56 | await page.click('input[type="submit"]'); 57 | await page.fill('[name=password]', password); 58 | // await page.check('[name=rememberMe]'); // no longer exists 59 | await page.click('input[type="submit"]'); 60 | page.waitForURL('**/ap/signin**').then(async () => { // check for wrong credentials 61 | const error = await page.locator('.a-alert-content').first().innerText(); 62 | if (!error.trim.length) return; 63 | console.error('Login error:', error); 64 | await notify(`prime-gaming: login: ${error}`); 65 | await context.close(); // finishes potential recording 66 | process.exit(1); 67 | }); 68 | // handle MFA, but don't await it 69 | page.waitForURL('**/ap/mfa**').then(async () => { 70 | console.log('Two-Step Verification - enter the One Time Password (OTP), e.g. generated by your Authenticator App'); 71 | await page.check('[name=rememberDevice]'); 72 | const otp = cfg.pg_otpkey && authenticator.generate(cfg.pg_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 73 | await page.locator('input[name=otpCode]').pressSequentially(otp.toString()); 74 | await page.click('input[type="submit"]'); 75 | }).catch(_ => { }); 76 | } else { 77 | console.log('Waiting for you to login in the browser.'); 78 | await notify('prime-gaming: no longer signed in and not enough options set for automatic login.'); 79 | if (cfg.headless) { 80 | console.log('Run `SHOW=1 node prime-gaming` to login in the opened browser.'); 81 | await context.close(); // finishes potential recording 82 | process.exit(1); 83 | } 84 | } 85 | await page.waitForURL('https://gaming.amazon.com/home?signedIn=true'); 86 | if (!cfg.debug) context.setDefaultTimeout(cfg.timeout); 87 | } 88 | user = await page.locator('[data-a-target="user-dropdown-first-name-text"]').first().innerText(); 89 | console.log(`Signed in as ${user}`); 90 | // await page.click('button[aria-label="User dropdown and more options"]'); 91 | // const twitch = await page.locator('[data-a-target="TwitchDisplayName"]').first().innerText(); 92 | // console.log(`Twitch user name is ${twitch}`); 93 | db.data[user] ||= {}; 94 | 95 | if (await page.getByRole('button', { name: 'Try Prime' }).count()) { 96 | console.error('User is currently not an Amazon Prime member, so no games to claim. Exit!'); 97 | await context.close(); 98 | process.exit(1); 99 | } 100 | 101 | const waitUntilStable = async (f, act) => { 102 | let v; 103 | while (true) { 104 | const v2 = await f(); 105 | console.log('waitUntilStable', v2); 106 | if (v == v2) break; 107 | v = v2; 108 | await act(); 109 | } 110 | }; 111 | const scrollUntilStable = async f => await waitUntilStable(f, async () => { 112 | // await page.keyboard.press('End'); // scroll to bottom to show all games 113 | // loading all games became flaky; see https://github.com/vogler/free-games-claimer/issues/357 114 | await page.keyboard.press('PageDown'); // scrolling to straight to the bottom started to skip loading some games 115 | await page.waitForLoadState('networkidle'); // wait for all games to be loaded 116 | await page.waitForTimeout(3000); // TODO networkidle wasn't enough to load all already collected games 117 | // do it again since once wasn't enough... 118 | await page.keyboard.press('PageDown'); 119 | await page.waitForTimeout(3000); 120 | }); 121 | 122 | await page.click('button[data-type="Game"]'); 123 | const games = page.locator('div[data-a-target="offer-list-FGWP_FULL"]'); 124 | await games.waitFor(); 125 | // await scrollUntilStable(() => games.locator('.item-card__action').count()); // number of games 126 | await scrollUntilStable(() => page.evaluate(() => document.querySelector('.tw-full-width').scrollHeight)); // height may change during loading while number of games is still the same? 127 | console.log('Number of already claimed games (total):', await games.locator('p:has-text("Collected")').count()); 128 | // can't use .all() since the list of elements via locator will change after click while we iterate over it 129 | const internal = await games.locator('.item-card__action:has(button[data-a-target="FGWPOffer"])').elementHandles(); 130 | const external = await games.locator('.item-card__action:has(a[data-a-target="FGWPOffer"])').all(); 131 | // bottom to top: oldest to newest games 132 | internal.reverse(); 133 | external.reverse(); 134 | const sameOrNewPage = async url => new Promise(async (resolve, _reject) => { 135 | const isNew = page.url() != url; 136 | let p = page; 137 | if (isNew) { 138 | p = await context.newPage(); 139 | await p.goto(url, { waitUntil: 'domcontentloaded' }); 140 | } 141 | resolve([p, isNew]); 142 | }); 143 | const skipBasedOnTime = async url => { 144 | // console.log(' Checking time left for game:', url); 145 | const [p, isNew] = await sameOrNewPage(url); 146 | const dueDateOrg = await p.locator('.availability-date .tw-bold').innerText(); 147 | const dueDate = new Date(Date.parse(dueDateOrg + ' 17:00')); 148 | const daysLeft = (dueDate.getTime() - Date.now())/1000/60/60/24; 149 | console.log(' ', await p.locator('.availability-date').innerText(), '->', daysLeft.toFixed(2)); 150 | if (isNew) await p.close(); 151 | return daysLeft > cfg.pg_timeLeft; 152 | } 153 | console.log('\nNumber of free unclaimed games (Prime Gaming):', internal.length); 154 | // claim games in internal store 155 | for (const card of internal) { 156 | await card.scrollIntoViewIfNeeded(); 157 | const title = await (await card.$('.item-card-details__body__primary')).innerText(); 158 | const slug = await (await card.$('a')).getAttribute('href'); 159 | const url = 'https://gaming.amazon.com' + slug.split('?')[0]; 160 | console.log('Current free game:', chalk.blue(title)); 161 | if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue; 162 | if (cfg.dryrun) continue; 163 | if (cfg.interactive && !await confirm()) continue; 164 | await (await card.$('.tw-button:has-text("Claim")')).click(); 165 | db.data[user][title] ||= { title, time: datetime(), url, store: 'internal' }; 166 | notify_games.push({ title, status: 'claimed', url }); 167 | // const img = await (await card.$('img.tw-image')).getAttribute('src'); 168 | // console.log('Image:', img); 169 | await card.screenshot({ path: screenshot('internal', `${filenamify(title)}.png`) }); 170 | } 171 | console.log('\nNumber of free unclaimed games (external stores):', external.length); 172 | // claim games in external/linked stores. Linked: origin.com, epicgames.com; Redeem-key: gog.com, legacygames.com, microsoft 173 | const external_info = []; 174 | 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) 175 | const title = await card.locator('.item-card-details__body__primary').innerText(); 176 | const slug = await card.locator('a:has-text("Claim")').first().getAttribute('href'); 177 | const url = 'https://gaming.amazon.com' + slug.split('?')[0]; 178 | // await (await card.$('text=Claim')).click(); // goes to URL of game, no need to wait 179 | external_info.push({ title, url }); 180 | } 181 | // external_info = [ { title: 'Fallout 76 (XBOX)', url: 'https://gaming.amazon.com/fallout-76-xbox-fgwp/dp/amzn1.pg.item.9fe17d7b-b6c2-4f58-b494-cc4e79528d0b?ingress=amzn&ref_=SM_Fallout76XBOX_S01_FGWP_CRWN' } ]; 182 | for (const { title, url } of external_info) { 183 | console.log('Current free game:', chalk.blue(title)); // , url); 184 | await page.goto(url, { waitUntil: 'domcontentloaded' }); 185 | if (cfg.debug) await page.pause(); 186 | const item_text = await page.innerText('[data-a-target="DescriptionItemDetails"]'); 187 | const store = item_text.toLowerCase().replace(/.* on /, '').slice(0, -1); 188 | console.log(' External store:', store); 189 | if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue; 190 | if (cfg.dryrun) continue; 191 | if (cfg.interactive && !await confirm()) continue; 192 | await Promise.any([page.click('[data-a-target="buy-box"] .tw-button:has-text("Get game")'), page.click('[data-a-target="buy-box"] .tw-button:has-text("Claim")'), page.click('.tw-button:has-text("Complete Claim")'), page.waitForSelector('div:has-text("Link game account")'), page.waitForSelector('.thank-you-title:has-text("Success")')]); // waits for navigation 193 | db.data[user][title] ||= { title, time: datetime(), url, store }; 194 | const notify_game = { title, url }; 195 | notify_games.push(notify_game); // status is updated below 196 | if (await page.locator('div:has-text("Link game account")').count() // TODO still needed? epic games store just has 'Link account' as the button text now. 197 | || await page.locator('div:has-text("Link account")').count()) { 198 | console.error(' Account linking is required to claim this offer!'); 199 | notify_game.status = `failed: need account linking for ${store}`; 200 | db.data[user][title].status = 'failed: need account linking'; 201 | // await page.pause(); 202 | // await page.click('[data-a-target="LinkAccountModal"] [data-a-target="LinkAccountButton"]'); 203 | // TODO login for epic games also needed if already logged in 204 | // wait for https://www.epicgames.com/id/authorize?redirect_uri=https%3A%2F%2Fservice.link.amazon.gg... 205 | // await page.click('button[aria-label="Allow"]'); 206 | } else { 207 | db.data[user][title].status = 'claimed'; 208 | // print code if there is one 209 | const redeem = { 210 | // 'origin': 'https://www.origin.com/redeem', // TODO still needed or now only via account linking? 211 | 'gog.com': 'https://www.gog.com/redeem', 212 | 'microsoft store': 'https://account.microsoft.com/billing/redeem', 213 | xbox: 'https://account.microsoft.com/billing/redeem', 214 | 'legacy games': 'https://www.legacygames.com/primedeal', 215 | }; 216 | if (store in redeem) { // did not work for linked origin: && !await page.locator('div:has-text("Successfully Claimed")').count() 217 | const code = await Promise.any([page.inputValue('input[type="text"]'), page.textContent('[data-a-target="ClaimStateClaimCodeContent"]').then(s => s.replace('Your code: ', ''))]); // input: Legacy Games; text: gog.com 218 | console.log(' Code to redeem game:', chalk.blue(code)); 219 | if (store == 'legacy games') { // may be different URL like https://legacygames.com/primeday/puzzleoftheyear/ 220 | redeem[store] = await (await page.$('li:has-text("Click here") a')).getAttribute('href'); // full text: Click here to enter your redemption code. 221 | } 222 | let redeem_url = redeem[store]; 223 | if (store == 'gog.com') redeem_url += '/' + code; // to log and notify, but can't use for goto below (captcha) 224 | console.log(' URL to redeem game:', redeem_url); 225 | db.data[user][title].code = code; 226 | let redeem_action = 'redeem'; 227 | if (cfg.pg_redeem) { // try to redeem keys on external stores 228 | console.log(` Trying to redeem ${code} on ${store} (need to be logged in)!`); 229 | const page2 = await context.newPage(); 230 | await page2.goto(redeem[store], { waitUntil: 'domcontentloaded' }); 231 | if (store == 'gog.com') { 232 | // await page.goto(`https://redeem.gog.com/v1/bonusCodes/${code}`); // {"reason":"Invalid or no captcha"} 233 | await page2.fill('#codeInput', code); 234 | // wait for responses before clicking on Continue and then Redeem 235 | // first there are requests with OPTIONS and GET to https://redeem.gog.com/v1/bonusCodes/XYZ?language=de-DE 236 | const r1 = page2.waitForResponse(r => r.request().method() == 'GET' && r.url().startsWith('https://redeem.gog.com/')); 237 | await page2.click('[type="submit"]'); // click Continue 238 | // console.log(await page2.locator('.warning-message').innerText()); // does not exist if there is no warning 239 | const r1t = await (await r1).text(); 240 | const reason = JSON.parse(r1t).reason; 241 | // {"reason":"Invalid or no captcha"} 242 | // {"reason":"code_used"} 243 | // {"reason":"code_not_found"} 244 | if (reason?.includes('captcha')) { 245 | redeem_action = 'redeem (got captcha)'; 246 | console.error(' Got captcha; could not redeem!'); 247 | } else if (reason == 'code_used') { 248 | redeem_action = 'already redeemed'; 249 | console.log(' Code was already used!'); 250 | } else if (reason == 'code_not_found') { 251 | redeem_action = 'redeem (not found)'; 252 | console.error(' Code was not found!'); 253 | } else { // TODO not logged in? need valid unused code to test. 254 | redeem_action = 'redeemed?'; 255 | // console.log(' Redeemed successfully? Please report your Responses (if new) in https://github.com/vogler/free-games-claimer/issues/5'); 256 | console.debug(` Response 1: ${r1t}`); 257 | // then after the click on Redeem there is a POST request which should return {} if claimed successfully 258 | const r2 = page2.waitForResponse(r => r.request().method() == 'POST' && r.url().startsWith('https://redeem.gog.com/')); 259 | await page2.click('[type="submit"]'); // click Redeem 260 | const r2t = await (await r2).text(); 261 | const reason2 = JSON.parse(r2t).reason; 262 | if (r2t == '{}') { 263 | redeem_action = 'redeemed'; 264 | console.log(' Redeemed successfully.'); 265 | db.data[user][title].status = 'claimed and redeemed'; 266 | } else if (reason2?.includes('captcha')) { 267 | redeem_action = 'redeem (got captcha)'; 268 | console.error(' Got captcha; could not redeem!'); 269 | } else { 270 | console.debug(` Response 2: ${r2t}`); 271 | console.log(' Unknown Response 2 - please report in https://github.com/vogler/free-games-claimer/issues/5'); 272 | } 273 | } 274 | } else if (store == 'microsoft store' || store == 'xbox') { 275 | console.error(` Redeem on ${store} is experimental!`); 276 | // await page2.pause(); 277 | if (page2.url().startsWith('https://login.')) { 278 | console.error(' Not logged in! Please redeem the code above manually. You can now login in the browser for next time. Waiting for 60s.'); 279 | await page2.waitForTimeout(60 * 1000); 280 | redeem_action = 'redeem (login)'; 281 | } else { 282 | const iframe = page2.frameLocator('#redeem-iframe'); 283 | const input = iframe.locator('[name=tokenString]'); 284 | await input.waitFor(); 285 | await input.fill(code); 286 | const r = page2.waitForResponse(r => r.url().startsWith('https://cart.production.store-web.dynamics.com/v1.0/Redeem/PrepareRedeem')); 287 | // console.log(await page2.locator('.redeem_code_error').innerText()); 288 | const rt = await (await r).text(); 289 | // {"code":"NotFound","data":[],"details":[],"innererror":{"code":"TokenNotFound",... 290 | const j = JSON.parse(rt); 291 | const reason = j?.events?.cart.length && j.events.cart[0]?.data?.reason; 292 | if (reason == 'TokenNotFound') { 293 | redeem_action = 'redeem (not found)'; 294 | console.error(' Code was not found!'); 295 | } else if (j?.productInfos?.length && j.productInfos[0]?.redeemable) { 296 | await iframe.locator('button:has-text("Next")').click(); 297 | await iframe.locator('button:has-text("Confirm")').click(); 298 | const r = page2.waitForResponse(r => r.url().startsWith('https://cart.production.store-web.dynamics.com/v1.0/Redeem/RedeemToken')); 299 | const j = JSON.parse(await (await r).text()); 300 | if (j?.events?.cart.length && j.events.cart[0]?.data?.reason == 'UserAlreadyOwnsContent') { 301 | redeem_action = 'already redeemed'; 302 | console.error(' error: UserAlreadyOwnsContent'); 303 | } else if (true) { // TODO what's returned on success? 304 | redeem_action = 'redeemed'; 305 | db.data[user][title].status = 'claimed and redeemed?'; 306 | console.log(' Redeemed successfully? Please report if not in https://github.com/vogler/free-games-claimer/issues/5'); 307 | } 308 | } else { // TODO find out other responses 309 | redeem_action = 'unknown'; 310 | console.debug(` Response: ${rt}`); 311 | console.log(' Redeemed successfully? Please report your Response from above (if it is new) in https://github.com/vogler/free-games-claimer/issues/5'); 312 | } 313 | } 314 | } else if (store == 'legacy games') { 315 | // await page2.pause(); 316 | await page2.fill('[name=coupon_code]', code); 317 | await page2.fill('[name=email]', cfg.lg_email); 318 | await page2.fill('[name=email_validate]', cfg.lg_email); 319 | await page2.uncheck('[name=newsletter_sub]'); 320 | await page2.click('[type="submit"]'); 321 | try { 322 | // await page2.waitForResponse(r => r.url().startsWith('https://promo.legacygames.com/promotion-processing/order-management.php')); // status code 302 323 | await page2.waitForSelector('h2:has-text("Thanks for redeeming")'); 324 | redeem_action = 'redeemed'; 325 | db.data[user][title].status = 'claimed and redeemed'; 326 | } catch (error) { 327 | console.error(' Got error', error); 328 | redeem_action = 'redeemed?'; 329 | db.data[user][title].status = 'claimed and redeemed?'; 330 | console.log(' Redeemed successfully? Please report problems in https://github.com/vogler/free-games-claimer/issues/5'); 331 | } 332 | } else { 333 | console.error(` Redeem on ${store} not yet implemented!`); 334 | } 335 | if (cfg.debug) await page2.pause(); 336 | await page2.close(); 337 | } 338 | notify_game.status = `${redeem_action} ${code} on ${store}`; 339 | } else { 340 | notify_game.status = `claimed on ${store}`; 341 | db.data[user][title].status = 'claimed'; 342 | } 343 | // save screenshot of potential code just in case 344 | await page.screenshot({ path: screenshot('external', `${filenamify(title)}.png`), fullPage: true }); 345 | // console.info(' Saved a screenshot of page to', p); 346 | } 347 | // await page.pause(); 348 | } 349 | await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); 350 | await page.click('button[data-type="Game"]'); 351 | 352 | if (notify_games.length) { // make screenshot of all games if something was claimed 353 | const p = screenshot(`${filenamify(datetime())}.png`); 354 | // await page.screenshot({ path: p, fullPage: true }); // fullPage does not make a difference since scroll not on body but on some element 355 | await scrollUntilStable(() => games.locator('.item-card__action').count()); 356 | const viewportSize = page.viewportSize(); // current viewport size 357 | await page.setViewportSize({ ...viewportSize, height: 3000 }); // increase height, otherwise element screenshot is cut off at the top and bottom 358 | await games.screenshot({ path: p }); // screenshot of all claimed games 359 | } 360 | 361 | // https://github.com/vogler/free-games-claimer/issues/55 362 | if (cfg.pg_claimdlc) { 363 | console.log('Trying to claim in-game content...'); 364 | await page.click('button[data-type="InGameLoot"]'); 365 | const loot = page.locator('div[data-a-target="offer-list-IN_GAME_LOOT"]'); 366 | await loot.waitFor(); 367 | 368 | process.stdout.write('Loading all DLCs on page...'); 369 | await scrollUntilStable(() => loot.locator('[data-a-target="item-card"]').count()) 370 | 371 | console.log('\nNumber of already claimed DLC:', await loot.locator('p:has-text("Collected")').count()); 372 | 373 | const cards = await loot.locator('[data-a-target="item-card"]:has(p:text-is("Claim"))').all(); 374 | console.log('Number of unclaimed DLC:', cards.length); 375 | const dlcs = await Promise.all(cards.map(async card => ({ 376 | game: await card.locator('.item-card-details__body p').innerText(), 377 | title: await card.locator('.item-card-details__body__primary').innerText(), 378 | url: 'https://gaming.amazon.com' + await card.locator('a').first().getAttribute('href'), 379 | }))); 380 | // console.log(dlcs); 381 | 382 | const dlc_unlinked = {}; 383 | for (const dlc of dlcs) { 384 | const title = `${dlc.game} - ${dlc.title}`; 385 | const url = dlc.url; 386 | console.log('Current DLC:', title); 387 | if (cfg.debug) await page.pause(); 388 | if (cfg.dryrun) continue; 389 | if (cfg.interactive && !await confirm()) continue; 390 | db.data[user][title] ||= { title, time: datetime(), store: 'DLC', status: 'failed: need account linking' }; 391 | const notify_game = { title, url }; 392 | notify_games.push(notify_game); // status is updated below 393 | try { 394 | await page.goto(url, { waitUntil: 'domcontentloaded' }); 395 | // most games have a button 'Get in-game content' 396 | // 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? 397 | await Promise.any([page.click('.tw-button:has-text("Get in-game content")'), page.click('.tw-button:has-text("Claim your gift")'), page.click('.tw-button:has-text("Claim")').then(() => page.click('button:has-text("Continue")'))]); 398 | page.click('button:has-text("Continue")').catch(_ => { }); 399 | const linkAccountButton = page.locator('[data-a-target="LinkAccountButton"]'); 400 | let unlinked_store; 401 | if (await linkAccountButton.count()) { 402 | unlinked_store = await linkAccountButton.first().getAttribute('aria-label'); 403 | console.debug(' LinkAccountButton label:', unlinked_store); 404 | const match = unlinked_store.match(/Link (.*) account/); 405 | if (match && match.length == 2) unlinked_store = match[1]; 406 | } else if (await page.locator('text=Link game account').count()) { // epic-games only? 407 | console.error(' Missing account linking (epic-games specific button?):', await page.locator('button[data-a-target="gms-cta"]').innerText()); // TODO needed? 408 | unlinked_store = 'epic-games'; 409 | } 410 | if (unlinked_store) { 411 | console.error(' Missing account linking:', unlinked_store, url); 412 | dlc_unlinked[unlinked_store] ??= []; 413 | dlc_unlinked[unlinked_store].push(title); 414 | } else { 415 | const code = await page.inputValue('input[type="text"]').catch(_ => undefined); 416 | console.log(' Code to redeem game:', chalk.blue(code)); 417 | db.data[user][title].code = code; 418 | db.data[user][title].status = 'claimed'; 419 | // notify_game.status = `${redeem_action} ${code} on ${store}`; 420 | } 421 | // await page.pause(); 422 | } catch (error) { 423 | console.error(error); 424 | } finally { 425 | await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); 426 | await page.click('button[data-type="InGameLoot"]'); 427 | } 428 | } 429 | console.log('DLC: Unlinked accounts:', dlc_unlinked); 430 | } 431 | } catch (error) { 432 | process.exitCode ||= 1; 433 | console.error('--- Exception:'); 434 | console.error(error); // .toString()? 435 | if (error.message && process.exitCode != 130) notify(`prime-gaming failed: ${error.message.split('\n')[0]}`); 436 | } finally { 437 | await db.write(); // write out json db 438 | if (notify_games.length) { // list should only include claimed games 439 | notify(`prime-gaming (${user}):
${html_game_list(notify_games)}`); 440 | } 441 | } 442 | if (page.video()) console.log('Recorded video:', await page.video().path()); 443 | await context.close(); 444 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------