Compare commits
393 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ebb57a706 | ||
|
|
949206dbf2 | ||
|
|
cfc1e0ee12 | ||
|
|
4d835013cc | ||
|
|
6f2e1e5b22 | ||
|
|
e3e6a6f36c | ||
|
|
a477bb3327 | ||
|
|
7ffc454e47 | ||
|
|
b9aa6e0073 | ||
|
|
bab4359977 | ||
|
|
52895fd991 | ||
|
|
3fd861f134 | ||
|
|
5f919039ab | ||
|
|
397871b012 | ||
|
|
405e801851 | ||
|
|
37ffd09545 | ||
|
|
69282c63d5 | ||
|
|
9e2bc89ff2 | ||
|
|
e4b1f60a66 | ||
|
|
f82c158a6b | ||
|
|
b5e9111039 | ||
|
|
94be980c95 | ||
|
|
00b36a65b1 | ||
|
|
2a4653062a | ||
|
|
25fb2d9838 | ||
|
|
6c4eb948fc | ||
|
|
405660e0f2 | ||
|
|
02972a04d4 | ||
|
|
608b6b87cd | ||
|
|
e11d40bdda | ||
|
|
8626fa5a0f | ||
|
|
56ca1f63d4 | ||
|
|
5b1d966c6e | ||
|
|
d40a577f47 | ||
|
|
0e5303da62 | ||
| e39cca93c2 | |||
|
|
9d79f9ac78 | ||
|
|
0a729d0cbf | ||
|
|
eb5b9bbb6e | ||
|
|
eba07721ca | ||
|
|
bde0f34a80 | ||
|
|
6f778d71ac | ||
|
|
a21dced86e | ||
|
|
76f578e2e6 | ||
|
|
faf22aafb1 | ||
|
|
99c1f05302 | ||
|
|
991e0a1449 | ||
|
|
cea5b11c95 | ||
|
|
6adc7e529a | ||
|
|
158caa6164 | ||
|
|
0a4cac3571 | ||
|
|
bf0c9032cc | ||
|
|
4ce0d44b79 | ||
|
|
7c8682ac91 | ||
|
|
a5ce5ec816 | ||
|
|
6aea18836d | ||
|
|
97ef14f514 | ||
|
|
5cfe57870a | ||
|
|
3e13e9fba8 | ||
|
|
dee47d2218 | ||
|
|
726db4527b | ||
|
|
04d1b7ea9e | ||
|
|
0fefcc47b7 | ||
|
|
92cb32ff2d | ||
|
|
90e3400072 | ||
|
|
041a77d9f6 | ||
|
|
787522473f | ||
|
|
cfe42db805 | ||
|
|
8b7018f54c | ||
|
|
ea69c76b50 | ||
|
|
3626fc1762 | ||
|
|
d2d85dee8c | ||
|
|
8d538290a8 | ||
|
|
daef12b562 | ||
|
|
acaf6691d4 | ||
|
|
e75975b273 | ||
|
|
cb22abfb2f | ||
|
|
67058850d5 | ||
|
|
3ac05a5593 | ||
|
|
d620ee2731 | ||
|
|
f47ffe0e9f | ||
|
|
253a3f7253 | ||
|
|
5e5c257b83 | ||
|
|
6aa0f9b817 | ||
|
|
bf2216f731 | ||
|
|
d6666aed03 | ||
|
|
041605dcf7 | ||
|
|
d76c03ed6a | ||
|
|
fed03428f3 | ||
|
|
4a018c20e9 | ||
|
|
ceb873ea0b | ||
|
|
9e87ce58ac | ||
|
|
b3ab8f7830 | ||
|
|
33d2493336 | ||
|
|
d5072a62c0 | ||
|
|
c5a7a10ca3 | ||
|
|
c8cf7362fa | ||
|
|
fef5b97e3b | ||
|
|
292aadae3c | ||
|
|
7279ba06e8 | ||
|
|
1f4af79e0e | ||
|
|
c8e0640490 | ||
|
|
eafb2316f7 | ||
|
|
c87deb393e | ||
|
|
23a611a2f1 | ||
|
|
eac11e8949 | ||
|
|
8605b70377 | ||
|
|
d9e91d22c9 | ||
|
|
a39d737999 | ||
|
|
b8f7068a87 | ||
|
|
17f1ee41c9 | ||
|
|
aee72327ea | ||
|
|
00275d825b | ||
|
|
e154b74e4d | ||
|
|
d85cd8d20c | ||
|
|
9af36e902c | ||
|
|
920fc4d186 | ||
|
|
c4be7ece21 | ||
|
|
b8071d442c | ||
|
|
9cf5d2f7f2 | ||
|
|
55226933c0 | ||
|
|
357a780aa9 | ||
|
|
afceb0aad9 | ||
|
|
c0eb6dbb0b | ||
|
|
076738e301 | ||
|
|
601e893714 | ||
|
|
43bef9b23c | ||
|
|
f920aa26d0 | ||
|
|
30b1835bdb | ||
|
|
f0f142733e | ||
|
|
cf59da5d9e | ||
|
|
2d81ed2145 | ||
|
|
f7c23569c7 | ||
|
|
9ef9798626 | ||
|
|
e49fa930e0 | ||
|
|
c4ae3505b3 | ||
|
|
8c535f48fa | ||
|
|
075106da11 | ||
|
|
3338d08a1d | ||
|
|
da6964c19a | ||
|
|
6f06fccd46 | ||
|
|
61fdf566c9 | ||
|
|
285c7a44fd | ||
|
|
2ea0c611e4 | ||
|
|
e4e4ce703d | ||
|
|
fc810af80e | ||
|
|
28bcceb285 | ||
|
|
0ec24ef062 | ||
|
|
c3657f05ac | ||
|
|
7ca79bd413 | ||
|
|
56cfab6e21 | ||
|
|
fb8f38706a | ||
|
|
a9e20928ee | ||
|
|
b68021b8e8 | ||
|
|
baeaaa64f8 | ||
|
|
105f6f414a | ||
|
|
64676795d1 | ||
|
|
6b9420804b | ||
|
|
5a4f07ce70 | ||
|
|
09a364c67d | ||
|
|
4518914bfd | ||
|
|
377ee736cb | ||
|
|
2dec0080d9 | ||
|
|
a2af1ccd09 | ||
|
|
e66d10574d | ||
|
|
68b66444ca | ||
|
|
2a19100601 | ||
|
|
5343535429 | ||
|
|
ace4ef8303 | ||
|
|
e078a1540a | ||
|
|
093ed813c6 | ||
|
|
e06ad3a27f | ||
|
|
9f97805517 | ||
|
|
30957d63d0 | ||
|
|
19e9bb9cfc | ||
|
|
bdc305aa83 | ||
|
|
e18de7e640 | ||
|
|
f4270e176f | ||
|
|
8bf36a2158 | ||
|
|
3c15252d8b | ||
|
|
76597f4315 | ||
|
|
9c89bf06a4 | ||
|
|
36fe60a2b1 | ||
|
|
0f549285b9 | ||
|
|
544eff8a23 | ||
|
|
5919d37efa | ||
|
|
324f6bffe7 | ||
|
|
4231b7dd28 | ||
|
|
3ddf1720bb | ||
|
|
a7cc68b6db | ||
|
|
739fb0dbfe | ||
|
|
110b2ea4c6 | ||
|
|
c5f75e06c8 | ||
|
|
d4685ff370 | ||
|
|
0832ae57f5 | ||
|
|
011eddf97a | ||
|
|
efe4faab3e | ||
|
|
e4e4f2eafa | ||
|
|
6a34cb541d | ||
|
|
5083ea408d | ||
|
|
2eaf6f0598 | ||
|
|
dec0b519a5 | ||
|
|
6113ea4b8d | ||
|
|
798b130c92 | ||
|
|
e5935faa13 | ||
|
|
b5ef699f4f | ||
|
|
a6b9ec9609 | ||
|
|
a62aa8c0c8 | ||
|
|
e192365b48 | ||
|
|
92ce3d405d | ||
|
|
584130f5d1 | ||
|
|
5fda138d8d | ||
|
|
11db31ea46 | ||
|
|
0ab9935fb5 | ||
|
|
28a1e42cc4 | ||
|
|
32cd0d8990 | ||
|
|
b99a154267 | ||
|
|
75f7d77445 | ||
|
|
bf870919a6 | ||
|
|
280ab70975 | ||
|
|
1dbe2f1457 | ||
|
|
4137bb5569 | ||
|
|
a374d48345 | ||
|
|
d73a523fe7 | ||
|
|
04787909c7 | ||
|
|
ad2301c3fd | ||
|
|
a8ab989a7f | ||
|
|
9fc68b881f | ||
|
|
0040d9d96c | ||
|
|
d318a57be1 | ||
|
|
9ebd15f204 | ||
|
|
41f1f95509 | ||
|
|
840d35c2d2 | ||
|
|
13b2917dd0 | ||
|
|
b748460b73 | ||
|
|
1fbabbc0f2 | ||
|
|
2a4da3f49c | ||
|
|
0ba693eeb6 | ||
|
|
6cdef56c09 | ||
|
|
30db49d9b9 | ||
|
|
44d712e333 | ||
|
|
d51f7310d9 | ||
|
|
e30216c9b8 | ||
|
|
c79f4cc40f | ||
|
|
97882c76c3 | ||
|
|
b449ee4d7f | ||
|
|
d4ebdd091a | ||
|
|
d8e2093a0d | ||
|
|
38975e811b | ||
|
|
59004cd4bb | ||
|
|
5ae4ce5666 | ||
|
|
93d082e700 | ||
|
|
621032e459 | ||
|
|
6bb1dca934 | ||
|
|
9261be690c | ||
|
|
6560afa2b5 | ||
|
|
d4d7ee3281 | ||
|
|
c211472d0c | ||
|
|
f528fbfd30 | ||
|
|
d7949fb9dd | ||
|
|
8a010dbcc7 | ||
|
|
2eb17a1419 | ||
|
|
24a9f23211 | ||
|
|
682c651224 | ||
|
|
c09d20766c | ||
|
|
70b5182bed | ||
|
|
a7d045f0e2 | ||
|
|
56d8c2d188 | ||
|
|
a3adaae99f | ||
|
|
66c12b8ea2 | ||
|
|
da23bc2f92 | ||
|
|
6a7cca31a4 | ||
|
|
3d1168f653 | ||
|
|
40bcf1c8a2 | ||
|
|
7551a6ca96 | ||
|
|
e2e28301e6 | ||
|
|
e794a3306f | ||
|
|
5c8f8fc3fd | ||
|
|
86832e7fe9 | ||
|
|
d0761dea26 | ||
|
|
490c4c0788 | ||
|
|
13def8ba18 | ||
|
|
08fc59520c | ||
|
|
f89b4a6a36 | ||
|
|
b5ead8ea21 | ||
|
|
22f673282b | ||
|
|
a90f90afc0 | ||
|
|
2e8a731573 | ||
|
|
04bd56cd77 | ||
|
|
8c6ff57054 | ||
|
|
a7dcfe72cc | ||
|
|
acc337a4f9 | ||
|
|
f0e15b5c7c | ||
|
|
85513031f2 | ||
|
|
0b9d5d0b63 | ||
|
|
7e4770b846 | ||
|
|
d3d22b1582 | ||
|
|
2ceccdae6b | ||
|
|
f906bef2a8 | ||
|
|
00e213cf50 | ||
|
|
feadfc5acf | ||
|
|
7fb872608d | ||
|
|
0d074d0397 | ||
|
|
368229be09 | ||
|
|
8ee63c7a35 | ||
|
|
819e4cc57e | ||
|
|
e4ebae3744 | ||
|
|
240e64ae4c | ||
|
|
98e4145708 | ||
|
|
60acf747d0 | ||
|
|
c4eb1e03ce | ||
|
|
590b01aba2 | ||
|
|
290fe289d4 | ||
|
|
491ee899a5 | ||
|
|
af935d4889 | ||
|
|
6b13287b61 | ||
|
|
8f174c4bf0 | ||
|
|
7fc0fbc69c | ||
|
|
066a99c77c | ||
|
|
ce51c269f8 | ||
|
|
8fdf930415 | ||
|
|
631197371f | ||
|
|
5809b0963a | ||
|
|
5214bea488 | ||
|
|
bb51fd8065 | ||
|
|
bc8a89f365 | ||
|
|
a235ce7915 | ||
|
|
2e0cc4d377 | ||
|
|
670262c118 | ||
|
|
351bf00c7b | ||
|
|
b2d69b4d26 | ||
|
|
28146c7d69 | ||
|
|
e22bb22a53 | ||
|
|
6cbd9fe5e3 | ||
|
|
04f503fea7 | ||
|
|
db5a98eb88 | ||
|
|
9285af2544 | ||
|
|
352ee753c9 | ||
|
|
b7d5d43078 | ||
|
|
b75f538d8a | ||
|
|
9435ff6edb | ||
|
|
4f1ca53d1b | ||
|
|
9df80fa6d8 | ||
|
|
0cfb9d29aa | ||
|
|
c48c80717a | ||
|
|
7520bf1976 | ||
|
|
74bd2f538a | ||
|
|
9ab44bd7aa | ||
|
|
07ce17f8e3 | ||
|
|
b51547a376 | ||
|
|
a5f42a9609 | ||
|
|
cbdea1b5d0 | ||
|
|
e45c3a5dca | ||
|
|
a8fa80cd05 | ||
|
|
944cca6715 | ||
|
|
0d2ff0c8a9 | ||
|
|
862fd20d5b | ||
|
|
cc39b4b3d1 | ||
|
|
dc28c30e7b | ||
|
|
73a7cffd47 | ||
|
|
114631da4d | ||
|
|
e73d3d47d7 | ||
|
|
792d2859b3 | ||
|
|
08b9df7cc4 | ||
|
|
fc3f0a6333 | ||
|
|
38c5402df0 | ||
|
|
21ed2794f4 | ||
|
|
a3892eaafb | ||
|
|
9df4836221 | ||
|
|
18c27ba881 | ||
|
|
97f6735833 | ||
|
|
518008584f | ||
|
|
b0f662479d | ||
|
|
66694d65e5 | ||
|
|
c1cd2db721 | ||
|
|
efeccf9493 | ||
|
|
8c2ac3b6d0 | ||
|
|
704c4b01e1 | ||
|
|
1b319cacf7 | ||
|
|
3158c5515f | ||
|
|
5f6d9ca830 | ||
|
|
992fe4fc8b | ||
|
|
957ba6d7ca | ||
|
|
95598887cc | ||
|
|
e2b07dc1e6 | ||
|
|
a90062b631 | ||
|
|
ec2d31ed79 | ||
|
|
c65f153090 | ||
|
|
c058bafcf3 | ||
|
|
af34113eaf | ||
|
|
acbfa9156e | ||
|
|
f873d95a89 | ||
|
|
3ada6bbc23 |
49 changed files with 6638 additions and 1327 deletions
|
|
@ -1,6 +1,10 @@
|
||||||
node_modules
|
node_modules/
|
||||||
data
|
data/
|
||||||
|
*.env
|
||||||
|
|
||||||
.gitignore
|
.gitignore
|
||||||
|
.github/
|
||||||
|
|
||||||
**Dockerfile**
|
**Dockerfile**
|
||||||
.dockerignore
|
.dockerignore
|
||||||
|
|
||||||
|
|
|
||||||
87
.forgejo/workflows/build.yml
Normal file
87
.forgejo/workflows/build.yml
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
name: build-and-push
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint:
|
||||||
|
runs-on: self-hosted
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
- name: Run ESLint
|
||||||
|
run: npm run lint
|
||||||
|
|
||||||
|
sonar:
|
||||||
|
needs: lint
|
||||||
|
runs-on: self-hosted
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
- name: Install Sonar Scanner (npm)
|
||||||
|
run: npm install -g sonarqube-scanner
|
||||||
|
- name: SonarQube Scan
|
||||||
|
env:
|
||||||
|
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
|
||||||
|
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||||
|
SONAR_PROJECT_KEY: ${{ secrets.SONAR_PROJECT_KEY }}
|
||||||
|
run: |
|
||||||
|
WORKDIR=${GITHUB_WORKSPACE:-$PWD}
|
||||||
|
HOST_URL=${SONAR_HOST_URL:?SONAR_HOST_URL secret not set}
|
||||||
|
PROJECT_KEY=${SONAR_PROJECT_KEY:-}
|
||||||
|
if [ -z "$PROJECT_KEY" ] && [ -f sonar-project.properties ]; then
|
||||||
|
PROJECT_KEY=$(grep -E '^sonar.projectKey=' sonar-project.properties | cut -d= -f2 | tr -d '\r')
|
||||||
|
fi
|
||||||
|
if [ -z "$PROJECT_KEY" ]; then
|
||||||
|
echo "SONAR_PROJECT_KEY secret not set and no sonar-project.properties entry found" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Sonar project key: $PROJECT_KEY"
|
||||||
|
echo "Listing workspace:"
|
||||||
|
ls -la
|
||||||
|
echo "Sample files:"
|
||||||
|
find . -maxdepth 2 -type f | head -n 20
|
||||||
|
echo "Running local sonar-scanner..."
|
||||||
|
sonar-scanner \
|
||||||
|
-Dsonar.host.url="$HOST_URL" \
|
||||||
|
-Dsonar.token="$SONAR_TOKEN" \
|
||||||
|
-Dsonar.projectKey="$PROJECT_KEY" \
|
||||||
|
-Dsonar.sources=. \
|
||||||
|
-Dsonar.scm.disabled=true \
|
||||||
|
-Dsonar.projectBaseDir="$WORKDIR"
|
||||||
|
|
||||||
|
docker:
|
||||||
|
needs: [lint, sonar]
|
||||||
|
runs-on: self-hosted
|
||||||
|
steps:
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Login to registry
|
||||||
|
run: echo "${{ secrets.REG_TOKEN }}" | docker login "${{ secrets.REGISTRY }}" -u "${{ secrets.REG_USER }}" --password-stdin
|
||||||
|
|
||||||
|
- name: Build image
|
||||||
|
run: |
|
||||||
|
docker buildx build --load \
|
||||||
|
-t "${{ secrets.REGISTRY_IMAGE }}:latest" .
|
||||||
|
|
||||||
|
- name: Push image
|
||||||
|
run: |
|
||||||
|
docker push "${{ secrets.REGISTRY_IMAGE }}:latest"
|
||||||
48
.github/workflows/docker.yml
vendored
48
.github/workflows/docker.yml
vendored
|
|
@ -1,48 +0,0 @@
|
||||||
name: Build and push Docker image (amd64, arm64 to hub.docker.com and ghcr.io)
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- "main"
|
|
||||||
paths-ignore:
|
|
||||||
- ".github/**"
|
|
||||||
- ".gitignore"
|
|
||||||
- "README.md"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
docker:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
-
|
|
||||||
name: Checkout
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
-
|
|
||||||
name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v2
|
|
||||||
-
|
|
||||||
name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v2
|
|
||||||
-
|
|
||||||
name: Login to Docker Hub
|
|
||||||
uses: docker/login-action@v2
|
|
||||||
with:
|
|
||||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
|
||||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
|
||||||
-
|
|
||||||
name: Login to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v2
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.repository_owner }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
-
|
|
||||||
name: Build and push
|
|
||||||
uses: docker/build-push-action@v3
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm64 # ,linux/arm/v7
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
voglerr/free-games-claimer:latest
|
|
||||||
ghcr.io/vogler/free-games-claimer:latest
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,2 +1,3 @@
|
||||||
node_modules/
|
node_modules/
|
||||||
data/
|
data/
|
||||||
|
*.env
|
||||||
|
|
|
||||||
10
.vscode/settings.json
vendored
Normal file
10
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
{
|
||||||
|
// https://eslint.style/guide/faq#vs-code
|
||||||
|
"editor.formatOnSave": true,
|
||||||
|
"editor.formatOnSaveMode": "modifications",
|
||||||
|
"editor.codeActionsOnSave": {
|
||||||
|
"source.fixAll.eslint": "explicit"
|
||||||
|
},
|
||||||
|
"eslint.experimental.useFlatConfig": true,
|
||||||
|
"eslint.codeActionsOnSave.rules": null,
|
||||||
|
}
|
||||||
6
CONTRIBUTING.md
Normal file
6
CONTRIBUTING.md
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
# Contribute
|
||||||
|
|
||||||
|
## Building and publishing docker images
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
85
Dockerfile
85
Dockerfile
|
|
@ -7,60 +7,103 @@ FROM ubuntu:jammy
|
||||||
# https://github.com/hadolint/hadolint/wiki/DL4006
|
# https://github.com/hadolint/hadolint/wiki/DL4006
|
||||||
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
|
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
|
||||||
ARG DEBIAN_FRONTEND=noninteractive
|
ARG DEBIAN_FRONTEND=noninteractive
|
||||||
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD true
|
|
||||||
|
|
||||||
# Install up-to-date node & npm, deps for virtual screen & noVNC, browser, pip for apprise.
|
# Install up-to-date node & npm, deps for virtual screen & noVNC, firefox, pip for apprise.
|
||||||
# Playwright needs --with-deps for firefox.
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get install -y curl \
|
&& apt-get install --no-install-recommends -y curl ca-certificates gnupg \
|
||||||
&& curl -fsSL https://deb.nodesource.com/setup_19.x | bash - \
|
&& mkdir -p /etc/apt/keyrings \
|
||||||
&& apt-get install -y nodejs \
|
&& curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \
|
||||||
&& apt-get install --no-install-recommends --no-install-suggests -y \
|
&& 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 \
|
||||||
|
&& apt-get update \
|
||||||
|
&& apt-get install --no-install-recommends -y \
|
||||||
|
nodejs \
|
||||||
xvfb \
|
xvfb \
|
||||||
ca-certificates \
|
|
||||||
x11vnc \
|
x11vnc \
|
||||||
tini \
|
tini \
|
||||||
novnc websockify \
|
novnc websockify \
|
||||||
dos2unix \
|
dos2unix \
|
||||||
python3-pip \
|
python3-pip \
|
||||||
&& npx playwright install-deps firefox \
|
libgtk-3-0 \
|
||||||
|
libasound2 \
|
||||||
|
libxcomposite1 \
|
||||||
|
libpangocairo-1.0-0 \
|
||||||
|
libpango-1.0-0 \
|
||||||
|
libatk1.0-0 \
|
||||||
|
libcairo-gobject2 \
|
||||||
|
libcairo2 \
|
||||||
|
libgdk-pixbuf-2.0-0 \
|
||||||
|
libdbus-glib-1-2 \
|
||||||
|
libxcursor1 \
|
||||||
|
libnss3 \
|
||||||
|
libnspr4 \
|
||||||
|
libgbm1 \
|
||||||
|
&& apt-get autoremove -y \
|
||||||
&& apt-get clean \
|
&& apt-get clean \
|
||||||
&& rm -rf \
|
&& rm -rf \
|
||||||
/tmp/* \
|
/tmp/* \
|
||||||
/usr/share/doc/* \
|
/usr/share/doc/* \
|
||||||
/var/cache/* \
|
/var/cache/* \
|
||||||
/var/lib/apt/lists/* \
|
/var/lib/apt/lists/* \
|
||||||
/var/tmp/*
|
/var/tmp/* \
|
||||||
|
&& useradd -ms /bin/bash fgc \
|
||||||
RUN ln -s /usr/share/novnc/vnc_auto.html /usr/share/novnc/index.html
|
&& ln -s /usr/share/novnc/vnc_auto.html /usr/share/novnc/index.html \
|
||||||
RUN pip install apprise
|
&& pip install apprise
|
||||||
|
|
||||||
WORKDIR /fgc
|
WORKDIR /fgc
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
|
|
||||||
# If firefox is installed (~/.cache/ms-playwright/firefox-*) before `npm install` it may be a newer version than in package.json and playwright will not find it; system deps are installed sep. via apt above to avoid having to pin the version there.
|
# Playwright installs patched firefox to ~/.cache/ms-playwright/firefox-*
|
||||||
RUN npm install && npx playwright install firefox
|
# Requires some system deps to run (see inlined install-deps above).
|
||||||
|
RUN npm install
|
||||||
|
# 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.
|
||||||
|
# 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
|
||||||
|
# RUN npx playwright install firefox
|
||||||
|
|
||||||
COPY . .
|
# Only copy the files we actually need in the image to avoid accidentally adding secrets.
|
||||||
|
COPY *.js ./
|
||||||
|
COPY eslint.config.js jsconfig.json sonar-project.properties ./
|
||||||
|
COPY src ./src
|
||||||
|
COPY test ./test
|
||||||
|
COPY docker-entrypoint.sh ./
|
||||||
|
|
||||||
# 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
|
# 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
|
||||||
RUN dos2unix *.sh && chmod +x *.sh
|
RUN dos2unix ./*.sh && chmod +x ./*.sh && chown -R fgc:fgc /fgc
|
||||||
COPY docker-entrypoint.sh /usr/local/bin/
|
COPY docker-entrypoint.sh /usr/local/bin/
|
||||||
|
|
||||||
|
ARG COMMIT=""
|
||||||
|
ARG BRANCH=""
|
||||||
|
ARG NOW=""
|
||||||
|
ENV COMMIT=${COMMIT}
|
||||||
|
ENV BRANCH=${BRANCH}
|
||||||
|
ENV NOW=${NOW}
|
||||||
|
|
||||||
|
LABEL org.opencontainers.image.title="free-games-claimer" \
|
||||||
|
org.opencontainers.image.name="free-games-claimer" \
|
||||||
|
org.opencontainers.image.description="Automatically claims free games on the Epic Games Store, Amazon Prime Gaming and GOG" \
|
||||||
|
org.opencontainers.image.url="https://github.com/vogler/free-games-claimer" \
|
||||||
|
org.opencontainers.image.source="https://github.com/vogler/free-games-claimer" \
|
||||||
|
org.opencontainers.image.revision=${COMMIT} \
|
||||||
|
org.opencontainers.image.ref.name=${BRANCH} \
|
||||||
|
org.opencontainers.image.base.name="ubuntu:jammy" \
|
||||||
|
org.opencontainers.image.version="latest"
|
||||||
|
|
||||||
# Configure VNC via environment variables:
|
# Configure VNC via environment variables:
|
||||||
ENV VNC_PORT 5900
|
ENV VNC_PORT 5900
|
||||||
ENV NOVNC_PORT 6080
|
ENV NOVNC_PORT 6080
|
||||||
EXPOSE 5900
|
# Ports are not exposed by default; publish explicitly with -p when you really need GUI access.
|
||||||
EXPOSE 6080
|
# EXPOSE 5900
|
||||||
|
# EXPOSE 6080
|
||||||
|
|
||||||
# Configure Xvfb via environment variables:
|
# Configure Xvfb via environment variables:
|
||||||
ENV WIDTH 1280
|
ENV WIDTH 1920
|
||||||
ENV HEIGHT 1280
|
ENV HEIGHT 1080
|
||||||
ENV DEPTH 24
|
ENV DEPTH 24
|
||||||
|
|
||||||
# Show browser instead of running headless
|
# Show browser instead of running headless
|
||||||
ENV SHOW 1
|
ENV SHOW 1
|
||||||
|
|
||||||
|
USER fgc
|
||||||
|
|
||||||
# Script to setup display server & VNC is always executed.
|
# Script to setup display server & VNC is always executed.
|
||||||
ENTRYPOINT ["docker-entrypoint.sh"]
|
ENTRYPOINT ["docker-entrypoint.sh"]
|
||||||
# Default command to run. This is replaced by appending own command, e.g. `docker run ... node prime-gaming` to only run this script.
|
# Default command to run. This is replaced by appending own command, e.g. `docker run ... node prime-gaming` to only run this script.
|
||||||
|
|
|
||||||
661
LICENSE
Normal file
661
LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published
|
||||||
|
by the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
255
README.md
255
README.md
|
|
@ -1,191 +1,88 @@
|
||||||
<p align="center">
|
Free Games Claimer (Fork)
|
||||||
<img alt="logo-free-games-claimer" src="https://user-images.githubusercontent.com/493741/214588518-a4c89998-127e-4a8c-9b1e-ee4a9d075715.png" />
|
==========================
|
||||||
</p>
|
|
||||||
|
|
||||||
# free-games-claimer
|
[](https://sonata.cyber77.de/dashboard?id=free-games-claimer)
|
||||||
|
|
||||||
Claims free games periodically on
|
Automates claiming of free games for:
|
||||||
- <img src="https://upload.wikimedia.org/wikipedia/commons/3/31/Epic_Games_logo.svg" width="32"/> [Epic Games Store](https://www.epicgames.com/store/free-games)
|
- Amazon Luna Gaming / Luna claims (including external stores like GOG, Epic Games, Legacy Games )
|
||||||
- <img src="https://seeklogo.com/images/P/prime-gaming-logo-61A701B3F5-seeklogo.com.png" width="32"/> [Amazon Prime Gaming](https://gaming.amazon.com)
|
- GOG giveaways
|
||||||
- <img src="https://static.wikia.nocookie.net/this-war-of-mine/images/1/1a/Logo_GoG.png/revision/latest?cb=20160711062658" width="32"/> [GOG](https://www.gog.com)
|
- Optional extras: Steam stats, AliExpress dailies (not implemated yet)
|
||||||
- <img src="https://www.freepnglogos.com/uploads/xbox-logo-picture-png-14.png" width="32"/> [Xbox Live Games with Gold](https://www.xbox.com/en-US/live/gold#gameswithgold) - planned
|
|
||||||
|
|
||||||
Pull requests welcome :)
|
Requirements
|
||||||
|
------------
|
||||||
|
- Docker or Podman (recommended), or Node.js ≥ 20 for local runs
|
||||||
|
- Optional notifications: `pip install apprise`
|
||||||
|
- Playwright dependencies are baked into the container; locally, `npm install` downloads Firefox.
|
||||||
|
|
||||||

|
Quickstart (Docker Run)
|
||||||
|
-----------------------
|
||||||
_Works on Windows/macOS/Linux._
|
|
||||||
|
|
||||||
Raspberry Pi (3, 4, Zero 2): Raspbian won't work since it's 32-bit, but Raspberry Pi OS (64-bit) or Ubuntu will.
|
|
||||||
|
|
||||||
## How to run
|
|
||||||
[Install Docker](https://docs.docker.com/get-docker/) and use
|
|
||||||
```
|
```
|
||||||
docker run --rm -it -p 6080:6080 -v fgc:/fgc/data --pull=always ghcr.io/vogler/free-games-claimer
|
docker run --rm -it \
|
||||||
|
-p 6080:6080 \
|
||||||
|
-v fgc:/fgc/data \
|
||||||
|
-e SHOW=1 \
|
||||||
|
git.sky-net.it/nocci/free-games-claimer:latest \
|
||||||
|
node prime-gaming.js
|
||||||
```
|
```
|
||||||
which 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.
|
- Ports 6080/5900: noVNC/VNC (only needed with `SHOW=1`)
|
||||||
Data (including json files with claimed games, codes to redeem, screenshots) is stored in the Docker volume `fgc`.
|
- Data/configs are stored in volume `fgc` under `/fgc/data`
|
||||||
|
|
||||||
<details>
|
Docker Compose Example
|
||||||
<summary>I want to run without Docker or develop locally.</summary>
|
----------------------
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
fgc:
|
||||||
|
image: git.sky-net.it/nocci/free-games-claimer:latest
|
||||||
|
container_name: fgc
|
||||||
|
environment:
|
||||||
|
- SHOW=1 # show browser via VNC/noVNC
|
||||||
|
# - PG_EMAIL=...
|
||||||
|
# - PG_PASSWORD=...
|
||||||
|
# - PG_OTPKEY=...
|
||||||
|
volumes:
|
||||||
|
- fgc:/fgc/data
|
||||||
|
ports:
|
||||||
|
- "6080:6080" # noVNC
|
||||||
|
# - "5900:5900" # VNC optional
|
||||||
|
command: bash -c "node epic-games; node prime-gaming; node gog"
|
||||||
|
volumes:
|
||||||
|
fgc:
|
||||||
|
```
|
||||||
|
|
||||||
1. [Install Node.js](https://nodejs.org/en/download)
|
Configuration (Environment Variables)
|
||||||
2. Clone/download this repository and `cd` into it in a terminal
|
-------------------------------------
|
||||||
3. Run `npm install && npx playwright install firefox`
|
Common options:
|
||||||
4. Run `pip install apprise` to install [apprise](https://github.com/caronc/apprise) if you want notifications
|
- `SHOW=0/1` (0 = headless, 1 = UI)
|
||||||
|
- `WIDTH`, `HEIGHT` (browser size)
|
||||||
|
- `TIMEOUT`, `LOGIN_TIMEOUT` (seconds)
|
||||||
|
- Login: `EMAIL`, `PASSWORD` global; per store `EG_EMAIL`, `EG_PASSWORD`, `EG_OTPKEY`, `PG_EMAIL`, `PG_PASSWORD`, `PG_OTPKEY`, `GOG_EMAIL`, `GOG_PASSWORD`
|
||||||
|
- Prime Gaming: `PG_REDEEM=1` (auto-redeem keys, experimental), `PG_CLAIMDLC=1`, `PG_TIMELEFT=<days>` to skip long-remaining offers
|
||||||
|
- Screenshots: `SCREENSHOTS_DIR` (default `data/screenshots`)
|
||||||
|
- Notifications: `NOTIFY='...'` (Apprise URL), optional `NOTIFY_TITLE`
|
||||||
|
- Browser profile: `BROWSER_DIR` (default `data/browser`)
|
||||||
|
- Recording: `RECORD=1` to save videos/HAR to `data/record/`
|
||||||
|
- Debugging: `DEBUG=1` (opens Playwright inspector), `DEBUG_NETWORK=1` (logs requests), `TIME=1` (prints timings)
|
||||||
|
- Dry run / Interaction: `DRYRUN=1` (do not claim), `INTERACTIVE=1` (ask before claiming), `HEADLESS` is derived from `SHOW`/`DEBUG`
|
||||||
|
- Directories: `SCREENSHOTS_DIR`, `BROWSER_DIR`, `DATA_DIR` (prefix for data; default under `data/`)
|
||||||
|
- VNC/noVNC: `VNC_PASSWORD` (for Docker entrypoint), `NOVNC_PORT`/`VNC_PORT` (Docker)
|
||||||
|
- General timeouts: `TIMEOUT` (per action), `LOGIN_TIMEOUT` (extra time for login)
|
||||||
|
|
||||||
This downloads Firefox to a cache in home ([doc](https://playwright.dev/docs/browsers#managing-browser-binaries)).
|
You can place a `data/config.env`; it is loaded via dotenv and is overridden by explicitly set environment variables.
|
||||||
If you are missing some dependencies for the browser on your system, you can use `sudo npx playwright install firefox --with-deps`.
|
|
||||||
|
|
||||||
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.
|
Local Run Without Docker
|
||||||
</details>
|
------------------------
|
||||||
|
```
|
||||||
|
npm install
|
||||||
|
SHOW=0 PG_EMAIL=... PG_PASSWORD=... PG_OTPKEY=... node prime-gaming.js
|
||||||
|
```
|
||||||
|
- Playwright downloads Firefox to `~/.cache/ms-playwright`.
|
||||||
|
- Use `SHOW=1` for a visible browser (requires GUI/Xvfb).
|
||||||
|
|
||||||
## Usage
|
Persistence & Outputs
|
||||||
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.
|
---------------------
|
||||||
|
- Data/status: `data/*.json` (per store)
|
||||||
|
- Browser profile: `data/browser`
|
||||||
|
- Screenshots: `data/screenshots/<store>/`
|
||||||
|
- Optional videos/HAR: `RECORD=1` → `data/record/`
|
||||||
|
|
||||||
- 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).
|
Tip: For captchas or first-time login, run with `SHOW=1` and log in once; cookies stay in the profile. Notifications via `NOTIFY` help surface errors (e.g., captcha, login).
|
||||||
- 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).
|
|
||||||
|
|
||||||
When running the first time, you have to login for each store you want to claim games on.
|
|
||||||
You can login indirectly via the terminal or directly in the browser. The scripts will wait until you are successfully logged in.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Configuration / Options
|
|
||||||
Options are set via [environment variables](https://kinsta.com/knowledgebase/what-is-an-environment-variable/) which allow for flexible configuration.
|
|
||||||
|
|
||||||
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.~~
|
|
||||||
|
|
||||||
Available options/variables and their default values:
|
|
||||||
|
|
||||||
| Option | Default | Description |
|
|
||||||
|--------------- |--------- |------------------------------------------------------------------------ |
|
|
||||||
| SHOW | 1 | Show browser if 1. Default for Docker, not shown when running outside. |
|
|
||||||
| WIDTH | 1280 | Width of the opened browser (and screen vor VNC in Docker). |
|
|
||||||
| HEIGHT | 1280 | Height of the opened browser (and screen vor VNC in Docker). |
|
|
||||||
| VNC_PASSWORD | | VNC password for Docker. No password used by default! |
|
|
||||||
| NOTIFY | | Notification services to use (Pushover, Slack, Telegram...), see below. |
|
|
||||||
| EMAIL | | Default email for any login. |
|
|
||||||
| PASSWORD | | Default password for any login. |
|
|
||||||
| EG_EMAIL | | Epic Games email for login. Overrides EMAIL. |
|
|
||||||
| EG_PASSWORD | | Epic Games password for login. Overrides PASSWORD. |
|
|
||||||
| EG_OTPKEY | | Epic Games MFA OTP key. |
|
|
||||||
| PG_EMAIL | | Prime Gaming email for login. Overrides EMAIL. |
|
|
||||||
| PG_PASSWORD | | Prime Gaming password for login. Overrides PASSWORD. |
|
|
||||||
| PG_OTPKEY | | Prime Gaming MFA OTP key. |
|
|
||||||
| GOG_EMAIL | | GOG email for login. Overrides EMAIL. |
|
|
||||||
| GOG_PASSWORD | | GOG password for login. Overrides PASSWORD. |
|
|
||||||
|
|
||||||
See `config.js` for all options.
|
|
||||||
|
|
||||||
#### How to set options
|
|
||||||
You can put options in `data/config.env` which will be loaded by [dotenv](https://github.com/motdotla/dotenv).
|
|
||||||
|
|
||||||
On Linux/macOS you can also 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.
|
|
||||||
|
|
||||||
For Docker you can pass variables using `-e VAR=VAL`, for example `docker run -e EMAIL=foo@bar.baz ...` or using `--env-file` (see [docs](https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables--e---env---env-file)). If you are using [docker compose](https://docs.docker.com/compose/environment-variables/), you can put them in the `environment:` section.
|
|
||||||
|
|
||||||
### Notifications
|
|
||||||
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).
|
|
||||||
|
|
||||||
[apprise](https://github.com/caronc/apprise) is used for notifications and offers many services including Pushover, Slack, Telegram, SMS, Email, desktop and custom notifications.
|
|
||||||
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).
|
|
||||||
|
|
||||||
### Automatic login, two-factor authentication
|
|
||||||
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.
|
|
||||||
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.
|
|
||||||
|
|
||||||
- **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`.
|
|
||||||
- **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`
|
|
||||||
- **GOG**: only offers OTP via email
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Epic Games Store
|
|
||||||
Run `node epic-games` (locally or in Docker).
|
|
||||||
|
|
||||||
### Amazon Prime Gaming
|
|
||||||
Run `node prime-gaming` (locally or in Docker).
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
- Stores that require account linking: Epic Games, Battle.net.
|
|
||||||
- Stores that require redeeming a key: Origin, GOG.com, Microsoft Games, Legacy Games.
|
|
||||||
|
|
||||||
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`.
|
|
||||||
[TODO](https://github.com/vogler/free-games-claimer/issues/5): ~~redeem keys on external stores.~~
|
|
||||||
|
|
||||||
### Run periodically
|
|
||||||
#### How often?
|
|
||||||
Epic Games usually has two free games *every week*, before Christmas every day.
|
|
||||||
Prime Gaming has new games *every month* or more often during Prime days.
|
|
||||||
GOG usually has one new game every couples of weeks.
|
|
||||||
|
|
||||||
It is save to run the scripts every day.
|
|
||||||
|
|
||||||
#### How to schedule?
|
|
||||||
The container/scripts will claim currently available games and then exit.
|
|
||||||
If you want it to run regularly, you have to schedule the runs yourself:
|
|
||||||
|
|
||||||
- Linux/macOS: `crontab -e`
|
|
||||||
- macOS: [launchd](https://stackoverflow.com/questions/132955/how-do-i-set-a-task-to-run-every-so-often)
|
|
||||||
- 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), [other options](https://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron)
|
|
||||||
|
|
||||||
TODO: ~~add some server-mode where the script just keeps running and claims games e.g. every day.~~
|
|
||||||
|
|
||||||
### Problems?
|
|
||||||
|
|
||||||
Check the open [issues](https://github.com/vogler/free-games-claimer/issues) and comment there or open a new issue.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
|
|
||||||
## History/DevLog
|
|
||||||
<details>
|
|
||||||
<summary>Click to expand</summary>
|
|
||||||
|
|
||||||
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)).
|
|
||||||
|
|
||||||
Played around with puppeteer before, now trying newer https://playwright.dev which is pretty similar.
|
|
||||||
Playwright Inspector and `codegen` to generate scripts are nice, but failed to generate the right code for clicking a button in an iframe.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
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)).
|
|
||||||
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.
|
|
||||||
Also, solving via [2captcha](https://2captcha.com?from=13225256) is a paid service which takes time and may be unreliable.
|
|
||||||
<!-- Alternative: https://anti-captcha.com -->
|
|
||||||
|
|
||||||
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)).
|
|
||||||
The listed evasions are enough to not show an hcaptcha. Script claimed game successfully in non-headless mode.
|
|
||||||
|
|
||||||
Removed `main.captcha.js`.
|
|
||||||
Using Playwright Test (`main.spec.ts`) instead of Library (`main.stealth.js`) has the advantage of free CLI like `--debug` and `--timeout`.
|
|
||||||
<!-- TODO: check if stealth plugin can be setup with `contextOptions` ([doc](https://playwright.dev/docs/test-configuration#more-browser-and-context-options)). -->
|
|
||||||
|
|
||||||
Button selectors should preferably use text in order to be more stable against changes in the DOM.
|
|
||||||
|
|
||||||
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`.
|
|
||||||
|
|
||||||
epic games: `headless` mode gets hcaptcha challenge. More details/references in [issue](https://github.com/vogler/free-games-claimer/issues/2).
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
v1.0 Standalone scripts node epic-games and node prime-gaming using Chromium.
|
|
||||||
|
|
||||||
Changed to Firefox for all scripts since Chromium led to captchas. Claiming then also worked in headless mode without Docker.
|
|
||||||
|
|
||||||
Added options via env vars, configurable in `data/config.env`.
|
|
||||||
|
|
||||||
Added OTP generation via otplib for automatic login, even with 2FA.
|
|
||||||
|
|
||||||
Added notifications via [apprise](https://github.com/caronc/apprise).
|
|
||||||
</details>
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
Logo with smaller aspect ratio (for Telegram bot etc.): 👾 - [emojipedia](https://emojipedia.org/alien-monster/)
|
|
||||||
|
|
||||||

|
|
||||||
|
|
|
||||||
113
aliexpress.js
Normal file
113
aliexpress.js
Normal file
|
|
@ -0,0 +1,113 @@
|
||||||
|
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||||
|
import { datetime, filenamify, prompt, handleSIGINT } from './src/util.js';
|
||||||
|
import { cfg } from './src/config.js';
|
||||||
|
|
||||||
|
// using https://github.com/apify/fingerprint-suite worked, but has no launchPersistentContext...
|
||||||
|
// from https://github.com/apify/fingerprint-suite/issues/162
|
||||||
|
import { FingerprintInjector } from 'fingerprint-injector';
|
||||||
|
import { FingerprintGenerator } from 'fingerprint-generator';
|
||||||
|
|
||||||
|
const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({
|
||||||
|
devices: ['mobile'],
|
||||||
|
operatingSystems: ['android'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||||
|
headless: cfg.headless,
|
||||||
|
locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL
|
||||||
|
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined, // will record a .webm video for each page navigated; without size, video would be scaled down to fit 800x800
|
||||||
|
recordHar: cfg.record ? { path: `data/record/aliexpress-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools
|
||||||
|
handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved
|
||||||
|
userAgent: fingerprint.navigator.userAgent,
|
||||||
|
viewport: {
|
||||||
|
width: fingerprint.screen.width,
|
||||||
|
height: fingerprint.screen.height,
|
||||||
|
},
|
||||||
|
extraHTTPHeaders: {
|
||||||
|
'accept-language': headers['accept-language'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
handleSIGINT(context);
|
||||||
|
await new FingerprintInjector().attachFingerprintToPlaywright(context, { fingerprint, headers });
|
||||||
|
|
||||||
|
context.setDefaultTimeout(cfg.debug ? 0 : cfg.timeout);
|
||||||
|
|
||||||
|
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||||
|
|
||||||
|
const auth = async url => {
|
||||||
|
console.log('auth', url);
|
||||||
|
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||||
|
// redirects to https://login.aliexpress.com/?return_url=https%3A%2F%2Fwww.aliexpress.com%2Fp%2Fcoin-pc-index%2Findex.html
|
||||||
|
await Promise.any([page.waitForURL(url => url.includes('login.aliexpress.com')).then(async () => {
|
||||||
|
console.error('Not logged in! Will wait for 120s for you to login...');
|
||||||
|
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
|
||||||
|
const login = page.locator('.login-container');
|
||||||
|
const email = cfg.ae_email || await prompt({ message: 'Enter email' });
|
||||||
|
const emailInput = login.locator('input[label="Email or phone number"]');
|
||||||
|
await emailInput.fill(email);
|
||||||
|
await emailInput.blur(); // otherwise Continue button stays disabled
|
||||||
|
const continueButton = login.locator('button:has-text("Continue")');
|
||||||
|
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
|
||||||
|
await continueButton.click();
|
||||||
|
const password = email && (cfg.ae_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||||
|
await login.locator('input[label="Password"]').fill(password);
|
||||||
|
await login.locator('button:has-text("Sign in")').click();
|
||||||
|
const error = login.locator('.error-text');
|
||||||
|
error.waitFor().then(async () => console.error('Login error:', await error.innerText()));
|
||||||
|
await page.waitForURL(url);
|
||||||
|
page.getByRole('button', { name: 'Accept cookies' }).click().then(() => console.log('Accepted cookies')).catch(() => { });
|
||||||
|
}), page.locator('#nav-user-account').waitFor()]).catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
// copied URLs from AliExpress app on tablet which has menu for the used webview
|
||||||
|
const urls = {
|
||||||
|
// works with desktop view, but stuck at 100% loading in mobile view:
|
||||||
|
coins: 'https://www.aliexpress.com/p/coin-pc-index/index.html',
|
||||||
|
// only work with mobile view:
|
||||||
|
grow: 'https://m.aliexpress.com/p/ae_fruit/index.html', // firefox: stuck at 60% loading, chrome: loads, but canvas
|
||||||
|
gogo: 'https://m.aliexpress.com/p/gogo-match-cc/index.html', // closes firefox?!
|
||||||
|
// only show notification to install the app
|
||||||
|
euro: 'https://m.aliexpress.com/p/european-cup/index.html', // doesn't load
|
||||||
|
merge: 'https://m.aliexpress.com/p/merge-market/index.html',
|
||||||
|
};
|
||||||
|
|
||||||
|
/* eslint-disable no-unused-vars */
|
||||||
|
const coins = async () => {
|
||||||
|
await Promise.any([page.locator('.checkin-button').click(), page.locator('.addcoin').waitFor()]);
|
||||||
|
console.log('Coins:', await page.locator('.mycoin-content-right-money').innerText());
|
||||||
|
console.log('Streak:', await page.locator('.title-box').innerText());
|
||||||
|
console.log('Tomorrow:', await page.locator('.addcoin').innerText());
|
||||||
|
};
|
||||||
|
|
||||||
|
const grow = async () => {
|
||||||
|
await page.pause();
|
||||||
|
};
|
||||||
|
|
||||||
|
const gogo = async () => {
|
||||||
|
await page.pause();
|
||||||
|
};
|
||||||
|
|
||||||
|
const euro = async () => {
|
||||||
|
await page.pause();
|
||||||
|
};
|
||||||
|
|
||||||
|
const merge = async () => {
|
||||||
|
await page.pause();
|
||||||
|
};
|
||||||
|
/* eslint-enable no-unused-vars */
|
||||||
|
|
||||||
|
try {
|
||||||
|
await [
|
||||||
|
merge,
|
||||||
|
].reduce((a, f) => a.then(async () => {
|
||||||
|
await auth(urls[f.name]);
|
||||||
|
await f();
|
||||||
|
console.log();
|
||||||
|
}), Promise.resolve());
|
||||||
|
} catch (error) {
|
||||||
|
process.exitCode ||= 1;
|
||||||
|
console.error('--- Exception:');
|
||||||
|
console.error(error); // .toString()?
|
||||||
|
}
|
||||||
|
if (page.video()) console.log('Recorded video:', await page.video().path());
|
||||||
|
await context.close();
|
||||||
27
config.js
27
config.js
|
|
@ -1,27 +0,0 @@
|
||||||
import * as dotenv from 'dotenv';
|
|
||||||
dotenv.config({ path: 'data/config.env' }); // loads env vars from file - will not set vars that are already set, i.e., can overwrite values from file by prefixing, e.g., VAR=VAL node ...
|
|
||||||
|
|
||||||
// Options - also see table in README.md
|
|
||||||
export const cfg = {
|
|
||||||
debug: process.env.PWDEBUG == '1', // runs non-headless and opens https://playwright.dev/docs/inspector
|
|
||||||
dryrun: process.env.DRYRUN == '1', // don't claim anything
|
|
||||||
show: process.env.SHOW == '1', // run non-headless
|
|
||||||
get headless() { return !this.debug && !this.show },
|
|
||||||
width: Number(process.env.WIDTH) || 1280, // width of the opened browser
|
|
||||||
height: Number(process.env.HEIGHT) || 1280, // height of the opened browser
|
|
||||||
timeout: (Number(process.env.TIMEOUT) || 20) * 1000, // 20s, default for playwright is 30s
|
|
||||||
novnc_port: process.env.NOVNC_PORT, // running in docker if set
|
|
||||||
notify: process.env.NOTIFY, // apprise notification services
|
|
||||||
// auth epic-games
|
|
||||||
eg_email: process.env.EG_EMAIL || process.env.EMAIL,
|
|
||||||
eg_password: process.env.EG_PASSWORD || process.env.PASSWORD,
|
|
||||||
eg_otpkey: process.env.EG_OTPKEY,
|
|
||||||
// auth prime-gaming
|
|
||||||
pg_email: process.env.PG_EMAIL || process.env.EMAIL,
|
|
||||||
pg_password: process.env.PG_PASSWORD || process.env.PASSWORD,
|
|
||||||
pg_otpkey: process.env.PG_OTPKEY,
|
|
||||||
// auth gog
|
|
||||||
gog_email: process.env.GOG_EMAIL || process.env.EMAIL,
|
|
||||||
gog_password: process.env.GOG_PASSWORD || process.env.PASSWORD,
|
|
||||||
// OTP only via GOG_EMAIL, can't add app...
|
|
||||||
};
|
|
||||||
|
|
@ -9,3 +9,7 @@ services:
|
||||||
- "6080:6080" # noVNC (browser-based VNC client)
|
- "6080:6080" # noVNC (browser-based VNC client)
|
||||||
volumes:
|
volumes:
|
||||||
- fgc:/fgc/data
|
- fgc:/fgc/data
|
||||||
|
# command: bash -c "node epic-games; node gog"
|
||||||
|
environment:
|
||||||
|
# - EMAIL=foo@bar.org
|
||||||
|
# - NOTIFY='tgram://...'
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,47 @@
|
||||||
#!/bin/bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
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
|
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
|
||||||
|
|
||||||
|
echo "Version: https://github.com/vogler/free-games-claimer/tree/${COMMIT}"
|
||||||
|
[ ! -z $BRANCH ] && [ $BRANCH != "main" ] && echo "Branch: ${BRANCH}"
|
||||||
|
echo "Build: $NOW"
|
||||||
|
|
||||||
# Remove chromium profile lock.
|
# Remove chromium profile lock.
|
||||||
# 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.
|
# 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.
|
||||||
# Maybe due to changed hostname of container or due to how the docker container kills playwright - didn't check.
|
# Maybe due to changed hostname of container or due to how the docker container kills playwright - didn't check.
|
||||||
# https://bugs.chromium.org/p/chromium/issues/detail?id=367048
|
# https://bugs.chromium.org/p/chromium/issues/detail?id=367048
|
||||||
rm -f /fgc/data/browser/SingletonLock
|
rm -f /fgc/data/browser/SingletonLock 2>/dev/null || true
|
||||||
|
|
||||||
|
# Firefox preferences are stored in $BROWSER_DIR/pref.js and can be overridden by a file user.js
|
||||||
|
# Since this file has to be in the volume (data/browser), we can't do this in Dockerfile.
|
||||||
|
mkdir -p /fgc/data/browser
|
||||||
|
# clean up stale firefox locks that can trigger "already running"
|
||||||
|
rm -f /fgc/data/browser/parent.lock /fgc/data/browser/lock /fgc/data/browser/.parentlock 2>/dev/null || true
|
||||||
|
# fix for 'Incorrect response' after solving a captcha correctly - https://github.com/vogler/free-games-claimer/issues/261#issuecomment-1868385830
|
||||||
|
# Only write the prefs file when the volume is writable (container runs as non-root).
|
||||||
|
if [ -w /fgc/data/browser ] && { [ ! -e /fgc/data/browser/user.js ] || [ -w /fgc/data/browser/user.js ] || rm -f /fgc/data/browser/user.js 2>/dev/null; }; then
|
||||||
|
cat << 'EOT' > /fgc/data/browser/user.js
|
||||||
|
user_pref("privacy.resistFingerprinting", true);
|
||||||
|
// user_pref("privacy.resistFingerprinting.letterboxing", true);
|
||||||
|
// user_pref("browser.contentblocking.category", "strict");
|
||||||
|
// user_pref("webgl.disabled", true);
|
||||||
|
EOT
|
||||||
|
else
|
||||||
|
echo "Warning: /fgc/data/browser not writable; skipping user.js creation."
|
||||||
|
fi
|
||||||
|
# TODO disable session restore message?
|
||||||
|
|
||||||
# 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
|
# 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
|
||||||
# echo $DISPLAY
|
# echo $DISPLAY
|
||||||
# ls -l /tmp/.X11-unix/
|
# ls -l /tmp/.X11-unix/
|
||||||
rm -f /tmp/.X1-lock
|
rm -f /tmp/.X1-lock
|
||||||
|
|
||||||
|
# Ensure X11 socket dir exists with sane ownership/permissions.
|
||||||
|
mkdir -p /tmp/.X11-unix
|
||||||
|
if [ "$(stat -c %U /tmp/.X11-unix 2>/dev/null)" != "root" ]; then
|
||||||
|
chown root:root /tmp/.X11-unix 2>/dev/null || chmod 1777 /tmp/.X11-unix
|
||||||
|
fi
|
||||||
|
|
||||||
# 6000+SERVERNUM is the TCP port Xvfb is listening on:
|
# 6000+SERVERNUM is the TCP port Xvfb is listening on:
|
||||||
# SERVERNUM=$(echo "$DISPLAY" | sed 's/:\([0-9][0-9]*\).*/\1/')
|
# SERVERNUM=$(echo "$DISPLAY" | sed 's/:\([0-9][0-9]*\).*/\1/')
|
||||||
|
|
||||||
|
|
@ -23,11 +52,23 @@ rm -f /tmp/.X1-lock
|
||||||
export DISPLAY=:1 # need to export this, otherwise playwright complains with 'Looks like you launched a headed browser without having a XServer running.'
|
export DISPLAY=:1 # need to export this, otherwise playwright complains with 'Looks like you launched a headed browser without having a XServer running.'
|
||||||
Xvfb $DISPLAY -ac -screen 0 "${WIDTH}x${HEIGHT}x${DEPTH}" &
|
Xvfb $DISPLAY -ac -screen 0 "${WIDTH}x${HEIGHT}x${DEPTH}" &
|
||||||
echo "Xvfb display server created screen with resolution ${WIDTH}x${HEIGHT}"
|
echo "Xvfb display server created screen with resolution ${WIDTH}x${HEIGHT}"
|
||||||
|
if [ -z "$VNC_PASSWORD" ]; then
|
||||||
pw="-nopw"
|
pw="-nopw"
|
||||||
[ -z "$VNC_PASSWORD" ] || pw="-passwd $VNC_PASSWORD"
|
pwt="no password!"
|
||||||
|
else
|
||||||
|
pw="-passwd $VNC_PASSWORD"
|
||||||
|
pwt="with password"
|
||||||
|
fi
|
||||||
x11vnc -display $DISPLAY -forever -shared -rfbport $VNC_PORT -bg $pw 2>/dev/null 1>&2
|
x11vnc -display $DISPLAY -forever -shared -rfbport $VNC_PORT -bg $pw 2>/dev/null 1>&2
|
||||||
echo "VNC is running on port $VNC_PORT (no password!)"
|
echo "VNC is running on port $VNC_PORT ($pwt)"
|
||||||
websockify -D --web "/usr/share/novnc/" $NOVNC_PORT "localhost:$VNC_PORT" 2>/dev/null 1>&2 &
|
websockify -D --web "/usr/share/novnc/" $NOVNC_PORT "localhost:$VNC_PORT" 2>/dev/null 1>&2 &
|
||||||
echo "noVNC (VNC via browser) is running on http://localhost:$NOVNC_PORT"
|
echo "noVNC (VNC via browser) is running on http://localhost:$NOVNC_PORT"
|
||||||
echo
|
echo
|
||||||
|
|
||||||
|
# Ensure Playwright browsers are available (chromium + firefox).
|
||||||
|
if [ ! -x /home/fgc/.cache/ms-playwright/firefox-1482/firefox/firefox ] || ! ls /home/fgc/.cache/ms-playwright/chromium-*/*/chrome >/dev/null 2>&1; then
|
||||||
|
echo "Playwright browsers missing; installing..."
|
||||||
|
npx playwright install chromium firefox || echo "Warning: failed to install Playwright browsers" >&2
|
||||||
|
fi
|
||||||
|
|
||||||
exec tini -g -- "$@" # https://github.com/krallin/tini/issues/8 node/playwright respond to signals like ctrl-c, but unsure about zombie processes
|
exec tini -g -- "$@" # https://github.com/krallin/tini/issues/8 node/playwright respond to signals like ctrl-c, but unsure about zombie processes
|
||||||
|
|
|
||||||
357
epic-games.js
357
epic-games.js
|
|
@ -1,203 +1,360 @@
|
||||||
import { firefox } from 'playwright'; // stealth plugin needs no outdated playwright-extra
|
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||||
import { authenticator } from 'otplib';
|
import { authenticator } from 'otplib';
|
||||||
import path from 'path';
|
import chalk from 'chalk';
|
||||||
import { existsSync, writeFileSync } from 'fs';
|
import path from 'node:path';
|
||||||
import { dirs, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list } from './util.js';
|
import { existsSync, writeFileSync, appendFileSync } from 'node:fs';
|
||||||
import { cfg } from './config.js';
|
import { resolve, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js';
|
||||||
|
import { cfg } from './src/config.js';
|
||||||
|
|
||||||
|
const screenshot = (...a) => resolve(cfg.dir.screenshots, 'epic-games', ...a);
|
||||||
|
|
||||||
const URL_CLAIM = 'https://store.epicgames.com/en-US/free-games';
|
const URL_CLAIM = 'https://store.epicgames.com/en-US/free-games';
|
||||||
const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM;
|
const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM;
|
||||||
|
|
||||||
console.log(datetime(), 'started checking epic-games');
|
console.log(datetime(), 'started checking epic-games');
|
||||||
|
|
||||||
const db = await jsonDb('epic-games.json');
|
const db = await jsonDb('epic-games.json', {});
|
||||||
db.data ||= {};
|
|
||||||
const migrateDb = (user) => {
|
|
||||||
if (user in db.data || !('claimed' in db.data)) return;
|
|
||||||
db.data[user] = {};
|
|
||||||
for (const e of db.data.claimed) {
|
|
||||||
const k = e.url.split('/').pop();
|
|
||||||
db.data[user][k] = e;
|
|
||||||
}
|
|
||||||
delete db.data.claimed;
|
|
||||||
delete db.data.runs;
|
|
||||||
}
|
|
||||||
|
|
||||||
// https://www.nopecha.com extension source from https://github.com/NopeCHA/NopeCHA/releases/tag/0.1.16
|
if (cfg.time) console.time('startup');
|
||||||
const ext = path.resolve('nopecha'); // used in Chromium, currently not needed in Firefox
|
|
||||||
|
const browserPrefs = path.join(cfg.dir.browser, 'prefs.js');
|
||||||
|
if (existsSync(browserPrefs)) {
|
||||||
|
console.log('Adding webgl.disabled to', browserPrefs);
|
||||||
|
appendFileSync(browserPrefs, 'user_pref("webgl.disabled", true);'); // apparently Firefox removes duplicates (and sorts), so no problem appending every time
|
||||||
|
} else {
|
||||||
|
console.log(browserPrefs, 'does not exist yet, will patch it on next run. Restart the script if you get a captcha.');
|
||||||
|
}
|
||||||
|
|
||||||
// https://playwright.dev/docs/auth#multi-factor-authentication
|
// https://playwright.dev/docs/auth#multi-factor-authentication
|
||||||
const context = await firefox.launchPersistentContext(dirs.browser, {
|
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||||
// chrome will not work in linux arm64, only chromium
|
|
||||||
// channel: 'chrome', // https://playwright.dev/docs/browsers#google-chrome--microsoft-edge
|
|
||||||
headless: cfg.headless,
|
headless: cfg.headless,
|
||||||
viewport: { width: cfg.width, height: cfg.height },
|
viewport: { width: cfg.width, height: cfg.height },
|
||||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36', // see replace of Headless in util.newStealthContext. TODO Windows UA enough to avoid 'device not supported'? update if browser is updated?
|
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0', // Windows UA avoids "device not supported"; update when browser version changes
|
||||||
// userAgent for firefox: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:106.0) Gecko/20100101 Firefox/106.0
|
locale: 'en-US', // ignore OS locale to be sure to have english text for locators
|
||||||
locale: "en-US", // ignore OS locale to be sure to have english text for locators
|
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
|
||||||
// recordVideo: { dir: 'data/videos/' }, // will record a .webm video for each page navigated
|
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
|
||||||
args: [ // https://peter.sh/experiments/chromium-command-line-switches
|
handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved
|
||||||
// don't want to see bubble 'Restore pages? Chrome didn't shut down correctly.'
|
// user settings for firefox have to be put in $BROWSER_DIR/user.js
|
||||||
// '--restore-last-session', // does not apply for crash/killed
|
args: [], // https://wiki.mozilla.org/Firefox/CommandLineOptions
|
||||||
'--hide-crash-restore-bubble',
|
|
||||||
// `--disable-extensions-except=${ext}`,
|
|
||||||
// `--load-extension=${ext}`,
|
|
||||||
],
|
|
||||||
// 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.'.
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
handleSIGINT(context);
|
||||||
|
|
||||||
// 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.
|
// 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.
|
||||||
await stealth(context);
|
await stealth(context);
|
||||||
|
|
||||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
|
|
||||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||||
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||||
|
|
||||||
|
// some debug info about the page (screen dimensions, user agent)
|
||||||
|
if (cfg.debug) {
|
||||||
|
/* global window, navigator */
|
||||||
|
const debugInfo = await page.evaluate(() => {
|
||||||
|
const { width, height, availWidth, availHeight } = window.screen;
|
||||||
|
return {
|
||||||
|
screen: { width, height, availWidth, availHeight },
|
||||||
|
userAgent: navigator.userAgent,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.debug(debugInfo);
|
||||||
|
}
|
||||||
|
if (cfg.debug_network) {
|
||||||
|
// const filter = _ => true;
|
||||||
|
const filter = r => r.url().includes('store.epicgames.com');
|
||||||
|
page.on('request', request => filter(request) && console.log('>>', request.method(), request.url()));
|
||||||
|
page.on('response', response => filter(response) && console.log('<<', response.status(), response.url()));
|
||||||
|
}
|
||||||
|
|
||||||
const notify_games = [];
|
const notify_games = [];
|
||||||
|
let user;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await context.addCookies([{name: 'OptanonAlertBoxClosed', value: new Date(Date.now() - 5*24*60*60*1000).toISOString(), domain: '.epicgames.com', path: '/'}]); // Accept cookies to get rid of banner to save space on screen. Set accept time to 5 days ago.
|
await 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.
|
||||||
|
{ 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'
|
||||||
|
]);
|
||||||
|
|
||||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // 'domcontentloaded' faster than default 'load' https://playwright.dev/docs/api/class-page#page-goto
|
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // 'domcontentloaded' faster than default 'load' https://playwright.dev/docs/api/class-page#page-goto
|
||||||
|
|
||||||
// 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.
|
if (cfg.time) console.timeEnd('startup');
|
||||||
|
if (cfg.time) console.time('login');
|
||||||
|
|
||||||
while (await page.locator('a[role="button"]:has-text("Sign In")').count() > 0) {
|
while (await page.locator('egs-navigation').getAttribute('isloggedin') != 'true') {
|
||||||
console.error('Not signed in anymore. Please login in the browser or here in the terminal.');
|
console.error('Not signed in anymore. Please login in the browser or here in the terminal.');
|
||||||
if (cfg.novnc_port) console.info(`Open http://localhost:${cfg.novnc_port} to login inside the docker container.`);
|
if (cfg.novnc_port) console.info(`Open http://localhost:${cfg.novnc_port} to login inside the docker container.`);
|
||||||
context.setDefaultTimeout(0); // give user time to log in without timeout
|
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
|
||||||
|
console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`);
|
||||||
await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' });
|
await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' });
|
||||||
|
|
||||||
if (cfg.eg_email && cfg.eg_password) console.info('Using email and password from environment.');
|
if (cfg.eg_email && cfg.eg_password) console.info('Using email and password from environment.');
|
||||||
else console.info('Press ESC to skip if you want to login in the browser.');
|
else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).');
|
||||||
|
const notifyBrowserLogin = async () => {
|
||||||
|
console.log('Waiting for you to login in the browser.');
|
||||||
|
await notify('epic-games: no longer signed in and not enough options set for automatic login.');
|
||||||
|
if (cfg.headless) {
|
||||||
|
console.log('Run `SHOW=1 node epic-games` to login in the opened browser.');
|
||||||
|
await context.close(); // finishes potential recording
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
const email = cfg.eg_email || await prompt({ message: 'Enter email' });
|
const email = cfg.eg_email || await prompt({ message: 'Enter email' });
|
||||||
const password = email && (cfg.eg_password || await prompt({type: 'password', message: 'Enter password'}));
|
if (email) {
|
||||||
if (email && password) {
|
const watchCaptchaChallenge = async () => {
|
||||||
await page.click('text=Sign in with Epic Games');
|
try {
|
||||||
|
await page.waitForSelector('.h_captcha_challenge iframe', { timeout: 15000 });
|
||||||
|
console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
|
||||||
|
await notify('epic-games: got captcha during login. Please check.');
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const watchCaptchaIncorrect = async () => {
|
||||||
|
try {
|
||||||
|
await page.waitForSelector('p:has-text("Incorrect response.")', { timeout: 15000 });
|
||||||
|
console.error('Incorrect response for captcha!');
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
watchCaptchaChallenge();
|
||||||
|
watchCaptchaIncorrect();
|
||||||
await page.fill('#email', email);
|
await page.fill('#email', email);
|
||||||
|
const password = cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' });
|
||||||
|
if (password) {
|
||||||
await page.fill('#password', password);
|
await page.fill('#password', password);
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
page.waitForSelector('#h_captcha_challenge_login_prod iframe').then(() => {
|
} else await notifyBrowserLogin();
|
||||||
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.');
|
const error = page.locator('#form-error-message');
|
||||||
notify('epic-games: got captcha during login. Please check.');
|
const watchLoginError = async () => {
|
||||||
}).catch(_ => { });
|
try {
|
||||||
// handle MFA, but don't await it
|
await error.waitFor({ timeout: 15000 });
|
||||||
page.waitForURL('**/id/login/mfa**').then(async () => {
|
console.error('Login error:', await error.innerText());
|
||||||
|
console.log('Please login in the browser!');
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const watchMfaStep = async () => {
|
||||||
|
try {
|
||||||
|
await page.waitForURL('**/id/login/mfa**', { timeout: cfg.login_timeout });
|
||||||
console.log('Enter the security code to continue - This appears to be a new device, browser or location. A security code has been sent to your email address at ...');
|
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 ...');
|
||||||
// TODO locator for text (email or app?)
|
|
||||||
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
|
const otp = cfg.eg_otpkey && authenticator.generate(cfg.eg_otpkey) || await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||||
await page.type('input[name="code-input-0"]', otp.toString());
|
await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString());
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
}).catch(_ => { });
|
} catch {
|
||||||
} else {
|
return;
|
||||||
console.log('Waiting for you to login in the browser.');
|
|
||||||
notify('epic-games: no longer signed in and not enough options set for automatic login.');
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
watchLoginError();
|
||||||
|
watchMfaStep();
|
||||||
|
} else await notifyBrowserLogin();
|
||||||
await page.waitForURL(URL_CLAIM);
|
await page.waitForURL(URL_CLAIM);
|
||||||
context.setDefaultTimeout(cfg.timeout);
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
}
|
}
|
||||||
const user = await page.locator('#user span').first().innerHTML();
|
user = await page.locator('egs-navigation').getAttribute('displayname'); // 'null' if !isloggedin
|
||||||
console.log(`Signed in as ${user}`);
|
console.log(`Signed in as ${user}`);
|
||||||
migrateDb(user); // TODO remove this after some time since it will run fine without and people can still use this commit to adjust their data epic-games.json
|
|
||||||
db.data[user] ||= {};
|
db.data[user] ||= {};
|
||||||
|
if (cfg.time) console.timeEnd('login');
|
||||||
|
if (cfg.time) console.time('claim all games');
|
||||||
|
|
||||||
// Detect free games
|
// Detect free games
|
||||||
const game_loc = await page.locator('a:has(span:text-is("Free Now"))');
|
const game_loc = page.locator('a:has(span:text-is("Free Now"))');
|
||||||
await game_loc.last().waitFor();
|
await game_loc.last().waitFor().catch(_ => {
|
||||||
|
// rarely there are no free games available -> catch Timeout
|
||||||
|
// waiting for timeout; alternative would be waiting for "coming soon"
|
||||||
|
// see https://github.com/vogler/free-games-claimer/issues/210#issuecomment-1727420943
|
||||||
|
console.error('Seems like currently there are no free games available in your region...');
|
||||||
|
// urls below should then be an empty list
|
||||||
|
});
|
||||||
// clicking on `game_sel` sometimes led to a 404, see https://github.com/vogler/free-games-claimer/issues/25
|
// clicking on `game_sel` sometimes led to a 404, see https://github.com/vogler/free-games-claimer/issues/25
|
||||||
// debug showed that in those cases the href was still correct, so we `goto` the urls instead of clicking.
|
// debug showed that in those cases the href was still correct, so we `goto` the urls instead of clicking.
|
||||||
// Alternative: parse the json loaded to build the page https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions
|
// Alternative: parse the json loaded to build the page https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions
|
||||||
// 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
|
// 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
|
||||||
const urlSlugs = await Promise.all((await game_loc.elementHandles()).map(a => a.getAttribute('href')));
|
const urlSlugs = await Promise.all((await game_loc.elementHandles()).map(a => a.getAttribute('href')));
|
||||||
const urls = urlSlugs.map(s => 'https://store.epicgames.com' + s);
|
const urls = urlSlugs.map(s => 'https://store.epicgames.com' + s);
|
||||||
console.log('Free games:', urls);
|
console.log('Free games:', urls);
|
||||||
|
|
||||||
for (const url of urls) {
|
for (const url of urls) {
|
||||||
|
if (cfg.time) console.time('claim game');
|
||||||
await page.goto(url); // , { waitUntil: 'domcontentloaded' });
|
await page.goto(url); // , { waitUntil: 'domcontentloaded' });
|
||||||
const btnText = await page.locator('//button[@data-testid="purchase-cta-button"][not(contains(.,"Loading"))]').first().innerText(); // barrier to block until page is loaded
|
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
|
||||||
|
await purchaseBtn.waitFor();
|
||||||
|
const btnText = (await purchaseBtn.innerText()).toLowerCase(); // barrier to block until page is loaded
|
||||||
|
|
||||||
// click Continue if 'This game contains mature content recommended only for ages 18+'
|
// click Continue if 'This game contains mature content recommended only for ages 18+'
|
||||||
if (await page.locator('button:has-text("Continue")').count() > 0) {
|
if (await page.locator('button:has-text("Continue")').count() > 0) {
|
||||||
console.log(' This game contains mature content recommended only for ages 18+');
|
console.log(' This game contains mature content recommended only for ages 18+');
|
||||||
await page.click('button:has-text("Continue")');
|
if (await page.locator('[data-testid="AgeSelect"]').count()) {
|
||||||
|
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');
|
||||||
|
await page.locator('#month_toggle').click();
|
||||||
|
await page.locator('#month_menu li:has-text("01")').click();
|
||||||
|
await page.locator('#day_toggle').click();
|
||||||
|
await page.locator('#day_menu li:has-text("01")').click();
|
||||||
|
await page.locator('#year_toggle').click();
|
||||||
|
await page.locator('#year_menu li:has-text("1987")').click();
|
||||||
|
}
|
||||||
|
await page.click('button:has-text("Continue")', { delay: 111 });
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
const title = await page.locator('h1').first().innerText();
|
let title;
|
||||||
|
let bundle_includes;
|
||||||
|
if (await page.locator('span:text-is("About Bundle")').count()) {
|
||||||
|
title = (await page.locator('span:has-text("Buy"):left-of([data-testid="purchase-cta-button"])').first().innerText()).replace('Buy ', '');
|
||||||
|
// 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'
|
||||||
|
try {
|
||||||
|
bundle_includes = await Promise.all((await page.locator('.product-card-top-row h5').all()).map(b => b.innerText()));
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to get "Bundle Includes":', e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
title = await page.locator('h1').first().innerText();
|
||||||
|
}
|
||||||
const game_id = page.url().split('/').pop();
|
const game_id = page.url().split('/').pop();
|
||||||
|
const existedInDb = db.data[user][game_id];
|
||||||
db.data[user][game_id] ||= { title, time: datetime(), url: page.url() }; // this will be set on the initial run only!
|
db.data[user][game_id] ||= { title, time: datetime(), url: page.url() }; // this will be set on the initial run only!
|
||||||
console.log('Current free game:', title);
|
console.log('Current free game:', chalk.blue(title));
|
||||||
|
if (bundle_includes) console.log(' This bundle includes:', bundle_includes);
|
||||||
const notify_game = { title, url, status: 'failed' };
|
const notify_game = { title, url, status: 'failed' };
|
||||||
notify_games.push(notify_game); // status is updated below
|
notify_games.push(notify_game); // status is updated below
|
||||||
|
|
||||||
if (btnText.toLowerCase() == 'in library') {
|
if (btnText == 'in library') {
|
||||||
console.log(' Already in library! Nothing to claim.');
|
console.log(' Already in library! Nothing to claim.');
|
||||||
|
if (!existedInDb) await notify(`Game already in library: ${url}`);
|
||||||
notify_game.status = 'existed';
|
notify_game.status = 'existed';
|
||||||
db.data[user][game_id].status ||= 'existed'; // does not overwrite claimed or failed
|
db.data[user][game_id].status ||= 'existed'; // does not overwrite claimed or failed
|
||||||
if (db.data[user][game_id].status == 'failed') db.data[user][game_id].status = 'manual'; // was failed but now it's claimed
|
if (db.data[user][game_id].status.startsWith('failed')) db.data[user][game_id].status = 'manual'; // was failed but now it's claimed
|
||||||
|
} else if (btnText == 'requires base game') {
|
||||||
|
console.log(' Requires base game! Nothing to claim.');
|
||||||
|
notify_game.status = 'requires base game';
|
||||||
|
db.data[user][game_id].status ||= 'failed:requires-base-game';
|
||||||
|
// if base game is free, add to queue as well
|
||||||
|
const baseUrl = 'https://store.epicgames.com' + await page.locator('a:has-text("Overview")').getAttribute('href');
|
||||||
|
console.log(' Base game:', baseUrl);
|
||||||
|
// await page.click('a:has-text("Overview")');
|
||||||
|
// re-add original add-on to queue after base game
|
||||||
|
urls.push(baseUrl, url); // add base game to the list of games to claim and re-add add-on itself
|
||||||
} else { // GET
|
} else { // GET
|
||||||
console.log(' Not in library yet! Click GET.');
|
console.log(' Not in library yet! Click', btnText);
|
||||||
await page.click('[data-testid="purchase-cta-button"]');
|
await purchaseBtn.click({ delay: 11 }); // got stuck here without delay (or mouse move), see #75, 1ms was also enough
|
||||||
|
|
||||||
// click Continue if 'Device not supported. This product is not compatible with your current device.' - avoided by Windows userAgent?
|
// Accept End User License Agreement (only needed once)
|
||||||
page.click('button:has-text("Continue")').catch(_ => { }); // needed since change from Chromium to Firefox?
|
const acceptEulaIfShown = async () => {
|
||||||
|
try {
|
||||||
if (cfg.dryrun) continue;
|
await page.locator(':has-text("end user license agreement")').waitFor({ timeout: 10000 });
|
||||||
if (cfg.debug) await page.pause();
|
console.log(' Accept End User License Agreement (only needed once)');
|
||||||
|
await page.locator('input#agree').check();
|
||||||
|
await page.locator('button:has-text("Accept")').click();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
acceptEulaIfShown();
|
||||||
|
|
||||||
// it then creates an iframe for the purchase
|
// it then creates an iframe for the purchase
|
||||||
await page.waitForSelector('#webPurchaseContainer iframe'); // TODO needed?
|
await page.waitForSelector('#webPurchaseContainer iframe');
|
||||||
const iframe = page.frameLocator('#webPurchaseContainer iframe');
|
const iframe = page.frameLocator('#webPurchaseContainer iframe');
|
||||||
// skip game if unavailable in region, https://github.com/vogler/free-games-claimer/issues/46 TODO check games for account's region
|
// skip game if unavailable in region, https://github.com/vogler/free-games-claimer/issues/46
|
||||||
if (await iframe.locator(':has-text("unavailable in your region")').count() > 0) {
|
if (await iframe.locator(':has-text("unavailable in your region")').count() > 0) {
|
||||||
console.error(' This product is unavailable in your region!');
|
console.error(' This product is unavailable in your region!');
|
||||||
db.data[user][game_id].status = notify_game.status = 'unavailable-in-region';
|
db.data[user][game_id].status = notify_game.status = 'unavailable-in-region';
|
||||||
|
if (cfg.time) console.timeEnd('claim game');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
await iframe.locator('button:has-text("Place Order")').click();
|
|
||||||
|
const enterParentalPinIfNeeded = async () => {
|
||||||
|
try {
|
||||||
|
await iframe.locator('.payment-pin-code').waitFor({ timeout: 10000 });
|
||||||
|
if (!cfg.eg_parentalpin) {
|
||||||
|
console.error(' EG_PARENTALPIN not set. Need to enter Parental Control PIN manually.');
|
||||||
|
notify('epic-games: EG_PARENTALPIN not set. Need to enter Parental Control PIN manually.');
|
||||||
|
}
|
||||||
|
await iframe.locator('input.payment-pin-code__input').first().pressSequentially(cfg.eg_parentalpin);
|
||||||
|
await iframe.locator('button:has-text("Continue")').click({ delay: 11 });
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
enterParentalPinIfNeeded();
|
||||||
|
|
||||||
|
if (cfg.debug) await page.pause();
|
||||||
|
if (cfg.dryrun) {
|
||||||
|
console.log(' DRYRUN=1 -> Skip order!');
|
||||||
|
notify_game.status = 'skipped';
|
||||||
|
if (cfg.time) console.timeEnd('claim game');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Playwright clicked before button was ready to handle event, https://github.com/vogler/free-games-claimer/issues/84#issuecomment-1474346591
|
||||||
|
await iframe.locator('button:has-text("Place Order"):not(:has(.payment-loading--loading))').click({ delay: 11 });
|
||||||
|
|
||||||
// I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872
|
// I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872
|
||||||
const btnAgree = iframe.locator('button:has-text("I Agree")');
|
const btnAgree = iframe.locator('button:has-text("I Accept")');
|
||||||
|
const acceptIfRequired = async () => {
|
||||||
try {
|
try {
|
||||||
context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s?
|
await btnAgree.waitFor({ timeout: 10000 });
|
||||||
await Promise.any([btnAgree.click(), page.waitForSelector('text=Thank you for buying').then(_ => { })]); // EU: wait for agree button, non-EU: potentially done
|
await btnAgree.click();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}; // EU: wait for and click 'I Agree'
|
||||||
|
acceptIfRequired();
|
||||||
|
try {
|
||||||
|
// context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s?
|
||||||
const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe');
|
const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe');
|
||||||
captcha.waitFor().then(async () => { // don't await, since element may not be shown
|
const watchCaptchaChallenge = async () => {
|
||||||
console.info(' Got hcaptcha challenge! NopeCHA extension will likely solve it.')
|
try {
|
||||||
// await page.waitForTimeout(2000);
|
await captcha.waitFor({ timeout: 10000 });
|
||||||
// const p = path.resolve(dirs.screenshots, 'epic-games', 'captcha', `${filenamify(datetime())}.png`);
|
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.');
|
||||||
// await captcha.screenshot({ path: p });
|
await notify(`epic-games: got captcha challenge for.\nGame link: ${url}`);
|
||||||
// console.info(' Saved a screenshot of hcaptcha challenge to', p);
|
} catch {
|
||||||
// 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?
|
return;
|
||||||
}).catch(_ => { }); // may time out if not shown
|
}
|
||||||
await page.waitForSelector('text=Thank you for buying'); // EU: wait, non-EU: wait again = no-op
|
}; // may time out if not shown
|
||||||
|
const watchCaptchaFailure = async () => {
|
||||||
|
try {
|
||||||
|
await iframe.locator('.payment__errors:has-text("Failed to challenge captcha, please try again later.")').waitFor({ timeout: 10000 });
|
||||||
|
console.error(' Failed to challenge captcha, please try again later.');
|
||||||
|
await notify('epic-games: failed to challenge captcha. Please check.');
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
watchCaptchaChallenge();
|
||||||
|
watchCaptchaFailure();
|
||||||
|
await page.locator('text=Thanks for your order!').waitFor({ state: 'attached' });
|
||||||
db.data[user][game_id].status = 'claimed';
|
db.data[user][game_id].status = 'claimed';
|
||||||
db.data[user][game_id].time = datetime(); // claimed time overwrites failed/dryrun time
|
db.data[user][game_id].time = datetime(); // claimed time overwrites failed/dryrun time
|
||||||
console.log(' Claimed successfully!');
|
console.log(' Claimed successfully!');
|
||||||
context.setDefaultTimeout(cfg.timeout);
|
// context.setDefaultTimeout(cfg.timeout);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log(e);
|
console.log(e);
|
||||||
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');
|
// 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');
|
||||||
const p = path.resolve(dirs.screenshots, 'epic-games', 'failed', `${game_id}_${filenamify(datetime())}.png`);
|
console.error(' Failed to claim! To avoid captchas try to get a new IP address.');
|
||||||
|
const p = screenshot('failed', `${game_id}_${filenamify(datetime())}.png`);
|
||||||
await page.screenshot({ path: p, fullPage: true });
|
await page.screenshot({ path: p, fullPage: true });
|
||||||
db.data[user][game_id].status = 'failed';
|
db.data[user][game_id].status = 'failed';
|
||||||
}
|
}
|
||||||
notify_game.status = db.data[user][game_id].status; // claimed or failed
|
notify_game.status = db.data[user][game_id].status; // claimed or failed
|
||||||
|
|
||||||
const p = path.resolve(dirs.screenshots, 'epic-games', `${game_id}.png`);
|
const p = screenshot(`${game_id}.png`);
|
||||||
if (!existsSync(p)) await page.screenshot({ path: p, fullPage: false }); // fullPage is quite long...
|
if (!existsSync(p)) await page.screenshot({ path: p, fullPage: false }); // fullPage is quite long...
|
||||||
}
|
}
|
||||||
|
if (cfg.time) console.timeEnd('claim game');
|
||||||
}
|
}
|
||||||
|
if (cfg.time) console.timeEnd('claim all games');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
process.exitCode ||= 1;
|
||||||
|
console.error('--- Exception:');
|
||||||
console.error(error); // .toString()?
|
console.error(error); // .toString()?
|
||||||
if (error.message && !error.message.includes('Target closed')) // e.g. when killed by Ctrl-C
|
if (error.message && process.exitCode != 130) notify(`epic-games failed: ${error.message.split('\n')[0]}`);
|
||||||
notify(`epic-games failed: ${error.message.split('\n')[0]}`);
|
|
||||||
} finally {
|
} finally {
|
||||||
await db.write(); // write out json db
|
await db.write(); // write out json db
|
||||||
if (notify_games.filter(g => g.status != 'existed').length) { // don't notify if all were already claimed; TODO don't notify if killed?
|
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'
|
||||||
notify(`epic-games:<br>${html_game_list(notify_games)}`);
|
notify(`epic-games (${user}):<br>${html_game_list(notify_games)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await writeFileSync(path.resolve(dirs.browser, 'cookies.json'), JSON.stringify(await context.cookies()));
|
if (cfg.debug) writeFileSync(path.resolve(cfg.dir.browser, 'cookies.json'), JSON.stringify(await context.cookies()));
|
||||||
|
if (page.video()) console.log('Recorded video:', await page.video().path());
|
||||||
await context.close();
|
await context.close();
|
||||||
|
|
|
||||||
76
eslint.config.js
Normal file
76
eslint.config.js
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
// https://eslint.org/docs/latest/use/configure/configuration-files-new
|
||||||
|
// https://eslint.org/docs/latest/use/configure/migration-guide
|
||||||
|
import js from '@eslint/js';
|
||||||
|
import globals from 'globals';
|
||||||
|
import stylistic from '@stylistic/eslint-plugin-js';
|
||||||
|
|
||||||
|
export default [
|
||||||
|
// https://eslint.org/docs/latest/use/configure/configuration-files-new#globally-ignoring-files-with-ignores
|
||||||
|
// object with just `ignores` applies to all configuration objects
|
||||||
|
// had `ln -s .gitignore .eslintignore` before, but .eslintignore no longer supported
|
||||||
|
{
|
||||||
|
ignores: ['data/**'],
|
||||||
|
},
|
||||||
|
js.configs.recommended,
|
||||||
|
{
|
||||||
|
// files: ['*.js'],
|
||||||
|
languageOptions: {
|
||||||
|
globals: globals.node,
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
'@stylistic/js': stylistic,
|
||||||
|
},
|
||||||
|
// https://eslint.org/docs/latest/rules/
|
||||||
|
// https://eslint.style/packages/js
|
||||||
|
rules: {
|
||||||
|
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
||||||
|
'prefer-const': 'error',
|
||||||
|
'@stylistic/js/array-bracket-newline': ['error', 'consistent'],
|
||||||
|
'@stylistic/js/array-bracket-spacing': 'error',
|
||||||
|
'@stylistic/js/array-element-newline': ['error', 'consistent'],
|
||||||
|
'@stylistic/js/arrow-parens': ['error', 'as-needed'],
|
||||||
|
'@stylistic/js/arrow-spacing': 'error',
|
||||||
|
'@stylistic/js/block-spacing': 'error',
|
||||||
|
'@stylistic/js/brace-style': 'error',
|
||||||
|
'@stylistic/js/comma-dangle': ['error', 'always-multiline'],
|
||||||
|
'@stylistic/js/comma-spacing': 'error',
|
||||||
|
'@stylistic/js/comma-style': 'error',
|
||||||
|
'@stylistic/js/eol-last': 'error',
|
||||||
|
'@stylistic/js/func-call-spacing': 'error',
|
||||||
|
'@stylistic/js/function-paren-newline': ['error', 'consistent'],
|
||||||
|
'@stylistic/js/implicit-arrow-linebreak': 'error',
|
||||||
|
'@stylistic/js/indent': ['error', 2],
|
||||||
|
'@stylistic/js/key-spacing': 'error',
|
||||||
|
'@stylistic/js/keyword-spacing': 'error',
|
||||||
|
'@stylistic/js/linebreak-style': 'error',
|
||||||
|
'@stylistic/js/no-extra-parens': 'error',
|
||||||
|
'@stylistic/js/no-extra-semi': 'error',
|
||||||
|
'@stylistic/js/no-mixed-spaces-and-tabs': 'error',
|
||||||
|
'@stylistic/js/no-multi-spaces': 'error',
|
||||||
|
'@stylistic/js/no-multiple-empty-lines': 'error',
|
||||||
|
'@stylistic/js/no-tabs': 'error',
|
||||||
|
'@stylistic/js/no-trailing-spaces': 'error',
|
||||||
|
'@stylistic/js/no-whitespace-before-property': 'error',
|
||||||
|
'@stylistic/js/nonblock-statement-body-position': 'error',
|
||||||
|
'@stylistic/js/object-curly-newline': 'error',
|
||||||
|
'@stylistic/js/object-curly-spacing': ['error', 'always'],
|
||||||
|
'@stylistic/js/object-property-newline': ['error', { allowAllPropertiesOnSameLine: true }],
|
||||||
|
'@stylistic/js/quote-props': ['error', 'as-needed'],
|
||||||
|
'@stylistic/js/quotes': ['error', 'single'],
|
||||||
|
'@stylistic/js/rest-spread-spacing': 'error',
|
||||||
|
'@stylistic/js/semi': 'error',
|
||||||
|
'@stylistic/js/semi-spacing': 'error',
|
||||||
|
'@stylistic/js/semi-style': 'error',
|
||||||
|
'@stylistic/js/space-before-blocks': 'error',
|
||||||
|
'@stylistic/js/space-before-function-paren': ['error', { anonymous: 'never', named: 'never', asyncArrow: 'always' }],
|
||||||
|
'@stylistic/js/space-in-parens': 'error',
|
||||||
|
'@stylistic/js/space-infix-ops': 'error',
|
||||||
|
'@stylistic/js/space-unary-ops': 'error',
|
||||||
|
'@stylistic/js/spaced-comment': 'error',
|
||||||
|
'@stylistic/js/switch-colon-spacing': 'error',
|
||||||
|
'@stylistic/js/template-curly-spacing': 'error',
|
||||||
|
'@stylistic/js/template-tag-spacing': 'error',
|
||||||
|
'@stylistic/js/wrap-regex': 'error',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
115
gog.js
115
gog.js
|
|
@ -1,48 +1,58 @@
|
||||||
import { firefox } from 'playwright'; // stealth plugin needs no outdated playwright-extra
|
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||||
import path from 'path';
|
import chalk from 'chalk';
|
||||||
import { dirs, jsonDb, datetime, filenamify, prompt, notify, html_game_list } from './util.js';
|
import { resolve, jsonDb, datetime, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js';
|
||||||
import { cfg } from './config.js';
|
import { cfg } from './src/config.js';
|
||||||
|
|
||||||
|
const screenshot = (...a) => resolve(cfg.dir.screenshots, 'gog', ...a);
|
||||||
|
|
||||||
const URL_CLAIM = 'https://www.gog.com/en';
|
const URL_CLAIM = 'https://www.gog.com/en';
|
||||||
|
|
||||||
console.log(datetime(), 'started checking gog');
|
console.log(datetime(), 'started checking gog');
|
||||||
|
|
||||||
const db = await jsonDb('gog.json');
|
const db = await jsonDb('gog.json', {});
|
||||||
db.data ||= {};
|
|
||||||
|
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
|
||||||
|
console.error(`Window width is set to ${cfg.width} but needs to be at least 1280 for GOG!`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
// https://playwright.dev/docs/auth#multi-factor-authentication
|
// https://playwright.dev/docs/auth#multi-factor-authentication
|
||||||
const context = await firefox.launchPersistentContext(dirs.browser, {
|
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||||
headless: cfg.headless,
|
headless: cfg.headless,
|
||||||
viewport: { width: cfg.width, height: cfg.height },
|
viewport: { width: cfg.width, height: cfg.height },
|
||||||
locale: "en-US", // ignore OS locale to be sure to have english text for locators -> done via /en in URL
|
locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL
|
||||||
// recordHar: { path: './data/gog.har' }, // https://toolbox.googleapps.com/apps/har_analyzer/
|
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
|
||||||
// recordVideo: { dir: './data/videos' }, // console.log(await page.video().path());
|
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
|
||||||
|
handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved
|
||||||
});
|
});
|
||||||
|
|
||||||
|
handleSIGINT(context);
|
||||||
|
|
||||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
|
|
||||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||||
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||||
|
|
||||||
const notify_games = [];
|
const notify_games = [];
|
||||||
|
let user;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await context.addCookies([{ name: 'CookieConsent', value: '{stamp:%274oR8MJL+bxVlG6g+kl2we5+suMJ+Tv7I4C5d4k+YY4vrnhCD+P23RQ==%27%2Cnecessary:true%2Cpreferences:true%2Cstatistics:true%2Cmarketing:true%2Cmethod:%27explicit%27%2Cver:1%2Cutc:1672331618201%2Cregion:%27de%27}', domain: 'www.gog.com', path: '/' }]); // to not waste screen space when non-headless
|
await context.addCookies([{ name: 'CookieConsent', value: '{stamp:%274oR8MJL+bxVlG6g+kl2we5+suMJ+Tv7I4C5d4k+YY4vrnhCD+P23RQ==%27%2Cnecessary:true%2Cpreferences:true%2Cstatistics:true%2Cmarketing:true%2Cmethod:%27explicit%27%2Cver:1%2Cutc:1672331618201%2Cregion:%27de%27}', domain: 'www.gog.com', path: '/' }]); // to not waste screen space when non-headless
|
||||||
|
|
||||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
||||||
|
|
||||||
// page.click('#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll').catch(_ => { }); // does not work reliably, solved by setting CookieConsent above
|
|
||||||
const signIn = page.locator('a:has-text("Sign in")').first();
|
const signIn = page.locator('a:has-text("Sign in")').first();
|
||||||
await Promise.any([signIn.waitFor(), page.waitForSelector('#menuUsername')]);
|
await Promise.any([signIn.waitFor(), page.waitForSelector('#menuUsername')]);
|
||||||
while (await signIn.isVisible()) {
|
while (await signIn.isVisible()) {
|
||||||
console.error('Not signed in anymore.');
|
console.error('Not signed in anymore.');
|
||||||
await signIn.click();
|
await signIn.click();
|
||||||
// it then creates an iframe for the login
|
// it then creates an iframe for the login
|
||||||
await page.waitForSelector('#GalaxyAccountsFrameContainer iframe'); // TODO needed?
|
await page.waitForSelector('#GalaxyAccountsFrameContainer iframe');
|
||||||
const iframe = page.frameLocator('#GalaxyAccountsFrameContainer iframe');
|
const iframe = page.frameLocator('#GalaxyAccountsFrameContainer iframe');
|
||||||
context.setDefaultTimeout(0); // give user time to log in without timeout
|
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
|
||||||
|
console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`);
|
||||||
if (cfg.gog_email && cfg.gog_password) console.info('Using email and password from environment.');
|
if (cfg.gog_email && cfg.gog_password) console.info('Using email and password from environment.');
|
||||||
else console.info('Press ESC to skip if you want to login in the browser (not possible in headless mode).');
|
else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).');
|
||||||
const email = cfg.gog_email || await prompt({ message: 'Enter email' });
|
const email = cfg.gog_email || await prompt({ message: 'Enter email' });
|
||||||
const password = email && (cfg.gog_password || await prompt({ type: 'password', message: 'Enter password' }));
|
const password = email && (cfg.gog_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||||
if (email && password) {
|
if (email && password) {
|
||||||
|
|
@ -50,54 +60,62 @@ try {
|
||||||
await iframe.locator('#login_username').fill(email);
|
await iframe.locator('#login_username').fill(email);
|
||||||
await iframe.locator('#login_password').fill(password);
|
await iframe.locator('#login_password').fill(password);
|
||||||
await iframe.locator('#login_login').click();
|
await iframe.locator('#login_login').click();
|
||||||
// handle MFA, but don't await it
|
const handleTwoFactor = async () => {
|
||||||
iframe.locator('form[name=second_step_authentication]').waitFor().then(async () => {
|
try {
|
||||||
|
await iframe.locator('form[name=second_step_authentication]').waitFor({ timeout: 15000 });
|
||||||
console.log('Two-Step Verification - Enter security code');
|
console.log('Two-Step Verification - Enter security code');
|
||||||
console.log(await iframe.locator('.form__description').innerText())
|
console.log(await iframe.locator('.form__description').innerText());
|
||||||
const otp = await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 4 || 'The code must be 4 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
const otp = await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 4 || 'The code must be 4 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||||
await iframe.locator('#second_step_authentication_token_letter_1').type(otp.toString(), {delay: 10});
|
await iframe.locator('#second_step_authentication_token_letter_1').pressSequentially(otp.toString(), { delay: 10 });
|
||||||
await iframe.locator('#second_step_authentication_send').click();
|
await iframe.locator('#second_step_authentication_send').click();
|
||||||
await page.waitForTimeout(1000); // TODO still needed with wait for username below?
|
await page.waitForTimeout(1000);
|
||||||
}).catch(_ => { });
|
} catch {
|
||||||
// iframe.locator('iframe[title=reCAPTCHA]').waitFor().then(() => {
|
return;
|
||||||
// iframe.locator('.g-recaptcha').waitFor().then(() => {
|
}
|
||||||
iframe.locator('text=Invalid captcha').waitFor().then(() => {
|
};
|
||||||
|
const watchInvalidCaptcha = async () => {
|
||||||
|
try {
|
||||||
|
await iframe.locator('text=Invalid captcha').waitFor({ timeout: 15000 });
|
||||||
console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
|
console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
|
||||||
notify('gog: got captcha during login. Please check.');
|
notify('gog: got captcha during login. Please check.');
|
||||||
// TODO solve reCAPTCHA?
|
} catch {
|
||||||
}).catch(_ => { });
|
return;
|
||||||
await page.waitForSelector('#menuUsername')
|
}
|
||||||
|
};
|
||||||
|
handleTwoFactor();
|
||||||
|
watchInvalidCaptcha();
|
||||||
|
await page.waitForSelector('#menuUsername');
|
||||||
} else {
|
} else {
|
||||||
console.log('Waiting for you to login in the browser.');
|
console.log('Waiting for you to login in the browser.');
|
||||||
notify('gog: no longer signed in and not enough options set for automatic login.');
|
await notify('gog: no longer signed in and not enough options set for automatic login.');
|
||||||
if (cfg.headless) {
|
if (cfg.headless) {
|
||||||
console.log('Run `SHOW=1 node gog` to login in the opened browser.');
|
console.log('Run `SHOW=1 node gog` to login in the opened browser.');
|
||||||
await context.close();
|
await context.close();
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
context.setDefaultTimeout(cfg.timeout);
|
await page.waitForSelector('#menuUsername');
|
||||||
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
}
|
}
|
||||||
const user = await page.locator('#menuUsername').first().textContent(); // innerText is uppercase due to styling!
|
user = await page.locator('#menuUsername').first().textContent(); // innerText is uppercase due to styling!
|
||||||
console.log(`Signed in as '${user}'`);
|
console.log(`Signed in as ${user}`);
|
||||||
db.data[user] ||= {};
|
db.data[user] ||= {};
|
||||||
|
|
||||||
const banner = page.locator('#giveaway');
|
const banner = page.locator('#giveaway');
|
||||||
if (!await banner.count()) {
|
const hasGiveaway = await banner.count();
|
||||||
|
if (!hasGiveaway) {
|
||||||
console.log('Currently no free giveaway!');
|
console.log('Currently no free giveaway!');
|
||||||
} else {
|
} else {
|
||||||
const text = await page.locator('.giveaway-banner__title').innerText();
|
const text = await page.locator('.giveaway__content-header').innerText();
|
||||||
const title = text.match(/Claim (.*) and don't miss/)[1];
|
const match_all = text.match(/Claim (.*) and don't miss the|Success! (.*) was added to/);
|
||||||
const slug = await banner.getAttribute('href');
|
const title = match_all[1] ? match_all[1] : match_all[2];
|
||||||
const url = `https://gog.com${slug}`;
|
const url = await banner.locator('a').first().getAttribute('href');
|
||||||
console.log(`Current free game: ${title} - ${url}`);
|
console.log(`Current free game: ${chalk.blue(title)} - ${url}`);
|
||||||
db.data[user][title] ||= { title, time: datetime(), url };
|
db.data[user][title] ||= { title, time: datetime(), url };
|
||||||
if (cfg.dryrun) process.exit(1);
|
if (cfg.dryrun) process.exit(1);
|
||||||
const p = path.resolve(dirs.screenshots, 'gog', `${filenamify(title)}.png`);
|
await banner.screenshot({ path: screenshot(`${filenamify(title)}.png`) }); // overwrites every time - only keep first?
|
||||||
await banner.screenshot({ path: p }); // overwrites every time - only keep first?
|
|
||||||
|
|
||||||
// await banner.getByRole('button', { name: 'Add to library' }).click();
|
// instead of clicking the button, visit the auto-claim URL which gives a JSON response
|
||||||
// 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
|
|
||||||
await page.goto('https://www.gog.com/giveaway/claim');
|
await page.goto('https://www.gog.com/giveaway/claim');
|
||||||
const response = await page.innerText('body');
|
const response = await page.innerText('body');
|
||||||
// console.log(response);
|
// console.log(response);
|
||||||
|
|
@ -122,20 +140,23 @@ try {
|
||||||
db.data[user][title].status ||= status;
|
db.data[user][title].status ||= status;
|
||||||
notify_games.push({ title, url, status });
|
notify_games.push({ title, url, status });
|
||||||
|
|
||||||
if (status == 'claimed') { // TODO check if this is enough or if newsleter is enabled if 'existed'
|
if (status == 'claimed' && !cfg.gog_newsletter) {
|
||||||
console.log("Unsubscribe from 'Promotions and hot deals' newsletter");
|
console.log('Unsubscribe from \'Promotions and hot deals\' newsletter');
|
||||||
await page.goto('https://www.gog.com/en/account/settings/subscriptions');
|
await page.goto('https://www.gog.com/en/account/settings/subscriptions');
|
||||||
|
await page.locator('li:has-text("Marketing communications through Trusted Partners") label').uncheck();
|
||||||
await page.locator('li:has-text("Promotions and hot deals") label').uncheck();
|
await page.locator('li:has-text("Promotions and hot deals") label').uncheck();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
process.exitCode ||= 1;
|
||||||
|
console.error('--- Exception:');
|
||||||
console.error(error); // .toString()?
|
console.error(error); // .toString()?
|
||||||
if (error.message && !error.message.includes('Target closed') && !error.message.includes('Browser closed')) // e.g. when killed by Ctrl-C
|
if (error.message && process.exitCode != 130) notify(`gog failed: ${error.message.split('\n')[0]}`);
|
||||||
notify(`gog failed: ${error.message.split('\n')[0]}`);
|
|
||||||
} finally {
|
} finally {
|
||||||
await db.write(); // write out json db
|
await db.write(); // write out json db
|
||||||
if (notify_games.filter(g => g.status != 'existed').length) { // don't notify if all were already claimed; TODO don't notify if killed?
|
if (notify_games.filter(g => g.status != 'existed').length) { // don't notify if all were already claimed
|
||||||
notify(`gog:<br>${html_game_list(notify_games)}`);
|
notify(`gog (${user}):<br>${html_game_list(notify_games)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (page.video()) console.log('Recorded video:', await page.video().path());
|
||||||
await context.close();
|
await context.close();
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"checkJs": true,
|
"checkJs": true,
|
||||||
"target": "es2021",
|
"target": "es2021",
|
||||||
"module": "esnext",
|
"module": "NodeNext",
|
||||||
"moduleResolution": "NodeNext", // https://github.com/typicode/lowdb/issues/554
|
"moduleResolution": "NodeNext", // https://github.com/typicode/lowdb/issues/554
|
||||||
},
|
},
|
||||||
"exclude": ["node_modules", "**/node_modules"]
|
"exclude": ["node_modules", "**/node_modules"]
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +0,0 @@
|
||||||
(async()=>{class d{static time(){return Date.now||(Date.now=()=>(new Date).getTime()),Date.now()}static sleep(t=1e3){return new Promise(e=>setTimeout(e,t))}static async random_sleep(e,t){t=Math.floor(Math.random()*(t-e)+e);return d.sleep(t)}static pad(e){var t=2-String(e).length+1;return 0<t?""+new Array(t).join("0")+e:""+e}static date(){return new Date}static string(e=null){return e=e||d.date(),d.pad(e.getMonth()+1)+`/${d.pad(e.getDate())}/${e.getFullYear()} ${d.pad(e.getHours()%12)}:${d.pad(e.getMinutes())}:${d.pad(e.getSeconds())} `+(12<=e.getHours()?"PM":"AM")}}class p{static exec(e,a){return new Promise(t=>{try{chrome.runtime.sendMessage({method:e,data:a},t)}catch(e){t()}})}}class h{static async fetch(e,t){return p.exec("fetch",{url:e,options:t})}}class g{static INFERENCE_URL="https://api.nopecha.com";static MAX_WAIT_POST=60;static MAX_WAIT_GET=60;static ERRORS={UNKNOWN:9,INVALID_REQUEST:10,RATE_LIIMTED:11,BANNED_USER:12,NO_JOB:13,INCOMPLETE_JOB:14,INVALID_KEY:15,NO_CREDIT:16,UPDATE_REQUIRED:17};static async post({captcha_type:e,task:t,image_urls:a,grid:r,key:n}){for(var i=Date.now(),c=await p.exec("info_tab");!(Date.now()-i>1e3*g.MAX_WAIT_POST);){const u={type:e,task:t,image_urls:a,v:chrome.runtime.getManifest().version,key:n,url:c.url};r&&(u.grid=r);var o=await h.fetch(g.INFERENCE_URL,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"}});try{var s=JSON.parse(o);if("error"in s){if(s.error===g.ERRORS.RATE_LIMITED){await d.sleep(2e3);continue}if(s.error===g.ERRORS.INVALID_KEY)break;if(s.error===g.ERRORS.NO_CREDIT)break;break}var l="id"in s?s.id:s.data;return await g.get({job_id:l,key:n})}catch(e){break}}return{job_id:null,clicks:null}}static async get({key:e,job_id:t}){for(var a=Date.now();!(Date.now()-a>1e3*g.MAX_WAIT_GET);){await d.sleep(500);var r=await h.fetch(g.INFERENCE_URL+`?id=${t}&key=`+e);try{var n=JSON.parse(r);if("error"in n){if(n.error!==g.ERRORS.INCOMPLETE_JOB)return{job_id:t,clicks:null};continue}return{job_id:t,clicks:n.data}}catch(e){break}}return{job_id:t,clicks:null}}}function u(e){const t=e?.style.background?.trim()?.match(/(?!^)".*?"/g);return t&&0!==t.length?t[0].replaceAll('"',""):null}async function y(){let e=document.querySelector("h2.prompt-text")?.innerText?.replace(/\s+/g," ")?.trim();if(!e)return null;var t={"0430":"a","0441":"c","0501":"d","0435":"e","04bb":"h","0456":"i","0458":"j","04cf":"l","03bf":"o","043e":"o","0440":"p","0455":"s","0445":"x","0443":"y","0065":"e","0069":"i","30fc":"一","571f":"士"};const a=[];for(const i of e){var r=function(e,t,a){for(;(""+e).length<a;)e=""+t+e;return e}(i.charCodeAt(0).toString(16),"0",4);r in t?a.push(t[r]):a.push(i)}e=a.join("");var n=function(){let e=document.querySelector(".display-language .text").innerText||window.navigator.userLanguage||window.navigator.language;return e?e=(e=e.toLowerCase()).split("-")[0]:null}();return e=n&&"en"!==n?await p.exec("translate",{from:n,to:"en",text:e}):e}let f=null;async function e(e){if("block"===document.querySelector("div.check")?.style.display)return a=a||!0,void(e.debug&&window.location.reload());a=!1,await d.sleep(e.hcaptcha_open_delay),document.querySelector("#checkbox")?.click()}async function t(e){o=!(o||!function(){const e=document.querySelector(".display-error");return"true"!==e?.getAttribute("aria-hidden")}());n=100;const{task:t,cells:a,urls:r}=await new Promise(o=>{let s=!1;const l=setInterval(async()=>{if(!s){s=!0;var e=await y();if(e){var t=document.querySelector(".challenge-example > .image > .image"),t=u(t);if(t&&""!==t){var a=document.querySelectorAll(".task-image");if(9!==a.length)s=!1;else{const n=[],i=[];for(const c of a){var r=c.querySelector("div.image");if(!r)return void(s=!1);r=u(r);if(!r||""===r)return void(s=!1);n.push(c),i.push(r)}a=JSON.stringify(i);if(f!==a)return f=a,clearInterval(l),s=!1,o({task:e,task_url:t,cells:n,urls:i});s=!1}}else s=!1}else s=!1}},n)});var n,i=d.time(),c=(await g.post({captcha_type:"hcaptcha",task:t,image_urls:r,key:e.key}))["clicks"];if(c){e=e.hcaptcha_solve_delay-(d.time()-i);0<e&&await d.sleep(e);for(let e=0;e<c.length;e++)!1!==c[e]&&"true"!==a[e].getAttribute("aria-pressed")&&a[e].click();await d.sleep(200);try{document.querySelector(".button-submit").click()}catch(e){}}}let a=!1,o=!1;for(;;){await d.sleep(1e3);var r=await p.exec("get_settings");r&&(r.hcaptcha_auto_open&&null!==document.querySelector("div.check")?await e(r):r.hcaptcha_auto_solve&&null!==document.querySelector("h2.prompt-text")&&await t(r))}})();
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
(async()=>{let a=null,t=!1,r=!1;function n(e,t,r=!1){e&&(r||a!==e)&&(!0===t&&"false"===e.getAttribute("aria-pressed")||!1===t&&"true"===e.getAttribute("aria-pressed"))&&e.click()}document.addEventListener("mousedown",e=>{"false"===e?.target?.parentNode?.getAttribute("aria-pressed")?(t=!0,r=!0):"true"===e?.target?.parentNode?.getAttribute("aria-pressed")&&(t=!0,r=!1),a=e?.target?.parentNode}),document.addEventListener("mouseup",e=>{t=!1,a=null}),document.addEventListener("mousemove",e=>{t&&(a!==e?.target?.parentNode&&null!==a&&n(a,r,!0),n(e?.target?.parentNode,r))})})();
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
(()=>{let e;function t(){var e=navigator.language.split("-")[0];for(const t of document.querySelectorAll('script[src*=".hcaptcha.com/1/api.js"]')){const r=new URL(t.src);"en"!==(r.searchParams.get("hl")||e)&&(r.searchParams.set("hl","en"),t.src=r.toString())}}e=new MutationObserver(t),setTimeout(()=>{t(),e.observe(document.head,{childList:!0})},0)})();
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 9 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.1 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.9 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.8 KiB |
|
|
@ -1 +0,0 @@
|
||||||
{"name": "NopeCHA: ReCAPTCHA & hCAPTCHA Solver", "action": {"default_title": "NopeCHA: ReCAPTCHA & hCAPTCHA Solver", "default_icon": "icon/16.png", "default_popup": "popup.html"}, "manifest_version": 3, "version": "0.1.16", "description": "Automatically solve CAPTCHAs using AI.", "permissions": ["declarativeNetRequest", "storage", "scripting"], "background": {"service_worker": "background.js"}, "content_scripts": [{"matches": ["*://*.hcaptcha.com/captcha/*"], "js": ["hcaptcha.js"], "all_frames": true, "run_at": "document_end"}, {"matches": ["*://*.hcaptcha.com/captcha/*"], "js": ["hcaptcha_fast.js"], "all_frames": true, "run_at": "document_start"}, {"matches": ["<all_urls>"], "js": ["recaptcha.js", "recaptcha_voice.js"], "all_frames": true, "run_at": "document_end"}, {"matches": ["<all_urls>"], "js": ["hcaptcha_language.js"], "all_frames": true, "run_at": "document_end"}, {"matches": ["*://*.google.com/recaptcha/*", "*://*.recaptcha.net/recaptcha/*", "*://recaptcha.net/recaptcha/*"], "js": ["recaptcha_fast.js"], "all_frames": true, "run_at": "document_start"}, {"matches": ["*://nopecha.com/setup"], "js": ["setup.js"], "all_frames": true, "run_at": "document_end"}], "host_permissions": ["<all_urls>"], "icons": {"16": "icon/16.png", "32": "icon/32.png", "48": "icon/48.png", "128": "icon/128.png"}}
|
|
||||||
|
|
@ -1,289 +0,0 @@
|
||||||
:root {
|
|
||||||
--input_scale_x: 1;
|
|
||||||
--input_scale_y: 0.8;
|
|
||||||
}
|
|
||||||
|
|
||||||
html * {
|
|
||||||
font-family: monospace, monospaSFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
html, body {
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
|
|
||||||
-webkit-touch-callout: none;
|
|
||||||
-webkit-user-select: none;
|
|
||||||
-khtml-user-select: none;
|
|
||||||
-moz-user-select: none;
|
|
||||||
-ms-user-select: none;
|
|
||||||
user-select: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.hidden {
|
|
||||||
display: none !important;
|
|
||||||
opacity: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.light {
|
|
||||||
font-size: 0.9em;
|
|
||||||
opacity: 0.5;
|
|
||||||
}
|
|
||||||
.green {
|
|
||||||
/* color: #8cd47e; */
|
|
||||||
color: #1a73e8;
|
|
||||||
}
|
|
||||||
.red {
|
|
||||||
color: #ff6961;
|
|
||||||
}
|
|
||||||
.yellow {
|
|
||||||
color: #ca1;
|
|
||||||
}
|
|
||||||
.clickable {
|
|
||||||
cursor: pointer;
|
|
||||||
transition: 250ms all;
|
|
||||||
}
|
|
||||||
.clickable:hover {
|
|
||||||
opacity: 0.8;
|
|
||||||
}
|
|
||||||
|
|
||||||
#main {
|
|
||||||
padding: 8px 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#footer {
|
|
||||||
margin-top: 8px;
|
|
||||||
width: 100%;
|
|
||||||
text-align: center;
|
|
||||||
color: #999;
|
|
||||||
height: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#manage {
|
|
||||||
width: 100%;
|
|
||||||
text-align: center;
|
|
||||||
background-color: #1a73e8;
|
|
||||||
color: #fff;
|
|
||||||
height: 20px;
|
|
||||||
line-height: 20px;
|
|
||||||
border-radius: 4px;
|
|
||||||
border: 1px solid #1a73e8;
|
|
||||||
padding: 8px;
|
|
||||||
font-size: 1.2em;
|
|
||||||
transition: 200ms all;
|
|
||||||
}
|
|
||||||
#manage:hover {
|
|
||||||
color: #1a73e8;
|
|
||||||
background-color: transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
.vspace {
|
|
||||||
min-height: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settings_group {
|
|
||||||
width: 280px;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
flex-wrap: nowrap;
|
|
||||||
padding: 6px 4px;
|
|
||||||
}
|
|
||||||
.settings_group.vertical {
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
.settings_group > .label {
|
|
||||||
flex-grow: 1;
|
|
||||||
font-size: 1.2em;
|
|
||||||
line-height: calc(34px * var(--input_scale_y));
|
|
||||||
padding-right: 16px;
|
|
||||||
}
|
|
||||||
.settings_group > .value {
|
|
||||||
font-size: 1.2em;
|
|
||||||
line-height: calc(34px * var(--input_scale_y));
|
|
||||||
}
|
|
||||||
.settings_group > input {
|
|
||||||
border-radius: 0;
|
|
||||||
}
|
|
||||||
.settings_group > input[type="text"],
|
|
||||||
.settings_group > input[type="button"],
|
|
||||||
.settings_group > select {
|
|
||||||
font-size: 0.9em;
|
|
||||||
outline: none;
|
|
||||||
border: 1px solid #999;
|
|
||||||
width: calc(60px * var(--input_scale_x));
|
|
||||||
height: calc(34px * var(--input_scale_y));
|
|
||||||
}
|
|
||||||
.settings_group > input[type="button"] {
|
|
||||||
background-color: #f0f0f0;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: 200ms all;
|
|
||||||
}
|
|
||||||
.settings_group > input[type="button"]:hover {
|
|
||||||
background-color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.switch {
|
|
||||||
position: relative;
|
|
||||||
display: inline-block;
|
|
||||||
width: calc(60px * var(--input_scale_x));
|
|
||||||
height: calc(34px * var(--input_scale_y));
|
|
||||||
}
|
|
||||||
.switch input {
|
|
||||||
opacity: 0;
|
|
||||||
width: 0;
|
|
||||||
height: 0;
|
|
||||||
}
|
|
||||||
.slider {
|
|
||||||
position: absolute;
|
|
||||||
cursor: pointer;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
right: 0;
|
|
||||||
bottom: 0;
|
|
||||||
background-color: #ccc;
|
|
||||||
-webkit-transition: .4s;
|
|
||||||
transition: .4s;
|
|
||||||
}
|
|
||||||
.slider:before {
|
|
||||||
position: absolute;
|
|
||||||
content: "";
|
|
||||||
height: calc(26px * var(--input_scale_y));
|
|
||||||
width: calc(26px * var(--input_scale_x));
|
|
||||||
left: calc(4px * var(--input_scale_x));
|
|
||||||
bottom: calc(4px * var(--input_scale_y));
|
|
||||||
background-color: white;
|
|
||||||
-webkit-transition: .4s;
|
|
||||||
transition: .4s;
|
|
||||||
}
|
|
||||||
input:checked + .slider {
|
|
||||||
background-color: #2196F3;
|
|
||||||
}
|
|
||||||
input:focus + .slider {
|
|
||||||
box-shadow: 0 0 1px #2196F3;
|
|
||||||
}
|
|
||||||
input:checked + .slider:before {
|
|
||||||
-webkit-transform: translateX(calc(26px * var(--input_scale_x)));
|
|
||||||
-ms-transform: translateX(calc(26px * var(--input_scale_x)));
|
|
||||||
transform: translateX(calc(26px * var(--input_scale_x)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#key {
|
|
||||||
padding: 4px;
|
|
||||||
border-radius: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.loading {
|
|
||||||
display: inline-block;
|
|
||||||
position: relative;
|
|
||||||
width: 40px;
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
.loading div {
|
|
||||||
position: absolute;
|
|
||||||
top: 8px;
|
|
||||||
width: 6px;
|
|
||||||
height: 6px;
|
|
||||||
border-radius: 50%;
|
|
||||||
background: #777;
|
|
||||||
animation-timing-function: cubic-bezier(0, 1, 1, 0);
|
|
||||||
}
|
|
||||||
.loading div:nth-child(1) {
|
|
||||||
left: 4px;
|
|
||||||
animation: loading1 0.6s infinite;
|
|
||||||
}
|
|
||||||
.loading div:nth-child(2) {
|
|
||||||
left: 4px;
|
|
||||||
animation: loading2 0.6s infinite;
|
|
||||||
}
|
|
||||||
.loading div:nth-child(3) {
|
|
||||||
left: 16px;
|
|
||||||
animation: loading2 0.6s infinite;
|
|
||||||
}
|
|
||||||
.loading div:nth-child(4) {
|
|
||||||
left: 28px;
|
|
||||||
animation: loading3 0.6s infinite;
|
|
||||||
}
|
|
||||||
@keyframes loading1 {
|
|
||||||
0% {
|
|
||||||
transform: scale(0);
|
|
||||||
}
|
|
||||||
100% {
|
|
||||||
transform: scale(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@keyframes loading3 {
|
|
||||||
0% {
|
|
||||||
transform: scale(1);
|
|
||||||
}
|
|
||||||
100% {
|
|
||||||
transform: scale(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@keyframes loading2 {
|
|
||||||
0% {
|
|
||||||
transform: translate(0, 0);
|
|
||||||
}
|
|
||||||
100% {
|
|
||||||
transform: translate(12px, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab_btn_row {
|
|
||||||
background-color: #efefef;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
flex-wrap: nowrap;
|
|
||||||
}
|
|
||||||
.tab_btn_row .tab_btn {
|
|
||||||
flex-grow: 1;
|
|
||||||
padding: 4px 8px;
|
|
||||||
border-top: 1px solid transparent;
|
|
||||||
border-left: 1px solid transparent;
|
|
||||||
border-right: 1px solid transparent;
|
|
||||||
border-bottom: 1px solid #ccc;
|
|
||||||
border-radius: 4px 4px 0 0;
|
|
||||||
text-align: center;
|
|
||||||
font-size: 1.2em;
|
|
||||||
transition: 200ms all;
|
|
||||||
}
|
|
||||||
.tab_btn:not(.active):hover {
|
|
||||||
background-color: #fafafa;
|
|
||||||
}
|
|
||||||
.tab_btn.active {
|
|
||||||
background-color: #fff;
|
|
||||||
border-top: 1px solid #ccc;
|
|
||||||
border-left: 1px solid #ccc;
|
|
||||||
border-right: 1px solid #ccc;
|
|
||||||
border-bottom: 1px solid transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
.content {
|
|
||||||
margin: 6px 0;
|
|
||||||
padding: 4px 8px 0 8px;
|
|
||||||
border-top: 1px solid #ccc;
|
|
||||||
border-left: 1px solid #ccc;
|
|
||||||
border-right: 1px solid #ccc;
|
|
||||||
border-bottom: 1px solid #ccc;
|
|
||||||
}
|
|
||||||
.tab_content.bordered {
|
|
||||||
padding: 16px 8px 8px 8px;
|
|
||||||
border-top: 1px solid transparent;
|
|
||||||
border-left: 1px solid #ccc;
|
|
||||||
border-right: 1px solid #ccc;
|
|
||||||
border-bottom: 1px solid #ccc;
|
|
||||||
border-radius: 0 0 4px 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.footer_group {
|
|
||||||
width: 296px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.warning_box {
|
|
||||||
border-color: #FCD62E;
|
|
||||||
border-radius: 0.25rem;
|
|
||||||
border-width: 0.125rem;
|
|
||||||
padding: 0 0.5rem;
|
|
||||||
margin: 0 4px;
|
|
||||||
background-color: #FEF9C3;
|
|
||||||
border-style: solid;
|
|
||||||
}
|
|
||||||
|
|
@ -1,149 +0,0 @@
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<link rel="stylesheet" href="popup.css">
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<!-- <div id="template" class="hidden">
|
|
||||||
<div class="loading"><div></div><div></div><div></div><div></div></div>
|
|
||||||
</div> -->
|
|
||||||
|
|
||||||
<div id="main">
|
|
||||||
<!-- <div class="settings_group">
|
|
||||||
<div class="label">Server Status</div>
|
|
||||||
<div id="server_status" class="value green">
|
|
||||||
<div class="loading"><div></div><div></div><div></div><div></div></div>
|
|
||||||
</div>
|
|
||||||
</div> -->
|
|
||||||
|
|
||||||
<div class="content">
|
|
||||||
<div class="settings_group">
|
|
||||||
<div id="manage" class="clickable">Manage Subscription</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group vertical">
|
|
||||||
<input id="key" type="text" placeholder="Subscription Key" style="width: 280px;">
|
|
||||||
<div id="incorrect_key" class="red hidden">Incorrect Key</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="ipbanned_warning" class="warning_box hidden">
|
|
||||||
<p>
|
|
||||||
Your IP has been flagged and is therefore illegible for free credits.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<a href="https://nopecha.com/pricing" target="_blank">Paid subscriptions</a> are not affected by this.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Subscription</div>
|
|
||||||
<div id="plan" class="value green">
|
|
||||||
<div class="loading"><div></div><div></div><div></div><div></div></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Credits</div>
|
|
||||||
<div id="credit" class="value">
|
|
||||||
<div class="loading"><div></div><div></div><div></div><div></div></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Refills</div>
|
|
||||||
<div id="refills" class="value green">
|
|
||||||
<div class="loading"><div></div><div></div><div></div><div></div></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="vspace"></div>
|
|
||||||
|
|
||||||
<div class="tab_btn_row">
|
|
||||||
<div class="tab_btn active" data-target="#hcaptcha_tab">hCaptcha</div>
|
|
||||||
<div class="tab_btn" data-target="#recaptcha_tab">reCAPTCHA</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="tab_content bordered">
|
|
||||||
|
|
||||||
<div id="hcaptcha_tab" class="tab">
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Auto Solve</div>
|
|
||||||
<label class="switch">
|
|
||||||
<input id="hcaptcha_auto_solve" type="checkbox" data-disables="hcaptcha_solve_delay">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Solve Delay <span class="light">(ms)</span></div>
|
|
||||||
<input id="hcaptcha_solve_delay" type="text" class="number">
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Auto Open</div>
|
|
||||||
<label class="switch">
|
|
||||||
<input id="hcaptcha_auto_open" type="checkbox" data-disables="hcaptcha_open_delay">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Open Delay <span class="light">(ms)</span></div>
|
|
||||||
<input id="hcaptcha_open_delay" type="text" class="number">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="recaptcha_tab" class="tab hidden">
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Auto Solve</div>
|
|
||||||
<label class="switch">
|
|
||||||
<input id="recaptcha_auto_solve" type="checkbox" data-disables="recaptcha_solve_delay,recaptcha_solve_method">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Solve Delay <span class="light">(ms)</span></div>
|
|
||||||
<input id="recaptcha_solve_delay" type="text" class="number">
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Auto Open</div>
|
|
||||||
<label class="switch">
|
|
||||||
<input id="recaptcha_auto_open" type="checkbox" data-disables="recaptcha_open_delay">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">Open Delay <span class="light">(ms)</span></div>
|
|
||||||
<input id="recaptcha_open_delay" type="text" class="number">
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings_group">
|
|
||||||
<div class="label">ReCAPTCHA Method</div>
|
|
||||||
<select id="recaptcha_solve_method">
|
|
||||||
<option value="image" selected>Image</option>
|
|
||||||
<option value="voice">Voice</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- <div class="settings_group footer_group">
|
|
||||||
<div class="label">Debug</div>
|
|
||||||
<label class="switch">
|
|
||||||
<input id="debug" type="checkbox">
|
|
||||||
<span class="slider"></span>
|
|
||||||
</label>
|
|
||||||
</div> -->
|
|
||||||
|
|
||||||
<div class="settings_group footer_group">
|
|
||||||
<div id="footer" class="clickable">Join us on Discord</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<script src="popup.js"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
Date.now||(Date.now=function(){return(new Date).getTime()});class BG{static exec(t,n){return new Promise(e=>{try{chrome.runtime.sendMessage({method:t,data:n},e)}catch{e()}})}}class Util{static sleep(t){return new Promise(e=>setTimeout(e,t))}static pad_left(e,t,n){for(;(""+e).length<n;)e=""+t+e;return e}static time_to_hms(e){e=Math.max(0,e);var t=Math.floor(e/3600),n=(e%=3600,Math.floor(e/60)),e=Math.floor(e%60);return`${Util.pad_left(t,"0",2)}:${Util.pad_left(n,"0",2)}:`+Util.pad_left(e,"0",2)}static capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}}let plan=null,checking_server_plan=!1,rendering_server_plan=!1;async function check_plan(){var e=await BG.exec("get_settings");e&&!checking_server_plan&&(checking_server_plan=!0,(plan=await BG.exec("get_server_plan",{key:e.key})).error&&(plan={plan:plan.message,credit:0,quota:0,duration:null,lastreset:null}),checking_server_plan=!1)}async function initialize_ui(){var e=await BG.exec("get_settings");async function t(e,t){const n=document.querySelector(`input#${e}[type="checkbox"]`);if(n){var a=n.dataset?.disables?.split(",");if(a)for(const i of a){const r=document.querySelector("#"+i);r.disabled=!t}n.checked=t,await BG.exec("set_settings",{id:e,value:t})}}async function n(e,t){const n=document.querySelector(`input#${e}[type="text"]`);if(n){try{t=t.trim()}catch{}if(n.classList.contains("number")){try{t=parseInt(t)}catch{t=0}999999<(t=(t=isNaN(t)?0:t)<0?0:t)&&(t=999999)}n.value=t,await BG.exec("set_settings",{id:e,value:t})}}async function a(e,t){const n=document.querySelector("select#"+e);n&&(n.value=t,await BG.exec("set_settings",{id:e,value:t}))}for(const r in e)try{await t(r,e[r]),await n(r,e[r]),await a(r,e[r])}catch{}for(const s of document.querySelectorAll('.settings_group input[type="checkbox"]'))s.addEventListener("change",()=>t(s.id,s.checked));for(const c of document.querySelectorAll('.settings_group input[type="text"]'))c.addEventListener("input",()=>n(c.id,c.value));for(const l of document.querySelectorAll(".settings_group select"))l.addEventListener("change",()=>a(l.id,l.value));document.querySelector("#manage").addEventListener("click",async()=>{await BG.exec("open_tab",{url:"https://nopecha.com/manage"})}),document.querySelector("#footer").addEventListener("click",async()=>{await BG.exec("open_tab",{url:"https://nopecha.com/discord"})});let i=null;document.querySelector("#key").addEventListener("input",()=>{clearTimeout(i),i=setTimeout(check_plan,500)});for(const d of document.querySelectorAll(".tab_btn")){d.dataset.target;d.addEventListener("click",()=>{for(const e of document.querySelectorAll(".tab"))e.classList.add("hidden");for(const t of document.querySelectorAll(".tab_btn"))t.classList.remove("active");d.classList.add("active"),document.querySelector(d.dataset.target).classList.remove("hidden")})}}async function render_plan(){var t=await BG.exec("get_settings");if(t&&plan&&!rendering_server_plan){rendering_server_plan=!0;const a=document.querySelector("#plan"),i=document.querySelector("#credit"),r=document.querySelector("#refills"),s=document.querySelector("#incorrect_key"),c=document.querySelector("#ipbanned_warning");var n=Date.now()/1e3;let e=null;plan.lastreset&&plan.duration&&(e=Math.floor(Math.max(0,plan.duration-(n-plan.lastreset)))),a.innerHTML=plan.plan,"free"===plan.plan?(""!==t.key?s.classList.remove("hidden"):s.classList.add("hidden"),a.classList.remove("green"),a.classList.add("red")):(s.classList.add("hidden"),a.classList.remove("red"),a.classList.add("green")),plan.plan.includes("Banned")?c.classList.remove("hidden"):c.classList.add("hidden"),0===e?(i.classList.remove("green"),i.classList.remove("red"),i.innerHTML='<div class="loading"><div></div><div></div><div></div><div></div></div>'):(i.innerHTML=plan.credit+" / "+plan.quota,0===plan.credit?(i.classList.remove("green"),i.classList.add("red")):(i.classList.remove("red"),i.classList.add("green"))),e?(n=Util.time_to_hms(e),r.innerHTML=""+n):r.innerHTML='<div class="loading"><div></div><div></div><div></div><div></div></div>',0!==plan.duration&&0===e&&await check_plan(),rendering_server_plan=!1}}async function main(){await initialize_ui(),await check_plan(),await render_plan(),setInterval(render_plan,250)}document.addEventListener("DOMContentLoaded",main);
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +0,0 @@
|
||||||
(async()=>{let i=null,n=!1,s=!1;function a(e){let t=e;for(;t&&!t.classList?.contains("rc-imageselect-tile");)t=t.parentNode;return t}function t(e,t,n=!1){!e||!n&&i===e||(!0===t&&e.classList.contains("rc-imageselect-tileselected")||!1===t&&!e.classList.contains("rc-imageselect-tileselected"))&&e.click()}document.addEventListener("mousedown",e=>{const t=a(e?.target);t&&(s=t.classList.contains("rc-imageselect-tileselected")?n=!0:!(n=!0),i=t)}),document.addEventListener("mouseup",e=>{n=!1,i=null}),document.addEventListener("mousemove",e=>{e=a(e?.target);n&&(i!==e&&null!==i&&t(i,s,!0),t(e,s))});window.addEventListener("load",function(e){const t=document.body.appendChild(document.createElement("style")).sheet;t.insertRule(".rc-imageselect-table-33, .rc-imageselect-table-42, .rc-imageselect-table-44 {transition-duration: 0.5s !important}",0),t.insertRule(".rc-imageselect-tile {transition-duration: 2s !important}",1),t.insertRule(".rc-imageselect-dynamic-selected {transition-duration: 1s !important}",2),t.insertRule(".rc-imageselect-progress {transition-duration: 0.5s !important}",3),t.insertRule(".rc-image-tile-overlay {transition-duration: 0.5s !important}",4),t.insertRule("#rc-imageselect img {pointer-events: none !important}",5)})})();
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
(async()=>{class r{static time(){return Date.now||(Date.now=()=>(new Date).getTime()),Date.now()}static sleep(t=1e3){return new Promise(e=>setTimeout(e,t))}static async random_sleep(e,t){t=Math.floor(Math.random()*(t-e)+e);return r.sleep(t)}static pad(e){var t=2-String(e).length+1;return 0<t?""+new Array(t).join("0")+e:""+e}static date(){return new Date}static string(e=null){return e=e||r.date(),r.pad(e.getMonth()+1)+`/${r.pad(e.getDate())}/${e.getFullYear()} ${r.pad(e.getHours()%12)}:${r.pad(e.getMinutes())}:${r.pad(e.getSeconds())} `+(12<=e.getHours()?"PM":"AM")}}class n{static exec(e,a){return new Promise(t=>{try{chrome.runtime.sendMessage({method:e,data:a},t)}catch(e){t()}})}}class o{static async fetch(e,t){return n.exec("fetch",{url:e,options:t})}}function i(){var e,t;if(!l())return e="true"===document.querySelector(".recaptcha-checkbox")?.getAttribute("aria-checked"),t=document.querySelector("#recaptcha-verify-button")?.disabled,e||t}function l(){return"Try again later"===document.querySelector(".rc-doscaptcha-header")?.innerText}async function e(e){i()||(await r.sleep(e.recaptcha_open_delay),document.querySelector("#recaptcha-anchor")?.click())}async function t(t){var a=await n.exec("get_cache",{name:"recaptcha_visible",tab_specific:!0});if(!0===a&&!i())if(l())await n.exec("reset_recaptcha");else{a=document.querySelector(".rc-audiochallenge-tdownload-link")?.href,a=(fetch(a),document.querySelector("#audio-source")?.src?.replace("recaptcha.net","google.com"));let e=document.querySelector("html")?.getAttribute("lang")?.trim();e&&0!==e.length||(e="en");var c=r.time(),a=await o.fetch("https://engageub.pythonanywhere.com",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"input="+encodeURIComponent(a)+"&lang="+e}),a=(document.querySelector("#audio-response").value=a,t.recaptcha_solve_delay-(r.time()-c));0<a&&await r.sleep(a),document.querySelector("#recaptcha-verify-button")?.click()}}for(;;){await r.sleep(1e3);var a=await n.exec("get_settings");a&&"voice"===a.recaptcha_solve_method&&(async function(){var t=document.querySelectorAll('iframe[src*="/recaptcha/api2/bframe"]');if(0<t.length){let e=!1;for(const a of t)if(e="visible"===window.getComputedStyle(a).visibility)break;e?await n.exec("set_cache",{name:"recaptcha_visible",value:!0,tab_specific:!0}):await n.exec("set_cache",{name:"recaptcha_visible",value:!1,tab_specific:!0})}}(),a.recaptcha_auto_open&&null!==document.querySelector(".recaptcha-checkbox")?await e(a):a.recaptcha_auto_solve&&null!==document.querySelector(".rc-imageselect-instructions")?(c=a,await(!0===await n.exec("get_cache",{name:"recaptcha_visible",tab_specific:!0})&&!i()&&(await r.sleep(c.recaptcha_open_delay),!document.querySelector("#recaptcha-audio-button")?.click()))):!a.recaptcha_auto_solve||null===document.querySelector("#audio-instructions")&&null===document.querySelector(".rc-doscaptcha-header")||await t(a))}var c})();
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
const url=new URL(document.location);class BG{static exec(e,n){return new Promise(t=>{try{chrome.runtime.sendMessage({method:e,data:n},t)}catch(e){t()}})}}document.location.hash?(document.body.innerText="Loading...",BG.exec("set_settings",{id:"key",value:document.location.hash.substring(1)}).then(()=>document.body.innerText="Key set!")):document.body.innerText="Missing key. Please set the hash and reload the page.\nExample: https://nopecha.com/setup#sub_testkey1234";
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
"use strict";class Type{static _string_constructor="string".constructor;static _array_constructor=[].constructor;static _object_constructor={}.constructor;static of(e){return null===e?"null":void 0===e?"undefined":e.constructor===Type._string_constructor?"string":e.constructor===Type._array_constructor?"array":e.constructor===Type._object_constructor?"object":""}}class Logger{static debug=!0;static log(e=0){const t=new Array(...arguments).map(e=>["array","object"].includes(Type.of(e))?JSON.stringify(e,null,4):""+e);t.join(" ")}}class Time{static time(){return Date.now||(Date.now=()=>(new Date).getTime()),Date.now()}static sleep(t=1e3){return new Promise(e=>setTimeout(e,t))}static async random_sleep(e,t){t=Math.floor(Math.random()*(t-e)+e);return Time.sleep(t)}static pad(e){var t=2-String(e).length+1;return 0<t?""+new Array(t).join("0")+e:""+e}static date(){return new Date}static string(e=null){return e=e||Time.date(),Time.pad(e.getMonth()+1)+`/${Time.pad(e.getDate())}/${e.getFullYear()} ${Time.pad(e.getHours()%12)}:${Time.pad(e.getMinutes())}:${Time.pad(e.getSeconds())} `+(12<=e.getHours()?"PM":"AM")}}class BG{static exec(e,r){return new Promise(t=>{try{chrome.runtime.sendMessage({method:e,data:r},t)}catch(e){t()}})}}class Net{static async fetch(e,t){return BG.exec("fetch",{url:e,options:t})}}class Image{static encode(t){return new Promise(r=>{if(null===t)return r(null);const e=new XMLHttpRequest;e.onload=()=>{const t=new FileReader;t.onloadend=()=>{let e=t.result;if(e.startsWith("data:text/html;base64,"))return r(null);e=e.replace("data:image/jpeg;base64,",""),r(e)},t.readAsDataURL(e.response)},e.onerror=()=>{r(null)},e.onreadystatechange=()=>{4==this.readyState&&200!=this.status&&r(null)},e.open("GET",t),e.responseType="blob",e.send()})}}class NopeCHA{static INFERENCE_URL="https://api.nopecha.com";static MAX_WAIT_POST=60;static MAX_WAIT_GET=60;static ERRORS={UNKNOWN:9,INVALID_REQUEST:10,RATE_LIIMTED:11,BANNED_USER:12,NO_JOB:13,INCOMPLETE_JOB:14,INVALID_KEY:15,NO_CREDIT:16,UPDATE_REQUIRED:17};static async post({captcha_type:e,task:t,image_urls:r,grid:a,key:n}){for(var o=Date.now(),s=await BG.exec("info_tab");!(Date.now()-o>1e3*NopeCHA.MAX_WAIT_POST);){const u={type:e,task:t,image_urls:r,v:chrome.runtime.getManifest().version,key:n,url:s.url};a&&(u.grid=a);var i=await Net.fetch(NopeCHA.INFERENCE_URL,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"}});try{var c=JSON.parse(i);if("error"in c){if(c.error===NopeCHA.ERRORS.RATE_LIMITED){await Time.sleep(2e3);continue}if(c.error===NopeCHA.ERRORS.INVALID_KEY)break;if(c.error===NopeCHA.ERRORS.NO_CREDIT)break;break}var l="id"in c?c.id:c.data;return await NopeCHA.get({job_id:l,key:n})}catch(e){break}}return{job_id:null,clicks:null}}static async get({key:e,job_id:t}){for(var r=Date.now();!(Date.now()-r>1e3*NopeCHA.MAX_WAIT_GET);){await Time.sleep(500);var a=await Net.fetch(NopeCHA.INFERENCE_URL+`?id=${t}&key=`+e);try{var n=JSON.parse(a);if("error"in n){if(n.error!==NopeCHA.ERRORS.INCOMPLETE_JOB)return{job_id:t,clicks:null};continue}return{job_id:t,clicks:n.data}}catch(e){break}}return{job_id:t,clicks:null}}}function oep(a,n=1,e=100){return new Promise(t=>{const r=setInterval(()=>{var e=document.querySelectorAll(a);if(e.length===n)return clearInterval(r),t(1===n?e[0]:e)},e)})}export{Type,Logger,Time,BG,Net,Image,NopeCHA,oep};
|
|
||||||
3961
package-lock.json
generated
3961
package-lock.json
generated
File diff suppressed because it is too large
Load diff
46
package.json
46
package.json
|
|
@ -1,27 +1,37 @@
|
||||||
{
|
{
|
||||||
"name": "free-games-claimer",
|
"name": "free-games-claimer",
|
||||||
"version": "1.0.0",
|
"version": "1.4.0",
|
||||||
"description": "Claims free games on the Epic Games Store and Amazon Prime Gaming.",
|
"description": "Automatically claims free games on the Epic Games Store, Amazon Prime Gaming and GOG.",
|
||||||
"homepage": "https://github.com/vogler/free-games-claimer",
|
"homepage": "https://github.com/vogler/free-games-claimer",
|
||||||
"main": "index.js",
|
|
||||||
"scripts": {
|
|
||||||
"docker:build": "docker build . -t ghcr.io/vogler/free-games-claimer",
|
|
||||||
"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"
|
|
||||||
},
|
|
||||||
"type": "module",
|
|
||||||
"dependencies": {
|
|
||||||
"cross-env": "^7.0.3",
|
|
||||||
"dotenv": "^16.0.3",
|
|
||||||
"lowdb": "^5.1.0",
|
|
||||||
"otplib": "^12.0.1",
|
|
||||||
"playwright": "^1.30.0",
|
|
||||||
"prompts": "^2.4.2",
|
|
||||||
"puppeteer-extra-plugin-stealth": "^2.11.1"
|
|
||||||
},
|
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/vogler/free-games-claimer.git"
|
"url": "https://github.com/vogler/free-games-claimer.git"
|
||||||
},
|
},
|
||||||
"author": "Ralf Vogler",
|
"author": "Ralf Vogler",
|
||||||
"license": "MIT"
|
"license": "AGPL-3.0-only",
|
||||||
|
"main": "index.js",
|
||||||
|
"scripts": {
|
||||||
|
"docker:build": "docker build . -t ghcr.io/vogler/free-games-claimer",
|
||||||
|
"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",
|
||||||
|
"lint": "npx eslint ."
|
||||||
|
},
|
||||||
|
"type": "module",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=17"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"chalk": "^5.4.1",
|
||||||
|
"cross-env": "^7.0.3",
|
||||||
|
"dotenv": "^16.5.0",
|
||||||
|
"enquirer": "^2.4.1",
|
||||||
|
"fingerprint-injector": "^2.1.66",
|
||||||
|
"lowdb": "^7.0.1",
|
||||||
|
"otplib": "^12.0.1",
|
||||||
|
"playwright-firefox": "^1.52.0",
|
||||||
|
"puppeteer-extra-plugin-stealth": "^2.11.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@stylistic/eslint-plugin-js": "^4.2.0",
|
||||||
|
"eslint": "^9.26.0"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
773
prime-gaming.js
773
prime-gaming.js
|
|
@ -1,81 +1,138 @@
|
||||||
import { firefox } from 'playwright'; // stealth plugin needs no outdated playwright-extra
|
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||||
import { authenticator } from 'otplib';
|
import { authenticator } from 'otplib';
|
||||||
import path from 'path';
|
import chalk from 'chalk';
|
||||||
import { dirs, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list } from './util.js';
|
import { resolve, jsonDb, datetime, stealth, filenamify, prompt, confirm, notify, html_game_list, handleSIGINT } from './src/util.js';
|
||||||
import { cfg } from './config.js';
|
import { cfg } from './src/config.js';
|
||||||
|
|
||||||
// const URL_LOGIN = 'https://www.amazon.de/ap/signin'; // wrong. needs some session args to be valid?
|
const screenshot = (...a) => resolve(cfg.dir.screenshots, 'prime-gaming', ...a);
|
||||||
const URL_CLAIM = 'https://gaming.amazon.com/home';
|
|
||||||
|
const URL_CLAIM = 'https://luna.amazon.com/claims/home';
|
||||||
|
|
||||||
console.log(datetime(), 'started checking prime-gaming');
|
console.log(datetime(), 'started checking prime-gaming');
|
||||||
|
|
||||||
const db = await jsonDb('prime-gaming.json');
|
const db = await jsonDb('prime-gaming.json', {});
|
||||||
db.data ||= {};
|
|
||||||
const migrateDb = (user) => {
|
|
||||||
if (user in db.data || !('claimed' in db.data)) return;
|
|
||||||
db.data[user] = {};
|
|
||||||
for (const e of db.data.claimed) {
|
|
||||||
db.data[user][e.title] = e;
|
|
||||||
}
|
|
||||||
delete db.data.claimed;
|
|
||||||
delete db.data.runs;
|
|
||||||
}
|
|
||||||
|
|
||||||
// https://playwright.dev/docs/auth#multi-factor-authentication
|
// https://playwright.dev/docs/auth#multi-factor-authentication
|
||||||
const context = await firefox.launchPersistentContext(dirs.browser, {
|
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||||
headless: cfg.headless,
|
headless: cfg.headless,
|
||||||
viewport: { width: cfg.width, height: cfg.height },
|
viewport: { width: cfg.width, height: cfg.height },
|
||||||
locale: "en-US", // ignore OS locale to be sure to have english text for locators
|
locale: 'en-US', // ignore OS locale to be sure to have english text for locators
|
||||||
|
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined, // will record a .webm video for each page navigated; without size, video would be scaled down to fit 800x800
|
||||||
|
recordHar: cfg.record ? { path: `data/record/pg-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools
|
||||||
|
handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved
|
||||||
});
|
});
|
||||||
|
|
||||||
// TODO test if needed
|
handleSIGINT(context);
|
||||||
|
|
||||||
await stealth(context);
|
await stealth(context);
|
||||||
|
|
||||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
|
|
||||||
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||||
// console.debug('userAgent:', await page.evaluate(() => navigator.userAgent));
|
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||||
|
|
||||||
const notify_games = [];
|
const notify_games = [];
|
||||||
|
let user;
|
||||||
|
|
||||||
|
const handleMFA = async p => {
|
||||||
|
const otpField = p.locator('#auth-mfa-otpcode, input[name=otpCode]');
|
||||||
|
if (!await otpField.count()) return false;
|
||||||
|
console.log('Two-Step Verification - enter the One Time Password (OTP), e.g. generated by your Authenticator App');
|
||||||
|
await p.locator('#auth-mfa-remember-device, [name=rememberDevice]').check().catch(() => {});
|
||||||
|
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
|
||||||
|
await otpField.first().pressSequentially(otp.toString());
|
||||||
|
await p.locator('input[type="submit"], button[type="submit"]').first().click();
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // default 'load' takes forever
|
||||||
// need to wait for some elements to exist before checking if signed in or accepting cookies:
|
const handleDirectLoginPage = async () => {
|
||||||
await Promise.any(['button:has-text("Sign in")', '[data-a-target="user-dropdown-first-name-text"]'].map(s => page.waitForSelector(s)));
|
if (!page.url().includes('/ap/signin')) return false;
|
||||||
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?
|
console.log('On Amazon login page (redirect). Trying to sign in automatically.');
|
||||||
while (await page.locator('button:has-text("Sign in")').count() > 0) {
|
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout);
|
||||||
console.error('Not signed in anymore.');
|
|
||||||
await page.click('button:has-text("Sign in")');
|
|
||||||
if (!cfg.debug) context.setDefaultTimeout(0); // give user time to log in without timeout
|
|
||||||
if (cfg.pg_email && cfg.pg_password) console.info('Using email and password from environment.');
|
|
||||||
else console.info('Press ESC to skip if you want to login in the browser (not possible in default headless mode).');
|
|
||||||
const email = cfg.pg_email || await prompt({ message: 'Enter email' });
|
const email = cfg.pg_email || await prompt({ message: 'Enter email' });
|
||||||
const password = email && (cfg.pg_password || await prompt({ type: 'password', message: 'Enter password' }));
|
const password = email && (cfg.pg_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||||
if (email && password) {
|
if (email && password) {
|
||||||
await page.fill('[name=email]', email);
|
await page.fill('[name=email]', email);
|
||||||
await page.fill('[name=password]', password);
|
|
||||||
await page.check('[name=rememberMe]');
|
|
||||||
await page.click('input[type="submit"]');
|
await page.click('input[type="submit"]');
|
||||||
page.waitForURL('**/ap/signin**').then(async () => { // check for wrong credentials
|
await page.fill('[name=password]', password);
|
||||||
|
await page.click('input[type="submit"]');
|
||||||
|
await handleMFA(page).catch(() => {});
|
||||||
|
try {
|
||||||
|
await page.waitForURL('**/ap/signin**');
|
||||||
const error = await page.locator('.a-alert-content').first().innerText();
|
const error = await page.locator('.a-alert-content').first().innerText();
|
||||||
console.error(error);
|
if (error.trim().length) {
|
||||||
notify(`prime-gaming: login: ${error}`);
|
console.error('Login error:', error);
|
||||||
|
await notify(`prime-gaming: login: ${error}`);
|
||||||
await context.close(); // finishes potential recording
|
await context.close(); // finishes potential recording
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
}
|
||||||
// handle MFA, but don't await it
|
} catch {
|
||||||
page.waitForURL('**/ap/mfa**').then(async () => {
|
// if navigation succeeded, continue
|
||||||
console.log('Two-Step Verification - enter the One Time Password (OTP), e.g. generated by your Authenticator App');
|
}
|
||||||
await page.check('[name=rememberDevice]');
|
await page.waitForURL(/luna\.amazon\.com\/claims\/.*signedIn=true/);
|
||||||
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
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
await page.type('input[name=otpCode]', otp.toString());
|
return true;
|
||||||
|
} else {
|
||||||
|
console.log('Waiting for manual login on redirect page.');
|
||||||
|
if (cfg.headless) {
|
||||||
|
console.log('Run `SHOW=1 node prime-gaming` to login in the opened browser.');
|
||||||
|
await context.close(); // finishes potential recording
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
await handleDirectLoginPage();
|
||||||
|
// need to wait for some elements to exist before checking if signed in or accepting cookies:
|
||||||
|
await Promise.any([
|
||||||
|
'button:has-text("Sign in")',
|
||||||
|
'button:has-text("Anmelden")',
|
||||||
|
'[data-a-target="user-dropdown-first-name-text"]',
|
||||||
|
'[data-testid="user-dropdown-first-name-text"]',
|
||||||
|
].map(s => page.waitForSelector(s)));
|
||||||
|
try {
|
||||||
|
await page.click('[aria-label="Cookies usage disclaimer banner"] button:has-text("Accept Cookies")'); // to not waste screen space when non-headless; could be flaky
|
||||||
|
} catch {
|
||||||
|
// ignore if banner not present
|
||||||
|
}
|
||||||
|
while (await page.locator('button:has-text("Sign in"), button:has-text("Anmelden")').count() > 0) {
|
||||||
|
console.error('Not signed in anymore.');
|
||||||
|
await page.click('button:has-text("Sign in")');
|
||||||
|
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
|
||||||
|
console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`);
|
||||||
|
if (cfg.pg_email && cfg.pg_password) console.info('Using email and password from environment.');
|
||||||
|
else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).');
|
||||||
|
const email = cfg.pg_email || await prompt({ message: 'Enter email' });
|
||||||
|
const password = email && (cfg.pg_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||||
|
if (email && password) {
|
||||||
|
await page.fill('[name=email]', email);
|
||||||
await page.click('input[type="submit"]');
|
await page.click('input[type="submit"]');
|
||||||
}).catch(_ => { });
|
await page.fill('[name=password]', password);
|
||||||
|
await page.click('input[type="submit"]');
|
||||||
|
try {
|
||||||
|
await page.waitForURL('**/ap/signin**');
|
||||||
|
const error = await page.locator('.a-alert-content').first().innerText();
|
||||||
|
if (error.trim().length) {
|
||||||
|
console.error('Login error:', error);
|
||||||
|
await notify(`prime-gaming: login: ${error}`);
|
||||||
|
await context.close(); // finishes potential recording
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// navigation ok
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await handleMFA(page);
|
||||||
|
} catch {
|
||||||
|
// ignore MFA watcher errors
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log('Waiting for you to login in the browser.');
|
console.log('Waiting for you to login in the browser.');
|
||||||
notify('prime-gaming: no longer signed in and not enough options set for automatic login.');
|
await notify('prime-gaming: no longer signed in and not enough options set for automatic login.');
|
||||||
if (cfg.headless) {
|
if (cfg.headless) {
|
||||||
console.log('Please run `node prime-gaming show` to login in the opened browser.');
|
console.log('Run `SHOW=1 node prime-gaming` to login in the opened browser.');
|
||||||
await context.close(); // finishes potential recording
|
await context.close(); // finishes potential recording
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
@ -83,101 +140,585 @@ try {
|
||||||
await page.waitForURL('https://gaming.amazon.com/home?signedIn=true');
|
await page.waitForURL('https://gaming.amazon.com/home?signedIn=true');
|
||||||
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
}
|
}
|
||||||
const user = await page.locator('[data-a-target="user-dropdown-first-name-text"]').first().innerText();
|
user = await page.locator('[data-a-target="user-dropdown-first-name-text"], [data-testid="user-dropdown-first-name-text"]').first().innerText();
|
||||||
console.log(`Signed in as ${user}`);
|
console.log(`Signed in as ${user}`);
|
||||||
// await page.click('button[aria-label="User dropdown and more options"]');
|
|
||||||
// const twitch = await page.locator('[data-a-target="TwitchDisplayName"]').first().innerText();
|
|
||||||
// console.log(`Twitch user name is ${twitch}`);
|
|
||||||
migrateDb(user); // TODO remove this after some time since it will run fine without and people can still use this commit to adjust their data/prime-gaming.json
|
|
||||||
db.data[user] ||= {};
|
db.data[user] ||= {};
|
||||||
|
|
||||||
await page.click('button[data-type="Game"]');
|
if (await page.getByRole('button', { name: 'Try Prime' }).count()) {
|
||||||
const games_sel = 'div[data-a-target="offer-list-FGWP_FULL"]';
|
console.error('User is currently not an Amazon Prime member, so no games to claim. Exit!');
|
||||||
await page.waitForSelector(games_sel);
|
await context.close();
|
||||||
console.log('Number of already claimed games (total):', await page.locator(`${games_sel} p:has-text("Collected")`).count());
|
process.exit(1);
|
||||||
const game_sel = `${games_sel} [data-a-target="item-card"]:has-text("Claim game")`;
|
|
||||||
console.log('Number of free unclaimed games (Prime Gaming):', await page.locator(game_sel).count());
|
|
||||||
const games = await page.$$(game_sel);
|
|
||||||
// for (let i=1; i<=n; i++) {
|
|
||||||
for (const card of games) {
|
|
||||||
// const card = page.locator(`:nth-match(${game_sel}, ${i})`); // this will reevaluate after games are claimed and index will be wrong
|
|
||||||
// const title = await card.locator('h3').first().innerText();
|
|
||||||
const title = await (await card.$('.item-card-details__body__primary')).innerText();
|
|
||||||
console.log('Current free game:', title);
|
|
||||||
if (cfg.dryrun) continue;
|
|
||||||
// const img = await (await card.$('img.tw-image')).getAttribute('src');
|
|
||||||
// console.log('Image:', img);
|
|
||||||
const p = path.resolve(dirs.screenshots, 'prime-gaming', 'internal', `${filenamify(title)}.png`);
|
|
||||||
await card.screenshot({ path: p });
|
|
||||||
await (await card.$('button:has-text("Claim game")')).click();
|
|
||||||
db.data[user][title] ||= { title, time: datetime(), store: 'internal' };
|
|
||||||
notify_games.push({ title, status: 'claimed', url: URL_CLAIM });
|
|
||||||
// await page.pause();
|
|
||||||
}
|
}
|
||||||
// claim games in external/linked stores. Linked: origin.com, epicgames.com; Redeem-key: gog.com, legacygames.com, microsoft
|
|
||||||
let n;
|
const waitUntilStable = async (f, act) => {
|
||||||
const game_sel_ext = `${games_sel} [data-a-target="item-card"]:has(p:text-is("Claim"))`;
|
let v;
|
||||||
do {
|
while (true) {
|
||||||
n = await page.locator(game_sel_ext).count();
|
const v2 = await f();
|
||||||
console.log('Number of free unclaimed games (external stores):', n);
|
console.log('waitUntilStable', v2);
|
||||||
const card = await page.$(game_sel_ext);
|
if (v == v2) break;
|
||||||
if (!card) break;
|
v = v2;
|
||||||
const title = await (await card.$('.item-card-details__body__primary')).innerText();
|
await act();
|
||||||
console.log('Current free game:', title);
|
}
|
||||||
if (cfg.dryrun) continue;
|
};
|
||||||
await (await card.$('text=Claim')).click(); // goes to URL of game, no need to wait
|
const scrollUntilStable = async f => await waitUntilStable(f, async () => {
|
||||||
await Promise.any([page.click('button:has-text("Claim now")'), page.click('button:has-text("Complete Claim")'), page.waitForSelector('div:has-text("Link game account")')]); // waits for navigation
|
// await page.keyboard.press('End'); // scroll to bottom to show all games
|
||||||
const store_text = await (await page.$('[data-a-target="hero-header-subtitle"]')).innerText();
|
// loading all games became flaky; see https://github.com/vogler/free-games-claimer/issues/357
|
||||||
// Full game for PC [and MAC] on: gog.com, Origin, Legacy Games, EPIC GAMES, Battle.net
|
await page.keyboard.press('PageDown'); // scrolling to straight to the bottom started to skip loading some games
|
||||||
// 3 Full PC Games on Legacy Games
|
await page.waitForLoadState('networkidle'); // wait for all games to be loaded
|
||||||
const store = store_text.toLowerCase().replace(/.* on /, '');
|
await page.waitForTimeout(3000); // extra wait to load all already collected games
|
||||||
console.log(' External store:', store);
|
// do it again since once wasn't enough...
|
||||||
const url = page.url().split('?')[0];
|
await page.keyboard.press('PageDown');
|
||||||
db.data[user][title] ||= { title, time: datetime(), url, store };
|
await page.waitForTimeout(3000);
|
||||||
const notify_game = { title, url, status: `failed - link ${store}` };
|
});
|
||||||
notify_games.push(notify_game); // status is updated below
|
|
||||||
if (await page.locator('div:has-text("Link game account")').count()) {
|
const openGamesTab = async () => {
|
||||||
console.error(' Account linking is required to claim this offer!');
|
const selectors = [
|
||||||
|
'button[data-type="Game"]', // old layout
|
||||||
|
'button:has-text("Games")',
|
||||||
|
'button:has-text("Games einlösen")',
|
||||||
|
'[data-test-selector="category-picker"] button:has-text("Games")',
|
||||||
|
'[data-testid="category-picker"] button:has-text("Games")',
|
||||||
|
];
|
||||||
|
for (const sel of selectors) {
|
||||||
|
const btn = page.locator(sel).first();
|
||||||
|
if (await btn.count()) {
|
||||||
|
await btn.click();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// New Luna claims home: try the filter/CTA button with embedded <p title="Games einlösen">
|
||||||
|
const gamesTitle = page.locator('p.offer-filters__button__title:has-text("Games"), p.offer-filters__button__title:has-text("einlösen")');
|
||||||
|
if (await gamesTitle.count()) {
|
||||||
|
const btn = gamesTitle.first().locator('xpath=ancestor::button[1]');
|
||||||
|
if (await btn.count()) {
|
||||||
|
await btn.click();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// New Luna claims home already shows games list
|
||||||
|
};
|
||||||
|
|
||||||
|
await openGamesTab();
|
||||||
|
|
||||||
|
const locateGamesList = async () => {
|
||||||
|
const selectors = [
|
||||||
|
'div[data-a-target="offer-list-FGWP_FULL"]', // old layout
|
||||||
|
'[data-testid="offer-list"]',
|
||||||
|
'[data-test-selector="offer-list"]',
|
||||||
|
'section:has(h2:has-text("Games with Prime"))',
|
||||||
|
'section:has(h2:has-text("Games"))',
|
||||||
|
];
|
||||||
|
for (const sel of selectors) {
|
||||||
|
const loc = page.locator(sel).first();
|
||||||
|
if (await loc.count()) return loc;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const games = await locateGamesList();
|
||||||
|
// Load all cards (old and new layout) by scrolling the container or the page
|
||||||
|
if (games) await scrollUntilStable(() => games.evaluate(el => el.scrollHeight).catch(() => 0));
|
||||||
|
await scrollUntilStable(() => page.evaluate(() => globalThis.document?.scrollingElement?.scrollHeight ?? 0));
|
||||||
|
|
||||||
|
const normalizeClaimUrl = url => {
|
||||||
|
if (!url) return { url, key: null };
|
||||||
|
const m = url.match(/(https?:\/\/[^/]+)?(\/claims\/[^?#]+)/);
|
||||||
|
if (!m) return { url, key: url };
|
||||||
|
const path = m[2];
|
||||||
|
const slug = path.split('/')[2];
|
||||||
|
return { url: 'https://luna.amazon.com' + path, key: slug || path };
|
||||||
|
};
|
||||||
|
|
||||||
|
const cards = [];
|
||||||
|
// New layout: direct claim buttons on cards (FGWPOffer) with "Spiel aktivieren"/"Claim"
|
||||||
|
const fgwps = page.locator('[data-a-target="FGWPOffer"]');
|
||||||
|
if (await fgwps.count()) {
|
||||||
|
for (const handle of await fgwps.elementHandles()) {
|
||||||
|
const href = await handle.getAttribute('href');
|
||||||
|
const { url, key } = normalizeClaimUrl(href?.startsWith('/') ? href : href || '');
|
||||||
|
const title =
|
||||||
|
await handle.$eval('p[title], span[title]', el => el.getAttribute('title')).catch(() => null) ||
|
||||||
|
await handle.$eval('p, span', el => el.textContent).catch(() => null) ||
|
||||||
|
key ||
|
||||||
|
'Unknown title';
|
||||||
|
cards.push({ kind: 'external', title, url, key });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const anchorClaims = page.locator('a[href*="/claims/"][href*="amzn1.pg.item"]');
|
||||||
|
if (await anchorClaims.count()) {
|
||||||
|
const hrefs = [...new Set(await anchorClaims.evaluateAll(anchors => anchors.map(a => a.getAttribute('href')).filter(Boolean)))];
|
||||||
|
for (const href of hrefs) {
|
||||||
|
const { url, key } = normalizeClaimUrl(href);
|
||||||
|
const title = key || await anchorClaims.first().innerText() || 'Unknown title';
|
||||||
|
cards.push({ kind: 'external', title, url, key });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cards.length && games) {
|
||||||
|
const cardLocator = games.locator([
|
||||||
|
'[data-testid="offer-card"]',
|
||||||
|
'[data-test-selector="offer-card"]',
|
||||||
|
'.item-card__action',
|
||||||
|
].join(','));
|
||||||
|
if (await cardLocator.count() === 0) {
|
||||||
|
console.log('No games found in list.');
|
||||||
} else {
|
} else {
|
||||||
|
for (const handle of await cardLocator.elementHandles()) {
|
||||||
|
const text = (await handle.textContent() || '').toLowerCase();
|
||||||
|
if (text.includes('collected')) continue; // skip already claimed
|
||||||
|
const title = await (await handle.$('h3, h4, [data-testid="item-card-title"], [data-test-selector="item-card-title"], .item-card-details__body__primary'))?.innerText() || 'Unknown title';
|
||||||
|
const linkEl = await handle.$('a[href]');
|
||||||
|
let url = linkEl && await linkEl.getAttribute('href');
|
||||||
|
if (url?.startsWith('/')) url = 'https://luna.amazon.com' + url;
|
||||||
|
const { url: normUrl, key } = normalizeClaimUrl(url);
|
||||||
|
const hasLinkClaim = await handle.$('a:has-text("Claim"), a:has-text("Get"), a:has-text("Details")');
|
||||||
|
const hasButtonClaim = await handle.$('button:has-text("Claim"), button:has-text("Get"), button:has-text("Get game"), button:has-text("Play")');
|
||||||
|
const hasGermanCTA = await handle.$(':is(button,p,a):has-text("Spiel aktivieren"), :is(button,p,a):has-text("Spiel holen")');
|
||||||
|
if (hasLinkClaim || hasGermanCTA) cards.push({ kind: 'external', title, url: normUrl, key });
|
||||||
|
else if (hasButtonClaim) cards.push({ kind: 'internal', title, url: normUrl, key, handle });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dedup by URL to avoid duplicates from multiple selectors
|
||||||
|
const seenUrl = new Set();
|
||||||
|
const uniq = cards.filter(c => {
|
||||||
|
const key = c.key || c.url || c.title;
|
||||||
|
if (seenUrl.has(key)) return false;
|
||||||
|
seenUrl.add(key);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const internal = uniq.filter(c => c.kind == 'internal');
|
||||||
|
const external = uniq.filter(c => c.kind == 'external');
|
||||||
|
// bottom to top: oldest to newest games
|
||||||
|
internal.reverse();
|
||||||
|
external.reverse();
|
||||||
|
const sameOrNewPage = async url => {
|
||||||
|
const isNew = page.url() != url;
|
||||||
|
let p = page;
|
||||||
|
if (isNew) {
|
||||||
|
p = await context.newPage();
|
||||||
|
await p.goto(url, { waitUntil: 'domcontentloaded' });
|
||||||
|
}
|
||||||
|
return [p, isNew];
|
||||||
|
};
|
||||||
|
const skipBasedOnTime = async url => {
|
||||||
|
const [p, isNew] = await sameOrNewPage(url);
|
||||||
|
const dueDateLoc = p.locator('.availability-date .tw-bold, [data-testid="availability-end-date"], [data-test-selector="availability-end-date"]');
|
||||||
|
if (!await dueDateLoc.count()) {
|
||||||
|
if (isNew) await p.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const dueDateOrg = await dueDateLoc.first().innerText();
|
||||||
|
const dueDate = new Date(Date.parse(dueDateOrg + ' 17:00'));
|
||||||
|
const daysLeft = (dueDate.getTime() - Date.now()) / 1000 / 60 / 60 / 24;
|
||||||
|
const availabilityText = await p.locator('.availability-date, [data-testid="availability-end-date"], [data-test-selector="availability-end-date"]').first().innerText().catch(() => dueDateOrg);
|
||||||
|
console.log(' ', availabilityText, '->', daysLeft.toFixed(2));
|
||||||
|
if (isNew) await p.close();
|
||||||
|
return daysLeft > cfg.pg_timeLeft;
|
||||||
|
};
|
||||||
|
console.log('\nNumber of free unclaimed games (Prime Gaming):', internal.length);
|
||||||
|
// claim games in internal store
|
||||||
|
for (const card of internal) {
|
||||||
|
await card.handle.scrollIntoViewIfNeeded();
|
||||||
|
const title = card.title;
|
||||||
|
const url = card.url;
|
||||||
|
console.log('Current free game:', chalk.blue(title));
|
||||||
|
if (cfg.pg_timeLeft && url && await skipBasedOnTime(url)) continue;
|
||||||
|
if (cfg.dryrun) continue;
|
||||||
|
if (cfg.interactive) {
|
||||||
|
const confirmed = await confirm();
|
||||||
|
if (!confirmed) continue;
|
||||||
|
}
|
||||||
|
await card.handle.locator('.tw-button:has-text("Claim"), .tw-button:has-text("Get"), button:has-text("Claim"), button:has-text("Get")').first().click();
|
||||||
|
db.data[user][title] ||= { title, time: datetime(), url, store: 'internal' };
|
||||||
|
notify_games.push({ title, status: 'claimed', url });
|
||||||
|
await card.handle.screenshot({ path: screenshot('internal', `${filenamify(title)}.png`) });
|
||||||
|
}
|
||||||
|
console.log('\nNumber of free unclaimed games (external stores):', external.length);
|
||||||
|
// claim games in external/linked stores. Linked: origin.com, epicgames.com; Redeem-key: gog.com, legacygames.com, microsoft
|
||||||
|
const external_info = [];
|
||||||
|
for (const card of external) { // need to get data incl. URLs in this loop and then navigate in another, otherwise .all() would update after coming back and .elementHandles() like above would lead to error due to page navigation: elementHandle.$: Protocol error (Page.adoptNode)
|
||||||
|
const title = card.title;
|
||||||
|
const url = card.url ? card.url.split('?')[0] : undefined;
|
||||||
|
if (!url) continue;
|
||||||
|
external_info.push({ title, url });
|
||||||
|
}
|
||||||
|
const clickCTA = async p => {
|
||||||
|
const candidates = [
|
||||||
|
p.locator('button[data-a-target="buy-box_call-to-action"]').first(),
|
||||||
|
p.locator('[data-a-target="buy-box_call-to-action"]').first(),
|
||||||
|
p.locator('[data-a-target="buy-box"] .tw-button:has-text("Get game")').first(),
|
||||||
|
p.locator('[data-a-target="buy-box"] .tw-button:has-text("Claim")').first(),
|
||||||
|
p.locator('.tw-button:has-text("Complete Claim")').first(),
|
||||||
|
p.locator('[data-a-target="buy-box_call-to-action-text"]').first().locator('xpath=ancestor::button[1]'),
|
||||||
|
p.locator('.tw-button:has-text("Spiel holen"), .tw-button:has-text("Spiel aktivieren")').first(),
|
||||||
|
p.locator('p:has-text("Spiel holen"), p:has-text("Spiel aktivieren")').first().locator('xpath=ancestor::button[1]'),
|
||||||
|
];
|
||||||
|
for (const c of candidates) {
|
||||||
|
if (await c.count()) {
|
||||||
|
try {
|
||||||
|
await c.waitFor({ state: 'visible', timeout: 5000 });
|
||||||
|
const enabled = await c.isEnabled();
|
||||||
|
if (enabled) await c.click();
|
||||||
|
else {
|
||||||
|
await c.evaluate(el => {
|
||||||
|
el.disabled = false;
|
||||||
|
el.removeAttribute('disabled');
|
||||||
|
el.click();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
// try next candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const { title, url } of external_info) {
|
||||||
|
console.log('Current free game:', chalk.blue(title)); // , url);
|
||||||
|
const existingStatus = db.data[user]?.[title]?.status;
|
||||||
|
if (existingStatus && !existingStatus.startsWith('failed')) {
|
||||||
|
console.log(` Already recorded as ${existingStatus}, skipping.`);
|
||||||
|
notify_games.push({ title, url, status: 'existed' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||||
|
await page.waitForSelector('[data-a-target="buy-box"]', { timeout: 10000 }).catch(() => {});
|
||||||
|
if (cfg.debug) await page.pause();
|
||||||
|
let store = 'unknown';
|
||||||
|
const detailLoc = page.locator('[data-a-target="DescriptionItemDetails"], [data-testid="DescriptionItemDetails"]');
|
||||||
|
if (await detailLoc.count()) {
|
||||||
|
const item_text = await detailLoc.first().innerText();
|
||||||
|
const lower = item_text.toLowerCase();
|
||||||
|
const onPos = lower.lastIndexOf(' on ');
|
||||||
|
if (onPos >= 0) store = lower.slice(onPos + 4).replace(/[.!]$/, '');
|
||||||
|
} else if (url.includes('/claims/')) {
|
||||||
|
const slug = url.split('/claims/')[1]?.split('/')[0] || '';
|
||||||
|
if (slug.includes('gog')) store = 'gog.com';
|
||||||
|
else if (slug.includes('epic')) store = 'epic-games';
|
||||||
|
else if (slug.includes('origin')) store = 'origin';
|
||||||
|
else if (slug.includes('xbox') || slug.includes('microsoft')) store = 'microsoft store';
|
||||||
|
else if (slug.includes('legacy')) store = 'legacy games';
|
||||||
|
const lunaPlay = await page.locator('[data-a-target="LunaOffer"], button[data-a-target="LunaOffer"], button:has-text("Spielen")').count();
|
||||||
|
if (store == 'unknown' && lunaPlay) store = 'luna';
|
||||||
|
}
|
||||||
|
console.log(' External store:', store);
|
||||||
|
const notify_game = { title, url };
|
||||||
|
notify_games.push(notify_game); // status is updated below
|
||||||
|
// Already collected? skip
|
||||||
|
const collectedLoc = page.locator('[data-a-target="ClaimStateQuantityAndDateContent"], [data-a-target="ClaimStateClaimCodeContent"]:has-text("Collected"), [data-a-target="ClaimStateVendorContent"], [data-a-target="ClaimStateViewDetailsAndInstructions"]');
|
||||||
|
const collectedText = page.getByText(/You collected this on/i);
|
||||||
|
const collectedEpic = page.getByText(/Sent to your Epic Games Store library/i);
|
||||||
|
const collectedBanner = page.locator('p.tw-c-text-alert-success:has-text("Collected"), p.tw-c-text-alert-success:has-text("Collected this")');
|
||||||
|
const collectedSuccessIcon = page.locator('[data-a-target="ItemCardDetailSuccessStatus"], .claim-state__success-icon');
|
||||||
|
const disabledCTA = page.locator('[data-a-target="buy-box_call-to-action"][disabled], button[disabled]:has-text("Get game")');
|
||||||
|
const collectedAny = await Promise.all([
|
||||||
|
collectedLoc.count(),
|
||||||
|
collectedBanner.count(),
|
||||||
|
collectedText.count(),
|
||||||
|
collectedEpic.count(),
|
||||||
|
collectedSuccessIcon.count(),
|
||||||
|
disabledCTA.count(),
|
||||||
|
]).then(([a, b, c, d, e, f]) => a + b + c + d + e + f > 0);
|
||||||
|
if (collectedAny) {
|
||||||
|
console.log(' Already collected, skipping.');
|
||||||
|
notify_game.status = 'existed';
|
||||||
|
db.data[user][title] ||= { title, time: datetime(), url, store, status: 'existed' };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Disabled CTA (e.g., needs linking or not available)
|
||||||
|
if (await disabledCTA.count()) {
|
||||||
|
if (store !== 'epic-games') {
|
||||||
|
console.log(' CTA is disabled, skipping (likely needs linking/not available).');
|
||||||
|
notify_game.status = 'disabled';
|
||||||
|
db.data[user][title] ||= { title, time: datetime(), url, store, status: 'disabled' };
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
console.log(' CTA disabled for epic-games, will still try to link/claim.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (store == 'luna') {
|
||||||
|
console.log(' Luna cloud title detected, skipping code redemption.');
|
||||||
|
notify_game.status = 'luna (play)';
|
||||||
|
db.data[user][title] ||= { title, time: datetime(), url, store: 'luna', status: 'luna (play)' };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (cfg.pg_timeLeft && await skipBasedOnTime(url)) continue;
|
||||||
|
if (cfg.dryrun) continue;
|
||||||
|
if (cfg.interactive) {
|
||||||
|
const confirmed = await confirm();
|
||||||
|
if (!confirmed) continue;
|
||||||
|
}
|
||||||
|
await clickCTA(page);
|
||||||
|
await Promise.any([
|
||||||
|
page.waitForSelector('.thank-you-title:has-text("Success")', { timeout: cfg.timeout }).catch(() => {}),
|
||||||
|
page.waitForSelector('div:has-text("Link game account")', { timeout: cfg.timeout }).catch(() => {}),
|
||||||
|
]).catch(() => {});
|
||||||
|
db.data[user][title] ||= { title, time: datetime(), url, store };
|
||||||
|
if (await page.locator('div:has-text("Link game account")').count() // epic games store also shows "Link account"
|
||||||
|
|| await page.locator('div:has-text("Link account")').count()) {
|
||||||
|
console.error(' Account linking is required to claim this offer!');
|
||||||
|
notify_game.status = `failed: need account linking for ${store}`;
|
||||||
|
db.data[user][title].status = 'failed: need account linking';
|
||||||
|
// await page.pause();
|
||||||
|
// await page.click('[data-a-target="LinkAccountModal"] [data-a-target="LinkAccountButton"]');
|
||||||
|
// login for epic games also needed if already logged in
|
||||||
|
// wait for https://www.epicgames.com/id/authorize?redirect_uri=https%3A%2F%2Fservice.link.amazon.gg...
|
||||||
|
// await page.click('button[aria-label="Allow"]');
|
||||||
|
} else {
|
||||||
|
db.data[user][title].status = 'claimed';
|
||||||
// print code if there is one
|
// print code if there is one
|
||||||
const redeem = {
|
const redeem = {
|
||||||
// 'origin': 'https://www.origin.com/redeem', // TODO still needed or now only via account linking?
|
// 'origin': 'https://www.origin.com/redeem', // kept for legacy flows; current path uses account linking
|
||||||
'gog.com': 'https://www.gog.com/redeem',
|
'gog.com': 'https://www.gog.com/redeem',
|
||||||
|
'microsoft store': 'https://account.microsoft.com/billing/redeem',
|
||||||
|
xbox: 'https://account.microsoft.com/billing/redeem',
|
||||||
'legacy games': 'https://www.legacygames.com/primedeal',
|
'legacy games': 'https://www.legacygames.com/primedeal',
|
||||||
'microsoft games': 'https://redeem.microsoft.com',
|
|
||||||
};
|
};
|
||||||
if (store in redeem) { // did not work for linked origin: && !await page.locator('div:has-text("Successfully Claimed")').count()
|
if (store in redeem) { // did not work for linked origin: && !await page.locator('div:has-text("Successfully Claimed")').count()
|
||||||
const code = await page.inputValue('input[type="text"]');
|
let code;
|
||||||
console.log(' Code to redeem game:', code);
|
try {
|
||||||
if (store == 'legacy games') { // may be different URL like https://legacygames.com/primeday/puzzleoftheyear/
|
// ensure CTA was clicked in case code is behind it
|
||||||
redeem[store] = await (await page.$('li:has-text("Click here") a')).getAttribute('href');
|
await clickCTA(page).catch(() => {});
|
||||||
|
code = await Promise.any([
|
||||||
|
page.inputValue('input[type="text"]'),
|
||||||
|
page.textContent('[data-a-target="ClaimStateClaimCodeContent"]').then(s => s.replace('Your code: ', '')),
|
||||||
|
]);
|
||||||
|
} catch {
|
||||||
|
console.error(' Could not find claim code on page (timeout). Please check manually.');
|
||||||
|
db.data[user][title].status = 'claimed (code not found)';
|
||||||
|
notify_game.status = 'claimed (code not found)';
|
||||||
|
await page.screenshot({ path: screenshot('external', `${filenamify(title)}_nocode.png`), fullPage: true }).catch(() => {});
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
console.log(' URL to redeem game:', redeem[store]);
|
console.log(' Code to redeem game:', chalk.blue(code));
|
||||||
|
if (store == 'legacy games') { // may be different URL like https://legacygames.com/primeday/puzzleoftheyear/
|
||||||
|
redeem[store] = await (await page.$('li:has-text("Click here") a')).getAttribute('href'); // full text: Click here to enter your redemption code.
|
||||||
|
}
|
||||||
|
let redeem_url = redeem[store];
|
||||||
|
if (store == 'gog.com') redeem_url += '/' + code; // to log and notify, but can't use for goto below (captcha)
|
||||||
|
console.log(' URL to redeem game:', redeem_url);
|
||||||
db.data[user][title].code = code;
|
db.data[user][title].code = code;
|
||||||
notify_game.status = `<a href="${redeem[store]}">redeem</a> ${code} on ${store}`;
|
let redeem_action = 'redeem';
|
||||||
|
if (cfg.pg_redeem) { // try to redeem keys on external stores
|
||||||
|
console.log(` Trying to redeem ${code} on ${store} (need to be logged in)!`);
|
||||||
|
const page2 = await context.newPage();
|
||||||
|
await page2.goto(redeem[store], { waitUntil: 'domcontentloaded' });
|
||||||
|
if (store == 'gog.com') {
|
||||||
|
await page2.fill('#codeInput', code);
|
||||||
|
const r1 = page2.waitForResponse(r => r.request().method() == 'GET' && r.url().startsWith('https://redeem.gog.com/'));
|
||||||
|
await page2.click('[type="submit"]'); // click Continue
|
||||||
|
const r1t = await (await r1).text();
|
||||||
|
const reason = JSON.parse(r1t).reason;
|
||||||
|
// {"reason":"Invalid or no captcha"}
|
||||||
|
// {"reason":"code_used"}
|
||||||
|
// {"reason":"code_not_found"}
|
||||||
|
if (reason?.includes('captcha')) {
|
||||||
|
redeem_action = 'redeem (got captcha)';
|
||||||
|
console.error(' Got captcha; could not redeem!');
|
||||||
|
} else if (reason == 'code_used') {
|
||||||
|
redeem_action = 'already redeemed';
|
||||||
|
console.log(' Code was already used!');
|
||||||
|
} else if (reason == 'code_not_found') {
|
||||||
|
redeem_action = 'redeem (not found)';
|
||||||
|
console.error(' Code was not found!');
|
||||||
|
} else { // unknown state; keep info log for later analysis
|
||||||
|
redeem_action = 'redeemed?';
|
||||||
|
console.debug(` Response 1: ${r1t}`);
|
||||||
|
const r2 = page2.waitForResponse(r => r.request().method() == 'POST' && r.url().startsWith('https://redeem.gog.com/'));
|
||||||
|
await page2.click('[type="submit"]'); // click Redeem
|
||||||
|
const r2t = await (await r2).text();
|
||||||
|
const reason2 = JSON.parse(r2t).reason;
|
||||||
|
if (r2t == '{}') {
|
||||||
|
redeem_action = 'redeemed';
|
||||||
|
console.log(' Redeemed successfully.');
|
||||||
|
db.data[user][title].status = 'claimed and redeemed';
|
||||||
|
} else if (reason2?.includes('captcha')) {
|
||||||
|
redeem_action = 'redeem (got captcha)';
|
||||||
|
console.error(' Got captcha; could not redeem!');
|
||||||
|
} else {
|
||||||
|
console.debug(` Response 2: ${r2t}`);
|
||||||
|
console.log(' Unknown Response 2 - please report in https://github.com/vogler/free-games-claimer/issues/5');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (store == 'microsoft store' || store == 'xbox') {
|
||||||
|
console.error(` Redeem on ${store} is experimental!`);
|
||||||
|
if (page2.url().startsWith('https://login.')) {
|
||||||
|
console.error(' Not logged in! Please redeem the code above manually. You can now login in the browser for next time. Waiting for 60s.');
|
||||||
|
await page2.waitForTimeout(60 * 1000);
|
||||||
|
redeem_action = 'redeem (login)';
|
||||||
|
} else {
|
||||||
|
const iframe = page2.frameLocator('#redeem-iframe');
|
||||||
|
const input = iframe.locator('[name=tokenString]');
|
||||||
|
await input.waitFor();
|
||||||
|
await input.fill(code);
|
||||||
|
const r = page2.waitForResponse(r => r.url().startsWith('https://cart.production.store-web.dynamics.com/v1.0/Redeem/PrepareRedeem'));
|
||||||
|
const rt = await (await r).text();
|
||||||
|
const j = JSON.parse(rt);
|
||||||
|
const reason = j?.events?.cart.length && j.events.cart[0]?.data?.reason;
|
||||||
|
if (reason == 'TokenNotFound') {
|
||||||
|
redeem_action = 'redeem (not found)';
|
||||||
|
console.error(' Code was not found!');
|
||||||
|
} else if (j?.productInfos?.length && j.productInfos[0]?.redeemable) {
|
||||||
|
await iframe.locator('button:has-text("Next")').click();
|
||||||
|
await iframe.locator('button:has-text("Confirm")').click();
|
||||||
|
const r = page2.waitForResponse(r => r.url().startsWith('https://cart.production.store-web.dynamics.com/v1.0/Redeem/RedeemToken'));
|
||||||
|
const j = JSON.parse(await (await r).text());
|
||||||
|
if (j?.events?.cart.length && j.events.cart[0]?.data?.reason == 'UserAlreadyOwnsContent') {
|
||||||
|
redeem_action = 'already redeemed';
|
||||||
|
console.error(' error: UserAlreadyOwnsContent');
|
||||||
|
} else { // success path not seen yet; log below if needed
|
||||||
|
redeem_action = 'redeemed';
|
||||||
|
db.data[user][title].status = 'claimed and redeemed?';
|
||||||
|
console.log(' Redeemed successfully? Please report if not in https://github.com/vogler/free-games-claimer/issues/5');
|
||||||
|
}
|
||||||
|
} else { // other responses; keep info log for analysis
|
||||||
|
redeem_action = 'unknown';
|
||||||
|
console.debug(` Response: ${rt}`);
|
||||||
|
console.log(' Redeemed successfully? Please report your Response from above (if it is new) in https://github.com/vogler/free-games-claimer/issues/5');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (store == 'legacy games') {
|
||||||
|
await page2.fill('[name=coupon_code]', code);
|
||||||
|
await page2.fill('[name=email]', cfg.lg_email);
|
||||||
|
await page2.fill('[name=email_validate]', cfg.lg_email);
|
||||||
|
await page2.uncheck('[name=newsletter_sub]');
|
||||||
|
await page2.click('[type="submit"]');
|
||||||
|
try {
|
||||||
|
await page2.waitForSelector('h2:has-text("Thanks for redeeming")');
|
||||||
|
redeem_action = 'redeemed';
|
||||||
|
db.data[user][title].status = 'claimed and redeemed';
|
||||||
|
} catch (error) {
|
||||||
|
console.error(' Got error', error);
|
||||||
|
redeem_action = 'redeemed?';
|
||||||
|
db.data[user][title].status = 'claimed and redeemed?';
|
||||||
|
console.log(' Redeemed successfully? Please report problems in https://github.com/vogler/free-games-claimer/issues/5');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error(` Redeem on ${store} not yet implemented!`);
|
||||||
|
}
|
||||||
|
if (cfg.debug) await page2.pause();
|
||||||
|
await page2.close();
|
||||||
|
}
|
||||||
|
notify_game.status = `<a href="${redeem_url}">${redeem_action}</a> ${code} on ${store}`;
|
||||||
} else {
|
} else {
|
||||||
notify_game.status = `claimed on ${store}`;
|
notify_game.status = `claimed on ${store}`;
|
||||||
|
db.data[user][title].status = 'claimed';
|
||||||
|
}
|
||||||
|
await page.screenshot({ path: screenshot('external', `${filenamify(title)}.png`), fullPage: true });
|
||||||
}
|
}
|
||||||
// save screenshot of potential code just in case
|
|
||||||
const p = path.resolve(dirs.screenshots, 'prime-gaming', 'external', `${filenamify(title)}.png`);
|
|
||||||
await page.screenshot({ path: p, fullPage: true });
|
|
||||||
// console.info(' Saved a screenshot of page to', p);
|
|
||||||
}
|
}
|
||||||
// await page.pause();
|
|
||||||
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
|
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
|
||||||
|
try {
|
||||||
await page.click('button[data-type="Game"]');
|
await page.click('button[data-type="Game"]');
|
||||||
} while (n);
|
} catch {
|
||||||
const p = path.resolve(dirs.screenshots, 'prime-gaming', `${filenamify(datetime())}.png`);
|
// ignore if filter already selected
|
||||||
// await page.screenshot({ path: p, fullPage: true });
|
}
|
||||||
await page.locator(games_sel).screenshot({ path: p });
|
|
||||||
|
if (notify_games.length && games) { // make screenshot of all games if something was claimed and list exists
|
||||||
|
const p = screenshot(`${filenamify(datetime())}.png`);
|
||||||
|
await scrollUntilStable(() => games.locator('.item-card__action').count());
|
||||||
|
const viewportSize = page.viewportSize(); // current viewport size
|
||||||
|
await page.setViewportSize({ ...viewportSize, height: 3000 }); // increase height, otherwise element screenshot is cut off at the top and bottom
|
||||||
|
await games.screenshot({ path: p }); // screenshot of all claimed games
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://github.com/vogler/free-games-claimer/issues/55
|
||||||
|
if (cfg.pg_claimdlc) {
|
||||||
|
console.log('Trying to claim in-game content...');
|
||||||
|
await page.click('button[data-type="InGameLoot"]');
|
||||||
|
const loot = page.locator('div[data-a-target="offer-list-IN_GAME_LOOT"]');
|
||||||
|
await loot.waitFor();
|
||||||
|
|
||||||
|
process.stdout.write('Loading all DLCs on page...');
|
||||||
|
await scrollUntilStable(() => loot.locator('[data-a-target="item-card"]').count());
|
||||||
|
|
||||||
|
console.log('\nNumber of already claimed DLC:', await loot.locator('p:has-text("Collected")').count());
|
||||||
|
|
||||||
|
const cards = await loot.locator('[data-a-target="item-card"]:has(p:text-is("Claim"))').all();
|
||||||
|
console.log('Number of unclaimed DLC:', cards.length);
|
||||||
|
const dlcs = await Promise.all(cards.map(async card => ({
|
||||||
|
game: await card.locator('.item-card-details__body p').innerText(),
|
||||||
|
title: await card.locator('.item-card-details__body__primary').innerText(),
|
||||||
|
url: 'https://gaming.amazon.com' + await card.locator('a').first().getAttribute('href'),
|
||||||
|
})));
|
||||||
|
// console.log(dlcs);
|
||||||
|
|
||||||
|
const dlc_unlinked = {};
|
||||||
|
for (const dlc of dlcs) {
|
||||||
|
const title = `${dlc.game} - ${dlc.title}`;
|
||||||
|
const url = dlc.url;
|
||||||
|
console.log('Current DLC:', title);
|
||||||
|
if (cfg.debug) await page.pause();
|
||||||
|
if (cfg.dryrun) continue;
|
||||||
|
if (cfg.interactive && !await confirm()) continue;
|
||||||
|
db.data[user][title] ||= { title, time: datetime(), store: 'DLC', status: 'failed: need account linking' };
|
||||||
|
const notify_game = { title, url };
|
||||||
|
notify_games.push(notify_game); // status is updated below
|
||||||
|
try {
|
||||||
|
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
||||||
|
// most games have a button 'Get in-game content'
|
||||||
|
// epic-games: Fall Guys: Claim -> Continue -> Go to Epic Games (despite account linked and logged into epic-games) -> not tied to account but via some cookie?
|
||||||
|
const claimOptions = [
|
||||||
|
page.click('.tw-button:has-text("Get in-game content")'),
|
||||||
|
page.click('.tw-button:has-text("Claim your gift")'),
|
||||||
|
(async () => {
|
||||||
|
await page.click('.tw-button:has-text("Claim")');
|
||||||
|
await page.click('button:has-text("Continue")').catch(() => {});
|
||||||
|
})(),
|
||||||
|
];
|
||||||
|
await Promise.any(claimOptions);
|
||||||
|
try {
|
||||||
|
await page.click('button:has-text("Continue")');
|
||||||
|
} catch {
|
||||||
|
// continue button not always present
|
||||||
|
}
|
||||||
|
const linkAccountButton = page.locator('[data-a-target="LinkAccountButton"]');
|
||||||
|
let unlinked_store;
|
||||||
|
if (await linkAccountButton.count()) {
|
||||||
|
unlinked_store = await linkAccountButton.first().getAttribute('aria-label');
|
||||||
|
console.debug(' LinkAccountButton label:', unlinked_store);
|
||||||
|
const match = unlinked_store?.match(/Link (.*) account/);
|
||||||
|
const extracted = match?.[1];
|
||||||
|
if (extracted) unlinked_store = extracted;
|
||||||
|
} else if (await page.locator('text=Link game account').count()) { // epic-games only?
|
||||||
|
console.error(' Missing account linking (epic-games specific button?):', await page.locator('button[data-a-target="gms-cta"]').innerText()); // track account-linking UI drift
|
||||||
|
unlinked_store = 'epic-games';
|
||||||
|
}
|
||||||
|
if (unlinked_store) {
|
||||||
|
console.error(' Missing account linking:', unlinked_store, url);
|
||||||
|
dlc_unlinked[unlinked_store] ??= [];
|
||||||
|
dlc_unlinked[unlinked_store].push(title);
|
||||||
|
} else {
|
||||||
|
const code = await page.inputValue('input[type="text"]').catch(() => undefined);
|
||||||
|
console.log(' Code to redeem game:', chalk.blue(code));
|
||||||
|
db.data[user][title].code = code;
|
||||||
|
db.data[user][title].status = 'claimed';
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
} finally {
|
||||||
|
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' });
|
||||||
|
await page.click('button[data-type="InGameLoot"]');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log('DLC: Unlinked accounts:', dlc_unlinked);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
process.exitCode ||= 1;
|
||||||
|
console.error('--- Exception:');
|
||||||
console.error(error); // .toString()?
|
console.error(error); // .toString()?
|
||||||
if (error.message && !error.message.includes('Target closed')) // e.g. when killed by Ctrl-C
|
if (error.message && process.exitCode != 130) notify(`prime-gaming failed: ${error.message.split('\n')[0]}`);
|
||||||
notify(`prime-gaming failed: ${error.message.split('\n')[0]}`);
|
|
||||||
} finally {
|
} finally {
|
||||||
await db.write(); // write out json db
|
await db.write(); // write out json db
|
||||||
if (notify_games.length) { // list should only include claimed games
|
if (notify_games.length) { // list should only include claimed games
|
||||||
notify(`prime-gaming:<br>${html_game_list(notify_games)}`);
|
notify(`prime-gaming (${user}):<br>${html_game_list(notify_games)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (page.video()) console.log('Recorded video:', await page.video().path());
|
||||||
await context.close();
|
await context.close();
|
||||||
|
|
|
||||||
9
sonar-project.properties
Normal file
9
sonar-project.properties
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
sonar.organization=vogler
|
||||||
|
sonar.projectKey=vogler_free-games-claimer
|
||||||
|
|
||||||
|
# relative paths to source directories. More details and properties are described
|
||||||
|
# in https://sonarcloud.io/documentation/project-administration/narrowing-the-focus/
|
||||||
|
sonar.sources=.
|
||||||
|
|
||||||
|
#Eslint issues
|
||||||
|
sonar.eslint.reportPaths = eslint_report.json
|
||||||
53
src/config.js
Normal file
53
src/config.js
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
import * as dotenv from 'dotenv';
|
||||||
|
import { dataDir } from './util.js';
|
||||||
|
|
||||||
|
dotenv.config({ path: 'data/config.env' }); // loads env vars from file - will not set vars that are already set, i.e., can overwrite values from file by prefixing, e.g., VAR=VAL node ...
|
||||||
|
|
||||||
|
// Options - also see table in README.md
|
||||||
|
export const cfg = {
|
||||||
|
debug: process.env.DEBUG == '1' || process.env.PWDEBUG == '1', // runs non-headless and opens https://playwright.dev/docs/inspector
|
||||||
|
debug_network: process.env.DEBUG_NETWORK == '1', // log network requests and responses
|
||||||
|
record: process.env.RECORD == '1', // `recordHar` (network) + `recordVideo`
|
||||||
|
time: process.env.TIME == '1', // log duration of each step
|
||||||
|
dryrun: process.env.DRYRUN == '1', // don't claim anything
|
||||||
|
interactive: process.env.INTERACTIVE == '1', // confirm to claim, default skip
|
||||||
|
show: process.env.SHOW == '1', // run non-headless
|
||||||
|
get headless() {
|
||||||
|
return !this.debug && !this.show;
|
||||||
|
},
|
||||||
|
width: Number(process.env.WIDTH) || 1920, // width of the opened browser
|
||||||
|
height: Number(process.env.HEIGHT) || 1080, // height of the opened browser
|
||||||
|
timeout: (Number(process.env.TIMEOUT) || 60) * 1000, // default timeout for playwright is 30s
|
||||||
|
login_timeout: (Number(process.env.LOGIN_TIMEOUT) || 180) * 1000, // higher timeout for login, will wait twice: prompt + wait for manual login
|
||||||
|
novnc_port: process.env.NOVNC_PORT, // running in docker if set
|
||||||
|
notify: process.env.NOTIFY, // apprise notification services
|
||||||
|
notify_title: process.env.NOTIFY_TITLE, // apprise notification title
|
||||||
|
get dir() { // avoids ReferenceError: Cannot access 'dataDir' before initialization
|
||||||
|
return {
|
||||||
|
browser: process.env.BROWSER_DIR || dataDir('browser'), // for multiple accounts or testing
|
||||||
|
screenshots: process.env.SCREENSHOTS_DIR || dataDir('screenshots'), // set to 0 to disable screenshots
|
||||||
|
};
|
||||||
|
},
|
||||||
|
// auth epic-games
|
||||||
|
eg_email: process.env.EG_EMAIL || process.env.EMAIL,
|
||||||
|
eg_password: process.env.EG_PASSWORD || process.env.PASSWORD,
|
||||||
|
eg_otpkey: process.env.EG_OTPKEY,
|
||||||
|
eg_parentalpin: process.env.EG_PARENTALPIN,
|
||||||
|
// auth prime-gaming
|
||||||
|
pg_email: process.env.PG_EMAIL || process.env.EMAIL,
|
||||||
|
pg_password: process.env.PG_PASSWORD || process.env.PASSWORD,
|
||||||
|
pg_otpkey: process.env.PG_OTPKEY,
|
||||||
|
// auth gog
|
||||||
|
gog_email: process.env.GOG_EMAIL || process.env.EMAIL,
|
||||||
|
gog_password: process.env.GOG_PASSWORD || process.env.PASSWORD,
|
||||||
|
gog_newsletter: process.env.GOG_NEWSLETTER == '1', // do not unsubscribe from newsletter after claiming a game
|
||||||
|
// auth AliExpress
|
||||||
|
ae_email: process.env.AE_EMAIL || process.env.EMAIL,
|
||||||
|
ae_password: process.env.AE_PASSWORD || process.env.PASSWORD,
|
||||||
|
// OTP only via GOG_EMAIL, can't add app...
|
||||||
|
// experimmental
|
||||||
|
pg_redeem: process.env.PG_REDEEM == '1', // prime-gaming: redeem keys on external stores
|
||||||
|
lg_email: process.env.LG_EMAIL || process.env.PG_EMAIL || process.env.EMAIL, // prime-gaming: external: legacy-games: email to use for redeeming
|
||||||
|
pg_claimdlc: process.env.PG_CLAIMDLC == '1', // prime-gaming: claim in-game content
|
||||||
|
pg_timeLeft: Number(process.env.PG_TIMELEFT), // prime-gaming: check time left to claim and skip game if there are more than PG_TIMELEFT days left to claim it
|
||||||
|
};
|
||||||
32
src/migrate.js
Normal file
32
src/migrate.js
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { Low } from 'lowdb';
|
||||||
|
import { JSONFile } from 'lowdb/node';
|
||||||
|
import { datetime } from './util.js';
|
||||||
|
|
||||||
|
const datetime_UTCtoLocalTimezone = async file => {
|
||||||
|
if (!existsSync(file)) return console.error('File does not exist:', file);
|
||||||
|
const db = new Low(new JSONFile(file));
|
||||||
|
await db.read();
|
||||||
|
db.data ||= {};
|
||||||
|
console.log('Migrating', file);
|
||||||
|
for (const user in db.data) {
|
||||||
|
for (const game in db.data[user]) {
|
||||||
|
const time1 = db.data[user][game].time;
|
||||||
|
const time1s = time1.endsWith('Z') ? time1 : time1 + ' UTC';
|
||||||
|
const time2 = datetime(new Date(time1s));
|
||||||
|
console.log([game, time1, time2]);
|
||||||
|
db.data[user][game].time = time2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await db.write(); // write out json db
|
||||||
|
};
|
||||||
|
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
if (args[0] == 'localtime') {
|
||||||
|
const files = args.slice(1);
|
||||||
|
console.log('Will convert UTC datetime to local timezone for', files);
|
||||||
|
files.forEach(datetime_UTCtoLocalTimezone);
|
||||||
|
} else {
|
||||||
|
console.log('Usage: node migrate.js <cmd> <args>');
|
||||||
|
console.log(' node migrate.js localtime data/*.json');
|
||||||
|
}
|
||||||
148
src/util.js
Normal file
148
src/util.js
Normal file
|
|
@ -0,0 +1,148 @@
|
||||||
|
// https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
// not the same since these will give the absolute paths for this file instead of for the file using them
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = path.dirname(__filename);
|
||||||
|
// explicit object instead of Object.fromEntries since the built-in type would loose the keys, better type: https://dev.to/svehla/typescript-object-fromentries-389c
|
||||||
|
export const dataDir = s => path.resolve(__dirname, '..', 'data', s);
|
||||||
|
|
||||||
|
// modified path.resolve to return null if first argument is '0', used to disable screenshots
|
||||||
|
export const resolve = (...a) => a.length && a[0] == '0' ? null : path.resolve(...a);
|
||||||
|
|
||||||
|
// json database
|
||||||
|
import { JSONFilePreset } from 'lowdb/node';
|
||||||
|
export const jsonDb = (file, defaultData) => JSONFilePreset(dataDir(file), defaultData);
|
||||||
|
|
||||||
|
export const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
// date and time as UTC (no timezone offset) in nicely readable and sortable format, e.g., 2022-10-06 12:05:27.313
|
||||||
|
export const datetimeUTC = (d = new Date()) => d.toISOString().replace('T', ' ').replace('Z', '');
|
||||||
|
// same as datetimeUTC() but for local timezone, e.g., UTC + 2h for the above in DE
|
||||||
|
export const datetime = (d = new Date()) => datetimeUTC(new Date(d.getTime() - d.getTimezoneOffset() * 60000));
|
||||||
|
export const filenamify = s => s
|
||||||
|
.replaceAll(':', '.')
|
||||||
|
.replaceAll(/[^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.
|
||||||
|
|
||||||
|
export const handleSIGINT = (context = null) => process.on('SIGINT', async () => { // e.g. when killed by Ctrl-C
|
||||||
|
console.error('\nInterrupted by SIGINT. Exit!'); // Exception shows where the script was:\n'); // killed before catch in docker...
|
||||||
|
process.exitCode = 130; // 128+SIGINT to indicate to parent that process was killed
|
||||||
|
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
|
||||||
|
});
|
||||||
|
|
||||||
|
export const launchChromium = async options => {
|
||||||
|
const { chromium } = await import('playwright-chromium'); // stealth plugin needs no outdated playwright-extra
|
||||||
|
|
||||||
|
// https://www.nopecha.com extension source from https://github.com/NopeCHA/NopeCHA/releases/tag/0.1.16
|
||||||
|
// const ext = path.resolve('nopecha'); // used in Chromium, currently not needed in Firefox
|
||||||
|
|
||||||
|
const context = chromium.launchPersistentContext(cfg.dir.browser, {
|
||||||
|
// chrome will not work in linux arm64, only chromium
|
||||||
|
// channel: 'chrome', // https://playwright.dev/docs/browsers#google-chrome--microsoft-edge
|
||||||
|
args: [ // https://peter.sh/experiments/chromium-command-line-switches
|
||||||
|
// don't want to see bubble 'Restore pages? Chrome didn't shut down correctly.'
|
||||||
|
// '--restore-last-session', // does not apply for crash/killed
|
||||||
|
'--hide-crash-restore-bubble',
|
||||||
|
// `--disable-extensions-except=${ext}`,
|
||||||
|
// `--load-extension=${ext}`,
|
||||||
|
],
|
||||||
|
// 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.'.
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
return context;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const stealth = async context => {
|
||||||
|
// stealth with playwright: https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212
|
||||||
|
// https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth/evasions
|
||||||
|
const enabledEvasions = [
|
||||||
|
'chrome.app',
|
||||||
|
'chrome.csi',
|
||||||
|
'chrome.loadTimes',
|
||||||
|
'chrome.runtime',
|
||||||
|
// 'defaultArgs',
|
||||||
|
'iframe.contentWindow',
|
||||||
|
'media.codecs',
|
||||||
|
'navigator.hardwareConcurrency',
|
||||||
|
'navigator.languages',
|
||||||
|
'navigator.permissions',
|
||||||
|
'navigator.plugins',
|
||||||
|
// 'navigator.vendor',
|
||||||
|
'navigator.webdriver',
|
||||||
|
'sourceurl',
|
||||||
|
// 'user-agent-override', // doesn't work since playwright has no page.browser()
|
||||||
|
'webgl.vendor',
|
||||||
|
'window.outerdimensions',
|
||||||
|
];
|
||||||
|
const stealth = {
|
||||||
|
callbacks: [],
|
||||||
|
async evaluateOnNewDocument(...args) {
|
||||||
|
this.callbacks.push({ cb: args[0], a: args[1] });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
for (const e of enabledEvasions) {
|
||||||
|
const evasion = await import(`puppeteer-extra-plugin-stealth/evasions/${e}/index.js`);
|
||||||
|
evasion.default().onPageCreated(stealth);
|
||||||
|
}
|
||||||
|
for (const evasion of stealth.callbacks) {
|
||||||
|
await context.addInitScript(evasion.cb, evasion.a);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// used prompts before, but couldn't cancel prompt
|
||||||
|
// alternative inquirer is big (node_modules 29MB, enquirer 9.7MB, prompts 9.8MB, none 9.4MB) and slower
|
||||||
|
// open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372
|
||||||
|
import Enquirer from 'enquirer'; const enquirer = new Enquirer();
|
||||||
|
const timeoutHint = () => 'timeout';
|
||||||
|
const cancelPromptWithHint = prompt => {
|
||||||
|
prompt.hint = timeoutHint;
|
||||||
|
prompt.cancel();
|
||||||
|
};
|
||||||
|
const applyPromptTimeout = (prompt, timeout) => {
|
||||||
|
if (!timeout) return;
|
||||||
|
const timer = setTimeout(cancelPromptWithHint, timeout, prompt);
|
||||||
|
const clearTimer = () => clearTimeout(timer);
|
||||||
|
prompt.on('submit', clearTimer);
|
||||||
|
prompt.on('cancel', clearTimer);
|
||||||
|
};
|
||||||
|
// cancel prompt after timeout ms; can be disabled per prompt via options.timeout = 0
|
||||||
|
const timeoutPlugin = defaultTimeout => enquirerInstance => {
|
||||||
|
const onPrompt = prompt => applyPromptTimeout(prompt, prompt.options?.timeout ?? defaultTimeout);
|
||||||
|
enquirerInstance.on('prompt', onPrompt);
|
||||||
|
};
|
||||||
|
enquirer.use(timeoutPlugin(cfg.login_timeout));
|
||||||
|
// single prompt that just returns the non-empty value instead of an object
|
||||||
|
// @ts-ignore
|
||||||
|
export const prompt = o => enquirer.prompt({ name: 'name', type: 'input', message: 'Enter value', ...o }).then(r => r.name).catch(() => {});
|
||||||
|
export const confirm = o => prompt({ type: 'confirm', message: 'Continue?', ...o });
|
||||||
|
|
||||||
|
// notifications via apprise CLI
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { cfg } from './config.js';
|
||||||
|
|
||||||
|
export const notify = html => new Promise(resolve => {
|
||||||
|
if (!cfg.notify) {
|
||||||
|
if (cfg.debug) console.debug('notify: NOTIFY is not set!');
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
|
const appriseBin = process.env.APPRISE_BIN || '/usr/local/bin/apprise';
|
||||||
|
const args = [cfg.notify, '-i', 'html', '-b', `'${html}'`];
|
||||||
|
if (cfg.notify_title) args.push('-t', cfg.notify_title);
|
||||||
|
if (cfg.debug) console.debug(`${appriseBin} ${args.join(' ')}`); // this also doesn't escape, but it's just for info
|
||||||
|
execFile(appriseBin, args, (error, stdout, stderr) => {
|
||||||
|
if (error) {
|
||||||
|
console.log(`error: ${error.message}`);
|
||||||
|
if (error.message.includes('command not found')) {
|
||||||
|
console.info('Run `pip install apprise`. See https://github.com/vogler/free-games-claimer#notifications');
|
||||||
|
}
|
||||||
|
// don't fail the whole run on notification errors
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
|
if (stderr) console.error(`stderr: ${stderr}`);
|
||||||
|
if (stdout) console.log(`stdout: ${stdout}`);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export const escapeHtml = unsafe => unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll('\'', ''');
|
||||||
|
|
||||||
|
export const html_game_list = games => games.map(g => `- <a href="${g.url}">${escapeHtml(g.title)}</a> (${g.status})`).join('<br>');
|
||||||
41
src/version.js
Normal file
41
src/version.js
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
import { log } from 'node:console';
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
|
||||||
|
const gitBin = process.env.GIT_BIN || '/usr/bin/git';
|
||||||
|
|
||||||
|
const runGit = (...args) => new Promise((resolve, reject) => {
|
||||||
|
execFile(gitBin, args, { cwd: process.cwd() }, (error, stdout, stderr) => {
|
||||||
|
if (stderr) console.error(`stderr: ${stderr}`);
|
||||||
|
if (error) {
|
||||||
|
console.log(`error: ${error.message}`);
|
||||||
|
if (error.code === 'ENOENT' || error.message.includes('command not found')) {
|
||||||
|
console.info('Install git to check for updates!');
|
||||||
|
}
|
||||||
|
return reject(error);
|
||||||
|
}
|
||||||
|
resolve(stdout.trim());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let sha, date;
|
||||||
|
if (process.env.NOVNC_PORT) {
|
||||||
|
log('Running inside Docker.');
|
||||||
|
['COMMIT', 'BRANCH', 'NOW'].forEach(v => log(` ${v}:`, process.env[v]));
|
||||||
|
sha = process.env.COMMIT;
|
||||||
|
date = process.env.NOW;
|
||||||
|
} else {
|
||||||
|
log('Not running inside Docker.');
|
||||||
|
sha = await runGit('rev-parse', 'HEAD');
|
||||||
|
date = await runGit('show', '-s', '--format=%cD'); // same as format as `date -R` (RFC2822)
|
||||||
|
}
|
||||||
|
|
||||||
|
const gh = await (await fetch('https://api.github.com/repos/vogler/free-games-claimer/commits/main')).json();
|
||||||
|
|
||||||
|
log('Local commit:', sha, new Date(date));
|
||||||
|
log('Online commit:', gh.sha, new Date(gh.commit.committer.date));
|
||||||
|
|
||||||
|
if (sha == gh.sha) {
|
||||||
|
log('Running the latest version!');
|
||||||
|
} else {
|
||||||
|
log('Not running the latest version!');
|
||||||
|
}
|
||||||
70
steam-games.js
Normal file
70
steam-games.js
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||||
|
import { jsonDb, prompt } from './src/util.js';
|
||||||
|
import { cfg } from './src/config.js';
|
||||||
|
|
||||||
|
const db = await jsonDb('steam-games.json', {});
|
||||||
|
|
||||||
|
const user = cfg.steam_id || await prompt({ message: 'Enter Steam community id ("View my profile", then copy from URL)' });
|
||||||
|
|
||||||
|
// using https://github.com/apify/fingerprint-suite worked, but has no launchPersistentContext...
|
||||||
|
// from https://github.com/apify/fingerprint-suite/issues/162
|
||||||
|
import { FingerprintInjector } from 'fingerprint-injector';
|
||||||
|
import { FingerprintGenerator } from 'fingerprint-generator';
|
||||||
|
|
||||||
|
const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({
|
||||||
|
devices: ['desktop'],
|
||||||
|
operatingSystems: ['windows'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||||
|
headless: cfg.headless,
|
||||||
|
locale: 'en-US', // ignore OS locale to be sure to have english text for locators -> done via /en in URL
|
||||||
|
userAgent: fingerprint.navigator.userAgent,
|
||||||
|
viewport: {
|
||||||
|
width: fingerprint.screen.width,
|
||||||
|
height: fingerprint.screen.height,
|
||||||
|
},
|
||||||
|
extraHTTPHeaders: {
|
||||||
|
'accept-language': headers['accept-language'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await new FingerprintInjector().attachFingerprintToPlaywright(context, { fingerprint, headers });
|
||||||
|
|
||||||
|
context.setDefaultTimeout(cfg.debug ? 0 : cfg.timeout);
|
||||||
|
|
||||||
|
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||||
|
|
||||||
|
try {
|
||||||
|
await page.goto(`https://steamcommunity.com/id/${user}/games?tab=all`);
|
||||||
|
const games = page.locator('div[data-featuretarget="gameslist-root"] > div.Panel > div.Panel > div');
|
||||||
|
await games.last().waitFor();
|
||||||
|
await page.keyboard.press('End');
|
||||||
|
await page.waitForLoadState('networkidle');
|
||||||
|
console.log('All Games:', await games.count());
|
||||||
|
for (const game of await games.all()) {
|
||||||
|
const title = await game.locator('span a').innerText();
|
||||||
|
let time, last, achievements, size;
|
||||||
|
const ltime = game.locator('span:has-text("total played")');
|
||||||
|
if (await ltime.count()) time = (await ltime.first().innerText()).split('\n')[1];
|
||||||
|
const llast = game.locator('span:has-text("last played")');
|
||||||
|
if (await llast.count()) last = (await llast.first().innerText()).split('\n')[1];
|
||||||
|
const lachievements = game.locator('a:has-text("achievements") + span');
|
||||||
|
if (await lachievements.count()) achievements = (await lachievements.first().innerText()).split('\n');
|
||||||
|
const lsize = game.locator('span:has(+ button)');
|
||||||
|
if (await lsize.count()) size = await lsize.first().innerText();
|
||||||
|
const url = await game.locator('a').first().getAttribute('href');
|
||||||
|
const img = await game.locator('img').first().getAttribute('src');
|
||||||
|
const stat = { title, time, last, achievements, size, url, img };
|
||||||
|
console.log(stat);
|
||||||
|
db.data[title] = stat;
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
process.exitCode ||= 1;
|
||||||
|
console.error('--- Exception:');
|
||||||
|
console.error(error); // .toString()?
|
||||||
|
} finally {
|
||||||
|
await db.write(); // write out json db
|
||||||
|
}
|
||||||
|
if (page.video()) console.log('Recorded video:', await page.video().path());
|
||||||
|
await context.close();
|
||||||
42
test/notify.js
Normal file
42
test/notify.js
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
import { delay, html_game_list, notify } from '../src/util.js';
|
||||||
|
import { cfg } from '../src/config.js';
|
||||||
|
|
||||||
|
const URL_CLAIM = 'https://gaming.amazon.com/home'; // dummy URL
|
||||||
|
|
||||||
|
console.debug('NOTIFY:', cfg.notify);
|
||||||
|
|
||||||
|
const scenarios = [
|
||||||
|
{
|
||||||
|
enabled: process.env.TEST_NOTIFY_EPIC === '1',
|
||||||
|
title: 'epic-games',
|
||||||
|
games: [
|
||||||
|
{ title: 'Epistory - Typing Chronicles', status: 'claimed', url: URL_CLAIM },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
enabled: process.env.TEST_NOTIFY_PG === '1',
|
||||||
|
delayMs: 1000,
|
||||||
|
title: 'prime-gaming',
|
||||||
|
games: [
|
||||||
|
{ title: 'Faraway 2: Jungle Escape', status: 'claimed', url: URL_CLAIM },
|
||||||
|
{ title: 'Chicken Police - Paint it RED!', status: 'claimed', url: URL_CLAIM },
|
||||||
|
{ title: 'Lawn Mowing Simulator', status: 'claimed', url: URL_CLAIM },
|
||||||
|
{ title: 'Breathedge', status: 'claimed', url: URL_CLAIM },
|
||||||
|
{ title: 'The Evil Within 2', status: `<a href="${URL_CLAIM}">redeem</a> H97S6FB38FA6D09DEA on gog.com`, url: URL_CLAIM },
|
||||||
|
{ title: 'Beat Cop', status: `<a href="${URL_CLAIM}">redeem</a> BMKM8558EC55F7B38F on gog.com`, url: URL_CLAIM },
|
||||||
|
{ title: 'Dishonored 2', status: `<a href="${URL_CLAIM}">redeem</a> NNEK0987AB20DFBF8F on gog.com`, url: URL_CLAIM },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
enabled: process.env.TEST_NOTIFY_GOG === '1',
|
||||||
|
delayMs: 1000,
|
||||||
|
title: 'gog',
|
||||||
|
games: [{ title: 'Haven Park', status: 'claimed', url: URL_CLAIM }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const scenario of scenarios) {
|
||||||
|
if (!scenario.enabled) continue;
|
||||||
|
if (scenario.delayMs) await delay(scenario.delayMs);
|
||||||
|
await notify(`${scenario.title}:<br>${html_game_list(scenario.games)}`);
|
||||||
|
}
|
||||||
21
test/sigint-enquirer-raw-keeps-running.js
Normal file
21
test/sigint-enquirer-raw-keeps-running.js
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
// open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372
|
||||||
|
function onRawSIGINT(fn) {
|
||||||
|
const { stdin, stdout } = process;
|
||||||
|
stdin.setRawMode(true);
|
||||||
|
stdin.resume();
|
||||||
|
stdin.on('data', data => {
|
||||||
|
const key = data.toString('utf-8');
|
||||||
|
if (key === '\u0003') { // ctrl + c
|
||||||
|
fn();
|
||||||
|
} else {
|
||||||
|
stdout.write(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log(1);
|
||||||
|
onRawSIGINT(() => {
|
||||||
|
console.log('raw'); process.exit(1);
|
||||||
|
});
|
||||||
|
console.log(2);
|
||||||
|
|
||||||
|
// onRawSIGINT workaround for enquirer keeps the process from exiting here...
|
||||||
18
test/sigint-enquirer-raw.js
Normal file
18
test/sigint-enquirer-raw.js
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
// https://github.com/enquirer/enquirer/issues/372
|
||||||
|
import { prompt, handleSIGINT } from '../src/util.js';
|
||||||
|
|
||||||
|
handleSIGINT();
|
||||||
|
|
||||||
|
console.log('hello');
|
||||||
|
console.error('hello error');
|
||||||
|
try {
|
||||||
|
const first = await prompt(); // SIGINT no longer handled if this is executed
|
||||||
|
const second = await prompt(); // SIGINT no longer handled if this is executed
|
||||||
|
console.log('values:', first, second);
|
||||||
|
setTimeout(() => console.log('timeout 3s'), 3000);
|
||||||
|
} catch (e) {
|
||||||
|
process.exitCode ||= 1;
|
||||||
|
console.log('catch. exitCode:', process.exitCode);
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
console.log('end. exitCode:', process.exitCode);
|
||||||
20
test/sigint-enquirer-simple.js
Normal file
20
test/sigint-enquirer-simple.js
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
// https://github.com/enquirer/enquirer/issues/372
|
||||||
|
import Enquirer from 'enquirer';
|
||||||
|
const enquirer = new Enquirer();
|
||||||
|
|
||||||
|
let interrupted = false;
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
if (interrupted) process.exit();
|
||||||
|
interrupted = true;
|
||||||
|
console.log('SIGINT');
|
||||||
|
});
|
||||||
|
await enquirer.prompt({
|
||||||
|
type: 'input',
|
||||||
|
name: 'username',
|
||||||
|
message: 'What is your username?',
|
||||||
|
});
|
||||||
|
await enquirer.prompt({
|
||||||
|
type: 'input',
|
||||||
|
name: 'username',
|
||||||
|
message: 'What is your username 2?',
|
||||||
|
});
|
||||||
223
unrealengine.js
Normal file
223
unrealengine.js
Normal file
|
|
@ -0,0 +1,223 @@
|
||||||
|
import { firefox } from 'playwright-firefox'; // stealth plugin needs no outdated playwright-extra
|
||||||
|
import { authenticator } from 'otplib';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { writeFileSync } from 'node:fs';
|
||||||
|
import { resolve, jsonDb, datetime, stealth, filenamify, prompt, notify, html_game_list, handleSIGINT } from './src/util.js';
|
||||||
|
import { cfg } from './src/config.js';
|
||||||
|
|
||||||
|
const screenshot = (...a) => resolve(cfg.dir.screenshots, 'unrealengine', ...a);
|
||||||
|
|
||||||
|
const URL_CLAIM = 'https://www.unrealengine.com/marketplace/en-US/assets?count=20&sortBy=effectiveDate&sortDir=DESC&start=0&tag=4910';
|
||||||
|
const URL_LOGIN = 'https://www.epicgames.com/id/login?lang=en-US&noHostRedirect=true&redirectUrl=' + URL_CLAIM;
|
||||||
|
|
||||||
|
console.log(datetime(), 'started checking unrealengine');
|
||||||
|
|
||||||
|
const db = await jsonDb('unrealengine.json', {});
|
||||||
|
|
||||||
|
// https://playwright.dev/docs/auth#multi-factor-authentication
|
||||||
|
const context = await firefox.launchPersistentContext(cfg.dir.browser, {
|
||||||
|
headless: cfg.headless,
|
||||||
|
viewport: { width: cfg.width, height: cfg.height },
|
||||||
|
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36', // Windows UA avoids "device not supported"; update when browser version changes
|
||||||
|
locale: 'en-US', // ignore OS locale to be sure to have english text for locators
|
||||||
|
recordVideo: cfg.record ? { dir: 'data/record/', size: { width: cfg.width, height: cfg.height } } : undefined, // will record a .webm video for each page navigated; without size, video would be scaled down to fit 800x800
|
||||||
|
recordHar: cfg.record ? { path: `data/record/ue-${filenamify(datetime())}.har` } : undefined, // will record a HAR file with network requests and responses; can be imported in Chrome devtools
|
||||||
|
handleSIGINT: false, // have to handle ourselves and call context.close(), otherwise recordings from above won't be saved
|
||||||
|
});
|
||||||
|
|
||||||
|
handleSIGINT(context);
|
||||||
|
|
||||||
|
await stealth(context);
|
||||||
|
|
||||||
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
|
|
||||||
|
const page = context.pages().length ? context.pages()[0] : await context.newPage(); // should always exist
|
||||||
|
await page.setViewportSize({ width: cfg.width, height: cfg.height }); // workaround for https://github.com/vogler/free-games-claimer/issues/277 until Playwright fixes it
|
||||||
|
|
||||||
|
const notify_games = [];
|
||||||
|
let user;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await context.addCookies([{ name: 'OptanonAlertBoxClosed', value: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(), domain: '.epicgames.com', path: '/' }]); // Accept cookies to get rid of banner to save space on screen. Set accept time to 5 days ago.
|
||||||
|
|
||||||
|
await page.goto(URL_CLAIM, { waitUntil: 'domcontentloaded' }); // 'domcontentloaded' faster than default 'load' https://playwright.dev/docs/api/class-page#page-goto
|
||||||
|
|
||||||
|
await page.waitForResponse(r => r.request().method() == 'POST' && r.url().startsWith('https://graphql.unrealengine.com/ue/graphql'));
|
||||||
|
|
||||||
|
while (await page.locator('unrealengine-navigation').getAttribute('isloggedin') != 'true') {
|
||||||
|
console.error('Not signed in anymore. Please login in the browser or here in the terminal.');
|
||||||
|
if (cfg.novnc_port) console.info(`Open http://localhost:${cfg.novnc_port} to login inside the docker container.`);
|
||||||
|
if (!cfg.debug) context.setDefaultTimeout(cfg.login_timeout); // give user some extra time to log in
|
||||||
|
console.info(`Login timeout is ${cfg.login_timeout / 1000} seconds!`);
|
||||||
|
await page.goto(URL_LOGIN, { waitUntil: 'domcontentloaded' });
|
||||||
|
if (cfg.eg_email && cfg.eg_password) console.info('Using email and password from environment.');
|
||||||
|
else console.info('Press ESC to skip the prompts if you want to login in the browser (not possible in headless mode).');
|
||||||
|
const email = cfg.eg_email || await prompt({ message: 'Enter email' });
|
||||||
|
const password = email && (cfg.eg_password || await prompt({ type: 'password', message: 'Enter password' }));
|
||||||
|
if (email && password) {
|
||||||
|
await page.fill('#email', email);
|
||||||
|
await page.click('button[type="submit"]');
|
||||||
|
await page.fill('#password', password);
|
||||||
|
await page.click('button[type="submit"]');
|
||||||
|
const watchCaptchaDuringLogin = async () => {
|
||||||
|
try {
|
||||||
|
await page.waitForSelector('#h_captcha_challenge_login_prod iframe', { timeout: 15000 });
|
||||||
|
console.error('Got a captcha during login (likely due to too many attempts)! You may solve it in the browser, get a new IP or try again in a few hours.');
|
||||||
|
notify('unrealengine: got captcha during login. Please check.');
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const watchMfa = async () => {
|
||||||
|
try {
|
||||||
|
await page.waitForURL('**/id/login/mfa**', { timeout: cfg.login_timeout });
|
||||||
|
console.log('Enter the security code to continue - This appears to be a new device, browser or location. A security code has been sent to your email address at ...');
|
||||||
|
const otp = cfg.eg_otpkey && authenticator.generate(cfg.eg_otpkey) || await prompt({ type: 'text', message: 'Enter two-factor sign in code', validate: n => n.toString().length == 6 || 'The code must be 6 digits!' }); // can't use type: 'number' since it strips away leading zeros and codes sometimes have them
|
||||||
|
await page.locator('input[name="code-input-0"]').pressSequentially(otp.toString());
|
||||||
|
await page.click('button[type="submit"]');
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
watchCaptchaDuringLogin();
|
||||||
|
watchMfa();
|
||||||
|
} else {
|
||||||
|
console.log('Waiting for you to login in the browser.');
|
||||||
|
await notify('unrealengine: no longer signed in and not enough options set for automatic login.');
|
||||||
|
if (cfg.headless) {
|
||||||
|
console.log('Run `SHOW=1 node unrealengine` to login in the opened browser.');
|
||||||
|
await context.close(); // finishes potential recording
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await page.waitForURL('**unrealengine.com/marketplace/**');
|
||||||
|
if (!cfg.debug) context.setDefaultTimeout(cfg.timeout);
|
||||||
|
}
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
|
user = await page.locator('unrealengine-navigation').getAttribute('displayname'); // 'null' if !isloggedin
|
||||||
|
console.log(`Signed in as ${user}`);
|
||||||
|
db.data[user] ||= {};
|
||||||
|
|
||||||
|
page.locator('button:has-text("Accept All Cookies")').click().catch(_ => { });
|
||||||
|
|
||||||
|
const ids = [];
|
||||||
|
for (const p of await page.locator('article.asset').all()) {
|
||||||
|
const link = p.locator('h3 a');
|
||||||
|
const title = await link.innerText();
|
||||||
|
const url = 'https://www.unrealengine.com' + await link.getAttribute('href');
|
||||||
|
console.log([title, url]);
|
||||||
|
const id = url.split('/').pop();
|
||||||
|
db.data[user][id] ||= { title, time: datetime(), url, status: 'failed' }; // this will be set on the initial run only!
|
||||||
|
const notify_game = { title, url, status: 'failed' };
|
||||||
|
notify_games.push(notify_game); // status is updated below
|
||||||
|
// if (await p.locator('.btn .add-review-btn').count()) { // did not work
|
||||||
|
if ((await p.getAttribute('class')).includes('asset--owned')) {
|
||||||
|
console.log(' ↳ Already claimed');
|
||||||
|
if (db.data[user][id].status != 'claimed') {
|
||||||
|
db.data[user][id].status = 'existed';
|
||||||
|
notify_game.status = 'existed';
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (await p.locator('.btn .in-cart').count()) {
|
||||||
|
console.log(' ↳ Already in cart');
|
||||||
|
} else {
|
||||||
|
await p.locator('.btn .add').click();
|
||||||
|
console.log(' ↳ Added to cart');
|
||||||
|
}
|
||||||
|
ids.push(id);
|
||||||
|
}
|
||||||
|
if (ids.length === 0) {
|
||||||
|
console.log('Nothing to claim');
|
||||||
|
} else {
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
const price = (await page.locator('.shopping-cart .total .price').innerText()).split(' ');
|
||||||
|
console.log('Price: ', price[1], 'instead of', price[0]);
|
||||||
|
if (price[1] != '0') {
|
||||||
|
const err = 'Price is not 0! Exit! Please <a href="https://github.com/vogler/free-games-claimer/issues/44">report</a>.';
|
||||||
|
console.error(err);
|
||||||
|
notify('unrealengine: ' + err);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
console.log('Click shopping cart');
|
||||||
|
await page.locator('.shopping-cart').click();
|
||||||
|
await page.locator('button.checkout').click();
|
||||||
|
console.log('Click checkout');
|
||||||
|
// maybe: Accept End User License Agreement
|
||||||
|
const acceptEulaIfPresent = async () => {
|
||||||
|
try {
|
||||||
|
await page.locator('[name=accept-label]').check({ timeout: 10000 });
|
||||||
|
console.log('Accept End User License Agreement');
|
||||||
|
await page.locator('span:text-is("Accept")').click(); // otherwise matches 'Accept All Cookies'
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
acceptEulaIfPresent();
|
||||||
|
await page.waitForSelector('#webPurchaseContainer iframe');
|
||||||
|
const iframe = page.frameLocator('#webPurchaseContainer iframe');
|
||||||
|
|
||||||
|
if (cfg.debug) await page.pause();
|
||||||
|
if (cfg.dryrun) {
|
||||||
|
console.log('DRYRUN=1 -> Skip order!');
|
||||||
|
throw new Error('DRYRUN=1');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Click Place Order');
|
||||||
|
// Playwright clicked before button was ready to handle event, https://github.com/vogler/free-games-claimer/issues/84#issuecomment-1474346591
|
||||||
|
await iframe.locator('button:has-text("Place Order"):not(:has(.payment-loading--loading))').click({ delay: 11 });
|
||||||
|
|
||||||
|
// I Agree button is only shown for EU accounts! https://github.com/vogler/free-games-claimer/pull/7#issuecomment-1038964872
|
||||||
|
const btnAgree = iframe.locator('button:has-text("I Agree")');
|
||||||
|
const acceptIfRequired = async () => {
|
||||||
|
try {
|
||||||
|
await btnAgree.waitFor({ timeout: 10000 });
|
||||||
|
await btnAgree.click();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}; // EU: wait for and click 'I Agree'
|
||||||
|
acceptIfRequired();
|
||||||
|
try {
|
||||||
|
// context.setDefaultTimeout(100 * 1000); // give time to solve captcha, iframe goes blank after 60s?
|
||||||
|
const captcha = iframe.locator('#h_captcha_challenge_checkout_free_prod iframe');
|
||||||
|
const watchCaptchaChallenge = async () => {
|
||||||
|
try {
|
||||||
|
await captcha.waitFor({ timeout: 10000 });
|
||||||
|
console.error(' Got hcaptcha challenge! Lost trust due to too many login attempts? You can solve the captcha in the browser or get a new IP address.');
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}; // may time out if not shown
|
||||||
|
watchCaptchaChallenge();
|
||||||
|
await page.waitForSelector('text=Thank you');
|
||||||
|
for (const id of ids) {
|
||||||
|
db.data[user][id].status = 'claimed';
|
||||||
|
db.data[user][id].time = datetime(); // claimed time overwrites failed/dryrun time
|
||||||
|
}
|
||||||
|
notify_games.forEach(g => g.status == 'failed' && (g.status = 'claimed'));
|
||||||
|
console.log('Claimed successfully!');
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
console.error(' Failed to claim! To avoid captchas try to get a new IP address.');
|
||||||
|
await page.screenshot({ path: screenshot('failed', `${filenamify(datetime())}.png`), fullPage: true });
|
||||||
|
notify_games.forEach(g => g.status = 'failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (notify_games.length) await page.screenshot({ path: screenshot(`${filenamify(datetime())}.png`), fullPage: false }); // fullPage is quite long...
|
||||||
|
console.log('Done');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
process.exitCode ||= 1;
|
||||||
|
console.error('--- Exception:');
|
||||||
|
console.error(error); // .toString()?
|
||||||
|
if (error.message && process.exitCode != 130) notify(`unrealengine failed: ${error.message.split('\n')[0]}`);
|
||||||
|
} finally {
|
||||||
|
await db.write(); // write out json db
|
||||||
|
if (notify_games.filter(g => g.status != 'existed').length) { // don't notify if all were already claimed
|
||||||
|
notify(`unrealengine (${user}):<br>${html_game_list(notify_games)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cfg.debug) writeFileSync(path.resolve(cfg.dir.browser, 'cookies.json'), JSON.stringify(await context.cookies()));
|
||||||
|
if (page.video()) console.log('Recorded video:', await page.video().path());
|
||||||
|
await context.close();
|
||||||
113
util.js
113
util.js
|
|
@ -1,113 +0,0 @@
|
||||||
// https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
|
|
||||||
import path from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
// not the same since these will give the absolute paths for this file instead of for the file using them
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
|
||||||
const __dirname = path.dirname(__filename);
|
|
||||||
// explicit object instead of Object.fromEntries since the built-in type would loose the keys, better type: https://dev.to/svehla/typescript-object-fromentries-389c
|
|
||||||
const dataDir = s => path.resolve(__dirname, 'data', s);
|
|
||||||
export const dirs = {
|
|
||||||
data: dataDir('.'),
|
|
||||||
browser: dataDir('browser'),
|
|
||||||
screenshots: dataDir('screenshots'),
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
// json database
|
|
||||||
import { Low } from 'lowdb';
|
|
||||||
import { JSONFile } from 'lowdb/node';
|
|
||||||
export const jsonDb = async file => {
|
|
||||||
const db = new Low(new JSONFile(dataDir(file)));
|
|
||||||
await db.read();
|
|
||||||
return db;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
// date and time as UTC (no timezone offset) in nicely readable and sortable format, e.g., 2022-10-06 12:05:27.313
|
|
||||||
export const datetime = (d = new Date()) => d.toISOString().replace('T', ' ').replace('Z', '');
|
|
||||||
// same as datetime() but for local timezone, e.g., UTC + 2h for the above in DE
|
|
||||||
export const datetimeLocal = (d = new Date()) => datetime(new Date(d.getTime() - new Date().getTimezoneOffset() * 60000));
|
|
||||||
export const filenamify = s => s.replaceAll(':', '.').replace(/[^a-z0-9 _\-.]/gi, '_'); // alternative: https://www.npmjs.com/package/filenamify - On Unix-like systems, / is reserved. On Windows, <>:"/\|?* along with trailing periods are reserved.
|
|
||||||
|
|
||||||
|
|
||||||
// stealth with playwright: https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212
|
|
||||||
// gets userAgent and then removes "Headless" from it
|
|
||||||
const newStealthContext = async (browser, contextOptions = {}, debug = false) => {
|
|
||||||
if (!debug) { // only need to fix userAgent in headless mode
|
|
||||||
const dummyContext = await browser.newContext();
|
|
||||||
const originalUserAgent = await (await dummyContext.newPage()).evaluate(() => navigator.userAgent);
|
|
||||||
await dummyContext.close();
|
|
||||||
// console.log('originalUserAgent:', originalUserAgent); // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/96.0.4664.110 Safari/537.36
|
|
||||||
contextOptions = {
|
|
||||||
...contextOptions,
|
|
||||||
userAgent: originalUserAgent.replace("Headless", ""), // HeadlessChrome -> Chrome, TODO needed?
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const stealth = async (context) => {
|
|
||||||
// stealth with playwright: https://github.com/berstend/puppeteer-extra/issues/454#issuecomment-917437212
|
|
||||||
// https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth/evasions
|
|
||||||
const enabledEvasions = [
|
|
||||||
'chrome.app',
|
|
||||||
'chrome.csi',
|
|
||||||
'chrome.loadTimes',
|
|
||||||
'chrome.runtime',
|
|
||||||
// 'defaultArgs',
|
|
||||||
'iframe.contentWindow',
|
|
||||||
'media.codecs',
|
|
||||||
'navigator.hardwareConcurrency',
|
|
||||||
'navigator.languages',
|
|
||||||
'navigator.permissions',
|
|
||||||
'navigator.plugins',
|
|
||||||
// 'navigator.vendor',
|
|
||||||
'navigator.webdriver',
|
|
||||||
'sourceurl',
|
|
||||||
// 'user-agent-override', // doesn't work since playwright has no page.browser()
|
|
||||||
'webgl.vendor',
|
|
||||||
'window.outerdimensions'
|
|
||||||
];
|
|
||||||
const stealth = {
|
|
||||||
callbacks: [],
|
|
||||||
async evaluateOnNewDocument(...args) {
|
|
||||||
this.callbacks.push({ cb: args[0], a: args[1] });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for (const e of enabledEvasions) {
|
|
||||||
const evasion = await import(`puppeteer-extra-plugin-stealth/evasions/${e}/index.js`);
|
|
||||||
evasion.default().onPageCreated(stealth);
|
|
||||||
}
|
|
||||||
for (let evasion of stealth.callbacks) {
|
|
||||||
await context.addInitScript(evasion.cb, evasion.a);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
import prompts from 'prompts'; // alternatives: enquirer, inquirer
|
|
||||||
// import enquirer from 'enquirer'; const { prompt } = enquirer;
|
|
||||||
// single prompt that just returns the non-empty value instead of an object - why name things if there's just one?
|
|
||||||
export const prompt = async o => (await prompts({name: 'name', type: 'text', message: 'Enter value', validate: s => s.length, ...o})).name;
|
|
||||||
|
|
||||||
|
|
||||||
// notifications via apprise CLI
|
|
||||||
import { exec } from 'child_process';
|
|
||||||
import { cfg } from './config.js';
|
|
||||||
|
|
||||||
export const notify = (html) => {
|
|
||||||
if (!cfg.notify) return;
|
|
||||||
exec(`apprise ${cfg.notify} -i html -b '${html}'`, (error, stdout, stderr) => {
|
|
||||||
if (error) {
|
|
||||||
console.log(`error: ${error.message}`);
|
|
||||||
if (error.message.includes('command not found')) {
|
|
||||||
console.info('Run `pip install apprise`. See https://github.com/vogler/free-games-claimer#notifications');
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (stderr) console.error(`stderr: ${stderr}`);
|
|
||||||
if (stdout) console.log(`stdout: ${stdout}`);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export const escapeHtml = (unsafe) => unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
|
|
||||||
|
|
||||||
export const html_game_list = games => games.map(g => `- <a href="${g.url}">${escapeHtml(g.title)}</a> (${g.status})`).join('<br>');
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue