├── .coveragerc
├── .github
├── CODEOWNERS
├── FUNDING.yml
└── workflows
│ ├── ci.yml
│ ├── nightly.yaml
│ └── release.yaml
├── .gitignore
├── .pylintrc
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.en.md
├── README.md
├── codecov.yml
├── config.example.ini
├── docker
├── Dockerfile
└── docker-compose.yml
├── docs
├── SETUP_ANDROID.md
└── SETUP_EMAIL_SERVICES.md
├── linux_start.sh
├── linux_validate.sh
├── mac_start.command
├── mac_validate.command
├── requirements.txt
├── setup.py
├── src
├── alerts.py
├── api_wrapper.py
├── common.py
├── config_generator.py
├── config_skeleton.py
├── impfbot.py
├── log.py
├── settings.py
└── validate_config.py
├── tests
├── configs
│ ├── test-config-advanced.ini
│ ├── test-config-apprise.ini
│ ├── test-config-browser.ini
│ ├── test-config-email-ssl.ini
│ ├── test-config-email.ini
│ ├── test-config-invalid-advanced.ini
│ ├── test-config-invalid-apprise.ini
│ ├── test-config-invalid-birthdate.ini
│ ├── test-config-invalid-email.ini
│ ├── test-config-invalid-telegram.ini
│ ├── test-config-invalid-zip-code.ini
│ ├── test-config-minimal.ini
│ ├── test-config-no-alerts.ini
│ ├── test-config-old.ini
│ ├── test-config-optional-missing.ini
│ ├── test-config-telegram.ini
│ ├── test-config-valid.ini
│ ├── test-config.ini
│ └── test-invalid-file.ini
├── test_alerts.py
├── test_api_wrapper.py
├── test_common.py
├── test_impfbot.py
└── test_settings.py
├── version.txt
├── windows_start.bat
└── windows_validate.bat
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | omit =
3 | src/config_generator.py
4 |
5 | [report]
6 | exclude_lines =
7 | if __name__ == .__main__.:
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @sibalzer
2 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | custom: https://www.aerzte-ohne-grenzen.de/spenden-sammeln?cfd=z1suz
2 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: ci
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | lint:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v2
10 | - name: Set up Python 3.9
11 | uses: actions/setup-python@v2
12 | with:
13 | python-version: 3.9
14 | - name: Install dependencies
15 | run: |
16 | python -m pip install --upgrade pip
17 | pip install flake8 pylint pytest
18 | pip install -r requirements.txt
19 | - name: Lint with flake8
20 | run: |
21 | # stop the build if there are Python syntax errors or undefined names
22 | flake8 src --count --select=E9,F63,F7,F82 --show-source --statistics
23 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
24 | flake8 src --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
25 | - name: Lint with pylint
26 | run: |
27 | pylint src --fail-under 8
28 | test:
29 | runs-on: ubuntu-latest
30 | steps:
31 | - uses: actions/checkout@v2
32 | - name: Set up Python 3.9
33 | uses: actions/setup-python@v2
34 | with:
35 | python-version: 3.9
36 | - name: Set up test env
37 | run: |
38 | pip install -e .
39 | pip install coverage
40 | - name: Generate Report
41 | run: |
42 | pip install coverage
43 | coverage run -m pytest
44 | - name: Upload Coverage to Codecov
45 | uses: codecov/codecov-action@v1
46 | with:
47 | token: ${{ secrets.CODECOV_TOKEN }}
48 |
--------------------------------------------------------------------------------
/.github/workflows/nightly.yaml:
--------------------------------------------------------------------------------
1 | name: nightly
2 | on:
3 | schedule:
4 | - cron: "0 0 * * *"
5 | workflow_dispatch: {}
6 | jobs:
7 | build-release:
8 | name: Build, tag, and release Docker image
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: Checkout repository
12 | uses: actions/checkout@v2
13 | - name: Set SHA
14 | run: echo "GITHUB_SHA=${GITHUB_SHA:0:7}" >> $GITHUB_ENV
15 |
16 | - name: Set up QEMU
17 | uses: docker/setup-qemu-action@v1
18 |
19 | - name: Set up Docker Buildx
20 | uses: docker/setup-buildx-action@v1
21 |
22 | - name: Login to GitHub Container Registry
23 | uses: docker/login-action@v1
24 | with:
25 | registry: ghcr.io
26 | username: ${{ github.repository_owner }}
27 | password: ${{ secrets.GITHUB_TOKEN }}
28 |
29 | - name: Build Docker image
30 | uses: docker/build-push-action@v2
31 | with:
32 | context: .
33 | file: docker/Dockerfile
34 | platforms: linux/amd64,linux/arm64
35 | push: true
36 | tags: |
37 | ghcr.io/${{ github.repository }}:nightly
38 | ghcr.io/${{ github.repository }}:${{ env.GITHUB_SHA }}
39 |
--------------------------------------------------------------------------------
/.github/workflows/release.yaml:
--------------------------------------------------------------------------------
1 | name: release
2 | on:
3 | workflow_run:
4 | workflows: ["ci"]
5 | branch: [main]
6 | types: [completed]
7 | jobs:
8 | build-tag-release:
9 | name: Build, tag, and release Docker image
10 | if: ${{ github.event.workflow_run.conclusion == 'success' }}
11 | runs-on: ubuntu-latest
12 | steps:
13 | - name: Checkout repository
14 | uses: actions/checkout@v2
15 | - name: Setup release please
16 | uses: google-github-actions/release-please-action@v2
17 | id: release
18 | with:
19 | token: ${{ secrets.GITHUB_TOKEN }}
20 | release-type: simple
21 | changelog-path: CHANGELOG.md
22 | package-name: impfbot
23 |
24 | - name: Set up QEMU
25 | uses: docker/setup-qemu-action@v1
26 |
27 | - name: Set up Docker Buildx
28 | uses: docker/setup-buildx-action@v1
29 |
30 | - name: Login to GitHub Container Registry
31 | if: ${{ steps.release.outputs.release_created }}
32 | uses: docker/login-action@v1
33 | with:
34 | registry: ghcr.io
35 | username: ${{ github.repository_owner }}
36 | password: ${{ secrets.GITHUB_TOKEN }}
37 |
38 | - name: Build Docker image
39 | if: ${{ steps.release.outputs.release_created }}
40 | uses: docker/build-push-action@v2
41 | with:
42 | context: .
43 | file: docker/Dockerfile
44 | platforms: linux/amd64,linux/arm64
45 | push: true
46 | tags: |
47 | ghcr.io/${{ github.repository }}:latest
48 | ghcr.io/${{ github.repository }}:${{ steps.release.outputs.tag_name }}
49 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .vs
2 | __pycache__
3 | config.ini
4 | *log
5 | .pytest_cache
6 | *.egg-info
7 | .vscode
8 | build
9 | dist
10 | .coverage
11 | htmlcov
--------------------------------------------------------------------------------
/.pylintrc:
--------------------------------------------------------------------------------
1 | [TYPECHECK]
2 | generated-members=settings.Datastore.*
3 | [LOGGING]
4 | disable=logging-fstring-interpolation
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## [3.4.0](https://www.github.com/sibalzer/impfbot/compare/v3.3.0...v3.4.0) (2021-06-26)
4 |
5 |
6 | ### Features
7 |
8 | * add vector option ([#127](https://www.github.com/sibalzer/impfbot/issues/127)) ([eb347fc](https://www.github.com/sibalzer/impfbot/commit/eb347fca1295ca9c365828fcecfcecf3282553ff))
9 |
10 | ## [3.3.0](https://www.github.com/sibalzer/impfbot/compare/v3.2.0...v3.3.0) (2021-06-21)
11 |
12 |
13 | ### Features
14 |
15 | * add message prefix ([#124](https://www.github.com/sibalzer/impfbot/issues/124)) ([d389f5f](https://www.github.com/sibalzer/impfbot/commit/d389f5f15b8030a8136d98bc99a4b87e77d6783a))
16 |
17 | ## [3.2.0](https://www.github.com/sibalzer/impfbot/compare/v3.1.1...v3.2.0) (2021-06-14)
18 |
19 |
20 | ### Features
21 |
22 | * arm64 docker images ([#76](https://www.github.com/sibalzer/impfbot/issues/76)) ([23bc387](https://www.github.com/sibalzer/impfbot/commit/23bc38794ee61839c8976f14b6010465f3425cad))
23 |
24 | ### [3.1.1](https://www.github.com/sibalzer/impfbot/compare/v3.1.0...v3.1.1) (2021-06-14)
25 |
26 |
27 | ### Bug Fixes
28 |
29 | * print list values as comma separated string ([#120](https://www.github.com/sibalzer/impfbot/issues/120)) ([680b088](https://www.github.com/sibalzer/impfbot/commit/680b088a3314abeb13298bb0667ba304c804aafa))
30 |
31 | ## [3.1.0](https://www.github.com/sibalzer/impfbot/compare/v3.0.5...v3.1.0) (2021-06-13)
32 |
33 |
34 | ### Features
35 |
36 | * add appointment date to message ([#113](https://www.github.com/sibalzer/impfbot/issues/113)) ([022cc03](https://www.github.com/sibalzer/impfbot/commit/022cc030eab65274a31ae2c9c82619f01c15aa68))
37 |
38 | ### [3.0.5](https://www.github.com/sibalzer/impfbot/compare/v3.0.4...v3.0.5) (2021-06-12)
39 |
40 |
41 | ### Bug Fixes
42 |
43 | * improve user input regexes ([#111](https://www.github.com/sibalzer/impfbot/issues/111)) ([b925a01](https://www.github.com/sibalzer/impfbot/commit/b925a0143021a0ba7b64d8c8236721b044f560a1))
44 | * more permissive user agent regex ([b925a01](https://www.github.com/sibalzer/impfbot/commit/b925a0143021a0ba7b64d8c8236721b044f560a1))
45 |
46 | ### [3.0.4](https://www.github.com/sibalzer/impfbot/compare/v3.0.3...v3.0.4) (2021-06-09)
47 |
48 |
49 | ### Bug Fixes
50 |
51 | * no result when using option --alert ([#90](https://www.github.com/sibalzer/impfbot/issues/90)) ([f895fbd](https://www.github.com/sibalzer/impfbot/commit/f895fbd357017b7a786e013f24e7b4652932bfb5))
52 |
53 | ### [3.0.3](https://www.github.com/sibalzer/impfbot/compare/v3.0.2...v3.0.3) (2021-06-09)
54 |
55 |
56 | ### Bug Fixes
57 |
58 | * lower yes/no input for comparison ([715dc87](https://www.github.com/sibalzer/impfbot/commit/715dc8768cd27003e761765abd4bfff971c9fb7d))
59 |
60 | ### [3.0.2](https://www.github.com/sibalzer/impfbot/compare/v3.0.1...v3.0.2) (2021-06-09)
61 |
62 |
63 | ### Bug Fixes
64 |
65 | * no tkinter and cli interface on servers [#88](https://www.github.com/sibalzer/impfbot/issues/88) [#89](https://www.github.com/sibalzer/impfbot/issues/89) ([8e6777f](https://www.github.com/sibalzer/impfbot/commit/8e6777f65aa7646dcde350fc7fb71789b4e5c6a9))
66 |
67 | ### [3.0.1](https://www.github.com/sibalzer/impfbot/compare/v3.0.0...v3.0.1) (2021-06-09)
68 |
69 |
70 | ### Bug Fixes
71 |
72 | * no tkinter on servers [#88](https://www.github.com/sibalzer/impfbot/issues/88) ([4d97f5d](https://www.github.com/sibalzer/impfbot/commit/4d97f5d7334d302605affbb5a514677656e94d31))
73 |
74 | ## [3.0.0](https://www.github.com/sibalzer/impfbot/compare/v2.0.0...v3.0.0) (2021-06-08)
75 |
76 |
77 | ### ⚠ BREAKING CHANGES
78 |
79 | * v3.0.0
80 |
81 | ### Features
82 |
83 | * add apprise ([#81](https://www.github.com/sibalzer/impfbot/issues/81)) ([3e458d5](https://www.github.com/sibalzer/impfbot/commit/3e458d5ecb864098cb613079a4f0570ef78e37fa))
84 | * add apprise notification service ([54cb3ff](https://www.github.com/sibalzer/impfbot/commit/54cb3ff6c7af8b83dfca8f452ad5a7507d388e46))
85 | * config gui generation (beta) ([54cb3ff](https://www.github.com/sibalzer/impfbot/commit/54cb3ff6c7af8b83dfca8f452ad5a7507d388e46))
86 | * group notifications ([54cb3ff](https://www.github.com/sibalzer/impfbot/commit/54cb3ff6c7af8b83dfca8f452ad5a7507d388e46))
87 | * v3.0.0 ([54cb3ff](https://www.github.com/sibalzer/impfbot/commit/54cb3ff6c7af8b83dfca8f452ad5a7507d388e46))
88 |
89 |
90 | ### Bug Fixes
91 |
92 | * **doc:** min -> sec ([06092d0](https://www.github.com/sibalzer/impfbot/commit/06092d056d4a5150fef0d635a629f5e4c09b3815))
93 | * explicit ConnectionError handling ([54cb3ff](https://www.github.com/sibalzer/impfbot/commit/54cb3ff6c7af8b83dfca8f452ad5a7507d388e46))
94 | * interpolation in config ([3f5a64e](https://www.github.com/sibalzer/impfbot/commit/3f5a64e4804fe7a8341963d5c123357185a20dbb))
95 | * make browser pop up ([5745805](https://www.github.com/sibalzer/impfbot/commit/57458058c66a2e8b30b91c6eeca78f906c180baf))
96 | * smtp starttls ([54cb3ff](https://www.github.com/sibalzer/impfbot/commit/54cb3ff6c7af8b83dfca8f452ad5a7507d388e46))
97 | * telegram token regex, email starttls ([bc0f07f](https://www.github.com/sibalzer/impfbot/commit/bc0f07f5f2a2d95694ef6031d65e5c963d099598))
98 |
99 | ## [2.0.0](https://www.github.com/sibalzer/impfbot/compare/v1.2.1...v2.0.0) (2021-05-27)
100 |
101 |
102 | ### ⚠ BREAKING CHANGES
103 |
104 | * Telegram Integration
105 | * Config Validation
106 |
107 | ### Features
108 |
109 | * Telegram Integration ([0540636](https://www.github.com/sibalzer/impfbot/commit/0540636f1e6b31a15ab28a438587615ffddbb33c))
110 | * Config Validation ([874f26c](https://www.github.com/sibalzer/impfbot/commit/874f26ce5328bb44911864a8b108a764d2b4cf25))
111 |
112 |
113 | ### Bug Fixes
114 |
115 | * alert bug ([774e611](https://www.github.com/sibalzer/impfbot/commit/774e611bef1249a352d9cf3178c1810af5d3cced))
116 | * change output handler from stderr to stdout ([312852a](https://www.github.com/sibalzer/impfbot/commit/312852af0cdba8d3c97cf9985bd601945dd207aa))
117 | * typo in README.md ([3e2c7a3](https://www.github.com/sibalzer/impfbot/commit/3e2c7a3af623ab2057d48fc0291549d76d253d1f))
118 |
119 | ### [1.2.1](https://www.github.com/sibalzer/impfbot/compare/v1.2.1...v1.2.1) (2021-05-26)
120 |
121 |
122 | ### Bug Fixes
123 |
124 | * change output handler from stderr to stdout ([249bf40](https://www.github.com/sibalzer/impfbot/commit/249bf409f1bac30f42e072c46fb191273f3a6fec))
125 |
126 | ## [1.2.1](https://www.github.com/sibalzer/impfbot/compare/v1.2.1...v1.2.1) (2021-05-25)
127 |
128 |
129 | ### ⚠ BREAKING CHANGES
130 |
131 | ### Bug Fixes
132 |
133 | * alert bug ([d5fd1ed](https://www.github.com/sibalzer/impfbot/commit/d5fd1ed2675683dd35cccce6868f3392d52c18df))
134 |
135 | ## [1.2.1](https://www.github.com/sibalzer/impfbot/compare/v1.2.1...v1.2.1) (2021-05-25)
136 |
137 |
138 | ### ⚠ BREAKING CHANGES
139 |
140 | * added Telegram Integration
141 |
142 | ### Features
143 |
144 | * added Telegram integration ([0540636](https://www.github.com/sibalzer/impfbot/commit/0540636f1e6b31a15ab28a438587615ffddbb33c))
145 |
146 | ### [1.2.1](https://www.github.com/sibalzer/impfbot/compare/v1.2.0...v1.2.1) (2021-05-25)
147 |
148 |
149 | ### Bug Fixes
150 |
151 | * flake8 warnings ([ea80a0b](https://www.github.com/sibalzer/impfbot/commit/ea80a0b2d07349bbf5460a8e1f634adec4e64dd9))
152 |
153 | ## [1.2.0](https://www.github.com/sibalzer/impfbot/compare/v1.1.4...v1.2.0) (2021-05-25)
154 |
155 |
156 | ### Features
157 |
158 | * added test email ([8207f11](https://www.github.com/sibalzer/impfbot/commit/8207f114da600d702c17bd45d8f73c7f8d15bb2e))
159 |
160 | ### [1.1.4](https://www.github.com/sibalzer/impfbot/compare/v1.1.3...v1.1.4) (2021-05-25)
161 |
162 |
163 | ### Bug Fixes
164 |
165 | * birthyear befor 1974 ([4065132](https://www.github.com/sibalzer/impfbot/commit/4065132914fb961390324d3387a51b021243260a))
166 |
167 | ### [1.1.3](https://www.github.com/sibalzer/impfbot/compare/v1.1.2...v1.1.3) (2021-05-25)
168 |
169 |
170 | ### Bug Fixes
171 |
172 | * email port ([556e16b](https://www.github.com/sibalzer/impfbot/commit/556e16b55a15d96a9082e29e390d074428193b82))
173 |
174 | ### [1.1.2](https://www.github.com/sibalzer/impfbot/compare/v1.1.1...v1.1.2) (2021-05-25)
175 |
176 |
177 | ### Bug Fixes
178 |
179 | * no py launcher for linux ([e876686](https://www.github.com/sibalzer/impfbot/commit/e876686f6132156cb1461cab826efc890a94591e))
180 |
181 | ### [1.1.1](https://www.github.com/sibalzer/impfbot/compare/v1.1.0...v1.1.1) (2021-05-25)
182 |
183 |
184 | ### Bug Fixes
185 |
186 | * email_list -> empfaenger ([80f4beb](https://www.github.com/sibalzer/impfbot/commit/80f4bebe794058ddd2bfa50a275a08f787f18e3f))
187 |
188 | ## [1.1.0](https://www.github.com/sibalzer/impfbot/compare/v1.0.0...v1.1.0) (2021-05-25)
189 |
190 |
191 | ### Features
192 |
193 | * sleep at night ([a724b3a](https://www.github.com/sibalzer/impfbot/commit/a724b3af579fa4d6347371a6ea78c7994d4d68eb))
194 |
195 | ## 1.0.0 (2021-05-25)
196 |
197 |
198 | ### ⚠ BREAKING CHANGES
199 |
200 | * initial release
201 |
202 | ### Features
203 |
204 | * initial release ([f533339](https://www.github.com/sibalzer/impfbot/commit/f533339cd9923863fbc64ee89d23dcb17e1bc393))
205 |
206 |
207 | ### Bug Fixes
208 |
209 | * context ([2e41b11](https://www.github.com/sibalzer/impfbot/commit/2e41b110b469652230aa4f5eb01fc928f649efcb))
210 | * docker build pwd ([c32aded](https://www.github.com/sibalzer/impfbot/commit/c32aded8c53f04a58d9d5482fc3b997eac2290ae))
211 | * line escapes ([fc1cda5](https://www.github.com/sibalzer/impfbot/commit/fc1cda5df14f1ce7ec5c7fb2c163ba85169f5b5a))
212 | * paths ([cecda5b](https://www.github.com/sibalzer/impfbot/commit/cecda5b460f6385ba646529e6c55c18dd8b038f4))
213 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Feature Requests
2 |
3 | Eröffne ein [Issue](https://github.com/sibalzer/impfbot/issues/new/choose).
4 |
5 | ## Pull Request
6 |
7 | Du möchtest mithelfen? Super! Gehe dazu wie folgt vor:
8 |
9 | 1. Eröffne ein Issue und/oder beantrage dich als Assignee
10 | 2. Nutze als Base Branch den Beta-Branch
11 | 3. Vervollständige benötigte Einstellungen unter `config-skeleton.py` (bei Sonderfällen muss evtl. der Parser `settings.py` bearbeitet werden) `config.ini.example`
12 | 4. Achte darauf, dass alle Test durchlaufen
13 | 5. Erstelle einen Pull Request & fertig
14 |
15 | ## Feature Requests
16 |
17 | Open an [issue](https://github.com/sibalzer/impfbot/issues/new/choose).
18 |
19 | ## Pull Request
20 |
21 | You want to help? Great! Proceed as follows:
22 |
23 | 1. open an issue and/or apply as assignee
24 | 2. use the beta branch as base branch
25 | 3. complete the needed settings in `config-skeleton.py` (in special cases you may have to edit the parser `settings.py`) `config.ini.example`.
26 | 4. make sure that all tests run through
27 | 5. create a pull request & thats it!
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.en.md:
--------------------------------------------------------------------------------
1 | # Notification bot for the Lower Saxony vaccination portal 🐴
2 |
3 | 
4 | [](https://codecov.io/gh/sibalzer/impfbot)
5 | [](https://www.python.org/)
6 | [](https://github.com/sibalzer/impfbot/blob/main/LICENSE)
7 |
8 | _Zur deutschen Version geht's [hier](https://github.com/sibalzer/impfbot/blob/main/README.md)._
9 |
10 | A little weekend project of mine. The bot monitors the REST-API of the lower saxony vaccination portal (https://impfportal-niedersachsen.de) for free vaccination slots and sends a notification via mail. From then on, unfortunately, the fastest wins. Please do not abuse the bot and use moderate intervals.
11 |
12 | ## 🤖 Features
13 |
14 | - Automatic search for short term vaccination dates
15 | - Notifications via email and telegram & many more
16 | - Opens your browser automatically when an appointment is found. All you have to do is enter your details!
17 | - Simple setup with GUI
18 |
19 | > What the impfbot doesn't do: Book the appointment for you and/or enter your data automatically.
20 |
21 | ### ⚠️ Disclaimer
22 |
23 | Using this bot does __not__ guarantee to get you a vaccination appointment. Please also use the waiting list of your local vaccination centre and your family physician!
24 |
25 | ## ⚙️ Setup
26 |
27 | ### Requirements
28 |
29 | - python 3.x via https://www.python.org/downloads/
30 |
31 | ### 📝 Instructions
32 |
33 | Using Windows as an example:
34 |
35 | 1. download and install python from here: [https://www.python.org/downloads/](https://www.python.org/downloads/)
36 | 2. download the bot (Releases on the right side or [here](https://github.com/sibalzer/impfbot/releases/latest))
37 | 3. unpack the archive (the zip file)
38 | 4. rename `config.example.ini` to `config.ini` and fill in your data (zip code, birthday, email server data)
39 | 5. double-click on `windows_validate.bat` to check the config file
40 | 6. double-click on `windows_start.bat`
41 |
42 | For advanced users, a docker container is also available as an alternative. See [docker](https://github.com/sibalzer/impfbot/tree/main/docker) for more information. Validating the config works via the command `docker exec impfbot python src/validate_config.py -a`.
43 |
44 | ### 📣 Setting up Telegram
45 |
46 | 1. write to https://t.me/BotFather and create bot. Then copy the token to `config.ini`.
47 |
48 | The following steps must be performed for everyone who wants to receive messages.
49 |
50 | 2. write to https://t.me/userinfobot and copy "Id"-number into `config.ini` (separated with `,`)
51 | 3. ⚠ You have to start a conversation with your own bot before! (URL is in the Botfather message, press /start there). ⚠
52 | 4. validate that everything works: Double click on `test_telegram.bat`
53 |
54 | ### 🛠️ config.ini parameters
55 |
56 | - **\[COMMON\]**: General settings
57 | - `birthday` - Birthday to be queried. Example: `23.06.1912`.
58 | - `group_size` - Size of the group for which an appointment is requested (2 to 15). Example: `5`
59 | - `zip_code` - Five-digit zip code for your vaccination center. Example: `49123`
60 | - `with_vector` - For the under 60s: should also be searched for vector vaccines? Example: `true`
61 | - **\[EMAIL\]**: Email settings
62 | - `enable` - Specifies whether emails should be sent. `true` if yes, `false` otherwise.
63 | - `sender` - The email address from which the notifications should be sent. Example: `sender@server.tld`.
64 | - `user` - Login name for the SMTP server (in most cases identical with the sender address)
65 | - `password` - The password for the SMTP server.
66 | - `server` - The SMTP server. Example: `smtp.server.tld`.
67 | - `port` - The port for the SMTP server. Example: `465`.
68 | - `receivers` - A list of e-mail addresses to which a message should be sent. Example: `sender@server.tld,foo@server.tld,hoo@server.tld` or (only to itself) `sender@server.tld`.
69 | - **\[TELEGRAM\]**: Telegram settings
70 | - `enable` - Specifies whether Telegram messages should be sent. `true` if yes, otherwise `false`.
71 | - `token` - The bot token from https://t.me/BotFather
72 | - `chat_ids` - User-ID of the recipient: use https://t.me/userinfobot
73 | - **\[WEBBROWSER\]**: Web browser settings
74 | - `enable` - Determines if the browser should be opened automatically. (Only on desktop systems) `true` if yes, otherwise `false`.
75 | - **\[APPRISE\]**: Various notification services (Pretty much anything you can think of).
76 | - `enable` - `true` if Apprise should be used, otherwise `false`'.
77 | - `service_uris` - Service-URIs. For more information please visit: [Apprise Documentation](https://github.com/caronc/apprise)
78 | - **\[ADVANCED\]**: Settings for advanced users. It's gettting experimental 🤓
79 | - `cooldown_between_requests` - wait time between requests. A too small wait time leads to an IP ban (default: 1min, but can be decreased empirically)
80 | - `cooldown_between_failed_requests` - waiting time between failed attempts. For each additional one, the waiting time is added again to prevent an IP ban. I.e. five failures = waiting time of 5\*10s until the next request.
81 | - `cooldown_after_ip_ban` - If a query fails 10 times the IP is probably banned. By default it will wait for 3h.
82 | - `cooldown_after_success` - Cooldown after an vaccination slot was found. By default it will wait 15min.
83 | - `jitter` - random time span from 0-jtter seconds which is added to the wait times (default: `5`)
84 | - `sleep_at_night` - Specifies if the bot should sleep at night (default: `true` since no events are published anyway)
85 | - `user_agent`- The user agent is passed in the header (default: `impfbot`)
86 |
87 | ##### Example Config:
88 |
89 | ```ini
90 | [COMMON]
91 | zip_code=42042
92 | birthdate=23.06.1912
93 | with_vector=true
94 |
95 | [EMAIL]
96 | enable=true
97 | sender=sender@server.de
98 | user=username
99 | password=xxxxxx
100 | server=smtp.server.de
101 | port=465
102 | receivers=sender@server.de,guenni@server.de,frida@server.de
103 |
104 | [TELEGRAM]
105 | enable=true
106 | token=TOKEN
107 | chat_ids=123456789,987654321
108 |
109 | [WEBBROWSER]
110 | enable=true
111 |
112 | [APPRISE]
113 | enable=false
114 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
115 |
116 | [ADVANCED]
117 | cooldown_between_requests=60
118 | cooldown_between_failed_requests=10
119 | cooldown_after_ip_ban=10800
120 | cooldown_after_success=900
121 | jitter=5
122 | sleep_at_night=true
123 | user_agent=impfbot
124 | ```
125 | ## Miscellaneous
126 |
127 | ### 🙋 Feedback & problems setting up.
128 |
129 | Write [here](https://github.com/sibalzer/impfbot/issues/5) or [twitter](https://twitter.com/datearl) me.
130 |
131 | ### ⭐ Sponsorship
132 |
133 | The impfbot helped you and you want to contribute monetarily? Then donate at [this fundraiser to Doctors Without Borders](https://www.aerzte-ohne-grenzen.de/spenden-sammeln?cfd=z1suz). (Yes, somewhat cribbed from [vaccipy](https://github.com/iamnotturner/vaccipy). But I liked the idea.)
134 |
135 | ### 🙏 Many thanks to:
136 |
137 | - [paulypeter](https://github.com/paulypeter) - Telegram Integration, Config-GUI & more
138 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Benachrichtigungs-Bot für das niedersächische Impfportal 🐴
2 |
3 | 
4 | [](https://codecov.io/gh/sibalzer/impfbot)
5 | [](https://www.python.org/)
6 | [](https://github.com/sibalzer/impfbot/blob/main/LICENSE)
7 |
8 | _English version [here](https://github.com/sibalzer/impfbot/blob/main/README.en.md)._
9 |
10 | Ein kleines Wochenend-Projekt von mir. Der Bot überwacht die REST-API des niedersächsischen Impfportals (https://impfportal-niedersachsen.de) auf freie Impfslots und sendet eine Benachrichtigung mit deinem bevorzugtem Service. Ab da gilt leider: der Schnellste gewinnt. Bitte missbraucht den Bot nicht und verwendet moderate Intervalle.
11 |
12 | ## 🤖 Features
13 |
14 | - Automatisches Suchen von kurzfristigen Impfterminen
15 | - Benachrichtigungen über E-Mail, Telegram und vielen anderen Services
16 | - Öffnet deinen Browser automatisch wenn ein Termin gefunden wurde. Du musst nur noch deine Daten eingeben!
17 | - Einfaches Einrichten mit GUI-Interface
18 |
19 |
20 | > Was der impfbot nicht macht: Den Termin für dich reservieren und/oder deine Daten automatisch eingeben.
21 |
22 | ### ⚠️ Achtung
23 |
24 | Die Nutzung des Bots garantiert __nicht__, einen Impftermin zu bekommen. Bitte nutze zusätzlich auch die Warteliste deines zuständigen Impfzentrums und deines Hausarztes!
25 |
26 | ## ⚙️ Setup
27 |
28 | ### Voraussetzungen
29 |
30 | - Python 3.x von hier [https://www.python.org/downloads/](https://www.python.org/downloads/)
31 |
32 | ### 📝 Anleitung - Schritt für Schritt
33 |
34 | Am Beispiel von Windows:
35 |
36 | 1. Python von hier runderladen und installieren: [https://www.python.org/downloads/](https://www.python.org/downloads/)
37 | 2. Den Bot runterladen (Rechts bei den Releases oder [hier](https://github.com/sibalzer/impfbot/releases/latest))
38 | 3. Das Archiv (Die Zip-Datei) entpacken
39 | 4. `config.example.ini` nach `config.ini` umbennen und deine Daten eintragen (PLZ, Geburtstag, Email-Server-Daten
40 | 5. Doppelklick auf `windows_validate.bat`, um die Einstellungen zu prüfen
41 | 6. Doppelklick auf `windows_start.bat`
42 |
43 | Wer den Impfbot auf seinem Android-Smartphone laufen lassen möchte, liest [hier](docs/SETUP_ANDROID.md) weiter.
44 |
45 | Für Fortgeschrittene steht alternativ auch ein Docker-Container zur Verfügung. Siehe dazu [docker](docker). Das Validieren der Config funktioniert über den Befehl `docker exec impfbot python src/validate_config.py -a`.
46 |
47 | ### 📣 Einrichten von Telegram
48 |
49 | 1. https://t.me/BotFather anschreiben und Bot erstellen. Den Token dann in die `config.ini` kopieren.
50 |
51 | Folgende Schritte muss für jeden ausgeführt werden, der Nachrichten empfangen will
52 |
53 | 2. https://t.me/userinfobot anschreiben und "Id"-Nummer in die `config.ini` kopieren (mehrere Nummern mit `,` getrennt).
54 | 3. ⚠ Mit dem eigenen Bot muss vorher eine Konversation begonnen werden! (URL steht in der Botfather-Nachricht, dort /start drücken) ⚠
55 | 4. Validieren, dass auch alles funktioniert: Doppelklick auf `windows_validate.bat`
56 |
57 |
58 | ### 🛠️ config.ini Parameter
59 |
60 | > Deine Daten werden nur lokal gespeichert!
61 |
62 | - **\[COMMON\]**: Allgemeine Einstellungen
63 | - `birthdate` - Dein Geburtstag - Da die Verteilung vom Alter abhängig ist, ist dieser zwingend notwendig. Beispiel: `23.06.1912`
64 | - `group_size` - Gruppengröße - Wenn du lieber einen Gruppentermin suchen möchtest musst du birthdate auskommentieren und eine Gruppengröße angeben (zwischen 2 und 15). Es darf nur eins von beiden in der Config sein! Beispiel: `5`
65 | - `zip_code` - Fünfstellige PLZ für das Impfzentrum, das der Bot überwachen soll. Beispiel: `49123`
66 | - `with_vector` - Für die unter 60-Jährigen: Soll auch nach Vector-Impfstoffen gesucht werden? Beispiel: `true`
67 | - **\[EMAIL\]**: E-Mail-Einstellungen. Bei manchen Anbietern müssen vorher bestimmte Einstellungen gemacht werden, eine Sammlung von Anleitungen findet ihr [hier](docs/SETUP_EMAIL_SERVICES.md).
68 | - `enable` - Legt fest, ob E-Mails versendet werden sollen. `true` wenn ja, sonst `false`.
69 | - `sender` - Die E-Mail-Adresse, von der die Benachrichtigungen versendet werden sollen. Beispiel: `sender@server.tld`
70 | - `user` - Login Name für den SMTP-Server (in den meisten Fällen identisch mit der Absender Adresse)
71 | - `password` - Das Passwort für die Absender-E-Mail-Adresse.
72 | - `server` - Der SMTP-Server. Beispiel: `smtp.server.tld`
73 | - `port` - Der Port für den SMTP-Server. Beispiel: `465`
74 | - `receivers` - E-Mail Empfänger Liste - Trag hier auch deine Absender-Adresse ein, wenn du selber Mails empfangen möchtest (Mit Kommata getrennt). Beispiel: `sender@server.tld,foo@server.tld,hoo@server.tld` oder (nur an sich selbst) `sender@server.tld`
75 | - **\[TELEGRAM\]**:Telegram-Einstellungen
76 | - `enable` - Legt fest, ob Telegram-Nachrichten versendet werden sollen. `true` wenn ja, sonst `false`.
77 | - `token` - Bot-Token - Dieser zunächst beim BotFather generiert werden: [https://t.me/BotFather](https://t.me/BotFather)
78 | - `chat_ids` - User-IDs der Empfänger - Die bekommst du am einfachsten wenn du den User-Info-Bot anschreibst https://t.me/userinfobot. Da bekommst du eine Id, die hier eingetragen werden muss. Mehrere Id's durch Kommata trennen.
79 | - **\[WEBBROWSER\]**: Webbrowser-Einstellungen
80 | - `enable` - Legt fest, ob der Browser automatisch geöffnet werden soll. (Nur auf Desktop-Systemen) `true` wenn ja, sonst `false`.
81 | - **\[APPRISE\]** Verschiedene Benachrichtigungsservices (So ziemlich alles was man sich vorstellen kann).
82 | - `enable` - 'true' wenn Apprise verwendet werden soll, sonst 'false'
83 | - `service_uris` - Service URIs. Für mehr Informationen: [Apprise Documentation](https://github.com/caronc/apprise) (Mehrere URIs durch Kommata trennen)
84 | - **\[ADVANCED\]**: Einstellungen für Fortgeschrittene, hier wird's experimentell
85 | - `cooldown_between_requests` - Wartezeit zwischen den Abfragen; Eine zu kleine Wartezeit führt zu einem IP-Ban (Default: 1 min, kann aber empirisch verkleinert werden)
86 | - `cooldown_between_failed_requests` - Wartezeit zwischen fehlgeschlagenen Versuchen. Bei jedem weiteren wird die Wartezeit nochmal hinzuaddiert, um einen IP Ban zu verhindern. D.h. fünf Fehlschläge = Wartezeit von 5\*15s bis zum nächsen Aufruf
87 | - `cooldown_after_ip_ban` - Wenn eine Abfrage 10x fehlschlaegt, ist die IP vermutlich gebannt. Standardmaeßig wird dann 3 h gewartet.
88 | - `cooldown_after_success` - Cooldown, nachdem ein Impftermin gefunden wurde. Standardmaeßig wird dann 15 min gewartet (in Sekunden)
89 | - `jitter` - Zufällige Zeitspanne von 0-jtter Sekunden, die auf die Wartezeiten addiert wird (Default: `5`)
90 | - `sleep_at_night` - Legt fest, ob der Bot nachts schlafen soll (Default: `true`, da eh keine Termine veröffentlicht werden)
91 | - `user_agent`- Der User Agent, der im Header übermittelt wird (Default: `impfbot`)
92 |
93 |
94 | Beispiel Config:
95 |
96 | ```ini
97 | [COMMON]
98 | zip_code=42042
99 | birthdate=23.06.1912
100 | with_vector=true
101 |
102 | [EMAIL]
103 | enable=true
104 | sender=sender@server.de
105 | user=username
106 | password=xxxxxx
107 | server=smtp.server.de
108 | port=465
109 | receivers=sender@server.de,guenni@server.de,frida@server.de
110 |
111 | [TELEGRAM]
112 | enable=true
113 | token=TOKEN
114 | chat_ids=123456789,987654321
115 |
116 | [WEBBROWSER]
117 | enable=true
118 |
119 | [APPRISE]
120 | enable=false
121 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
122 |
123 | [ADVANCED]
124 | cooldown_between_requests=60
125 | cooldown_between_failed_requests=10
126 | cooldown_after_ip_ban=10800
127 | cooldown_after_success=900
128 | jitter=5
129 | sleep_at_night=true
130 | user_agent=impfbot
131 | ```
132 |
133 | ## Sonstiges
134 |
135 | ### 🙋 Feedback & Probleme beim Einrichten
136 |
137 | Schreib [hier](https://github.com/sibalzer/impfbot/issues/5) oder [twitter](https://twitter.com/datearl) mich an.
138 |
139 | ### ⭐ Sponsoring
140 |
141 | Dir hat der impfbot geholfen und du möchtest monetär etwas beitragen? Dann spende doch unter [dieser Spendenaktion an Ärzte ohne Grenzen](https://www.aerzte-ohne-grenzen.de/spenden-sammeln?cfd=z1suz). (Ja, etwas abgekupfert von [vaccipy](https://github.com/iamnotturner/vaccipy). Aber ich fand die Idee gut.)
142 |
143 | ### 🙏 Vielen Dank an:
144 |
145 | - [paulypeter](https://github.com/paulypeter) - Telegram Integration, Config-GUI & mehr
146 |
--------------------------------------------------------------------------------
/codecov.yml:
--------------------------------------------------------------------------------
1 | coverage:
2 | status:
3 | project:
4 | default:
5 | target: auto
6 | threshold: 5%
--------------------------------------------------------------------------------
/config.example.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | ;;; Dein Geburtstag - Da die Verteilung vom Alter abhängig ist, ist dieser zwingend notwendig.
3 | birthdate=23.06.1912
4 | ;;; Gruppengröße - Wenn du lieber einen Gruppentermin suchen möchtest musst du birthdate auskommentieren und eine Gruppengröße angeben. Es darf nur eins von beiden in der Config sein! (zwischen 2 und 15)
5 | ; group_size=5
6 | ;;; Postleitzahl - Die Postleitzahl in der Impftermine gesucht werden.
7 | zip_code=42042
8 | ;;; Für die unter 60-Jährigen: Soll auch nach Vector-Impfstoffen gesucht werden? Wenn ja 'true' sonst 'false'
9 | with_vector=true
10 |
11 | [EMAIL]
12 | ;;; 'true' wenn eine Benachrichtigung per E-Mail gesendet werden soll, sonst 'false'
13 | enable=true
14 | ;;; Absender Adresse - Die E-Mail Adresse von der die Nachrichten versendet werden soll
15 | sender=sender@server.de
16 | ;;; Login Name für den SMTP-Server (in den meisten Fällen identisch mit der Absender Adresse)
17 | user=username
18 | ;;; Login Passwort für den SMTP-Server
19 | password=xxxxxx
20 | ;;; SMTP-Server - Findest du bei deinem Anbieter
21 | server=smtp.server.de
22 | ;;; SMTP-Port- Findest du bei deinem Anbieter (sollte 465 sein)
23 | port=465
24 | ;;; E-Mail Empfänger Liste - Trag hier auch deine Absender Adresse ein, wenn du selber Mails empfangen möchtest (Mit Kommata getrennt).
25 | receivers=sender@server.de,guenni@server.de,frida@server.de
26 |
27 | [TELEGRAM]
28 | ;;; 'true' wenn Telegram verwendet werden soll, sonst 'false'
29 | enable=true
30 | ;;; Bot-Token - Dieser zunächst beim BotFather generiert werden: https://t.me/BotFather
31 | token=TOKEN
32 | ;;; User-IDs der Empfänger - Die bekommst du am einfachsten wenn du den User-Info-Bot anschreibst https://t.me/userinfobot. Da bekommst du eine Id, die hier eingetragen werden muss. Mehrere Id's durch Kommata trennen.
33 | chat_ids=123456789,987654321
34 |
35 | [WEBBROWSER]
36 | ;;; Soll der default Browser automatisch geöffnet werden? Wenn ja 'true' sonst 'false'
37 | enable=true
38 |
39 | [APPRISE]
40 | ;;; 'true' wenn Apprise verwendet werden soll, sonst 'false'
41 | enable=false
42 | ;;; Verschiedene Benachrichtigungsservices (So ziemlich alles was man sich vorstellen kann). Mehrere URIs durch Kommata trennen -> https://github.com/caronc/apprise
43 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
44 |
45 | [ADVANCED]
46 | ;;; Ein Präfix (optional), das der gesendeten Nachricht vorangestellt wird.
47 | custom_message_prefix=Impfbot
48 | ;;; Wartezeit zwischen den Abfragen eine zu kleine Wartezeit führt (vermutlich) zu einem IP-Ban (Default: 1min, kann aber empirisch verkleinert werden)
49 | cooldown_between_requests=60
50 | ;;; Wartezeit zwischen fehlgeschlagenen Versuchen. Bei jedem weiteren wird die Wartezeit nochmal hinzuaddiert. D.h. fünf Fehlschläge = Wartezeit von 5*30s bis zum nächsen Aufruf
51 | cooldown_between_failed_requests=10
52 | ;;; Wenn eine Abfrage mehrfach fehlschlaegt ist die IP vermutlich gebannt. Default wird dann 3h gewartet.
53 | cooldown_after_ip_ban=10800
54 | ;;; Cooldown nachdem ein Impftermin gefunden wurde. Standardmaeßig wird dann 15min gewartet (in Sekunden).
55 | cooldown_after_success=900
56 | ;;; Zufällige Zeitspanne von 0-jtter die auf die Wartezeiten addiert wird
57 | jitter=5
58 | ;;; Legt fest ob der Bot nachts schlafen soll (Default: true da Nachts eh keine Termine veröffentlicht werden)
59 | sleep_at_night=true
60 | ;;; User-Agent für die Anfrage an die API
61 | user_agent=impfbot
62 |
--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3
2 |
3 | WORKDIR /src
4 |
5 | COPY requirements.txt .
6 | RUN pip install -r requirements.txt
7 |
8 | COPY src/ .
9 |
10 | WORKDIR /
11 | CMD [ "python", "/src/impfbot.py" ]
--------------------------------------------------------------------------------
/docker/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3"
2 | services:
3 | impfbot:
4 | container_name: impfbot
5 | image: ghcr.io/sibalzer/impfbot:latest
6 | restart: unless-stopped
7 | volumes:
8 | - ./config.ini:/config.ini # must exist before launching
9 | environment:
10 | - TZ=Europe/Berlin
11 |
--------------------------------------------------------------------------------
/docs/SETUP_ANDROID.md:
--------------------------------------------------------------------------------
1 | # Anleitung für Nutzung auf Android-Geräten
2 |
3 | Termux ist eine App, die eine Linux-Umgebung inkl. Terminal Emulator auf dem Android-Smartphone zugänglich macht. Dort lässt sich u. a. `python` installieren. Die anschließende Einrichtung unterscheidet sich nicht von der unter Linux. E-Mails und Telegram-Benachrichtigungen können versendet werden, eine direkte Implementierung von Push-Nachrichten könnte ggf. noch implementiert werden.
4 |
5 | ## Voraussetzungen
6 |
7 | - Termux https://termux.com/
8 | - ggf. PC mit `ssh`-Client für einfachere Einrichtung
9 |
10 | ## Anleitung
11 |
12 | 1. [Termux](https://termux.com/) über [f-droid](https://f-droid.org/en/packages/com.termux/) installieren (ggf. apk von dort runterladen). [Installation über Playstore macht Probleme](https://github.com/termux/termux-packages/issues/6726)
13 |
14 | 2. Termux-Umgebung vorbereiten:
15 | ```
16 | pkg upgrade
17 | pkg install python
18 | termux-setup-storage
19 | ```
20 | Der letzte Befehl ermöglicht (wenn ihr dem Dateizugriff zustimmt) den Dateiaustausch mit gewissen Directories des Smartphones. So könnt ihr die `config.ini` auf dem Rechner ausfüllen bzw. die dort bereits funktionierende kopieren.
21 |
22 | 3. Den Bot runterladen und entpacken:
23 | ```
24 | curl -L https://api.github.com/repos/sibalzer/impfbot/tarball -o impfbot.tar.gz
25 | mkdir impfbot && cd impfbot
26 | tar xf ../impfbot.tar.gz --strip-components 1
27 | ```
28 |
29 | 4. config.ini kopieren (unter der Annahme, dass sie im Android-Download-Ordner liegt)
30 | ```
31 | cp ../storage/downloads/config.ini .
32 | ```
33 |
34 | 5. Bot starten (installiert beim ersten Mal die benötigten Pakete)
35 | ```
36 | ./linux_start.sh
37 | ```
38 |
39 | 6. Einstellungen (Mailversand, Telegram) testen kann man ggf. mit
40 | ```
41 | ./linux_validate.sh
42 | ```
43 |
44 | ## mögliche Probleme
45 |
46 | - Die Energiesparfunktionen könnten ggf. Termux beenden. Infos für dein Gerät ggf. hier lesen: https://dontkillmyapp.com/
47 |
48 | Die Benachrichtung von Termux selbst hat bei mir den Knopf "Acquire wakelock". Das allein reicht aber nicht, die App wurde irgendwann beendet (ohne Deaktivierung anderer Energiesparfunktionen)
49 |
50 | - wenn du dich durch Funklöcher bewegst und das Impfportal nicht erreichbar ist, denkt der Bot, dass du einem IP-Ban unterliegst und wartet (bei den Standardeinstellungen)
51 |
52 |
53 | ## weitere Ideen
54 |
55 | wenn du in Termux `ssh` installierst kannst du (als Server oder Client) mit `scp` das Directory vom PC einfach komplett rüberkopieren
56 |
57 | man könnte in den Impfbot noch direkte Push-Nachrichten über die Termux:API integrieren
58 |
--------------------------------------------------------------------------------
/docs/SETUP_EMAIL_SERVICES.md:
--------------------------------------------------------------------------------
1 | # Anleitung für das Aufsetzen des E-Mail-Versands bei verschiedenen Anbietern
2 |
3 | Bei manchen Anbietern müssen zunächst bestimmte Einstellungen vorgenommen werden, um dem Bot den Zugriff zu erlauben. (Wenn ihr den Bot nicht mehr nutzt, einfach alles rückgängig machen 😉)
4 |
5 | ## GMail
6 |
7 | 1. Bei Gmail anmelden
8 | 2. Unter den [IMAP-Einstellungen](https://mail.google.com/mail/u/0/#settings/fwdandpop) IMAP aktivieren
9 | 3. Unter [Zugriff durch weniger sichere Apps](https://myaccount.google.com/lesssecureapps) weniger sichere Apps zulassen
10 |
11 |
12 | ### Beispiel-Config
13 |
14 | ```ini
15 | [EMAIL]
16 | enable=true
17 | sender=meinemail@gmail.com
18 | user=meinemail@gmail.com
19 | password=xxxxxx
20 | server=smtp.gmail.com
21 | port=465
22 | receivers=meinemail@gmail.com
23 | ```
24 |
25 | ## Web.de
26 |
27 | 1. Bei Webmail auf Einstellungen Gehen
28 | 2. Den Reiter POP3/IMAP Abruf auswählen
29 | 3. Unter "WEB.DE Mail über POP3 & IMAP" das Häkchen neben "POP3 und IMAP Zugriff erlauben" setzen
30 | 4. Speichern
31 |
32 | Alternativ: Anleitung mit Video von Web.de gibt es [hier](https://hilfe.web.de/pop-imap/einschalten.html)
33 |
34 | ### Beispiel-Config
35 |
36 | ```ini
37 | [EMAIL]
38 | enable=true
39 | sender=meinemail@web.de
40 | user=meinemail@web.de
41 | password=xxxxxx
42 | server=smtp.web.de
43 | port=587
44 | receivers=meinemail@web.de
45 | ```
46 |
47 | ## GMX
48 |
49 | 1. Bei E-Mail auf Einstellungen Gehen
50 | 2. Den Reiter POP3/IMAP Abruf auswählen
51 | 3. Unter "GMX Mail über POP3 & IMAP" das Häkchen neben "POP3 und IMAP Zugriff erlauben" setzen
52 | 4. Speichern
53 |
54 | Alternativ: Anleitung mit Video von GMX gibt es [hier](https://hilfe.gmx.net/pop-imap/imap/outlook.html#textlink_help_pop-imap_imap_imap-serverdaten)
55 |
56 | ### Beispiel-Config
57 |
58 | ```ini
59 | [EMAIL]
60 | enable=true
61 | sender=meinemail@gmx.net
62 | user=meinemail@gmx.net
63 | password=xxxxxx
64 | server=mail.gmx.net
65 | port=587
66 | receivers=meinemail@gmx.net
67 | ```
68 |
69 | ## iCloud
70 |
71 | 1. Den [Apple-ID-Account](https://appleid.apple.com/account/home) aufrufen
72 | 2. "Sicherheit" anklicken
73 | 3. "Anwendungsspezifische Passwörter" auswählen und dort "Passwort erstellen"
74 | 4. Den Anweisungen folgen
75 | 5. Das so erstellte Passwort in der `config.ini` speichern
76 |
77 | ### Beispiel-Config
78 |
79 | ```ini
80 | [EMAIL]
81 | enable=true
82 | sender=meinemail@icloud.com
83 | user=meinemail@icloud.com
84 | password=xxxxxx
85 | server=smtp.mail.me.com
86 | port=587
87 | receivers=meinemail@icloud.com
88 | ```
89 |
--------------------------------------------------------------------------------
/linux_start.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | pip3 install -q -r requirements.txt
3 | python3 src/impfbot.py --config config.ini
--------------------------------------------------------------------------------
/linux_validate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | pip3 install -q -r requirements.txt
3 | python3 src/validate_config.py --config config.ini
--------------------------------------------------------------------------------
/mac_start.command:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | pip3 install -q -r requirements.txt
3 | python3 src/impfbot.py --config config.ini
--------------------------------------------------------------------------------
/mac_validate.command:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | pip3 install -q -r requirements.txt
3 | python3 src/validate_config.py --config config.ini
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | requests==2.25.1
2 | pytest==6.2.4
3 | requests-mock==1.9.3
4 | freezegun==1.1.0
5 | tkcalendar==1.6.1
6 | apprise==0.9.3
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from pathlib import Path
4 |
5 | import setuptools
6 |
7 | project_dir = Path(__file__).parent
8 |
9 | setuptools.setup(
10 | name="impfbot",
11 | version=project_dir.joinpath(
12 | "version.txt").read_text().split("\n")[0],
13 | description="Notification bot for the lower saxony vaccination portal",
14 | long_description=project_dir.joinpath(
15 | "README.md").read_text(encoding="utf-8"),
16 | keywords=["python"],
17 | author="sibalzer",
18 | url="https://github.com/sibalzer/impfbot",
19 | packages=setuptools.find_packages("src"),
20 | package_dir={"": "src"},
21 | python_requires=">=3.6",
22 | include_package_data=True,
23 | install_requires=project_dir.joinpath(
24 | "requirements.txt").read_text().split("\n"),
25 | zip_safe=False,
26 | license="GPL v3",
27 | )
28 |
--------------------------------------------------------------------------------
/src/alerts.py:
--------------------------------------------------------------------------------
1 | """alert service handler"""
2 |
3 | import apprise
4 | import smtplib
5 | import webbrowser
6 | import logging
7 | from email.message import EmailMessage
8 | from email.utils import formatdate
9 | import ssl
10 |
11 | from common import APPOINTMENT_URL
12 | from settings import settings
13 |
14 | log = logging.getLogger(__name__)
15 |
16 |
17 | def alert(msg: str) -> None:
18 | """Calls alert services with message"""
19 | if settings.EMAIL_ENABLE:
20 | log.debug("[EMAIL] try to send e-mail")
21 | try:
22 | send_mail(msg)
23 | log.info("[EMAIL] sending e-mail was successful")
24 | except smtplib.SMTPException as ex:
25 | log.error(f"[EMAIL] Couldn't send mail: {ex}")
26 | else:
27 | log.debug("[EMAIL] enable is not set to true. Skipping...")
28 |
29 | if settings.TELEGRAM_ENABLE:
30 | log.debug("[TELEGRAM] Try to send telegram message")
31 | try:
32 | send_telegram(msg)
33 | except Exception as ex:
34 | log.error(f"[TELEGRAM] Couldn't send Telegram message: {ex}")
35 | else:
36 | log.debug(
37 | "[TELEGRAM] enable is not set to true. Skipping...")
38 |
39 | if settings.WEBBROWSER_ENABLE:
40 | log.debug("[WEBBROWSER] try to open browser")
41 | try:
42 | webbrowser.open(APPOINTMENT_URL, new=1, autoraise=True)
43 | log.info("[WEBBROWSER] Open browser was successful")
44 | except webbrowser.Error as ex:
45 | log.error(f"[WEBBROWSER] Couldn't open browser: {ex}")
46 | else:
47 | log.debug(
48 | "[WEBBROWSER] enable is not set to true. Skipping...")
49 |
50 | if settings.APPRISE_ENABLE:
51 | log.debug(f"[APPRISE] try to send Apprise Notification")
52 | try:
53 | send_apprise(msg)
54 | except Exception as ex:
55 | log.error(f"Couldn't send Apprise Notification: {ex}")
56 | else:
57 | log.debug(f"[APPRISE] send_apprise is not set to true skipping")
58 |
59 |
60 | def send_mail(msg: str) -> None:
61 | """email alert service"""
62 | mail = EmailMessage()
63 |
64 | mail['From'] = settings.EMAIL_SENDER
65 | mail['To'] = settings.EMAIL_SENDER
66 | mail['Bcc'] = settings.EMAIL_RECEIVERS
67 | mail['Date'] = formatdate(localtime=True)
68 | mail['subject'] = msg
69 | mail.set_content(APPOINTMENT_URL)
70 |
71 | if settings.EMAIL_PORT == 465:
72 | with smtplib.SMTP_SSL(settings.EMAIL_SERVER, settings.EMAIL_PORT)as smtp:
73 | smtp.login(settings.EMAIL_USER, settings.EMAIL_PASSWORD)
74 | smtp.send_message(mail)
75 | elif settings.EMAIL_PORT == 587:
76 | with smtplib.SMTP(settings.EMAIL_SERVER, settings.EMAIL_PORT)as smtp:
77 | smtp.starttls(context=ssl.create_default_context())
78 | smtp.login(settings.EMAIL_USER, settings.EMAIL_PASSWORD)
79 | smtp.send_message(mail)
80 | else:
81 | with smtplib.SMTP(settings.EMAIL_SERVER, settings.EMAIL_PORT)as smtp:
82 | smtp.login(settings.EMAIL_USER, settings.EMAIL_PASSWORD)
83 | smtp.send_message(mail)
84 |
85 |
86 | def send_telegram(msg: str) -> None:
87 | """telegram alert service"""
88 | appobj = apprise.Apprise()
89 |
90 | url = f"tgram://{settings.TELEGRAM_TOKEN}"
91 | for chat_id in settings.TELEGRAM_CHAT_IDS:
92 | url += f"/{chat_id}"
93 | url += "?format=markdown"
94 |
95 | appobj.add(url)
96 |
97 | appobj.notify(
98 | body=f"{APPOINTMENT_URL}",
99 | title=f"**{msg}**",
100 | )
101 |
102 |
103 | def send_apprise(msg: str) -> None:
104 | """apprise alert service"""
105 | appobj = apprise.Apprise()
106 |
107 | for url in settings.APPRISE_SERVICE_URIS:
108 | appobj.add(url)
109 |
110 | appobj.notify(
111 | body=f"{APPOINTMENT_URL}",
112 | title=f"{msg}",
113 | )
114 |
--------------------------------------------------------------------------------
/src/api_wrapper.py:
--------------------------------------------------------------------------------
1 |
2 | """api wrapper for the lower saxony vaccination portal"""
3 | import logging
4 |
5 | from requests.sessions import Session
6 | from requests.exceptions import ConnectionError as RequestConnectionError
7 | from common import sleep
8 |
9 | log = logging.getLogger(__name__)
10 |
11 |
12 | class ShadowBanException(Exception):
13 | """Exception for ip ban detection"""
14 |
15 |
16 | def fetch_api(
17 | zip_code: int,
18 | birthdate_timestamp: int = None,
19 | group_size: int = None,
20 | with_vector: bool = True,
21 | max_retries: int = 10,
22 | sleep_after_error: int = 30,
23 | jitter: int = 5,
24 | user_agent: str = 'python'
25 | ) -> any:
26 | """fetches the api with ip ban avoidance"""
27 | url = f"https://www.impfportal-niedersachsen.de/portal/rest/appointments/findVaccinationCenterListFree/{zip_code}?stiko="
28 | if birthdate_timestamp:
29 | url += f"&count=1&birthdate={int(birthdate_timestamp)*1000}"
30 | elif group_size:
31 | url += f"&count={group_size}"
32 | if with_vector:
33 | url += f"&showWithVectorVaccine=true"
34 | fail_counter = 0
35 |
36 | headers = {
37 | 'Accept': 'application/json',
38 | 'User-Agent': user_agent
39 | }
40 |
41 | for fail_counter in range(0, max_retries+1):
42 | try:
43 | session = Session()
44 | with session.get(url=url, headers=headers, timeout=10) as data:
45 | return data.json()["resultList"]
46 | except RequestConnectionError as ex:
47 | raise ex
48 | except Exception as ex:
49 | log.debug(f"Exeption during request {ex}")
50 | sleep_time = sleep_after_error*fail_counter
51 | sleep(sleep_time, jitter)
52 | raise ShadowBanException
53 |
--------------------------------------------------------------------------------
/src/common.py:
--------------------------------------------------------------------------------
1 | """common methods and constants"""
2 | from datetime import datetime, timedelta, time as dt
3 | import random
4 | import sys
5 | import time
6 |
7 | APPOINTMENT_URL = r"https://www.impfportal-niedersachsen.de/portal/#/appointment/public"
8 |
9 | ZIP_REGEX = r"^(19|21|26|27|28|29|30|31|34|37|38|48|49)([0-9]{3})$"
10 | BIRTHDATE_REGEX = r"^[0-3]?[0-9]\.[0-3]?[0-9]\.(?:19|20)?[0-9]{2}$"
11 | NUMBER_REGEX = r"^[0-9]*(?:\.[0-9])?$"
12 | GROUP_SIZE_REGEX = r"^[2-9]|1[0-5]$"
13 | BOOL_REGEX = r"(?i)^(?:true)|(?:false)$"
14 | USER_AGENT_REGEX = r"^.*$"
15 |
16 |
17 | MAIL_REGEX = r"\b(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])\b"
18 | NOTIFIERS = ["EMAIL", "TELEGRAM", "WEBBROWSER", "APPRISE"]
19 | NOTIFIER_REGEX = {
20 | "sender": MAIL_REGEX,
21 | "user": r"^[^ ]*$", # match anything execpt space
22 | "password": r"^[^ ]*$", # match anything execpt space
23 | # match alphanumeric characters, dash, and dot
24 | "server": r"^[a-zA-Z0-9-\.]+$",
25 | "port": r"^\d{2,}$",
26 | "receivers": r"^" + MAIL_REGEX + r"(," + MAIL_REGEX + r")*$",
27 | # I hope this covers all possible tokens
28 | "token": r"^[0-9]+:[a-zA-Z0-9\-_]+$",
29 | "chat_ids": r"^\-?\d{5,}(,\-?\d{5,})*$", # matches a list of numbers with possible leading dash
30 | "service_uris": r"^[^ ]+$", # match anything not a space
31 | }
32 |
33 |
34 | YES = ["yes", "y", "ja", "j"]
35 | NO = ["no", "n", "nein"]
36 |
37 |
38 | def datetime2timestamp(date: datetime) -> int:
39 | """transforms a datetime in a timestamp (datetime.datetime.timestamp() fails pre epoch)"""
40 | now = datetime.now()
41 | s_since_date = (now - date).total_seconds()
42 | return int(now.timestamp() - s_since_date)
43 |
44 |
45 | def is_night() -> bool:
46 | """test if it is night"""
47 | morning = dt(hour=7, minute=0)
48 | evening = dt(hour=23, minute=0)
49 | now = datetime.now().time()
50 | return not (morning < now < evening)
51 |
52 |
53 | GOOD_PLZ = ['19', '21', '26', '27', '28', '29',
54 | '30', '31', '34', '37', '38', '48', '49']
55 |
56 |
57 | def sleep(time_in_s: int, jitter: int = 0) -> None:
58 | """sleeps for time and random jitter; prints output"""
59 | time_to_wait = time_in_s + random.random()*jitter
60 | start = datetime.now()
61 | end = datetime.now() + timedelta(seconds=time_to_wait)
62 | while end > datetime.now():
63 | elapsed_time_s = (datetime.now() - start).total_seconds()
64 | time_to_wait_s = time_to_wait
65 | elapsed_time_delta = time_to_wait_s - elapsed_time_s
66 |
67 | time_str = f"\rSleeping ({int(elapsed_time_s)}s/{int(time_to_wait_s)}s)"
68 | sys.stdout.write(time_str)
69 | sys.stdout.flush()
70 |
71 | if elapsed_time_delta < 1:
72 | time.sleep(elapsed_time_delta)
73 | else:
74 | time.sleep(1)
75 | sys.stdout.write("\r")
76 | sys.stdout.flush()
77 |
78 |
79 | def sleep_until(hour, minute) -> None:
80 | """sleep until certain time"""
81 | today = datetime.today()
82 | future = datetime(today.year, today.month, today.day, hour, minute)
83 | if today.timestamp() > future.timestamp():
84 | future += timedelta(days=1)
85 | sleep((future-today).total_seconds())
86 |
--------------------------------------------------------------------------------
/src/config_generator.py:
--------------------------------------------------------------------------------
1 | """ generate a config if none found """
2 | import re
3 |
4 | from common import (
5 | NOTIFIERS,
6 | NOTIFIER_REGEX,
7 | ZIP_REGEX,
8 | GROUP_SIZE_REGEX,
9 | BIRTHDATE_REGEX
10 | )
11 | from config_skeleton import SKELETON
12 |
13 | try:
14 | import tkinter as tk
15 | from tkinter import ttk
16 | from tkcalendar import DateEntry
17 | run_gui = True
18 | except ImportError:
19 | # tk is missing -> run CLI config
20 | run_gui = False
21 |
22 |
23 | FIELDS = {
24 | "EMAIL": {
25 | "sender": "Absender",
26 | "user": "User",
27 | "password": "Passwort",
28 | "server": "Server",
29 | "port": "Port",
30 | "receivers": "Empfänger"
31 | },
32 | "TELEGRAM": {
33 | "token": "Token",
34 | "chat_ids": "Chat-ID(s)"
35 | },
36 | "APPRISE": {
37 | "service_urls": "Different Service URLs"
38 | }
39 | }
40 |
41 |
42 | def init_input(config_dict):
43 | config_dict["COMMON"] = {}
44 | for item in NOTIFIERS:
45 | config_dict[item.upper()] = {}
46 | config_dict["ADVANCED"] = {}
47 | config_dict["ADVANCED"]["custom_message_prefix"] = str(
48 | SKELETON["ADVANCED"]["custom_message_prefix"]["default"])
49 | config_dict["ADVANCED"]["cooldown_between_requests"] = str(
50 | SKELETON["ADVANCED"]["cooldown_between_requests"]["default"])
51 | config_dict["ADVANCED"]["cooldown_between_failed_requests"] = str(
52 | SKELETON["ADVANCED"]["cooldown_between_failed_requests"]["default"])
53 | config_dict["ADVANCED"]["cooldown_after_ip_ban"] = str(
54 | SKELETON["ADVANCED"]["cooldown_after_ip_ban"]["default"])
55 | config_dict["ADVANCED"]["cooldown_after_success"] = str(
56 | SKELETON["ADVANCED"]["cooldown_after_success"]["default"])
57 | config_dict["ADVANCED"]["jitter"] = str(
58 | SKELETON["ADVANCED"]["jitter"]["default"])
59 | config_dict["ADVANCED"]["sleep_at_night"] = str(
60 | SKELETON["ADVANCED"]["sleep_at_night"]["default"])
61 | config_dict["ADVANCED"]["user_agent"] = str(
62 | SKELETON["ADVANCED"]["user_agent"]["default"])
63 |
64 |
65 | def start_config_generation(config_dict: dict = dict()):
66 | """ entry point for config generation """
67 | global run_gui
68 | if run_gui:
69 | try:
70 | gui_window = tk.Tk()
71 | except tk.TclError:
72 | # most likely no display was found (i. e. running headless)
73 | run_gui = False
74 |
75 | init_input(config_dict)
76 | if run_gui:
77 | run_gui_config(gui_window, config_dict)
78 | else:
79 | config_dict = run_cli_config(config_dict)
80 |
81 | if config_dict != {}:
82 | with open("config.ini", "w") as configfile:
83 | config_dict.write(configfile)
84 |
85 |
86 | def run_gui_config(tk_window, config_dict):
87 | """ create a window for data entry """
88 |
89 | def toggle_group_request(event):
90 | """ toggle input for group appointment search """
91 | if not search_group_appointments.get():
92 | birthday.grid_remove()
93 | birthday_label.grid_remove()
94 | group_size_label.grid(row=2, column=1)
95 | group_size.grid(row=3, column=1)
96 | else:
97 | birthday.grid(row=3, column=1)
98 | birthday_label.grid(row=2, column=1)
99 | group_size.grid_remove()
100 | group_size_label.grid_remove()
101 |
102 | def get_input():
103 | """ read config from form """
104 | if search_group_appointments.get():
105 | config_dict["COMMON"]["group_size"] = group_size.get()
106 | else:
107 | config_dict["COMMON"]["birthdate"] = birthday.get_date().strftime(
108 | "%d.%m.%Y")
109 | config_dict["COMMON"]["zip_code"] = plz.get()
110 | for item in NOTIFIERS:
111 | config_dict[item.upper()]["enable"] = str(
112 | enable[item].get()).lower()
113 |
114 | def create_subwindow(event):
115 | """ when selecting a notifier, show a new window with the required options """
116 | def close_subwindow():
117 | """ get values and close window """
118 | if validate_notifier_input():
119 | for field in FIELDS[notifier]:
120 | config_dict[notifier.upper(
121 | )][field] = input_arr[field].get()
122 | subwindow.destroy()
123 | else:
124 | open_alert_window(msg="Bitte alle Felder ausfüllen.")
125 |
126 | def validate_notifier_input():
127 | """ check for empty input """
128 | for item in input_arr:
129 | match = re.match(
130 | NOTIFIER_REGEX[item], input_arr[item].get())
131 | if match is None:
132 | return False
133 | return True
134 |
135 | notifier = event.widget.cget("text")
136 | if notifier != "WEBBROWSER" and not enable[notifier].get():
137 | enable[notifier].set(not enable[notifier].get())
138 | input_arr = {}
139 | subwindow = tk.Toplevel(tk_window)
140 | row_index = 0
141 | notifier_fields = FIELDS[notifier]
142 | for field in notifier_fields:
143 | tk.Label(subwindow, text=notifier_fields[field]).grid(
144 | row=row_index, column=0)
145 | input_arr[field] = tk.Entry(subwindow)
146 | input_arr[field].grid(row=row_index, column=1)
147 | row_index += 1
148 | close = tk.Button(
149 | subwindow, text="Fenster schließen", command=close_subwindow)
150 | close.grid(row=row_index, column=1)
151 | return 0
152 |
153 | def open_alert_window(msg):
154 | """ create an alert window """
155 | def close_alert_window():
156 | alert_window.destroy()
157 |
158 | alert_window = tk.Toplevel(tk_window)
159 | tk.Label(alert_window, text=msg).grid(row=0, column=0)
160 | close_alert = tk.Button(alert_window, text="OK",
161 | command=close_alert_window)
162 | close_alert.grid(row=1, column=0)
163 |
164 | def check_notifiers_enabled():
165 | """ check whether any notifier is enabled """
166 | for item in enable:
167 | if enable[item].get():
168 | return True
169 | return False
170 |
171 | def validate_input():
172 | """ validate user input """
173 | if search_group_appointments.get():
174 | entered_group_size = group_size.get()
175 | match_group_size = re.match(GROUP_SIZE_REGEX, entered_group_size)
176 | if match_group_size is None:
177 | return False
178 | entered_plz = plz.get()
179 | return bool(re.match(ZIP_REGEX, entered_plz))
180 |
181 | def close_window():
182 | """ close the window """
183 | if not check_notifiers_enabled():
184 | open_alert_window(
185 | msg="Bitte eine Art der Benachrichtigung auswählen!")
186 | elif not validate_input():
187 | open_alert_window(msg="Bitte korrekte Daten eingeben.")
188 | else:
189 | get_input()
190 | tk_window.destroy()
191 |
192 | def cancel():
193 | config_dict = {}
194 | tk_window.destroy()
195 |
196 | def advanced_settings():
197 | def close_settings_window():
198 | for field in config_dict["ADVANCED"]:
199 | config_dict["ADVANCED"][field] = advanced_settings_input[field].get()
200 | settings_window.destroy()
201 |
202 | settings_window_row_index = 0
203 | settings_window = tk.Toplevel(tk_window)
204 | advanced_settings_input = {}
205 | for field in config_dict["ADVANCED"]:
206 | tk.Label(
207 | settings_window,
208 | text=field
209 | ).grid(row=settings_window_row_index, column=0)
210 | advanced_settings_input[field] = tk.Entry(settings_window)
211 | advanced_settings_input[field].grid(
212 | row=settings_window_row_index, column=1)
213 | advanced_settings_input[field].insert(
214 | 0, config_dict["ADVANCED"][field])
215 | settings_window_row_index += 1
216 | close_advanced = tk.Button(
217 | settings_window, text="Fenster schließen", command=close_settings_window)
218 | close_advanced.grid(row=settings_window_row_index, column=1)
219 |
220 | tk_window.geometry("400x400+250+100")
221 |
222 | row_index = 7
223 | checkboxes = {}
224 | enable = {}
225 |
226 | search_group_appointments = tk.BooleanVar()
227 | search_group_appointments.set(False)
228 | group_request = ttk.Checkbutton(
229 | tk_window,
230 | text="Gruppentermin",
231 | variable=search_group_appointments,
232 | onvalue=True
233 | )
234 | group_request.bind('', toggle_group_request)
235 | group_request.grid(row=1, column=1)
236 |
237 | birthday_label = tk.Label(tk_window, text="Geburtsdatum", font="bold")
238 | birthday_label.grid(row=2, column=1)
239 | tk.Label(tk_window, text="PLZ", font="bold").grid(row=4, column=1)
240 |
241 | group_size_label = tk.Label(tk_window, text="Gruppengröße", font="bold")
242 | group_size_label.grid_remove()
243 |
244 | birthday = DateEntry(tk_window, width=18)
245 | group_size = tk.Entry(tk_window)
246 | plz = tk.Entry(tk_window)
247 |
248 | birthday.grid(row=3, column=1)
249 | plz.grid(row=5, column=1)
250 | group_size.grid_remove()
251 |
252 | tk.Label(tk_window, text="Benachrichtigung",
253 | font="bold").grid(row=6, column=1)
254 | for item in NOTIFIERS:
255 | enable[item] = tk.BooleanVar()
256 | enable[item].set(False)
257 | checkboxes[item] = ttk.Checkbutton(
258 | tk_window,
259 | text=item,
260 | variable=enable[item],
261 | onvalue=True
262 | )
263 | checkboxes[item].bind('', create_subwindow)
264 | checkboxes[item].grid(row=row_index, column=1)
265 | row_index += 1
266 |
267 | tk_window.columnconfigure(0, weight=1)
268 | tk_window.columnconfigure(2, weight=1)
269 |
270 | confirm = tk.Button(tk_window, text="Abbrechen", command=cancel)
271 | confirm.grid(row=row_index, column=1)
272 |
273 | close = tk.Button(
274 | tk_window, text="Speichern und schließen", command=close_window)
275 | close.grid(row=row_index + 1, column=1)
276 |
277 | advanced = tk.Button(
278 | tk_window, text="Weitere Einstellungen", command=advanced_settings)
279 | advanced.grid(row=row_index + 2, column=1)
280 |
281 | tk_window.mainloop()
282 |
283 |
284 | def run_cli_config(config_dict):
285 | def get_notifier_credentials(notifier):
286 | notifier_input = {}
287 | notifier_input["enable"] = "true"
288 | for field in FIELDS[notifier]:
289 | match = None
290 | while match is None:
291 | notifier_input[field] = input(f'{FIELDS[notifier][field]}: ')
292 | match = re.match(
293 | NOTIFIER_REGEX[field], notifier_input[field])
294 | return notifier_input
295 |
296 | birthday = ""
297 | plz = ""
298 | match = None
299 | config_for_group_input = ""
300 | while config_for_group_input.lower() not in ["j", "n"]:
301 | config_for_group_input = input(
302 | 'Soll nach Gruppenterminen gesucht werden? (j/n): ')
303 | config_for_group = config_for_group_input.lower() == "j"
304 | while match is None and not config_for_group:
305 | birthday = input('Bitte den Geburtstag eingeben: ')
306 | match = re.match(BIRTHDATE_REGEX, birthday)
307 | match = None
308 | while match is None and config_for_group:
309 | group_size = input('Bitte die Gruppengröße eingeben: ')
310 | match = re.match(GROUP_SIZE_REGEX, group_size)
311 | while match is None or bool(re.match(ZIP_REGEX, plz)):
312 | plz = input('Bitte die PLZ eingeben: ')
313 | match = re.match(ZIP_REGEX, plz)
314 |
315 | enable_notifier = {}
316 | for notifier in FIELDS:
317 | input_res = ""
318 | while input_res.lower() not in ["j", "n"]:
319 | input_res = input(
320 | f'Soll per {notifier} benachrichtigt werden? (j/n): '
321 | ).lower()
322 | enable_notifier[notifier] = input_res == "j"
323 | if enable_notifier[notifier]:
324 | config_dict[notifier.upper()] = get_notifier_credentials(notifier)
325 | else:
326 | config_dict[notifier.upper()]["enable"] = "false"
327 |
328 | enable_browser_input = ""
329 | while enable_browser_input.lower() not in ["j", "n"]:
330 | enable_browser_input = input('Soll bei Benachrichtigung ein '
331 | 'Browserfenster geöffnet werden? (j/n): ').lower()
332 | enable_browser = str(enable_browser_input.lower() == "j").lower()
333 |
334 | if config_for_group:
335 | config_dict["COMMON"]["group_size"] = group_size
336 | else:
337 | config_dict["COMMON"]["birthday"] = birthday
338 | config_dict["COMMON"]["zip_cpde"] = plz
339 | config_dict["WEBBROWSER"]["enable"] = enable_browser
340 |
341 | return config_dict
342 |
343 |
344 | if __name__ == "__main__":
345 |
346 | start_config_generation()
347 |
--------------------------------------------------------------------------------
/src/config_skeleton.py:
--------------------------------------------------------------------------------
1 | """skelton data for the settings"""
2 |
3 | from datetime import datetime
4 | from common import (
5 | BIRTHDATE_REGEX,
6 | BOOL_REGEX,
7 | NOTIFIER_REGEX,
8 | NUMBER_REGEX,
9 | USER_AGENT_REGEX,
10 | ZIP_REGEX,
11 | GROUP_SIZE_REGEX
12 | )
13 |
14 |
15 | SKELETON = {
16 | "COMMON": {
17 | "zip_code": {
18 | "default": None,
19 | "type": int,
20 | "regex": ZIP_REGEX
21 | },
22 | "birthdate": {
23 | "default": None,
24 | "type": datetime,
25 | "regex": BIRTHDATE_REGEX
26 | },
27 | "group_size": {
28 | "default": None,
29 | "type": int,
30 | "regex": GROUP_SIZE_REGEX
31 | },
32 | "with_vector": {
33 | "default": True,
34 | "type": bool,
35 | "regex": BOOL_REGEX
36 | }
37 | },
38 | "EMAIL": {
39 | "enable": {
40 | "default": False,
41 | "type": bool,
42 | "regex": BOOL_REGEX
43 | },
44 | "sender": {
45 | "default": None,
46 | "type": str,
47 | "regex": NOTIFIER_REGEX["sender"]
48 | },
49 | "user": {
50 | "default": None,
51 | "type": str,
52 | "regex": NOTIFIER_REGEX["user"]
53 | },
54 | "password": {
55 | "default": None,
56 | "type": str,
57 | "regex": NOTIFIER_REGEX["password"],
58 | },
59 | "server": {
60 | "default": None,
61 | "type": str,
62 | "regex": NOTIFIER_REGEX["server"]
63 | },
64 | "port": {
65 | "default": None,
66 | "type": int,
67 | "regex": NOTIFIER_REGEX["port"]
68 | },
69 | "receivers": {
70 | "default": None,
71 | "type": list,
72 | "regex": NOTIFIER_REGEX["receivers"]
73 | }
74 | },
75 | "TELEGRAM": {
76 | "enable": {
77 | "default": False,
78 | "type": bool,
79 | "regex": BOOL_REGEX
80 | },
81 | "token": {
82 | "default": 30,
83 | "type": str,
84 | "regex": NOTIFIER_REGEX["token"]
85 | },
86 | "chat_ids": {
87 | "default": 30,
88 | "type": list,
89 | "regex": NOTIFIER_REGEX["chat_ids"]
90 | },
91 | },
92 | "WEBBROWSER": {
93 | "enable": {
94 | "default": False,
95 | "type": bool,
96 | "regex": BOOL_REGEX
97 | },
98 | },
99 | "APPRISE": {
100 | "enable": {
101 | "default": False,
102 | "type": bool,
103 | "regex": BOOL_REGEX
104 | },
105 | "service_uris": {
106 | "default": 30,
107 | "type": list,
108 | "regex": NOTIFIER_REGEX["service_uris"]
109 | },
110 | },
111 | "ADVANCED": {
112 | "custom_message_prefix": {
113 | "default": "Impfbot",
114 | "type": str,
115 | "regex": USER_AGENT_REGEX
116 | },
117 | "cooldown_between_requests": {
118 | "default": 30,
119 | "type": float,
120 | "regex": NUMBER_REGEX
121 | },
122 | "cooldown_between_failed_requests": {
123 | "default": 5,
124 | "type": float,
125 | "regex": NUMBER_REGEX
126 | },
127 | "cooldown_after_ip_ban": {
128 | "default": 60*60*3,
129 | "type": float,
130 | "regex": NUMBER_REGEX
131 | },
132 | "cooldown_after_success": {
133 | "default": 60*15,
134 | "type": float,
135 | "regex": NUMBER_REGEX
136 | },
137 | "jitter": {
138 | "default": 10,
139 | "type": float,
140 | "regex": NUMBER_REGEX
141 | },
142 | "sleep_at_night": {
143 | "default": True,
144 | "type": bool,
145 | "regex": BOOL_REGEX
146 | },
147 | "user_agent": {
148 | "default": "impfbot",
149 | "type": str,
150 | "regex": USER_AGENT_REGEX
151 | },
152 | }
153 | }
154 |
155 | DEPRACATED_CONFIG_MAP = {
156 | ("COMMON", "postleitzahl"): "zip_code",
157 | ("COMMON", "geburtstag"): "birthdate",
158 | ("EMAIL", "empfaenger"): "receivers",
159 | ("TELEGRAM", "enable_telegram"): "enable",
160 | ("TELEGRAM", "chat_id"): "chat_ids",
161 | ("WEBBROWSER", "open_browser"): "enable",
162 | ("ADVANCED", "sleep_between_requests_in_s"): "cooldown_between_requests",
163 | ("ADVANCED", "sleep_between_failed_requests_in_s"): "cooldown_between_failed_requests",
164 | ("ADVANCED", "sleep_after_ipban_in_min"): "cooldown_after_ip_ban",
165 | ("ADVANCED", "cooldown_after_found_in_min"): "cooldown_after_success",
166 | }
167 |
--------------------------------------------------------------------------------
/src/impfbot.py:
--------------------------------------------------------------------------------
1 | """Notification bot for the lower saxony vaccination portal"""
2 | import argparse
3 | from datetime import datetime, timezone, timedelta
4 | import sys
5 |
6 | from alerts import alert
7 | from api_wrapper import fetch_api, ShadowBanException, RequestConnectionError
8 | from common import sleep, sleep_until, is_night, datetime2timestamp, YES, NO
9 | from config_generator import start_config_generation
10 | from log import log
11 | from settings import load, settings, ParseExeption
12 |
13 |
14 | def check_for_slot() -> None:
15 | """checks if a slot is available"""
16 | try:
17 | if hasattr(settings, "COMMON_BIRTHDATE"):
18 | birthdate_timestamp = datetime2timestamp(settings.COMMON_BIRTHDATE)
19 | result = fetch_api(
20 | zip_code=settings.COMMON_ZIP_CODE,
21 | birthdate_timestamp=birthdate_timestamp,
22 | with_vector=settings.COMMON_WITH_VECTOR,
23 | max_retries=10,
24 | sleep_after_error=settings.COOLDOWN_BETWEEN_FAILED_REQUESTS,
25 | user_agent=settings.USER_AGENT,
26 | jitter=settings.JITTER
27 | )
28 | else:
29 | result = fetch_api(
30 | zip_code=settings.COMMON_ZIP_CODE,
31 | group_size=settings.COMMON_GROUP_SIZE,
32 | with_vector=settings.COMMON_WITH_VECTOR,
33 | max_retries=10,
34 | sleep_after_error=settings.COOLDOWN_BETWEEN_FAILED_REQUESTS,
35 | user_agent=settings.USER_AGENT,
36 | jitter=settings.JITTER
37 | )
38 | if result == []:
39 | log.error("Result is emtpy. (Invalid ZIP Code (PLZ)?)")
40 | for elem in result:
41 | if not elem['outOfStock']:
42 | local_timezone = timezone(timedelta(hours=2))
43 |
44 | free_slots = elem['freeSlotSizeOnline']
45 | vaccine_name = elem['vaccineName']
46 | vaccine_type = elem['vaccineType']
47 | first_appoinment_date = datetime.fromtimestamp(
48 | elem['firstAppoinmentDateSorterOnline'] /
49 | 1000, local_timezone
50 | ).strftime("%d.%m.%Y")
51 |
52 | log.info(
53 | f"Free slot! ({free_slots}) {vaccine_name}/{vaccine_type} Appointment date: {first_appoinment_date}")
54 | msg = f"[{settings.CUSTOM_MESSAGE_PREFIX}] Freier Impfslot ({free_slots})! {vaccine_name}/{vaccine_type} verfügbar ab dem {first_appoinment_date}"
55 |
56 | alert(msg)
57 | sleep(settings.COOLDOWN_AFTER_SUCCESS)
58 | else:
59 | log.info("No free slot.")
60 | sleep(settings.COOLDOWN_BETWEEN_REQUESTS, settings.JITTER)
61 |
62 | except RequestConnectionError as ex:
63 | log.error(
64 | f"Couldn't fetch api: ConnectionError (No internet?) {ex}")
65 | sleep(10)
66 |
67 | except ShadowBanException:
68 | sleep_after_shadowban_min = settings.COOLDOWN_AFTER_IP_BAN/60
69 | log.error(
70 | f"Couldn't fetch api. (Shadowbanned IP?) "
71 | f"Sleeping for {sleep_after_shadowban_min}min")
72 | sleep(settings.COOLDOWN_AFTER_IP_BAN)
73 |
74 | except Exception as ex:
75 | log.error(f"Something went wrong ({ex})")
76 | sleep(settings.COOLDOWN_BETWEEN_REQUESTS, settings.JITTER)
77 |
78 |
79 | if __name__ == "__main__":
80 | try:
81 | parser = argparse.ArgumentParser(
82 | description='Notification bot for the lower saxony vaccination portal')
83 | parser.add_argument('-f', '-c', '--config',
84 | dest='configfile',
85 | help='Path to config.ini file',
86 | required=False,
87 | default='config.ini')
88 | arg = vars(parser.parse_args())
89 |
90 | try:
91 | load(arg['configfile'])
92 | except FileNotFoundError:
93 | while True:
94 | log.error("config file not found")
95 | print("Do you want to use the interface to generate a config? yes/no")
96 | result = input().lower()
97 | if result in YES:
98 | log.info("Starting config generator")
99 | start_config_generation()
100 | break
101 | elif result in NO:
102 | sys.exit(1)
103 | else:
104 | print("Invalid input")
105 |
106 | except ParseExeption as ex:
107 | log.error(ex)
108 | print("Press [enter] to close.")
109 | input()
110 | sys.exit(1)
111 | except Exception as ex:
112 | log.warning(ex)
113 |
114 | print(settings)
115 |
116 | while True:
117 | if is_night() and settings.SLEEP_AT_NIGHT:
118 | log.info("It's night. Sleeping until 7am")
119 | sleep_until(hour=7, minute=0)
120 |
121 | check_for_slot()
122 |
123 | except (KeyboardInterrupt, SystemExit):
124 | print("Bye...")
125 |
--------------------------------------------------------------------------------
/src/log.py:
--------------------------------------------------------------------------------
1 | """logging config modul"""
2 | import logging
3 | import sys
4 |
5 | logging.basicConfig(
6 | level=logging.INFO,
7 | format="%(asctime)s [%(levelname)s] %(message)s",
8 | datefmt='%Y-%m-%d %H:%M:%S',
9 | handlers=[
10 | logging.FileHandler("impfbot.log"),
11 | logging.StreamHandler(sys.stdout)
12 | ]
13 | )
14 |
15 | log = logging.getLogger()
16 |
--------------------------------------------------------------------------------
/src/settings.py:
--------------------------------------------------------------------------------
1 | """config parser modul"""
2 | from configparser import RawConfigParser
3 | import re
4 | import logging
5 | from datetime import datetime
6 |
7 | from config_skeleton import SKELETON, DEPRACATED_CONFIG_MAP
8 | from common import NOTIFIERS
9 |
10 | __log = logging.getLogger(__name__)
11 |
12 |
13 | class Datastore():
14 | """data-class for settings"""
15 |
16 | def __str__(self):
17 | result = ""
18 | for section in SKELETON:
19 | result += f"[{section}]\n"
20 | for option in SKELETON[section]:
21 | name_builder = option.upper()
22 | if section not in "ADVANCED":
23 | name_builder = f"{section.upper()}_{option.upper()}"
24 | value = getattr(self, name_builder, "not set")
25 | if isinstance(value, list):
26 | value = ', '.join(value)
27 | result += f" {option}: {value}\n"
28 | return result
29 |
30 | def clear(self):
31 | """removes all settings"""
32 | attributes = list(settings.__dict__)
33 | for att in attributes:
34 | delattr(self, att)
35 |
36 |
37 | settings = Datastore()
38 |
39 |
40 | class ParseExeption(BaseException):
41 | """data-class for settings"""
42 |
43 |
44 | def __set_option(section: str, option: str, value: str, multiplyer: int = 1):
45 | """sets an option in the data class"""
46 | regex = SKELETON[section][option]["regex"]
47 |
48 | name_builder = option.upper()
49 | if section != "ADVANCED":
50 | name_builder = f"{section.upper()}_" + name_builder
51 |
52 | if re.match(regex, value):
53 | typ: any = SKELETON[section][option]["type"]
54 |
55 | if issubclass(typ, datetime):
56 | value = datetime.strptime(value, r'%d.%m.%Y')
57 | elif typ is float:
58 | value = typ(value)*multiplyer
59 | elif typ is bool:
60 | value = value == "true"
61 | elif typ is list:
62 | value = value.split(',')
63 | else:
64 | value = typ(value)
65 |
66 | setattr(settings, name_builder, value)
67 |
68 |
69 | def __parse(config: RawConfigParser):
70 | for section in config.sections():
71 | if section in SKELETON:
72 | __parse_section(config, section)
73 | else:
74 | __log.warning(
75 | f"[{section}] is unknown")
76 |
77 |
78 | def __parse_section(config: RawConfigParser, section: str):
79 | """parse a settings section"""
80 | for option in config.options(section):
81 | try:
82 | __parse_option(config, section, option)
83 | except Exception as ex:
84 | __log.error(
85 | f"[{section}] '{option}' error during parsing: {ex}")
86 |
87 |
88 | def __parse_option(config: RawConfigParser, section: str, option: str):
89 | """parse a single setting option"""
90 | if option in SKELETON[section]:
91 | value = config[section][option]
92 | __set_option(section, option, value)
93 |
94 | # depracated config
95 | elif (section, option) in DEPRACATED_CONFIG_MAP:
96 | new_option = DEPRACATED_CONFIG_MAP[(section, option)]
97 | value = config[section][option]
98 | if option[-7:] == "_in_min":
99 | __set_option(section, new_option, value, 60)
100 | else:
101 | __set_option(section, new_option, value)
102 |
103 | __log.warning(
104 | f"[{section}] '{option}' is depracated please use: '{new_option}'")
105 |
106 | # unknown
107 | else:
108 | __log.warning(f"[{section}] '{option}' is unknown.")
109 |
110 |
111 | def __validate():
112 | for section in SKELETON:
113 | __validate_section(section)
114 |
115 |
116 | def __validate_section(section: str):
117 | for option in SKELETON[section]:
118 | __validate_option(section, option)
119 |
120 |
121 | def __validate_option(section: str, option: str):
122 | if section == "COMMON":
123 | option_name = f'COMMON_{option.upper()}'
124 | if option in ["birthdate", "group_size"]:
125 | if not hasattr(settings, "COMMON_BIRTHDATE") and not hasattr(settings, "COMMON_GROUP_SIZE"):
126 | raise ParseExeption(
127 | f"[{section}] 'birthdate' or 'group_size' must be in the config.")
128 |
129 | if not hasattr(settings, "COMMON_BIRTHDATE") ^ hasattr(settings, "COMMON_GROUP_SIZE"):
130 | raise ParseExeption(
131 | f"[{section}] only one of 'birthdate' or 'group_size' is allowed in the same config.")
132 | else:
133 | if getattr(settings, option_name, None) is None:
134 | if option_name == "COMMON_WITH_VECTOR":
135 | if getattr(settings, option_name, None) is None:
136 | value = SKELETON[section][option]["default"]
137 | typ: any = SKELETON[section][option]["type"]
138 | setattr(settings, option_name, typ(value))
139 |
140 | __log.warning(
141 | f"[{section}] '{option}' not set. Using default: '{value}'")
142 | return
143 | else:
144 | raise ParseExeption(
145 | f"[{section}] '{option}' must be in the config.")
146 |
147 | elif section in NOTIFIERS:
148 | option_name = f"{section.upper()}_{option.upper()}"
149 | name_enable = f"{section.upper()}_ENABLE"
150 | if getattr(settings, name_enable, False):
151 | if getattr(settings, option_name, None) is None:
152 | if (section == "EMAIL" and option == "user"
153 | # depracated special case email user
154 | and getattr(settings, "EMAIL_SENDER") is not None):
155 | __set_option(section, "user", getattr(
156 | settings, "EMAIL_SENDER"))
157 | __log.warning(
158 | f"[{section}] '{option}' is missing; set sender as user")
159 | else:
160 | __set_option(section, "enable", "False")
161 | __log.warning(
162 | f"[{section}] '{option}' not valid or missing. Disable [{section}]")
163 | else:
164 | __set_option(section, "enable", "False")
165 | if option == "enable":
166 | __log.info(
167 | f"[{section}] '{option}' is set to 'false'. Disable [{section}]")
168 |
169 | elif section == "ADVANCED":
170 | name = option.upper()
171 | if getattr(settings, name, None) is None:
172 | value = SKELETON[section][option]["default"]
173 | typ: any = SKELETON[section][option]["type"]
174 | setattr(settings, option.upper(), typ(value))
175 |
176 | __log.warning(
177 | f"[{section}] '{option}' not set. Using default: '{value}'")
178 | return
179 | else:
180 | raise ParseExeption(
181 | f"[{section}] '{option}' is unknown")
182 |
183 |
184 | def load(path):
185 | """loads a config file"""
186 | settings.clear()
187 | config = RawConfigParser()
188 | dataset = config.read(path)
189 | if not dataset:
190 | raise FileNotFoundError("config.ini not found.")
191 |
192 | __parse(config)
193 | __validate()
194 |
--------------------------------------------------------------------------------
/src/validate_config.py:
--------------------------------------------------------------------------------
1 | """cli interface for validating the config"""
2 |
3 | import argparse
4 | from log import log
5 | from settings import load, settings
6 | from alerts import alert
7 | from common import YES, NO
8 |
9 | parser = argparse.ArgumentParser()
10 | parser.add_argument('-f', '-c', '--config',
11 | dest='configfile',
12 | help='Path to config.ini file',
13 | required=False,
14 | default='config.ini')
15 | parser.add_argument('-a', '--alert',
16 | action='store_true',
17 | help='validate alert with a test message. Default=False',
18 | default=False)
19 | arg = vars(parser.parse_args())
20 |
21 | log.info("validate config.ini")
22 |
23 | load(arg['configfile'])
24 |
25 | log.info("settings validation finished")
26 |
27 |
28 | while True:
29 | result = ""
30 | if not arg['alert']:
31 | print("Do you want to send a test message? yes/no")
32 | result = input().lower()
33 |
34 | if result in YES or arg['alert']:
35 | alert("Test")
36 | log.info("Finished: Sending test massages")
37 | break
38 | elif result in NO:
39 | break
40 | else:
41 | print("Invalid input")
42 |
43 | if not arg['alert']:
44 | while True:
45 | print("Do you want to see your config? yes/no")
46 | result = input().lower()
47 | if result in YES:
48 | print(settings)
49 | break
50 | elif result in NO:
51 | break
52 | else:
53 | print("Invalid input")
54 |
55 |
56 | if not arg['alert']:
57 | log.info("Finished validation script. Press [enter] to close")
58 | input()
59 |
--------------------------------------------------------------------------------
/tests/configs/test-config-advanced.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=23.6.1912
3 | zip_code=49042
4 |
5 | [ADVANCED]
6 | custom_message_prefix=Impfbot
7 | cooldown_between_requests=60
8 | cooldown_between_failed_requests=10
9 | cooldown_after_ip_ban=10800
10 | cooldown_after_success=900
11 | jitter=5
12 | sleep_at_night=false
13 | user_agent=impfbot
--------------------------------------------------------------------------------
/tests/configs/test-config-apprise.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=5.5.1900
3 | zip_code=37042
4 |
5 | [APPRISE]
6 | enable=true
7 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
--------------------------------------------------------------------------------
/tests/configs/test-config-browser.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=01.03.2000
3 | zip_code=38123
4 |
5 | [WEBBROWSER]
6 | enable=true
--------------------------------------------------------------------------------
/tests/configs/test-config-email-ssl.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=1.1.1984
3 | zip_code=49000
4 |
5 | [EMAIL]
6 | enable=true
7 | user=username
8 | sender=test@test.tld
9 | password=testpw
10 | server=mail.test.tld
11 | port=465
12 | empfaenger=test@test.tld,test2@test.tld
--------------------------------------------------------------------------------
/tests/configs/test-config-email.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=1.1.1984
3 | zip_code=49000
4 |
5 | [EMAIL]
6 | enable=true
7 | user=username
8 | sender=test@test.tld
9 | password=testpw
10 | server=mail.test.tld
11 | port=420
12 | receivers=test@test.tld,test2@test.tld
--------------------------------------------------------------------------------
/tests/configs/test-config-invalid-advanced.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | zip_code=30042
3 | birthdate=23.6.1912
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=sender@server.de
8 | user=username
9 | password=secret
10 | server=mail.server.de
11 | port=465
12 | receivers=sender@server.de,guenni@server.de,frida@server.de
13 |
14 | [TELEGRAM]
15 | enable=true
16 | token=123456789:alphanumeric_characters
17 | chat_ids=123456789,987654321
18 |
19 | [WEBBROWSER]
20 | enable=true
21 |
22 | [APPRISE]
23 | enable=true
24 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
25 |
26 | [ADVANCED]
27 | custom_message_prefix=Impfbot
28 | cooldown_between_requests=60a
29 | cooldown_between_failed_requests=10a
30 | cooldown_after_ip_ban=10800a
31 | cooldown_after_success=900a
32 | jitter=5a
33 | sleep_at_night=falsea
34 | user_agent=impfbot
--------------------------------------------------------------------------------
/tests/configs/test-config-invalid-apprise.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | zip_code=49042
3 | birthdate=23.6.1912
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=sender@server.de
8 | user=username
9 | password=secret
10 | server=mail.server.de
11 | port=465
12 | receivers=sender@server.de,guenni@server.de,frida@server.de
13 |
14 | [TELEGRAM]
15 | enable=true
16 | token=123456789:alphanumeric_characters
17 | chat_ids=12345ab6789,9876c54321
18 |
19 | [WEBBROWSER]
20 | enable=true
21 |
22 | [APPRISE]
23 | enable=true
24 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
25 |
26 | [ADVANCED]
27 | custom_message_prefix=Impfbot
28 | cooldown_between_requests=60
29 | cooldown_between_failed_requests=10
30 | cooldown_after_ip_ban=10800
31 | cooldown_after_success=900
32 | jitter=5
33 | sleep_at_night=false
34 | user_agent=impfbot_v3
--------------------------------------------------------------------------------
/tests/configs/test-config-invalid-birthdate.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | zip_code=49000
3 | birthdate=june
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=sender@server.de
8 | user=username
9 | password=secret
10 | server=mail.server.de
11 | port=465
12 | receivers=sender@server.de,guenni@server.de,frida@server.de
13 |
14 | [TELEGRAM]
15 | enable=true
16 | token=123456789:alphanumeric_characters
17 | chat_ids=123456789,987654321
18 |
19 | [WEBBROWSER]
20 | enable=true
21 |
22 | [APPRISE]
23 | enable=true
24 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
25 |
26 | [ADVANCED]
27 | custom_message_prefix=Impfbot
28 | cooldown_between_requests=60
29 | cooldown_between_failed_requests=10
30 | cooldown_after_ip_ban=10800
31 | cooldown_after_success=900
32 | jitter=5
33 | sleep_at_night=false
34 | user_agent=impfbot_v3
--------------------------------------------------------------------------------
/tests/configs/test-config-invalid-email.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | zip_code=49042
3 | birthdate=23.6.1912
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=senderver.de
8 | user=usern ame
9 | password=ä ö
10 | server=s de
11 | port=blub
12 | receivers=sendeerver.de,guenni@server.de,frida@server.de
13 |
14 | [TELEGRAM]
15 | enable=true
16 | token=123456789:alphanumeric_characters
17 | chat_ids=123456789,987654321
18 |
19 | [WEBBROWSER]
20 | enable=true
21 |
22 | [APPRISE]
23 | enable=true
24 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
25 |
26 | [ADVANCED]
27 | custom_message_prefix=Impfbot
28 | cooldown_between_requests=60
29 | cooldown_between_failed_requests=10
30 | cooldown_after_ip_ban=10800
31 | cooldown_after_success=900
32 | jitter=5
33 | sleep_at_night=false
34 | user_agent=impfbot_v3
--------------------------------------------------------------------------------
/tests/configs/test-config-invalid-telegram.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | zip_code=49042
3 | birthdate=23.6.1912
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=sender@server.de
8 | user=username
9 | password=secret
10 | server=mail.server.de
11 | port=465
12 | receivers=sender@server.de,guenni@server.de,frida@server.de
13 |
14 | [TELEGRAM]
15 | enable=true
16 | token=äöäöü:TOKEN
17 | chat_ids=12345ab6789,9876c54321
18 |
19 | [WEBBROWSER]
20 | enable=true
21 |
22 | [APPRISE]
23 | enable=true
24 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
25 |
26 | [ADVANCED]
27 | custom_message_prefix=Impfbot
28 | cooldown_between_requests=60
29 | cooldown_between_failed_requests=10
30 | cooldown_after_ip_ban=10800
31 | cooldown_after_success=900
32 | jitter=5
33 | sleep_at_night=false
34 | user_agent=impfbot_v3
--------------------------------------------------------------------------------
/tests/configs/test-config-invalid-zip-code.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | zip_code=bla
3 | birthdate=june
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=sender@server.de
8 | user=username
9 | password=secret
10 | server=mail.server.de
11 | port=465
12 | receivers=sender@server.de,guenni@server.de,frida@server.de
13 |
14 | [TELEGRAM]
15 | enable=true
16 | token=123456789:alphanumeric_characters
17 | chat_ids=123456789,987654321
18 |
19 | [WEBBROWSER]
20 | enable=true
21 |
22 | [ADVANCED]
23 | custom_message_prefix=Impfbot
24 | cooldown_between_requests=60
25 | cooldown_between_failed_requests=10
26 | cooldown_after_ip_ban=10800
27 | cooldown_after_success=900
28 | jitter=5
29 | sleep_at_night=false
30 | user_agent=impfbot_v3
--------------------------------------------------------------------------------
/tests/configs/test-config-minimal.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | geburtstag=1.12.1994
3 | postleitzahl=19000
--------------------------------------------------------------------------------
/tests/configs/test-config-no-alerts.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | geburtstag=23.6.1912
3 | postleitzahl=38042
4 |
5 | [EMAIL]
6 | enable=false
7 | sender=sender@server.de
8 | password=xxxx
9 | server=mail.server.de
10 | port=465
11 | empfaenger=sender@server.de,guenni@server.de,frida@server.de
12 |
13 | [TELEGRAM]
14 | enable_telegram=false
15 | token=123456789:alphanumeric_characters
16 | chat_id=123456789,987654321
17 |
18 | [WEBBROWSER]
19 | open_browser=false
20 |
21 | [ADVANCED]
22 | custom_message_prefix=Impfbot
23 | sleep_between_requests_in_s=1
24 | sleep_between_failed_requests_in_s=2
25 | sleep_after_ipban_in_min=3
26 | cooldown_after_found_in_min=4
27 | jitter=5
28 | sleep_at_night=false
29 | user_agent=impfbot
--------------------------------------------------------------------------------
/tests/configs/test-config-old.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | geburtstag=23.6.1912
3 | postleitzahl=19042
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=sender@server.de
8 | password=xxxx
9 | server=mail.server.de
10 | port=465
11 | empfaenger=sender@server.de,guenni@server.de,frida@server.de
12 |
13 | [TELEGRAM]
14 | enable_telegram=true
15 | token=123456789:alphanumeric_characters
16 | chat_id=123456789,987654321
17 |
18 | [WEBBROWSER]
19 | open_browser=true
20 |
21 | [ADVANCED]
22 | sleep_between_requests_in_s=1
23 | sleep_between_failed_requests_in_s=2
24 | sleep_after_ipban_in_min=3
25 | cooldown_after_found_in_min=4
26 | jitter=5
27 | sleep_at_night=false
28 | user_agent=impfbot
--------------------------------------------------------------------------------
/tests/configs/test-config-optional-missing.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=1.12.1994
3 | zip_code=19000
--------------------------------------------------------------------------------
/tests/configs/test-config-telegram.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=5.5.1900
3 | zip_code=37042
4 |
5 | [TELEGRAM]
6 | enable=true
7 | token=123456789:alphanumeric_characters
8 | chat_ids=123456789,987654321
--------------------------------------------------------------------------------
/tests/configs/test-config-valid.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | zip_code=30042
3 | birthdate=23.6.1912
4 | with_vector=true
5 |
6 | [EMAIL]
7 | enable=true
8 | sender=sender@server.de
9 | user=username
10 | password=secret
11 | server=mail.server.de
12 | port=465
13 | receivers=sender@server.de,guenni@server.de,frida@server.de
14 |
15 | [TELEGRAM]
16 | enable=true
17 | token=123456789:alphanumeric_characters
18 | chat_ids=123456789,987654321
19 |
20 | [WEBBROWSER]
21 | enable=true
22 |
23 | [APPRISE]
24 | enable=true
25 | service_uris=discord://webhook_id/webhook_token,matrix://hostname
26 |
27 | [ADVANCED]
28 | custom_message_prefix=Impfbot
29 | cooldown_between_requests=60
30 | cooldown_between_failed_requests=10
31 | cooldown_after_ip_ban=10800
32 | cooldown_after_success=900
33 | jitter=5
34 | sleep_at_night=false
35 | user_agent=impfbot_v3
--------------------------------------------------------------------------------
/tests/configs/test-config.ini:
--------------------------------------------------------------------------------
1 | [COMMON]
2 | birthdate=23.6.1912
3 | zip_code=19042
4 |
5 | [EMAIL]
6 | enable=true
7 | sender=sender@server.de
8 | user=xxxx
9 | password=xxxx
10 | server=mail.server.de
11 | port=465
12 | receivers=sender@server.de,guenni@server.de,frida@server.de
13 |
14 | [TELEGRAM]
15 | enable=true
16 | token=123456789:alphanumeric_characters
17 | chat_ids=123456789,987654321
18 |
19 | [WEBBROWSER]
20 | enable=true
21 |
22 | [ADVANCED]
23 | custom_message_prefix=Impfbot
24 | cooldown_between_requests=1
25 | cooldown_between_failed_requests=2
26 | cooldown_after_ip_ban=3
27 | cooldown_after_success=4
28 | jitter=5
29 | sleep_at_night=false
30 | user_agent=impfbot
--------------------------------------------------------------------------------
/tests/configs/test-invalid-file.ini:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sibalzer/impfbot/49b5dbdb3c4fe685a3cbf9352717880d8214eccc/tests/configs/test-invalid-file.ini
--------------------------------------------------------------------------------
/tests/test_alerts.py:
--------------------------------------------------------------------------------
1 | import unittest.mock as mock
2 |
3 | from settings import settings, load
4 | import alerts
5 |
6 |
7 | @mock.patch('alerts.send_mail')
8 | @mock.patch('alerts.send_telegram')
9 | @mock.patch('webbrowser.open', return_value=None)
10 | def test_alert(browser_mock, telegram_mock, email_mock):
11 | load("tests/configs/test-config.ini")
12 |
13 | msg = 'test'
14 | alerts.alert(msg)
15 |
16 | email_mock.assert_called_once_with(msg)
17 | telegram_mock.assert_called_once_with(msg)
18 | browser_mock.assert_called_once_with(
19 | alerts.APPOINTMENT_URL, new=1, autoraise=True)
20 |
21 |
22 | @mock.patch('smtplib.SMTP', create=True)
23 | def test_send_email(smtp_mock):
24 | load("tests/configs/test-config-email.ini")
25 |
26 | msg = 'test'
27 | alerts.send_mail(msg)
28 |
29 | smtp_mock.assert_called_once()
30 |
31 | smtp_mock_obj = smtp_mock.return_value.__enter__.return_value
32 |
33 | smtp_mock_obj.login.assert_called_once_with(
34 | settings.EMAIL_USER, settings.EMAIL_PASSWORD)
35 | smtp_mock_obj.send_message.assert_called_once()
36 |
37 |
38 | @mock.patch('apprise.Apprise.notify', return_value=None)
39 | def test_send_telegram_msg(apprise_notify_mock):
40 | load("tests/configs/test-config-telegram.ini")
41 |
42 | msg = 'test'
43 | alerts.send_telegram(msg)
44 |
45 | assert apprise_notify_mock.called_once()
46 |
47 |
48 | @mock.patch('webbrowser.open', return_value=None)
49 | def test_open_browser(webbrowser_mock):
50 | load("tests/configs/test-config-browser.ini")
51 |
52 | alerts.alert('')
53 |
54 | webbrowser_mock.assert_called_once_with(
55 | alerts.APPOINTMENT_URL, new=1, autoraise=True)
56 |
57 |
58 | @mock.patch('apprise.Apprise.notify', return_value=None)
59 | def test_send_apprise(apprise_notify_mock):
60 | load("tests/configs/test-config-apprise.ini")
61 |
62 | msg = 'test'
63 | alerts.send_apprise(msg)
64 |
65 | assert apprise_notify_mock.called_once()
66 |
--------------------------------------------------------------------------------
/tests/test_api_wrapper.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import json
3 | import unittest.mock as mock
4 | import requests_mock
5 | import api_wrapper
6 |
7 | invalid_json = {
8 | "resultList": [
9 | {
10 | "vaccinationCenterPk": 12345678901234,
11 | "name": "IZ Test-Impfbot",
12 | "streetName": "Rainbow Road",
13 | "streetNumber": "42",
14 | "zipcode": "49000",
15 | "city": "Toadcity",
16 | "scheduleSaturday": True,
17 | "scheduleSunday": True,
18 | "vaccinationCenterType": 0,
19 | "vaccineName": "AstraZeneca",
20 | "vaccineType": "Vector",
21 | "interval1to2": 84,
22 | "offsetStart2Appointment": 0,
23 | "offsetEnd2Appointment": 5,
24 | "distance": 10,
25 | "outOfStock": True,
26 | "publicAppointment": True
27 | }
28 | ],
29 | "succeeded": True
30 | }
31 |
32 |
33 | valid_json = {
34 | "resultList": [
35 | {
36 | "vaccinationCenterPk": 12345678901234,
37 | "name": "IZ Test-Impfbot",
38 | "streetName": "Rainbow Road",
39 | "streetNumber": "42",
40 | "zipcode": "49000",
41 | "city": "Toadcity",
42 | "scheduleSaturday": True,
43 | "scheduleSunday": True,
44 | "vaccinationCenterType": 0,
45 | "vaccineName": "AstraZeneca",
46 | "vaccineType": "Vector",
47 | "interval1to2": 84,
48 | "offsetStart2Appointment": 0,
49 | "offsetEnd2Appointment": 5,
50 | "distance": 5,
51 | "outOfStock": False,
52 | "firstAppoinmentDateSorterOnline": 1622412000000,
53 | "freeSlotSizeOnline": 253,
54 | "maxFreeSlotPerDay": 24,
55 | "publicAppointment": True
56 | }
57 | ],
58 | "succeeded": True
59 | }
60 |
61 |
62 | @mock.patch("api_wrapper.sleep", return_value=None)
63 | def test_valid(mock_common_sleep):
64 | with requests_mock.Mocker() as mocker:
65 | zip_code = 49049
66 | timestamp = 1620505010
67 | url = f'https://www.impfportal-niedersachsen.de/portal/rest/appointments/findVaccinationCenterListFree/{zip_code}?stiko=&count=1'
68 |
69 | mocker.get(
70 | url,
71 | json=valid_json
72 |
73 | )
74 |
75 | result = api_wrapper.fetch_api(
76 | zip_code=zip_code,
77 | birthdate_timestamp=timestamp,
78 | max_retries=0,
79 | )
80 |
81 | a, b = json.dumps(result, sort_keys=True), json.dumps(
82 | valid_json["resultList"], sort_keys=True)
83 | assert a == b
84 |
85 |
86 | @mock.patch("api_wrapper.sleep", return_value=None)
87 | def test_shadowban(common_sleep_mock):
88 | with requests_mock.Mocker() as mocker:
89 | zip_code = 49049
90 | timestamp = 1620505010000
91 |
92 | mocker.get(
93 | f'https://www.impfportal-niedersachsen.de/portal/rest/appointments/findVaccinationCenterListFree/{zip_code}?stiko=&count=1',
94 | json=None
95 |
96 | )
97 |
98 | with pytest.raises(api_wrapper.ShadowBanException):
99 | api_wrapper.fetch_api(
100 | zip_code=zip_code,
101 | birthdate_timestamp=timestamp,
102 | max_retries=2,
103 | sleep_after_error=4,
104 | jitter=7
105 | )
106 |
107 | assert common_sleep_mock.call_count == 3 # 1 + 2 retries
108 |
--------------------------------------------------------------------------------
/tests/test_common.py:
--------------------------------------------------------------------------------
1 | from logging import FATAL
2 | from unittest import mock
3 | from freezegun import freeze_time
4 | from datetime import datetime
5 | import time
6 | import common
7 |
8 |
9 | @freeze_time("2012-01-14 03:21:34")
10 | def test_is_night_night():
11 | assert common.is_night()
12 |
13 |
14 | @freeze_time("2012-01-14 14:21:34")
15 | def test_is_night_day():
16 | assert not common.is_night()
17 |
18 |
19 | @freeze_time("2012-01-14 13:59:10", tick=True)
20 | def test_sleep():
21 | start = time.time()
22 | common.sleep(2)
23 | end = time.time()
24 | delta = (end - start)
25 | assert 1.9 < delta < 2.1
26 |
27 |
28 | @freeze_time("2012-01-14 13:59:58", tick=True)
29 | def test_sleep_until():
30 | common.sleep_until(14, 0)
31 | end = time.gmtime()
32 | assert end.tm_hour == 14
33 | assert end.tm_min == 0
34 | assert end.tm_sec == 0
35 |
--------------------------------------------------------------------------------
/tests/test_impfbot.py:
--------------------------------------------------------------------------------
1 | """tests for module impfbot"""
2 | import unittest.mock as mock
3 | import requests_mock
4 | import requests
5 |
6 | import impfbot
7 | from settings import settings, load
8 |
9 | in_stock = {
10 | "resultList": [
11 | {
12 | "vaccinationCenterPk": 12345678901234,
13 | "name": "IZ Test-Impfbot",
14 | "streetName": "Rainbow Road",
15 | "streetNumber": "42",
16 | "zipcode": "49000",
17 | "city": "Toadcity",
18 | "scheduleSaturday": True,
19 | "scheduleSunday": True,
20 | "vaccinationCenterType": 0,
21 | "vaccineName": "AstraZeneca",
22 | "vaccineType": "Vector",
23 | "interval1to2": 84,
24 | "offsetStart2Appointment": 0,
25 | "offsetEnd2Appointment": 5,
26 | "distance": 5,
27 | "outOfStock": False,
28 | "firstAppoinmentDateSorterOnline": 1622412000000,
29 | "freeSlotSizeOnline": 253,
30 | "maxFreeSlotPerDay": 24,
31 | "publicAppointment": True
32 | }
33 | ],
34 | "succeeded": True
35 | }
36 |
37 |
38 | out_of_stock = {
39 | "resultList": [
40 | {
41 | "vaccinationCenterPk": 12345678901234,
42 | "name": "IZ Test-Impfbot",
43 | "streetName": "Rainbow Road",
44 | "streetNumber": "42",
45 | "zipcode": "49000",
46 | "city": "Toadcity",
47 | "scheduleSaturday": True,
48 | "scheduleSunday": True,
49 | "vaccinationCenterType": 0,
50 | "vaccineName": "AstraZeneca",
51 | "vaccineType": "Vector",
52 | "interval1to2": 84,
53 | "offsetStart2Appointment": 0,
54 | "offsetEnd2Appointment": 5,
55 | "distance": 10,
56 | "outOfStock": True,
57 | "publicAppointment": True
58 | }
59 | ],
60 | "succeeded": True
61 | }
62 |
63 | empty = {
64 | "resultList": [],
65 | "succeeded": True
66 | }
67 |
68 | load("tests/configs/test-config-valid.ini")
69 | zip_code = settings.COMMON_ZIP_CODE
70 | api_url = f'https://www.impfportal-niedersachsen.de/portal/rest/appointments/findVaccinationCenterListFree/{zip_code}?stiko=&count=1&showWithVectorVaccine=true'
71 |
72 | error_none = None
73 |
74 |
75 | @mock.patch('impfbot.sleep', return_value=None)
76 | @mock.patch('impfbot.alert', return_value=None)
77 | @mock.patch('logging.Logger.error')
78 | @mock.patch('logging.Logger.warning')
79 | @mock.patch('logging.Logger.info')
80 | def test_check_for_slot_in_stock(log_info_mock,
81 | log_warning_mock,
82 | log_error_mock,
83 | alert_mock,
84 | sleep_mock):
85 | """test for vaccine in stock"""
86 | load("tests/configs/test-config-valid.ini")
87 | with requests_mock.Mocker() as mocker:
88 | mocker.get(
89 | url=api_url,
90 | json=in_stock
91 | )
92 | impfbot.check_for_slot()
93 |
94 | alert_mock.assert_called_once_with(
95 | "[Impfbot] Freier Impfslot (253)! AstraZeneca/Vector verfügbar ab dem 31.05.2021")
96 | log_info_mock.assert_called_once_with(
97 | "Free slot! (253) AstraZeneca/Vector Appointment date: 31.05.2021")
98 | log_warning_mock.assert_not_called()
99 | log_error_mock.assert_not_called()
100 |
101 | sleep_mock.assert_called_once_with(settings.COOLDOWN_AFTER_SUCCESS)
102 |
103 |
104 | @mock.patch('impfbot.sleep', return_value=None)
105 | @mock.patch('logging.Logger.error')
106 | @mock.patch('logging.Logger.warning')
107 | @mock.patch('logging.Logger.info')
108 | def test_check_for_slot_out_of_stock(log_info_mock,
109 | log_warning_mock,
110 | log_error_mock,
111 | sleep_mock):
112 | """test for vaccine out of stock"""
113 | load("tests/configs/test-config-valid.ini")
114 | with requests_mock.Mocker() as mocker:
115 | mocker.get(
116 | url=api_url,
117 | json=out_of_stock
118 | )
119 | impfbot.check_for_slot()
120 |
121 | log_info_mock.assert_called_with('No free slot.')
122 | log_warning_mock.assert_not_called()
123 | log_error_mock.assert_not_called()
124 |
125 |
126 | @mock.patch('api_wrapper.sleep', return_value=None)
127 | @mock.patch('impfbot.sleep', return_value=None)
128 | @mock.patch('logging.Logger.error')
129 | @mock.patch('logging.Logger.warning')
130 | @mock.patch('logging.Logger.info')
131 | def test_check_for_slot_shadowban(log_info_mock,
132 | log_warning_mock,
133 | log_error_mock,
134 | sleep_mock,
135 | sleep_api_mock):
136 | """test for shadowban exception"""
137 | load("tests/configs/test-config-valid.ini")
138 | with requests_mock.Mocker() as mocker:
139 | mocker.get(
140 | url=api_url,
141 | json=None
142 | )
143 | impfbot.check_for_slot()
144 |
145 | sleep_mock.assert_called_with(
146 | settings.COOLDOWN_AFTER_IP_BAN)
147 |
148 | log_info_mock.assert_not_called()
149 | log_warning_mock.assert_not_called()
150 | log_error_mock.assert_called_with(
151 | f"Couldn't fetch api. (Shadowbanned IP?) "
152 | f"Sleeping for {settings.COOLDOWN_AFTER_IP_BAN/60}min")
153 |
154 |
155 | @mock.patch('api_wrapper.sleep', return_value=None)
156 | @mock.patch('impfbot.sleep', return_value=None)
157 | @mock.patch('logging.Logger.error')
158 | @mock.patch('logging.Logger.warning')
159 | @mock.patch('logging.Logger.info')
160 | def test_check_for_slot_connection_lost(log_info_mock,
161 | log_warning_mock,
162 | log_error_mock,
163 | sleep_mock,
164 | sleep_api_mock):
165 | """test for shadowban exception"""
166 | load("tests/configs/test-config-valid.ini")
167 | with requests_mock.Mocker() as mocker:
168 | mocker.get(
169 | url=api_url,
170 | exc=requests.exceptions.ConnectionError
171 | )
172 | impfbot.check_for_slot()
173 |
174 | log_info_mock.assert_not_called()
175 | log_warning_mock.assert_not_called()
176 | log_error_mock.assert_called_with(
177 | f"Couldn't fetch api: ConnectionError (No internet?) ")
178 |
--------------------------------------------------------------------------------
/tests/test_settings.py:
--------------------------------------------------------------------------------
1 | """tests for settings.py"""
2 | from datetime import datetime
3 | from unittest import mock
4 | import pytest
5 | from freezegun import freeze_time
6 |
7 | from settings import settings, load, ParseExeption
8 |
9 |
10 | @freeze_time("2021-01-01 03:21:34")
11 | @mock.patch('logging.Logger.error')
12 | @mock.patch('logging.Logger.warning')
13 | @mock.patch('logging.Logger.info')
14 | def test_valid(log_info_mock,
15 | log_warning_mock,
16 | log_error_mock):
17 | """test for vaccine in stock"""
18 | load("tests/configs/test-config-valid.ini")
19 |
20 | # Check output
21 | log_info_mock.assert_not_called()
22 | log_warning_mock.assert_not_called()
23 | log_error_mock.assert_not_called()
24 |
25 | # COMMON
26 | assert settings.COMMON_ZIP_CODE == 30042
27 | assert settings.COMMON_BIRTHDATE == datetime(1912, 6, 23)
28 |
29 | # EMAIL
30 | assert settings.EMAIL_ENABLE is True
31 | assert settings.EMAIL_USER == "username"
32 | assert settings.EMAIL_PASSWORD == "secret"
33 | assert settings.EMAIL_SERVER == "mail.server.de"
34 | assert settings.EMAIL_PORT == 465
35 | assert settings.EMAIL_SENDER == "sender@server.de"
36 | assert settings.EMAIL_RECEIVERS == [
37 | "sender@server.de", "guenni@server.de", "frida@server.de"]
38 |
39 | # TELEGRAM
40 | assert settings.TELEGRAM_ENABLE is True
41 | assert settings.TELEGRAM_TOKEN == "123456789:alphanumeric_characters"
42 | assert settings.TELEGRAM_CHAT_IDS == ["123456789", "987654321"]
43 |
44 | # WEBBROWSER
45 | assert settings.WEBBROWSER_ENABLE is True
46 |
47 | # ADVANCED
48 | assert settings.CUSTOM_MESSAGE_PREFIX == "Impfbot"
49 | assert settings.COOLDOWN_BETWEEN_REQUESTS == 60
50 | assert settings.COOLDOWN_BETWEEN_FAILED_REQUESTS == 10
51 | assert settings.COOLDOWN_AFTER_IP_BAN == 10800
52 | assert settings.COOLDOWN_AFTER_SUCCESS == 900
53 | assert settings.JITTER == 5
54 | assert settings.SLEEP_AT_NIGHT is False
55 | assert settings.USER_AGENT == "impfbot_v3"
56 |
57 |
58 | @mock.patch('logging.Logger.error')
59 | @mock.patch('logging.Logger.warning')
60 | @mock.patch('logging.Logger.info')
61 | def test_invalid_zip_code(log_info_mock,
62 | log_warning_mock,
63 | log_error_mock):
64 | with pytest.raises(ParseExeption):
65 | load("tests/configs/test-config-invalid-zip-code.ini")
66 |
67 |
68 | @mock.patch('logging.Logger.error')
69 | @mock.patch('logging.Logger.warning')
70 | @mock.patch('logging.Logger.info')
71 | def test_invalid_birthdate(log_info_mock,
72 | log_warning_mock,
73 | log_error_mock):
74 |
75 | with pytest.raises(ParseExeption):
76 | load("tests/configs/test-config-invalid-birthdate.ini")
77 |
78 |
79 | @mock.patch('logging.Logger.error')
80 | @mock.patch('logging.Logger.warning')
81 | @mock.patch('logging.Logger.info')
82 | def test_invalid_email(log_info_mock,
83 | log_warning_mock,
84 | log_error_mock):
85 | load("tests/configs/test-config-invalid-email.ini")
86 |
87 | # Check output
88 | log_info_mock.assert_not_called()
89 | log_warning_mock.call_count = 6
90 | log_error_mock.assert_not_called()
91 |
92 | # EMAIL
93 | assert settings.EMAIL_ENABLE is False
94 |
95 |
96 | @mock.patch('logging.Logger.error')
97 | @mock.patch('logging.Logger.warning')
98 | @mock.patch('logging.Logger.info')
99 | def test_invalid_telegram(log_info_mock,
100 | log_warning_mock,
101 | log_error_mock):
102 | load("tests/configs/test-config-invalid-telegram.ini")
103 |
104 | # Check output
105 | log_info_mock.assert_not_called()
106 | log_warning_mock.call_count = 3
107 | log_error_mock.assert_not_called()
108 |
109 | # TELEGRAM
110 | assert settings.TELEGRAM_ENABLE is False
111 |
112 |
113 | @mock.patch('logging.Logger.error')
114 | @mock.patch('logging.Logger.warning')
115 | @mock.patch('logging.Logger.info')
116 | def test_invalid_advanced(log_info_mock,
117 | log_warning_mock,
118 | log_error_mock):
119 | load("tests/configs/test-config-invalid-advanced.ini")
120 |
121 | # Check output
122 | log_info_mock.assert_not_called()
123 | log_warning_mock.call_count = 7 - 1
124 | log_error_mock.assert_not_called()
125 |
126 | # ADVANCED
127 | assert settings.CUSTOM_MESSAGE_PREFIX == "Impfbot"
128 | assert settings.COOLDOWN_BETWEEN_REQUESTS == 30
129 | assert settings.COOLDOWN_BETWEEN_FAILED_REQUESTS == 5
130 | assert settings.COOLDOWN_AFTER_IP_BAN == 10800
131 | assert settings.COOLDOWN_AFTER_SUCCESS == 900
132 | assert settings.JITTER == 10
133 | assert settings.SLEEP_AT_NIGHT is True
134 | assert settings.USER_AGENT == "impfbot"
135 |
136 |
137 | @mock.patch('logging.Logger.error')
138 | @mock.patch('logging.Logger.warning')
139 | @mock.patch('logging.Logger.info')
140 | def test_old(log_info_mock,
141 | log_warning_mock,
142 | log_error_mock):
143 | load("tests/configs/test-config-old.ini")
144 |
145 | # Check output
146 | assert log_info_mock.call_count == 1
147 | assert log_warning_mock.call_count == 13
148 | for msg in log_warning_mock.call_args_list:
149 | assert (" is depracated please use: " in msg.args[0]
150 | or "[EMAIL] 'user' is missing; set sender as user" in msg.args[0]
151 | or "[COMMON] 'with_vector' not set. Using default: 'True'"
152 | or "[ADVANCED] 'custom_message_prefix' not set. Using default: 'Impfbot'" in msg.args[0])
153 | log_error_mock.assert_not_called()
154 |
155 | # COMMON
156 | assert settings.COMMON_ZIP_CODE == 19042
157 | assert settings.COMMON_BIRTHDATE == datetime(1912, 6, 23)
158 |
159 | # EMAIL
160 | assert settings.EMAIL_ENABLE is True
161 | assert settings.EMAIL_USER == "sender@server.de"
162 | assert settings.EMAIL_PASSWORD == "xxxx"
163 | assert settings.EMAIL_SERVER == "mail.server.de"
164 | assert settings.EMAIL_PORT == 465
165 | assert settings.EMAIL_SENDER == "sender@server.de"
166 | assert settings.EMAIL_RECEIVERS == [
167 | "sender@server.de", "guenni@server.de", "frida@server.de"]
168 |
169 | # TELEGRAM
170 | assert settings.TELEGRAM_ENABLE is True
171 | assert settings.TELEGRAM_TOKEN == "123456789:alphanumeric_characters"
172 | assert settings.TELEGRAM_CHAT_IDS == ["123456789", "987654321"]
173 |
174 | # WEBBROWSER
175 | assert settings.WEBBROWSER_ENABLE is True
176 |
177 | # ADVANCED
178 | assert settings.CUSTOM_MESSAGE_PREFIX == "Impfbot"
179 | assert settings.COOLDOWN_BETWEEN_REQUESTS == 1
180 | assert settings.COOLDOWN_BETWEEN_FAILED_REQUESTS == 2
181 | assert settings.COOLDOWN_AFTER_IP_BAN == 3*60
182 | assert settings.COOLDOWN_AFTER_SUCCESS == 4*60
183 | assert settings.JITTER == 5
184 | assert settings.SLEEP_AT_NIGHT is False
185 | assert settings.USER_AGENT == "impfbot"
186 |
187 |
188 | @ mock.patch('logging.Logger.error')
189 | @ mock.patch('logging.Logger.warning')
190 | @ mock.patch('logging.Logger.info')
191 | def test_missing_optional(log_info_mock,
192 | log_warning_mock,
193 | log_error_mock):
194 | load("tests/configs/test-config-optional-missing.ini")
195 |
196 | # Check output
197 | assert log_info_mock.call_count == 4
198 | assert log_warning_mock.call_count == 9
199 | log_error_mock.assert_not_called()
200 |
201 | # EMAIL
202 | assert settings.EMAIL_ENABLE is False
203 | # TELEGRAM
204 | assert settings.TELEGRAM_ENABLE is False
205 | # WEBBROWSER
206 | assert settings.WEBBROWSER_ENABLE is False
207 | # ADVANCED
208 | assert settings.CUSTOM_MESSAGE_PREFIX == "Impfbot"
209 | assert settings.COOLDOWN_BETWEEN_REQUESTS == 30
210 | assert settings.COOLDOWN_BETWEEN_FAILED_REQUESTS == 5
211 | assert settings.COOLDOWN_AFTER_IP_BAN == 3*60*60
212 | assert settings.COOLDOWN_AFTER_SUCCESS == 15*60
213 | assert settings.JITTER == 10
214 | assert settings.SLEEP_AT_NIGHT is True
215 | assert settings.USER_AGENT == "impfbot"
216 |
217 |
218 | @ mock.patch('logging.Logger.error')
219 | @ mock.patch('logging.Logger.warning')
220 | @ mock.patch('logging.Logger.info')
221 | def test_missing_all(log_info_mock,
222 | log_warning_mock,
223 | log_error_mock):
224 | with pytest.raises(ParseExeption):
225 | load("tests/configs/test-invalid-file.ini")
226 |
227 |
228 | @ mock.patch('logging.Logger.error')
229 | @ mock.patch('logging.Logger.warning')
230 | @ mock.patch('logging.Logger.info')
231 | def test_invalid_file(log_info_mock,
232 | log_warning_mock,
233 | log_error_mock):
234 | with pytest.raises(FileNotFoundError):
235 | load("no file 4 u")
236 |
--------------------------------------------------------------------------------
/version.txt:
--------------------------------------------------------------------------------
1 | 3.4.0
2 |
--------------------------------------------------------------------------------
/windows_start.bat:
--------------------------------------------------------------------------------
1 | py -3 -m pip install -q -r requirements.txt
2 | py -3 src/impfbot.py --config config.ini
--------------------------------------------------------------------------------
/windows_validate.bat:
--------------------------------------------------------------------------------
1 | py -3 -m pip install -q -r requirements.txt
2 | py -3 src/validate_config.py --config config.ini
--------------------------------------------------------------------------------