├── .github └── workflows │ └── docker-publish.yaml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── VERSION ├── docker-compose.yaml ├── requirements.txt └── src ├── app.py ├── block_allow_lists └── __init__.py ├── blocked_services └── __init__.py ├── common.py ├── custom_rules └── __init__.py ├── entries └── __init__.py ├── exceptions.py └── settings ├── dns.py ├── encryption.py └── general.py /.github/workflows/docker-publish.yaml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | env: 9 | IMAGE_NAME: atoy3731/adguard-sync 10 | 11 | jobs: 12 | push: 13 | runs-on: ubuntu-latest 14 | if: github.event_name == 'push' 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | 19 | - name: Set up QEMU 20 | uses: docker/setup-qemu-action@master 21 | with: 22 | platforms: all 23 | 24 | - name: Set up Docker Buildx 25 | id: buildx 26 | uses: docker/setup-buildx-action@master 27 | 28 | # Login: Log into Docker Hub using Github secrets. 29 | - name: Log into Docker 30 | env: 31 | DOCKER_USER: ${{ secrets.DOCKER_USER }} 32 | DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} 33 | run: | 34 | echo "$DOCKER_PASSWORD" | docker login -u $DOCKER_USER --password-stdin 35 | 36 | - name: Prepare 37 | id: prep 38 | run: | 39 | VERSION=$(cat VERSION) 40 | 41 | TAGS="${IMAGE_NAME}:${VERSION},${IMAGE_NAME}:latest" 42 | 43 | # Set output parameters. 44 | echo ::set-output name=tags::${TAGS} 45 | echo ::set-output name=docker_image::${DOCKER_IMAGE} 46 | 47 | - name: Build 48 | uses: docker/build-push-action@v2 49 | with: 50 | builder: ${{ steps.buildx.outputs.name }} 51 | context: . 52 | file: ./Dockerfile 53 | platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7 54 | push: true 55 | tags: ${{ steps.prep.outputs.tags }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | venv/ 2 | *.pyc 3 | .idea/ 4 | *.iml 5 | .venv/ 6 | .vscode/ 7 | .env 8 | __pycache__ 9 | 10 | .DS_Store 11 | .AppleDouble 12 | .LSOverride -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.13 2 | 3 | ENV PYTHONUNBUFFERED=1 4 | 5 | RUN apk update && \ 6 | apk add python3 curl && \ 7 | curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | python3 && \ 8 | apk del curl 9 | 10 | COPY requirements.txt /tmp/requirements.txt 11 | 12 | RUN pip3 install -r /tmp/requirements.txt && \ 13 | rm -f /tmp/requirements.txt 14 | 15 | COPY src /opt/app 16 | 17 | WORKDIR /opt/app 18 | 19 | ENTRYPOINT ["python3"] 20 | CMD ["app.py"] 21 | 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Adam Toy 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AdGuard Sync 2 | 3 | ![Docker](https://github.com/atoy3731/adguard-sync/workflows/Docker/badge.svg) 4 | 5 | 6 | This project will sync entries between a Primary and Secondary AdGuard Home instance using the API. 7 | 8 | This is useful if you're dependent on local DNS and want to ensure relative High Availability. 9 | 10 | ### How to Run 11 | 12 | AdGuard Sync is packaged as a Docker image and can be ran anywhere with access to your instances, though it is advisable to run this on the same instance that is running your Primary Adguard instance. This makes your primary instance the "source of truth" for local DNS, but allows your secondary instance to stay in sync as a fallback. Once running, set your router DNS to point to both your primary and secondary. You can update the `docker-compose.yaml` file with your values based on the following: 13 | 14 | | Variable | Required | Description | Default | 15 | |---|---|---|---| 16 | | ADGUARD_PRIMARY | Yes | Primary base URL for the primary AdGuard instance. It is highly advisable to use IP over hostnames to avoid DNS issues. (ie. http://192.168.1.2) | N/A | 17 | | ADGUARD_SECONDARY | Yes | Secondary base URL for the primary AdGuard instance It is highly advisable to use IP over hostnames to avoid DNS issues. (ie. http://192.168.1.3) | N/A | 18 | | ADGUARD_USER | Yes | Username to log into your AdGuard instances. | N/A | 19 | | ADGUARD_PASS | Yes | Password to log into your AdGuard instances. | N/A | 20 | | SECONDARY_ADGUARD_USER | No | Username to log into your secondary AdGuard instance. Only necessary if credentials are different between primary and secondary | Value of 'ADGUARD_USER' | 21 | | SECONDARY_ADGUARD_PASS | No | Password to log into your secondary AdGuard instance. Only necessary if credentials are different between primary and secondary | Value of 'ADGUARD_PASS' | 22 | | REFRESH_INTERVAL_SECS | No | Frequency in seconds to refresh entries. | 60 | 23 | | SYNC_ENTRIES | No | If 'true', will sync rewrite entries. | true | 24 | | SYNC_BLOCKED_SERVICES | No | If 'true', will sync blocked services. | true | 25 | | SYNC_BLOCK_ALLOW_LISTS | No | If 'true', will sync block/allow lists. | true | 26 | | SYNC_CUSTOM_RULES | No | If 'true', will sync custom rules. | true | 27 | | SYNC_GENERAL_SETTINGS | No | If 'true', will sync general settings. | true | 28 | | SYNC_DNS_SETTINGS | No | If 'true', will sync DNS settings. | true | 29 | | SYNC_ENCRYPTION_SETTINGS | No | If 'true', will sync encrypt settings. | false | 30 | 31 | Once you've updated the file and ensure you have `docker` and `docker-compose` installed, run the following in the root directory: 32 | 33 | ```bash 34 | docker-compose up -d 35 | ``` 36 | 37 | You can check on the status of your newly running pod with: 38 | 39 | ```bash 40 | docker-compose logs 41 | ``` 42 | 43 | If you'd prefer to utilize Docker without docker-compose, you can use the following command (substituting your values and adding any necessary environment variables): 44 | 45 | ```bash 46 | docker run -d --name adguard-sync --restart=always \ 47 | -e "ADGUARD_PRIMARY=http://192.168.1.2" \ 48 | -e "ADGUARD_SECONDARY=http://192.168.1.3" \ 49 | -e "ADGUARD_USER=admin" \ 50 | -e "ADGUARD_PASS=password" \ 51 | atoy3731/adguard-sync:2.1 52 | ``` 53 | 54 | **NOTE:** The container is set to automatically restart when the docker daemon restarts. 55 | 56 | ### Encryption Syncing with Certifications/Keys 57 | 58 | If you plan to sync encryption settings across environments and you're using paths for certificates/keys, you *must make sure the files exist in both primary and secondary AdGuard instances*! Given this, `SYNC_ENCRYPTION_SETTINGS` is defaulted to `false` as a safety measure. 59 | 60 | ### Known Issues 61 | 62 | #### Permission Error Running on Raspbian 63 | 64 | When running on older versions of Raspbian, you may run into permission issues and see errors like the following in your logs: 65 | ``` 66 | Fatal Python error: pyinit_main: can't initialize time 67 | Python runtime state: core initialized 68 | PermissionError: [Errno 1] Operation not permitted 69 | ``` 70 | 71 | For this, you'll need to update to a newer version of `libseccomp2`: 72 | ``` 73 | wget http://ftp.us.debian.org/debian/pool/main/libs/libseccomp/libseccomp2_2.5.1-1_armhf.deb 74 | sudo dpkg -i libseccomp2_2.5.1-1_armhf.deb 75 | ``` -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 2.3 -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | adguard-sync: 5 | image: atoy3731/adguard-sync:latest 6 | container_name: adguard-sync 7 | 8 | restart: always 9 | environment: 10 | # Required variables 11 | - ADGUARD_PRIMARY=http://dns01.example.com 12 | - ADGUARD_SECONDARY=http://dns02.example.com 13 | - ADGUARD_USER=admin 14 | - ADGUARD_PASS=password 15 | 16 | # Optional variables 17 | # - SECONDARY_ADGUARD_USER=other_admin 18 | # - SECONDARY_ADGUARD_PASS=other_password 19 | # - REFRESH_INTERVAL_SECS=10 20 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests -------------------------------------------------------------------------------- /src/app.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | import json 4 | import time 5 | import entries 6 | import blocked_services 7 | import block_allow_lists 8 | import custom_rules 9 | from exceptions import UnauthenticatedError, SystemError 10 | from settings import general, dns, encryption 11 | import common 12 | 13 | ADGUARD_PRIMARY = os.environ['ADGUARD_PRIMARY'] 14 | ADGUARD_SECONDARY = os.environ['ADGUARD_SECONDARY'] 15 | 16 | ADGUARD_USER = os.environ['ADGUARD_USER'] 17 | ADGUARD_PASS = os.environ['ADGUARD_PASS'] 18 | 19 | # Optional, use if your secondary AdGuard has different credentials 20 | SECONDARY_ADGUARD_USER = os.environ.get('SECONDARY_ADGUARD_USER', ADGUARD_USER) 21 | SECONDARY_ADGUARD_PASS = os.environ.get('SECONDARY_ADGUARD_PASS', ADGUARD_PASS) 22 | 23 | # By default, sync all 24 | SYNC_ENTRIES = os.environ.get('SYNC_ENTRIES', 'true').lower() == 'true' 25 | SYNC_BLOCKED_SERVICES = os.environ.get('SYNC_BLOCKED_SERVICES', 'true').lower() == 'true' 26 | SYNC_BLOCK_ALLOW_LISTS = os.environ.get('SYNC_BLOCK_ALLOW_LISTS', 'true').lower() == 'true' 27 | SYNC_CUSTOM_RULES = os.environ.get('SYNC_CUSTOM_RULES', 'true').lower() == 'true' 28 | SYNC_GENERAL_SETTINGS = os.environ.get('SYNC_GENERAL_SETTINGS', 'true').lower() == 'true' 29 | SYNC_DNS_SETTINGS = os.environ.get('SYNC_DNS_SETTINGS', 'true').lower() == 'true' 30 | SYNC_ENCRYPTION_SETTINGS = os.environ.get('SYNC_ENCRYPTION_SETTINGS', 'false').lower() == 'true' 31 | 32 | REFRESH_INTERVAL_SECS = int(os.environ.get('REFRESH_INTERVAL_SECS', '60')) 33 | 34 | 35 | def get_login_cookie(url, user, passwd): 36 | """ 37 | Logs into AdGuard URL using username/password and returns a valid session cookie. 38 | :param url: Base URL of AdGuard 39 | :param user: Username of AdGuard 40 | :param passwd: Password of AdGuard 41 | :return: Session token 42 | """ 43 | 44 | creds = { 45 | 'name': user, 46 | 'password': passwd 47 | } 48 | 49 | response = requests.post('{}/control/login'.format(url), data=json.dumps(creds), headers=common.REQUEST_HEADERS) 50 | 51 | if response.status_code != 200: 52 | print('ERROR: Unable to acquire cookie.') 53 | print('Message: {}'.format(response.text)) 54 | return None 55 | 56 | return response.cookies['agh_session'] 57 | 58 | 59 | if __name__ == '__main__': 60 | print("Running Adguard Sync for '{}' => '{}'..".format(ADGUARD_PRIMARY, ADGUARD_SECONDARY)) 61 | 62 | # Get initial login cookie 63 | primary_cookie = get_login_cookie(ADGUARD_PRIMARY, ADGUARD_USER, ADGUARD_PASS) 64 | secondary_cookie = get_login_cookie(ADGUARD_SECONDARY, SECONDARY_ADGUARD_USER, SECONDARY_ADGUARD_PASS) 65 | 66 | if primary_cookie is None or secondary_cookie is None: 67 | exit(1) 68 | 69 | while True: 70 | try: 71 | # Since a bunch of things use filtering status, only retrieve it once per loop to reduce API calls 72 | primary_filtering_status = common.get_response('{}/control/filtering/status'.format(ADGUARD_PRIMARY), primary_cookie) 73 | secondary_filtering_status = common.get_response('{}/control/filtering/status'.format(ADGUARD_SECONDARY), secondary_cookie) 74 | 75 | # Reconcile entries 76 | if SYNC_ENTRIES: 77 | entries.reconcile(ADGUARD_PRIMARY, ADGUARD_SECONDARY, primary_cookie, secondary_cookie) 78 | 79 | # Reconcile blocked services 80 | if SYNC_BLOCKED_SERVICES: 81 | blocked_services.reconcile(ADGUARD_PRIMARY, ADGUARD_SECONDARY, primary_cookie, secondary_cookie) 82 | 83 | # Reconcile block/allow lists 84 | if SYNC_BLOCK_ALLOW_LISTS: 85 | block_allow_lists.reconcile(primary_filtering_status, secondary_filtering_status, ADGUARD_SECONDARY, secondary_cookie) 86 | 87 | # Reconcile custom rules 88 | if SYNC_CUSTOM_RULES: 89 | custom_rules.reconcile(primary_filtering_status, secondary_filtering_status, ADGUARD_SECONDARY, secondary_cookie) 90 | 91 | # Reconcile general settings 92 | if SYNC_GENERAL_SETTINGS: 93 | general.reconcile(primary_filtering_status, secondary_filtering_status, ADGUARD_PRIMARY, primary_cookie, ADGUARD_SECONDARY, secondary_cookie) 94 | 95 | # Reconcile DNS settings 96 | if SYNC_DNS_SETTINGS: 97 | dns.reconcile(ADGUARD_PRIMARY, primary_cookie, ADGUARD_SECONDARY, secondary_cookie) 98 | 99 | # Reconcile encrypting settings 100 | if SYNC_ENCRYPTION_SETTINGS: 101 | encryption.reconcile(ADGUARD_PRIMARY, primary_cookie, ADGUARD_SECONDARY, secondary_cookie) 102 | 103 | except UnauthenticatedError: 104 | primary_cookie = get_login_cookie(ADGUARD_PRIMARY, ADGUARD_USER, ADGUARD_PASS) 105 | secondary_cookie = get_login_cookie(ADGUARD_SECONDARY, SECONDARY_ADGUARD_USER, SECONDARY_ADGUARD_PASS) 106 | 107 | if primary_cookie is None or secondary_cookie is None: 108 | exit(1) 109 | 110 | except SystemError: 111 | print('ERROR: Not able to reach AdGuard. Is it running?') 112 | 113 | time.sleep(REFRESH_INTERVAL_SECS) 114 | -------------------------------------------------------------------------------- /src/block_allow_lists/__init__.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | from exceptions import UnauthenticatedError, SystemError 4 | import common 5 | 6 | 7 | def _get_block_allow_lists(filtering_status): 8 | """ 9 | Retrieves all existing blocklists from AdGuard. 10 | :param url: Base AdGuard URL 11 | :param cookie: Session token 12 | :return: List of Entries 13 | """ 14 | formatted_block_allow_lists = { 15 | 'blocklists': {}, 16 | 'allowlists': {} 17 | } 18 | 19 | blocklist_array = filtering_status['filters'] 20 | 21 | if blocklist_array is not None: 22 | for blocklist in blocklist_array: 23 | formatted_block_allow_lists['blocklists'][blocklist['url']] = { 24 | 'id': blocklist['id'], 25 | 'name': blocklist['name'], 26 | 'url': blocklist['url'], 27 | 'enabled': blocklist['enabled'] 28 | } 29 | 30 | allowlist_array = filtering_status['whitelist_filters'] 31 | 32 | if allowlist_array is not None: 33 | for allowlist in allowlist_array: 34 | formatted_block_allow_lists['allowlists'][allowlist['url']] = { 35 | 'id': allowlist['id'], 36 | 'name': allowlist['name'], 37 | 'url': allowlist['url'], 38 | 'enabled': allowlist['enabled'] 39 | } 40 | 41 | return formatted_block_allow_lists 42 | 43 | 44 | def _update_block_allow_lists(url, cookie, sync_block_allow_lists): 45 | """ 46 | Update blocked services from your primary to secondary AdGuard. 47 | :param url: URL of the Secondary AdGuard 48 | :param cookie: Secondary AdGuard Auth Cookie. 49 | :param sync_blocked_services: Array of entries to be sync. 50 | :return: None 51 | """ 52 | 53 | cookies = { 54 | 'agh_session': cookie 55 | } 56 | 57 | # Perform deletes first to avoid any conflicts since URLs cannot exist in both. 58 | for del_allowlist in sync_block_allow_lists['allowlists']['del']: 59 | print(" - Deleting allowlist entry ({})".format(del_allowlist['url'])) 60 | data = { 61 | 'url': del_allowlist['url'], 62 | 'whitelist': True 63 | } 64 | response = requests.post('{}/control/filtering/remove_url'.format(url), cookies=cookies, data=json.dumps(data), headers=common.REQUEST_HEADERS) 65 | 66 | if response.status_code == 403: 67 | raise UnauthenticatedError 68 | elif response.status_code != 200: 69 | raise SystemError 70 | 71 | for del_blocklist in sync_block_allow_lists['blocklists']['del']: 72 | print(" - Deleting blocklist entry ({})".format(del_blocklist['url'])) 73 | data = { 74 | 'url': del_blocklist['url'], 75 | 'whitelist': False 76 | } 77 | response = requests.post('{}/control/filtering/remove_url'.format(url), cookies=cookies, data=json.dumps(data), headers=common.REQUEST_HEADERS) 78 | 79 | if response.status_code == 403: 80 | raise UnauthenticatedError 81 | elif response.status_code != 200: 82 | raise SystemError 83 | 84 | # Perform adds second 85 | for add_allowlist in sync_block_allow_lists['allowlists']['add']: 86 | print(" - Adding allowlist entry ({})".format(add_allowlist['url'])) 87 | data = { 88 | 'name': add_allowlist['name'], 89 | 'url': add_allowlist['url'], 90 | 'whitelist': True 91 | } 92 | response = requests.post('{}/control/filtering/add_url'.format(url), cookies=cookies, data=json.dumps(data), headers=common.REQUEST_HEADERS) 93 | 94 | if response.status_code == 403: 95 | raise UnauthenticatedError 96 | elif response.status_code != 200: 97 | raise SystemError 98 | 99 | for add_blocklist in sync_block_allow_lists['blocklists']['add']: 100 | print(" - Adding blocklist entry ({})".format(add_blocklist['url'])) 101 | data = { 102 | 'name': add_blocklist['name'], 103 | 'url': add_blocklist['url'], 104 | 'whitelist': False 105 | } 106 | response = requests.post('{}/control/filtering/add_url'.format(url), cookies=cookies, data=json.dumps(data), headers=common.REQUEST_HEADERS) 107 | 108 | if response.status_code == 403: 109 | raise UnauthenticatedError 110 | elif response.status_code != 200: 111 | raise SystemError 112 | 113 | # Modify any existing out of sync entry 114 | for mod in sync_block_allow_lists['mods']: 115 | data = { 116 | 'url': mod['url'], 117 | 'data': { 118 | 'name': mod['name'], 119 | 'url': mod['url'], 120 | 'enabled': mod['enabled'] 121 | }, 122 | 'whitelist': mod['allowlist'] 123 | } 124 | 125 | print(" - Updating modified entry ({})".format(mod['url'])) 126 | response = requests.post('{}/control/filtering/set_url'.format(url), cookies=cookies, data=json.dumps(data), headers=common.REQUEST_HEADERS) 127 | 128 | if response.status_code == 403: 129 | raise UnauthenticatedError 130 | elif response.status_code != 200: 131 | raise SystemError 132 | 133 | 134 | def reconcile(primary_filtering_status, secondary_filtering_status, adguard_secondary, secondary_cookie): 135 | """ 136 | Reconcile blocklists from primary to secondary Adguards. 137 | Uses the URL as the unique identifier between instances. 138 | :param adguard_primary: URL of primary Adguard. 139 | :param adguard_secondary: URL of secondardy Adguard. 140 | :param primary_cookie: Auth cookie for primary Adguard. 141 | :param secondary_cookie: Auth cookie for secondary Adguard. 142 | """ 143 | primary_block_allow_lists = _get_block_allow_lists(primary_filtering_status) 144 | secondary_block_allow_lists = _get_block_allow_lists(secondary_filtering_status) 145 | 146 | sync_block_allow_lists = { 147 | 'blocklists': { 148 | 'add': [], 149 | 'del': [] 150 | }, 151 | 'allowlists': { 152 | 'add': [], 153 | 'del': [] 154 | }, 155 | 'mods': [] 156 | } 157 | 158 | 159 | for k,v in primary_block_allow_lists['blocklists'].items(): 160 | if k not in secondary_block_allow_lists['blocklists']: 161 | sync_block_allow_lists['blocklists']['add'].append({ 162 | 'url': v['url'], 163 | 'name': v['name'], 164 | 'enabled': v['enabled'] 165 | }) 166 | else: 167 | if primary_block_allow_lists['blocklists'][k]['enabled'] != secondary_block_allow_lists['blocklists'][k]['enabled'] or primary_block_allow_lists['blocklists'][k]['name'] != secondary_block_allow_lists['blocklists'][k]['name']: 168 | sync_block_allow_lists['mods'].append({ 169 | 'enabled': primary_block_allow_lists['blocklists'][k]['enabled'], 170 | 'name': primary_block_allow_lists['blocklists'][k]['name'], 171 | 'url': k, 172 | 'allowlist': False 173 | }) 174 | 175 | for k,v in secondary_block_allow_lists['blocklists'].items(): 176 | if k not in primary_block_allow_lists['blocklists']: 177 | sync_block_allow_lists['blocklists']['del'].append({ 178 | 'url': v['url'] 179 | }) 180 | 181 | for k,v in primary_block_allow_lists['allowlists'].items(): 182 | if k not in secondary_block_allow_lists['allowlists']: 183 | sync_block_allow_lists['allowlists']['add'].append({ 184 | 'url': v['url'], 185 | 'name': v['name'], 186 | 'enabled': v['enabled'] 187 | }) 188 | else: 189 | if primary_block_allow_lists['allowlists'][k]['enabled'] != secondary_block_allow_lists['allowlists'][k]['enabled'] or primary_block_allow_lists['allowlists'][k]['name'] != secondary_block_allow_lists['allowlists'][k]['name']: 190 | sync_block_allow_lists['mods'].append({ 191 | 'enabled': primary_block_allow_lists['allowlists'][k]['enabled'], 192 | 'name': primary_block_allow_lists['allowlists'][k]['name'], 193 | 'url': k, 194 | 'allowlist': True 195 | }) 196 | 197 | for k,v in secondary_block_allow_lists['allowlists'].items(): 198 | if k not in primary_block_allow_lists['allowlists']: 199 | sync_block_allow_lists['allowlists']['del'].append({ 200 | 'url': v['url'] 201 | }) 202 | 203 | _update_block_allow_lists(adguard_secondary, secondary_cookie, sync_block_allow_lists) -------------------------------------------------------------------------------- /src/blocked_services/__init__.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import common 4 | from exceptions import UnauthenticatedError, SystemError 5 | 6 | 7 | def _get_blocked_services(url, cookie): 8 | """ 9 | Retrieves all existing blocked services from AdGuard. 10 | :param url: Base AdGuard URL 11 | :param cookie: Session token 12 | :return: List of Entries 13 | """ 14 | 15 | return common.get_response('{}/control/blocked_services/list'.format(url), cookie) 16 | 17 | 18 | def _update_blocked_services(url, cookie, sync_blocked_services): 19 | """ 20 | Update blocked services from your primary to secondary AdGuard. 21 | :param url: URL of the Secondary AdGuard 22 | :param cookie: Secondary AdGuard Auth Cookie. 23 | :param sync_blocked_services: Array of entries to be sync. 24 | :return: None 25 | """ 26 | 27 | cookies = { 28 | 'agh_session': cookie 29 | } 30 | 31 | print(" - Syncing blocked services") 32 | response = requests.post('{}/control/blocked_services/set'.format(url), cookies=cookies, data=json.dumps(sync_blocked_services), headers=common.REQUEST_HEADERS) 33 | 34 | if response.status_code == 403: 35 | raise UnauthenticatedError 36 | elif response.status_code != 200: 37 | raise SystemError 38 | 39 | 40 | def reconcile(adguard_primary, adguard_secondary, primary_cookie, secondary_cookie): 41 | """ 42 | Reconcile blocked services from primary to secondary Adguards. 43 | :param adguard_primary: URL of primary Adguard. 44 | :param adguard_secondary: URL of secondardy Adguard. 45 | :param primary_cookie: Auth cookie for primary Adguard. 46 | :param secondary_cookie: Auth cookie for secondary Adguard. 47 | """ 48 | primary_blocked_services = _get_blocked_services(adguard_primary, primary_cookie) 49 | secondary_blocked_services = _get_blocked_services(adguard_secondary, secondary_cookie) 50 | 51 | for bs in primary_blocked_services: 52 | if bs not in secondary_blocked_services: 53 | _update_blocked_services(adguard_secondary, secondary_cookie, primary_blocked_services) 54 | break 55 | 56 | for bs in secondary_blocked_services: 57 | if bs not in primary_blocked_services: 58 | _update_blocked_services(adguard_secondary, secondary_cookie, primary_blocked_services) 59 | break 60 | -------------------------------------------------------------------------------- /src/common.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | import json 4 | import time 5 | from exceptions import UnauthenticatedError, SystemError 6 | 7 | REQUEST_HEADERS = {'Content-Type': 'application/json'} 8 | 9 | def get_response(url, cookie): 10 | """ 11 | Helper function to handle errors and keep it DRY 12 | """ 13 | cookies = { 14 | 'agh_session': cookie 15 | } 16 | 17 | response = requests.get(url, cookies=cookies) 18 | 19 | if response.status_code == 403: 20 | raise UnauthenticatedError 21 | elif response.status_code != 200: 22 | raise SystemError 23 | 24 | return json.loads(response.text) 25 | 26 | 27 | def update_settings(setting, primary_settings, secondary_settings, url, cookie): 28 | """ 29 | Update main DNS settings on secondary AdGuard if necessary 30 | :param setting: Name of the setting to change. 31 | :param primary_settings: Primary settings for primary AdGuard. 32 | :param secondary_settings: Secondary settings for secondary AdGuard. 33 | :param url: Base URL for updating settings. 34 | :param cookie: Auth cookie. 35 | """ 36 | cookies = { 37 | 'agh_session': cookie 38 | } 39 | 40 | if primary_settings != secondary_settings: 41 | print(" - Updating {} settings".format(setting)) 42 | response = requests.post(url, cookies=cookies, data=json.dumps(primary_settings), headers=REQUEST_HEADERS) 43 | 44 | if response.status_code == 403: 45 | raise UnauthenticatedError 46 | elif response.status_code != 200: 47 | raise SystemError -------------------------------------------------------------------------------- /src/custom_rules/__init__.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | import json 4 | import time 5 | import common 6 | from exceptions import UnauthenticatedError, SystemError 7 | 8 | 9 | def _get_custom_rules(filtering_status): 10 | """ 11 | Retrieves all existing blocked services from AdGuard. 12 | :param url: Base AdGuard URL 13 | :param cookie: Session token 14 | :return: List of Entries 15 | """ 16 | 17 | custom_rules_array = filtering_status['user_rules'] 18 | custom_rules_str = '\n'.join(custom_rules_array) 19 | 20 | return { 21 | 'array': custom_rules_array, 22 | 'string': custom_rules_str 23 | } 24 | 25 | 26 | def _update_custom_rules(url, cookie, custom_rules): 27 | """ 28 | Update blocked services from your primary to secondary AdGuard. 29 | :param url: URL of the Secondary AdGuard 30 | :param cookie: Secondary AdGuard Auth Cookie. 31 | :param sync_blocked_services: Array of entries to be sync. 32 | :return: None 33 | """ 34 | 35 | cookies = { 36 | 'agh_session': cookie 37 | } 38 | 39 | body = { 40 | 'rules': custom_rules 41 | } 42 | 43 | print(" - Syncing custom rules") 44 | response = requests.post('{}/control/filtering/set_rules'.format(url), headers=common.REQUEST_HEADERS, cookies=cookies, data=json.dumps(body)) 45 | 46 | if response.status_code == 403: 47 | raise UnauthenticatedError 48 | elif response.status_code != 200: 49 | raise SystemError 50 | 51 | 52 | def reconcile(primary_filtering_status, secondary_filtering_status, adguard_secondary, secondary_cookie): 53 | """ 54 | Reconcile blocked services from primary to secondary Adguards. 55 | :param adguard_primary: URL of primary Adguard. 56 | :param adguard_secondary: URL of secondardy Adguard. 57 | :param primary_cookie: Auth cookie for primary Adguard. 58 | :param secondary_cookie: Auth cookie for secondary Adguard. 59 | """ 60 | primary_custom_rules = _get_custom_rules(primary_filtering_status) 61 | secondary_custom_rules = _get_custom_rules(secondary_filtering_status) 62 | 63 | if primary_custom_rules['string'] != secondary_custom_rules['string']: 64 | _update_custom_rules(adguard_secondary, secondary_cookie, primary_custom_rules['array']) -------------------------------------------------------------------------------- /src/entries/__init__.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import common 4 | from exceptions import UnauthenticatedError, SystemError 5 | 6 | 7 | def _get_entries(url, cookie): 8 | """ 9 | Retrieves all existing entries from AdGuard. 10 | :param url: Base AdGuard URL 11 | :param cookie: Session token 12 | :return: List of Entries 13 | """ 14 | 15 | return common.get_response('{}/control/rewrite/list'.format(url), cookie) 16 | 17 | 18 | def _update_entries(url, cookie, sync_entries): 19 | """ 20 | Update entries from your primary to secondary AdGuard. 21 | 22 | ADD: Will add the entry with the domain pointing to IP. 23 | UPDATE: Will update existing entry to point the domain to the new IP. 24 | DEL: Will delete the existing entry from secondary AdGuard. 25 | :param url: URL of the Secondary AdGuard 26 | :param cookie: Secondary AdGuard Auth Cookie. 27 | :param sync_entries: Array of entries to be sync. 28 | :return: None 29 | """ 30 | 31 | cookies = { 32 | 'agh_session': cookie 33 | } 34 | 35 | for entry in sync_entries: 36 | if entry['action'] == 'ADD': 37 | print(" - Adding entry ({} => {})".format(entry['domain'], entry['answer'])) 38 | data = { 39 | 'domain': entry['domain'], 40 | 'answer': entry['answer'] 41 | } 42 | response = requests.post('{}/control/rewrite/add'.format(url), cookies=cookies, data=json.dumps(data), headers=common.REQUEST_HEADERS) 43 | if response.status_code == 403: 44 | raise UnauthenticatedError 45 | elif response.status_code != 200: 46 | raise SystemError 47 | 48 | elif entry['action'] == 'DEL': 49 | print(" - Deleting entry ({} => {})".format(entry['domain'], entry['answer'])) 50 | data = { 51 | 'domain': entry['domain'], 52 | 'answer': entry['answer'] 53 | } 54 | response = requests.post('{}/control/rewrite/delete'.format(url), cookies=cookies, data=json.dumps(data), headers=common.REQUEST_HEADERS) 55 | if response.status_code == 403: 56 | raise UnauthenticatedError 57 | elif response.status_code != 200: 58 | raise SystemError 59 | 60 | def reconcile(adguard_primary, adguard_secondary, primary_cookie, secondary_cookie): 61 | primary_entries = _get_entries(adguard_primary, primary_cookie) 62 | secondary_entries = _get_entries(adguard_secondary, secondary_cookie) 63 | 64 | sync_entries = [] 65 | 66 | for e in primary_entries: 67 | if e not in secondary_entries: 68 | sync_entries.append({ 69 | 'action': 'ADD', 70 | 'domain': e['domain'], 71 | 'answer': e['answer'] 72 | }) 73 | 74 | for s in secondary_entries: 75 | if s not in primary_entries: 76 | sync_entries.append({ 77 | 'action': 'DEL', 78 | 'domain': s['domain'], 79 | 'answer': s['answer'] 80 | }) 81 | 82 | _update_entries(adguard_secondary, secondary_cookie, sync_entries) -------------------------------------------------------------------------------- /src/exceptions.py: -------------------------------------------------------------------------------- 1 | class UnauthenticatedError(Exception): 2 | pass 3 | 4 | class SystemError(Exception): 5 | pass -------------------------------------------------------------------------------- /src/settings/dns.py: -------------------------------------------------------------------------------- 1 | import common 2 | 3 | def _get_dns_settings(url, cookie): 4 | """ 5 | Retrieves all existing blocked services from AdGuard. 6 | :param url: Base AdGuard URL 7 | :param cookie: Session token 8 | :return: List of Entries 9 | """ 10 | 11 | settings = { 12 | 'upstream': {}, 13 | 'server': {}, 14 | 'cache': {}, 15 | 'access': {} 16 | } 17 | 18 | # Retrieve DNS/cache setting 19 | response = common.get_response('{}/control/dns_info'.format(url), cookie) 20 | settings['upstream']['upstream_dns'] = response['upstream_dns'] 21 | settings['upstream']['bootstrap_dns'] = response['bootstrap_dns'] 22 | settings['upstream']['local_ptr_upstreams'] = response['local_ptr_upstreams'] 23 | settings['upstream']['resolve_clients'] = response['resolve_clients'] 24 | settings['upstream']['upstream_mode'] = response['upstream_mode'] 25 | 26 | settings['server']['blocking_ipv4'] = response['blocking_ipv4'] 27 | settings['server']['blocking_ipv6'] = response['blocking_ipv6'] 28 | settings['server']['blocking_mode'] = response['blocking_mode'] 29 | settings['server']['disable_ipv6'] = response['disable_ipv6'] 30 | settings['server']['dnssec_enabled'] = response['dnssec_enabled'] 31 | settings['server']['edns_cs_enabled'] = response['edns_cs_enabled'] 32 | settings['server']['ratelimit'] = response['ratelimit'] 33 | 34 | settings['cache']['cache_size'] =response['cache_size'] 35 | settings['cache']['cache_ttl_max'] = response['cache_ttl_max'] 36 | settings['cache']['cache_ttl_min'] = response['cache_ttl_min'] 37 | 38 | # Retrieve safesearch setting 39 | response = common.get_response('{}/control/access/list'.format(url), cookie) 40 | settings['access'] = response 41 | 42 | return settings 43 | 44 | 45 | def reconcile(adguard_primary, primary_cookie, adguard_secondary, secondary_cookie): 46 | """ 47 | Reconcile blocked services from primary to secondary Adguards. 48 | :param adguard_primary: URL of primary Adguard. 49 | :param adguard_secondary: URL of secondardy Adguard. 50 | :param primary_cookie: Auth cookie for primary Adguard. 51 | :param secondary_cookie: Auth cookie for secondary Adguard. 52 | """ 53 | primary_dns_settings = _get_dns_settings(adguard_primary, primary_cookie) 54 | secondary_dns_settings = _get_dns_settings(adguard_secondary, secondary_cookie) 55 | 56 | common.update_settings('DNS upstream', primary_dns_settings['upstream'], secondary_dns_settings['upstream'], '{}/control/dns_config'.format(adguard_secondary), secondary_cookie) 57 | common.update_settings('DNS server', primary_dns_settings['server'], secondary_dns_settings['server'], '{}/control/dns_config'.format(adguard_secondary), secondary_cookie) 58 | common.update_settings('DNS cache', primary_dns_settings['cache'], secondary_dns_settings['cache'], '{}/control/dns_config'.format(adguard_secondary), secondary_cookie) 59 | common.update_settings('access', primary_dns_settings['access'], secondary_dns_settings['access'], '{}/control/access/set'.format(adguard_secondary), secondary_cookie) -------------------------------------------------------------------------------- /src/settings/encryption.py: -------------------------------------------------------------------------------- 1 | import common 2 | 3 | def _get_encryption_settings(url, cookie): 4 | """ 5 | Retrieves all existing encryption settings from AdGuard. 6 | :param url: Base AdGuard URL 7 | :param cookie: Session token 8 | :return: List of Entries 9 | """ 10 | 11 | # Retrieve encryption setting 12 | return common.get_response('{}/control/tls/status'.format(url), cookie) 13 | 14 | 15 | def reconcile(adguard_primary, primary_cookie, adguard_secondary, secondary_cookie): 16 | """ 17 | Reconcile encryption settings from primary to secondary Adguards. 18 | :param adguard_primary: URL of primary Adguard. 19 | :param adguard_secondary: URL of secondardy Adguard. 20 | :param primary_cookie: Auth cookie for primary Adguard. 21 | :param secondary_cookie: Auth cookie for secondary Adguard. 22 | """ 23 | primary_encryption_settings = _get_encryption_settings(adguard_primary, primary_cookie) 24 | secondary_encryption_settings = _get_encryption_settings(adguard_secondary, secondary_cookie) 25 | 26 | common.update_settings('encryption', primary_encryption_settings, secondary_encryption_settings, '{}/control/tls/configure'.format(adguard_secondary), secondary_cookie) 27 | -------------------------------------------------------------------------------- /src/settings/general.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from exceptions import UnauthenticatedError, SystemError 3 | import common 4 | import json 5 | 6 | 7 | def _get_general_settings(filtering_status, url, cookie): 8 | """ 9 | Retrieves all general settings from AdGuard. 10 | :param url: Base AdGuard URL 11 | :param cookie: Session token 12 | :return: List of Entries 13 | """ 14 | 15 | settings = {} 16 | 17 | # Retrieve overarching protection setting 18 | response = common.get_response('{}/control/status'.format(url), cookie) 19 | settings['protection_enabled'] = response['protection_enabled'] 20 | 21 | # Retrieve safebrowsing setting 22 | response = common.get_response('{}/control/safebrowsing/status'.format(url), cookie) 23 | settings['safebrowsing'] = response['enabled'] 24 | 25 | # Retrieve safesearch setting 26 | response = common.get_response('{}/control/safesearch/status'.format(url), cookie) 27 | settings['safesearch'] = response['enabled'] 28 | 29 | # Retrieve parental setting 30 | response = common.get_response('{}/control/parental/status'.format(url), cookie) 31 | settings['parental'] = response['enabled'] 32 | 33 | # Retrieve querylog setting 34 | response = common.get_response('{}/control/querylog_info'.format(url), cookie) 35 | settings['querylog_info'] = response 36 | 37 | # Retrieve stats setting 38 | response = common.get_response('{}/control/stats_info'.format(url), cookie) 39 | settings['stats_info'] = response 40 | 41 | # Set relevant filtering status 42 | settings['filtering'] = { 43 | 'enabled': filtering_status['enabled'], 44 | 'interval': filtering_status['interval'] 45 | } 46 | 47 | return settings 48 | 49 | 50 | def _update_enable_setting(setting, enabled, url, cookie): 51 | """ 52 | Update enable/disable setting in secondary AdGuard. 53 | :param setting: Name of the setting to be added to URL 54 | :param enabled: Bool if the setting should be enabled/disabled 55 | :param url: URL of the Secondary AdGuard 56 | :param cookie: Secondary AdGuard Auth Cookie. 57 | :return: None 58 | """ 59 | cookies = { 60 | 'agh_session': cookie 61 | } 62 | 63 | print(" - Updating {} setting".format(setting)) 64 | if enabled: 65 | response = requests.post('{}/control/{}/enable'.format(url, setting), cookies=cookies) 66 | else: 67 | response = requests.post('{}/control/{}/disable'.format(url, setting), cookies=cookies) 68 | 69 | if response.status_code == 403: 70 | raise UnauthenticatedError 71 | elif response.status_code != 200: 72 | raise SystemError 73 | 74 | def _update_protection_enabled(enabled, url, cookie): 75 | """ 76 | Update enable/disable of overarching protection in secondary AdGuard. 77 | :param enabled: Bool if the setting should be enabled/disabled 78 | :param url: URL of the Secondary AdGuard 79 | :param cookie: Secondary AdGuard Auth Cookie. 80 | :return: None 81 | """ 82 | cookies = { 83 | 'agh_session': cookie 84 | } 85 | 86 | data = { 87 | 'protection_enabled': enabled 88 | } 89 | 90 | if enabled: 91 | print(" - Enabling global protection") 92 | else: 93 | print(" - Disabling global protection") 94 | 95 | response = requests.post('{}/control/dns_config'.format(url), data=json.dumps(data), headers=common.REQUEST_HEADERS, cookies=cookies) 96 | 97 | if response.status_code == 403: 98 | raise UnauthenticatedError 99 | elif response.status_code != 200: 100 | raise SystemError 101 | 102 | def reconcile(primary_filtering_status, secondary_filtering_status, adguard_primary, primary_cookie, adguard_secondary, secondary_cookie): 103 | """ 104 | Reconcile blocked services from primary to secondary Adguards. 105 | :param adguard_primary: URL of primary Adguard. 106 | :param adguard_secondary: URL of secondardy Adguard. 107 | :param primary_cookie: Auth cookie for primary Adguard. 108 | :param secondary_cookie: Auth cookie for secondary Adguard. 109 | """ 110 | primary_general_settings = _get_general_settings(primary_filtering_status, adguard_primary, primary_cookie) 111 | secondary_general_settings = _get_general_settings(secondary_filtering_status, adguard_secondary, secondary_cookie) 112 | 113 | # Overarching protection 114 | if primary_general_settings['protection_enabled'] != secondary_general_settings['protection_enabled']: 115 | _update_protection_enabled(primary_general_settings['protection_enabled'], adguard_secondary, secondary_cookie) 116 | 117 | # Safesearch Update 118 | if primary_general_settings['safesearch'] != secondary_general_settings['safesearch']: 119 | _update_enable_setting('safesearch', primary_general_settings['safesearch'], adguard_secondary, secondary_cookie) 120 | 121 | # Safebrowsing Update 122 | if primary_general_settings['safebrowsing'] != secondary_general_settings['safebrowsing']: 123 | _update_enable_setting('safebrowsing', primary_general_settings['safebrowsing'], adguard_secondary, secondary_cookie) 124 | 125 | # Parental Update 126 | if primary_general_settings['parental'] != secondary_general_settings['parental']: 127 | _update_enable_setting('parental', primary_general_settings['parental'], adguard_secondary, secondary_cookie) 128 | 129 | # Updating other settings, a little more complicated so passing all logic to function 130 | common.update_settings('filtering', primary_general_settings['filtering'], secondary_general_settings['filtering'], '{}/control/filtering/config'.format(adguard_secondary), secondary_cookie) 131 | common.update_settings('querylog', primary_general_settings['querylog_info'], secondary_general_settings['querylog_info'], '{}/control/querylog_config'.format(adguard_secondary), secondary_cookie) 132 | common.update_settings('status', primary_general_settings['stats_info'], secondary_general_settings['stats_info'], '{}/control/stats_config'.format(adguard_secondary), secondary_cookie) 133 | --------------------------------------------------------------------------------