pax_global_header00006660000000000000000000000064146675527250014535gustar00rootroot0000000000000052 comment=5c3afacffb6952dea9932911051a45a8e05c4f50 nextdns-3.3.0/000077500000000000000000000000001466755272500132235ustar00rootroot00000000000000nextdns-3.3.0/.devcontainer/000077500000000000000000000000001466755272500157625ustar00rootroot00000000000000nextdns-3.3.0/.devcontainer/Dockerfile000066400000000000000000000004471466755272500177610ustar00rootroot00000000000000ARG VARIANT="3.12" FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} COPY requirements*.txt /tmp/pip-tmp/ RUN pip --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements-test.txt -r /tmp/pip-tmp/requirements.txt && rm -rf /tmp/pip-tmp ENV SHELL /bin/bash nextdns-3.3.0/.devcontainer/devcontainer.json000066400000000000000000000017051466755272500213410ustar00rootroot00000000000000{ "name": "NextDNS", "build": { "dockerfile": "Dockerfile", "context": ".." }, "customizations": { "vscode": { "settings": { "terminal.integrated.profiles.linux": { "zsh": { "path": "/usr/bin/zsh" } }, "terminal.integrated.defaultProfile.linux": "zsh", "python.pythonPath": "/usr/local/bin/python", "python.languageServer": "Pylance", "[python]": { "editor.defaultFormatter": "charliermarsh.ruff" } }, "extensions": [ "ms-python.python", "ms-python.vscode-pylance", "ms-python.pylint", "charliermarsh.ruff" ] } }, "postCreateCommand": "scripts/setup-devcontainer-env.sh", "remoteUser": "vscode" } nextdns-3.3.0/.github/000077500000000000000000000000001466755272500145635ustar00rootroot00000000000000nextdns-3.3.0/.github/FUNDING.yml000066400000000000000000000001241466755272500163750ustar00rootroot00000000000000custom: ['https://www.paypal.me/bieniu79', 'https://www.buymeacoffee.com/QnLdxeaqO']nextdns-3.3.0/.github/dependabot.yml000066400000000000000000000003141466755272500174110ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly"nextdns-3.3.0/.github/release-drafter.yml000066400000000000000000000013441466755272500203550ustar00rootroot00000000000000change-template: "- #$NUMBER $TITLE @$AUTHOR" sort-direction: ascending categories: - title: ":boom: Breaking Changes" label: "breaking-change" - title: ":sparkles: New Features" label: "new-feature" - title: ":zap: Performance" label: "performance" - title: ":recycle: Refactor" label: "refactor" - title: ":green_heart: CI" label: "ci" - title: ":bug: Bug Fixes" label: "bugfix" - title: ":white_check_mark: Tests" label: "tests" - title: ":arrow_up: Dependency Updates" label: "dependencies" collapse-after: 1 include-labels: - "breaking-change" - "performance" - "refactor" - "new-feature" - "bugfix" - "dependencies" - "tests" - "ci" template: | $CHANGES nextdns-3.3.0/.github/workflows/000077500000000000000000000000001466755272500166205ustar00rootroot00000000000000nextdns-3.3.0/.github/workflows/codeql.yml000066400000000000000000000013361466755272500206150ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [master] pull_request: branches: [master] schedule: - cron: "21 5 * * 0" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: ["python"] steps: - name: Checkout repository uses: actions/checkout@v4.1.7 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} - name: Autobuild uses: github/codeql-action/autobuild@v3 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 nextdns-3.3.0/.github/workflows/pre-commit-update.yml000066400000000000000000000015601466755272500227010ustar00rootroot00000000000000name: Pre-commit auto-update on: schedule: # Run on fridays - cron: "0 0 * * 1" jobs: auto-update: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4.1.7 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.x" - name: Install pre-commit run: pip install pre-commit - name: Run pre-commit autoupdate run: pre-commit autoupdate - name: Create Pull Request uses: peter-evans/create-pull-request@v6.1.0 with: token: ${{ secrets.GITHUB_TOKEN }} branch: update/pre-commit-autoupdate title: Auto-update pre-commit hooks commit-message: Auto-update pre-commit hooks body: | Update versions of tools in pre-commit configs to latest version labels: dependencies nextdns-3.3.0/.github/workflows/publish.yml000066400000000000000000000012411466755272500210070ustar00rootroot00000000000000name: Upload Python Package on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4.1.7 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine - name: Build and publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | python setup.py sdist bdist_wheel twine upload dist/* nextdns-3.3.0/.github/workflows/release-drafter.yml000066400000000000000000000014431466755272500224120ustar00rootroot00000000000000name: Release Drafter on: push: branches: - master jobs: update_release_draft: runs-on: ubuntu-latest name: Release Drafter steps: - name: Checkout the repository uses: actions/checkout@v4.1.7 with: fetch-depth: 0 - name: Find Version id: version run: | declare -i newpost version=$(python setup.py --version) echo Version from setup.py: $version echo "::set-output name=version::$version" - name: Run Release Drafter uses: release-drafter/release-drafter@v6.0.0 with: tag: ${{ steps.version.outputs.version }} name: Version ${{ steps.version.outputs.version }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} nextdns-3.3.0/.github/workflows/stale.yml000066400000000000000000000010101466755272500204430ustar00rootroot00000000000000name: Mark stale issues and pull requests on: schedule: - cron: '25 8 * * *' jobs: stale: runs-on: ubuntu-latest permissions: issues: write pull-requests: write steps: - name: Stale uses: actions/stale@v9 with: repo-token: ${{ secrets.GITHUB_TOKEN }} stale-issue-message: 'Stale issue message' stale-pr-message: 'Stale pull request message' stale-issue-label: 'no-issue-activity' stale-pr-label: 'no-pr-activity'nextdns-3.3.0/.github/workflows/test.yml000066400000000000000000000012521466755272500203220ustar00rootroot00000000000000name: Test on: push: branches: [master] pull_request: branches: [master] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: - "3.11" - "3.12" - "3.13.0-rc.1" steps: - name: Check out repository uses: actions/checkout@v4.1.7 with: fetch-depth: 2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install uv tox tox-gh-actions tox-uv - name: Test with tox run: tox nextdns-3.3.0/.gitignore000066400000000000000000000034201466755272500152120ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ .dccache nextdns-3.3.0/.pre-commit-config.yaml000066400000000000000000000023761466755272500175140ustar00rootroot00000000000000repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.6.4 hooks: - id: ruff args: - --fix - id: ruff-format - repo: https://github.com/codespell-project/codespell rev: v2.3.0 hooks: - id: codespell args: - --ignore-words-list=hass,alot,datas,dof,dur,ether,farenheit,hist,iff,ines,ist,lightsensor,mut,nd,pres,referer,ser,serie,te,technik,ue,uint,visability,wan,wanna,withing,iam,incomfort,ba - --skip="./.*,*.csv,*.json" - --quiet-level=2 exclude_types: [csv, json] exclude: ^tests/fixtures/ - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks: - id: end-of-file-fixer - id: mixed-line-ending - id: trailing-whitespace - id: check-yaml - id: check-json - id: check-toml - id: pretty-format-json args: - --no-sort-keys - id: no-commit-to-branch args: - --branch=master - repo: https://github.com/pre-commit/mirrors-prettier rev: v4.0.0-alpha.8 hooks: - id: prettier stages: [manual] - repo: https://github.com/pre-commit/mirrors-mypy rev: "v1.11.2" hooks: - id: mypy files: ^(nextdns)/.+\.py$ nextdns-3.3.0/.vscode/000077500000000000000000000000001466755272500145645ustar00rootroot00000000000000nextdns-3.3.0/.vscode/launch.json000066400000000000000000000007111466755272500167300ustar00rootroot00000000000000{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Fetch data", "type": "python", "request": "launch", "program": "example.py", "console": "integratedTerminal" } ] } nextdns-3.3.0/.vscode/settings.json000066400000000000000000000003451466755272500173210ustar00rootroot00000000000000{ "python.testing.pytestArgs": [ "tests" ], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "[python]": { "editor.defaultFormatter": "charliermarsh.ruff" } } nextdns-3.3.0/LICENSE000066400000000000000000000261201466755272500142310ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2024 Maciej Bieniek Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. nextdns-3.3.0/MANIFEST.in000066400000000000000000000001201466755272500147520ustar00rootroot00000000000000include LICENSE README.md include requirements.txt include requirements-test.txtnextdns-3.3.0/README.md000066400000000000000000000046031466755272500145050ustar00rootroot00000000000000[![GitHub Release][releases-shield]][releases] [![PyPI][pypi-releases-shield]][pypi-releases] [![PyPI - Downloads][pypi-downloads]][pypi-statistics] [![Buy me a coffee][buy-me-a-coffee-shield]][buy-me-a-coffee] [![PayPal_Me][paypal-me-shield]][paypal-me] # nextdns Python wrapper for [NextDNS](https://nextdns.io/?from=u4xqh6ud) API. ## How to use package ```python """Example of usage.""" import asyncio import logging from aiohttp import ClientSession from nextdns import ApiError, InvalidApiKeyError, NextDns API_KEY = "xxx" logging.basicConfig(level=logging.DEBUG) async def main(): """Main function.""" async with ClientSession() as websession: try: nextdns = await NextDns.create(websession, API_KEY) profile_id, profile_name = nextdns.profiles[2] profile = await nextdns.get_profile(profile_id) status = await nextdns.get_analytics_status(profile_id) dnssec = await nextdns.get_analytics_dnssec(profile_id) encryption = await nextdns.get_analytics_encryption(profile_id) ip_versions = await nextdns.get_analytics_ip_versions(profile_id) protocols = await nextdns.get_analytics_protocols(profile_id) except InvalidApiKeyError: print("Invalid API Key") except ApiError as error: print(f"API Error: {error.status}") else: print(f"Profile: {profile_name} ({profile_id})") print(profile) print(status) print(dnssec) print(encryption) print(ip_versions) print(protocols) loop = asyncio.new_event_loop() loop.run_until_complete(main()) loop.close() ``` [releases]: https://github.com/bieniu/nextdns/releases [releases-shield]: https://img.shields.io/github/release/bieniu/nextdns.svg?style=popout [pypi-releases]: https://pypi.org/project/nextdns/ [pypi-statistics]: https://pepy.tech/project/nextdns [pypi-releases-shield]: https://img.shields.io/pypi/v/nextdns [pypi-downloads]: https://pepy.tech/badge/nextdns/month [buy-me-a-coffee-shield]: https://img.shields.io/static/v1.svg?label=%20&message=Buy%20me%20a%20coffee&color=6f4e37&logo=buy%20me%20a%20coffee&logoColor=white [buy-me-a-coffee]: https://www.buymeacoffee.com/QnLdxeaqO [paypal-me-shield]: https://img.shields.io/static/v1.svg?label=%20&message=PayPal.Me&logo=paypal [paypal-me]: https://www.paypal.me/bieniu79 nextdns-3.3.0/example.py000066400000000000000000000055631466755272500152410ustar00rootroot00000000000000"""Example of usage.""" import asyncio import logging from dataclasses import astuple from aiohttp import ClientConnectorError, ClientSession from tenacity import RetryError from nextdns import ApiError, InvalidApiKeyError, NextDns API_KEY = "xxx" logging.basicConfig(level=logging.DEBUG) async def main() -> None: """Run main function.""" async with ClientSession() as websession: try: nextdns = await NextDns.create(websession, API_KEY) profile_id, profile_fingerprint, profile_name = astuple(nextdns.profiles[0]) status = await nextdns.get_analytics_status(profile_id) dnssec = await nextdns.get_analytics_dnssec(profile_id) encryption = await nextdns.get_analytics_encryption(profile_id) ip_versions = await nextdns.get_analytics_ip_versions(profile_id) protocols = await nextdns.get_analytics_protocols(profile_id) connection_status = await nextdns.connection_status(profile_id) settings = await nextdns.get_settings(profile_id) # set logs retention to 1 month (30 days) # allowed values are: 1, 6, 24, 168, 720, 960, 4320, 8760, 17520 # await nextdns.set_logs_retention(profile_id, 720) # set logs location to Switzerland # allowed values are: ch, eu, gb, us # await nextdns.set_logs_location(profile_id, "ch") # clear logs # await nextdns.clear_logs(profile_id) # get CSV logs and save to file # logs = await nextdns.get_logs(profile_id) # with open( # f"nextdns_{profile_id}_logs.csv", "w", encoding="utf-8" # ) as file: # file.write(logs) # enable block page # await nextdns.set_setting(profile_id, "block_page", True) except ValueError as error: print(error) except InvalidApiKeyError: print("Invalid API Key") except ApiError as error: print(f"API Error: {error.status}") except ClientConnectorError as error: print(f"ClientConnectorError: {error}") except TimeoutError as error: print(f"TimeoutError: {error}") except RetryError as error: print(f"RetryError: {error}") else: print( f"Profile: {profile_name} " f"(id: {profile_id}, fingerprint: {profile_fingerprint})" ) print( f"Does this device use NextDNS?: {connection_status.connected}, " f"using profile: {connection_status.profile_id}" ) print(status) print(dnssec) print(encryption) print(ip_versions) print(protocols) print(settings) loop = asyncio.new_event_loop() loop.run_until_complete(main()) loop.close() nextdns-3.3.0/nextdns/000077500000000000000000000000001466755272500147065ustar00rootroot00000000000000nextdns-3.3.0/nextdns/__init__.py000066400000000000000000000517621466755272500170320ustar00rootroot00000000000000"""Python wrapper for NextDNS API.""" from __future__ import annotations import asyncio import logging from collections.abc import Iterable from http import HTTPStatus from typing import Any, cast from aiohttp import ClientConnectorError, ClientSession from tenacity import ( after_log, retry, retry_if_exception_type, stop_after_attempt, wait_incrementing, ) from .const import ( ALLOWED_LOGS_LOCATION, ALLOWED_LOGS_RETENTION, ATTR_ANALYTICS, ATTR_CLEAR_LOGS, ATTR_ENABLED, ATTR_GET_LOGS, ATTR_LOCATION, ATTR_LOGS, ATTR_LOGS_LOCATION, ATTR_LOGS_RETENTION, ATTR_PARENTAL_CONTROL_CATEGORIES, ATTR_PARENTAL_CONTROL_SERVICES, ATTR_PERFORMANCE, ATTR_PROFILE, ATTR_PROFILES, ATTR_RETENTION, ATTR_TEST, ATTR_WEB3, ENDPOINTS, HTTP_STATUS_TIMEOUT, MAP_DNSSEC, MAP_ENCRYPTED, MAP_IP_VERSIONS, MAP_PROFILE, MAP_PROTOCOLS, MAP_SETTING, MAP_STATUS, PARENTAL_CONTROL_CATEGORIES, PARENTAL_CONTROL_SERVICES, STOP_AFTER_ATTEMPT, TIMEOUT, WAIT_INCREMENT, WAIT_START, ) from .exceptions import ( ApiError, InvalidApiKeyError, ProfileIdNotFoundError, ProfileNameNotFoundError, SettingNotSupportedError, ) from .model import ( AllAnalytics, AnalyticsDnssec, AnalyticsEncryption, AnalyticsIpVersions, AnalyticsProtocols, AnalyticsStatus, ApiNames, ConnectionStatus, ParentalControlCategories, ParentalControlServices, Profile, ProfileInfo, Settings, ) _LOGGER = logging.getLogger(__name__) class NextDns: """Main class of NextDNS API wrapper.""" def __init__(self, session: ClientSession, api_key: str) -> None: """Initialize NextDNS API wrapper.""" self._session = session self._headers = {"X-Api-Key": api_key, "Content-Type": "application/json"} self._api_key = api_key self._profiles: list[ProfileInfo] @classmethod async def create(cls, session: ClientSession, api_key: str) -> NextDns: """Create a new instance.""" instance = cls(session, api_key) await instance.initialize() return instance async def initialize(self) -> None: """Initialize.""" _LOGGER.debug("Initializing with API Key: %s...", self._api_key[:10]) self._profiles = list(self._parse_profiles(await self.get_profiles())) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_profiles(self) -> list[dict[str, str]]: """Get all profiles.""" url = ENDPOINTS[ATTR_PROFILES] return cast(list[dict[str, str]], await self._http_request("get", url)) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_profile(self, profile_id: str) -> Profile: """Get profile.""" url = ENDPOINTS[ATTR_PROFILE].format(profile_id=profile_id) resp = await self._http_request("get", url) return Profile( **{MAP_PROFILE.get(key, key): value for key, value in resp.items()} ) async def get_settings(self, profile_id: str) -> Settings: """Get profile settings.""" profile_data = await self.get_profile(profile_id) services = { service["id"]: service["active"] for service in profile_data.parental_control[ApiNames.SERVICES] } categories = { category["id"]: category["active"] for category in profile_data.parental_control[ApiNames.CATEGORIES] } return Settings( block_page=profile_data.settings["blockPage"][ATTR_ENABLED], cache_boost=profile_data.settings[ATTR_PERFORMANCE][ApiNames.CACHE_BOOST], cname_flattening=profile_data.settings[ATTR_PERFORMANCE][ ApiNames.CNAME_FLATTENING ], anonymized_ecs=profile_data.settings[ATTR_PERFORMANCE][ApiNames.ECS], logs=profile_data.settings[ATTR_LOGS][ATTR_ENABLED], logs_location=profile_data.settings[ATTR_LOGS][ATTR_LOCATION], logs_retention=int(profile_data.settings[ATTR_LOGS][ATTR_RETENTION] / 3600), web3=profile_data.settings[ATTR_WEB3], allow_affiliate=profile_data.privacy[ApiNames.ALLOW_AFFILIATE], block_disguised_trackers=profile_data.privacy[ApiNames.DISGUISED_TRACKERS], ai_threat_detection=profile_data.security[ApiNames.AI_THREAT_TETECTION], block_csam=profile_data.security[ApiNames.CSAM], block_ddns=profile_data.security[ApiNames.DDNS], block_nrd=profile_data.security[ApiNames.NRD], block_parked_domains=profile_data.security[ApiNames.PARKING], cryptojacking_protection=profile_data.security[ApiNames.CRYPTOJACKING], dga_protection=profile_data.security[ApiNames.DGA], dns_rebinding_protection=profile_data.security[ApiNames.DNS_REBINDING], google_safe_browsing=profile_data.security[ApiNames.GOOGLE_SAFE_BROWSING], idn_homograph_attacks_protection=profile_data.security[ ApiNames.IDN_HOMOGRAPHS ], threat_intelligence_feeds=profile_data.security[ ApiNames.THREAT_INTELLIGENCE_FEEDS ], typosquatting_protection=profile_data.security[ApiNames.TYPOSQUATTING], block_bypass_methods=profile_data.parental_control[ApiNames.BLOCK_BYPASS], safesearch=profile_data.parental_control[ApiNames.SAFESEARCH], youtube_restricted_mode=profile_data.parental_control[ ApiNames.YOUTUBE_RESTRICTED_MODE ], block_9gag=services.get(ParentalControlServices.NINEGAG, False), block_amazon=services.get(ParentalControlServices.AMAZON, False), block_bereal=services.get(ParentalControlServices.BEREAL, False), block_blizzard=services.get(ParentalControlServices.BLIZZARD, False), block_chatgpt=services.get(ParentalControlServices.CHATGPT, False), block_dailymotion=services.get(ParentalControlServices.DAILYMOTION, False), block_discord=services.get(ParentalControlServices.DISCORD, False), block_disneyplus=services.get(ParentalControlServices.DISNEYPLUS, False), block_ebay=services.get(ParentalControlServices.EBAY, False), block_facebook=services.get(ParentalControlServices.FACEBOOK, False), block_fortnite=services.get(ParentalControlServices.FORTNITE, False), block_google_chat=services.get(ParentalControlServices.GOOGLE_CHAT, False), block_hbomax=services.get(ParentalControlServices.HBOMAX, False), block_hulu=services.get(ParentalControlServices.HULU, False), block_imgur=services.get(ParentalControlServices.IMGUR, False), block_instagram=services.get(ParentalControlServices.INSTAGRAM, False), block_leagueoflegends=services.get( ParentalControlServices.LEAGUEOFLEGENDS, False ), block_mastodon=services.get(ParentalControlServices.MASTODON, False), block_messenger=services.get(ParentalControlServices.MESSENGER, False), block_minecraft=services.get(ParentalControlServices.MINECRAFT, False), block_netflix=services.get(ParentalControlServices.NETFLIX, False), block_pinterest=services.get(ParentalControlServices.PINTEREST, False), block_primevideo=services.get(ParentalControlServices.PRIMEVIDEO, False), block_reddit=services.get(ParentalControlServices.REDDIT, False), block_roblox=services.get(ParentalControlServices.ROBLOX, False), block_signal=services.get(ParentalControlServices.SIGNAL, False), block_skype=services.get(ParentalControlServices.SKYPE, False), block_snapchat=services.get(ParentalControlServices.SNAPCHAT, False), block_spotify=services.get(ParentalControlServices.SPOTIFY, False), block_steam=services.get(ParentalControlServices.STEAM, False), block_telegram=services.get(ParentalControlServices.TELEGRAM, False), block_tiktok=services.get(ParentalControlServices.TIKTOK, False), block_tinder=services.get(ParentalControlServices.TINDER, False), block_tumblr=services.get(ParentalControlServices.TUMBLR, False), block_twitch=services.get(ParentalControlServices.TWITCH, False), block_twitter=services.get(ParentalControlServices.TWITTER, False), block_vimeo=services.get(ParentalControlServices.VIMEO, False), block_vk=services.get(ParentalControlServices.VK, False), block_whatsapp=services.get(ParentalControlServices.WHATSAPP, False), block_xboxlive=services.get(ParentalControlServices.XBOXLIVE, False), block_youtube=services.get(ParentalControlServices.YOUTUBE, False), block_zoom=services.get(ParentalControlServices.ZOOM, False), block_dating=categories.get(ParentalControlCategories.DATING, False), block_gambling=categories.get(ParentalControlCategories.GAMBLING, False), block_piracy=categories.get(ParentalControlCategories.PIRACY, False), block_playstation_network=services.get( ParentalControlServices.PLAYSTATION_NETWORK, False ), block_porn=categories.get(ParentalControlCategories.PORN, False), block_social_networks=categories.get( ParentalControlCategories.SOCIAL_NETWORKS, False ), block_online_gaming=categories.get( ParentalControlCategories.ONLINE_GAMING, False ), block_video_streaming=categories.get( ParentalControlCategories.VIDEO_STREAMING, False ), ) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_analytics_status(self, profile_id: str) -> AnalyticsStatus: """Get profile analytics status.""" url = ENDPOINTS[ATTR_ANALYTICS].format(profile_id=profile_id, type="status") resp = await self._http_request("get", url) return AnalyticsStatus( **{MAP_STATUS[item["status"]]: item["queries"] for item in resp} ) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_analytics_dnssec(self, profile_id: str) -> AnalyticsDnssec: """Get profile analytics dnssec.""" url = ENDPOINTS[ATTR_ANALYTICS].format(profile_id=profile_id, type="dnssec") resp = await self._http_request("get", url) return AnalyticsDnssec( **{MAP_DNSSEC[item["validated"]]: item["queries"] for item in resp} ) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_analytics_encryption(self, profile_id: str) -> AnalyticsEncryption: """Get profile analytics encryption.""" url = ENDPOINTS[ATTR_ANALYTICS].format(profile_id=profile_id, type="encryption") resp = await self._http_request("get", url) return AnalyticsEncryption( **{MAP_ENCRYPTED[item["encrypted"]]: item["queries"] for item in resp} ) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_analytics_ip_versions(self, profile_id: str) -> AnalyticsIpVersions: """Get profile analytics IP versions.""" url = ENDPOINTS[ATTR_ANALYTICS].format(profile_id=profile_id, type="ipVersions") resp = await self._http_request("get", url) return AnalyticsIpVersions( **{MAP_IP_VERSIONS[item["version"]]: item["queries"] for item in resp} ) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_analytics_protocols(self, profile_id: str) -> AnalyticsProtocols: """Get profile analytics protocols.""" url = ENDPOINTS[ATTR_ANALYTICS].format(profile_id=profile_id, type="protocols") resp = await self._http_request("get", url) return AnalyticsProtocols( **{MAP_PROTOCOLS[item["protocol"]]: item["queries"] for item in resp} ) @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def connection_status(self, profile_id: str) -> ConnectionStatus: """Return True if the device is using NextDNS.""" url = ENDPOINTS[ATTR_TEST].format(profile_id=profile_id) resp = await self._http_request("get", url) used_profile_id = None if status := resp["status"] == "ok": for item in self.profiles: if item.fingerprint == resp.get("profile"): used_profile_id = item.id return ConnectionStatus(status, used_profile_id) async def clear_logs(self, profile_id: str) -> bool: """Clear NextDNS logs.""" url = ENDPOINTS[ATTR_CLEAR_LOGS].format(profile_id=profile_id) result = await self._http_request("delete", url) return result.get("success", False) is True @retry( retry=retry_if_exception_type((TimeoutError, ClientConnectorError)), stop=stop_after_attempt(STOP_AFTER_ATTEMPT), wait=wait_incrementing(start=WAIT_START, increment=WAIT_INCREMENT), after=after_log(_LOGGER, logging.DEBUG), ) async def get_logs(self, profile_id: str) -> str: """Get NextDNS logs.""" url = ENDPOINTS[ATTR_GET_LOGS].format(profile_id=profile_id) result = await self._http_request("get", url) return cast(str, result) async def get_all_analytics(self, profile_id: str) -> AllAnalytics: """Get profile analytics.""" resp = await asyncio.gather( self.get_analytics_dnssec(profile_id), self.get_analytics_encryption(profile_id), self.get_analytics_ip_versions(profile_id), self.get_analytics_protocols(profile_id), self.get_analytics_status(profile_id), ) return AllAnalytics(*resp) async def set_logs_location(self, profile_id: str, location: str) -> bool: """Set logs location.""" if location not in ALLOWED_LOGS_LOCATION: raise ValueError( "Invalid logs location value. " f"Allowed values are: {ALLOWED_LOGS_LOCATION}" ) url = MAP_SETTING[ATTR_LOGS_LOCATION].url.format(profile_id=profile_id) name = MAP_SETTING[ATTR_LOGS_LOCATION].name result = await self._http_request("patch", url, data={name: location}) return result.get("success", False) is True async def set_logs_retention(self, profile_id: str, hours: int) -> bool: """Set logs retention.""" if hours not in ALLOWED_LOGS_RETENTION: raise ValueError( "Invalid logs retention value. " f"Allowed values are: {ALLOWED_LOGS_RETENTION}" ) url = MAP_SETTING[ATTR_LOGS_RETENTION].url.format(profile_id=profile_id) name = MAP_SETTING[ATTR_LOGS_RETENTION].name result = await self._http_request("patch", url, data={name: hours * 60 * 60}) return result.get("success", False) is True async def set_setting(self, profile_id: str, setting: str, state: bool) -> bool: """Toggle settings.""" data: dict[str, Any] resp = {} if setting not in MAP_SETTING: raise SettingNotSupportedError if setting in PARENTAL_CONTROL_CATEGORIES: url = MAP_SETTING[setting].url.format( profile_id=profile_id, category=MAP_SETTING[setting].name ) data = {"active": state} try: resp = await self._http_request("patch", url, data=data) except ApiError as exc: if "404, notFound" in exc.status and state is True: url = ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORIES].format( profile_id=profile_id ) data = {"id": MAP_SETTING[setting].name} resp = await self._http_request("post", url, data=data) elif setting in PARENTAL_CONTROL_SERVICES: url = MAP_SETTING[setting].url.format( profile_id=profile_id, service=MAP_SETTING[setting].name ) data = {"active": state} try: resp = await self._http_request("patch", url, data=data) except ApiError as exc: if "404, notFound" in exc.status and state is True: url = ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICES].format( profile_id=profile_id ) data = {"id": MAP_SETTING[setting].name} resp = await self._http_request("post", url, data=data) else: url = MAP_SETTING[setting].url.format(profile_id=profile_id) data = {str(MAP_SETTING[setting].name): state} resp = await self._http_request("patch", url, data=data) return resp.get("success", False) is True async def _http_request( self, method: str, url: str, data: dict[str, Any] | None = None ) -> Any: """Make an HTTP request.""" _LOGGER.debug("Requesting %s, method: %s, data: %s", url, method, data) if data: resp = await self._session.request( method, url, headers=self._headers, json=data, timeout=TIMEOUT, ) else: resp = await self._session.request(method, url, headers=self._headers) _LOGGER.debug("Response status %s for %s", resp.status, url) if resp.status == HTTPStatus.FORBIDDEN.value: raise InvalidApiKeyError if resp.status == HTTPStatus.NO_CONTENT.value and method in ( "delete", "patch", "post", ): return {"success": True} if resp.status == HTTPStatus.TOO_MANY_REQUESTS.value: raise ApiError("Too many requests") if resp.status == HTTP_STATUS_TIMEOUT: raise TimeoutError("Timeout occurred: HTTP 524") if resp.status != HTTPStatus.OK.value: if resp.content_type == "application/json": result = await resp.json() error = result["errors"][0] raise ApiError( f"{resp.status}, {error['code']}, " f"{error.get('detail', 'no detail')}" ) raise ApiError(f"Error code: {resp.status}") if resp.content_type == "application/json": result = await resp.json() else: result = await resp.text() if isinstance(result, dict) and "data" in result: return result["data"] return result def get_profile_name(self, profile_id: str) -> str: """Get profile name.""" for profile in self.profiles: if profile.id == profile_id: return profile.name raise ProfileIdNotFoundError def get_profile_id(self, profile_name: str) -> str: """Get profile ID.""" for profile in self.profiles: if profile.name == profile_name: return profile.id raise ProfileNameNotFoundError @staticmethod def _parse_profiles(profiles: list[dict[str, str]]) -> Iterable[ProfileInfo]: """Parse profiles.""" for profile in profiles: yield ProfileInfo(profile["id"], profile["fingerprint"], profile["name"]) @property def profiles(self) -> list[ProfileInfo]: """Return profiles.""" return self._profiles nextdns-3.3.0/nextdns/const.py000066400000000000000000000360261466755272500164150ustar00rootroot00000000000000"""NextDNS constants.""" from aiohttp import ClientTimeout from .model import ( ApiNames, ParentalControlCategories, ParentalControlCategoriesAttrs, ParentalControlServices, ParentalControlServicesAttrs, SettingDescription, ) API_ENDPOINT = "https://api.nextdns.io" ATTR_ANALYTICS = "analytics" ATTR_CLEAR_LOGS = "clear_logs" ATTR_ENABLED = "enabled" ATTR_GET_LOGS = "get_logs" ATTR_PARENTAL_CONTROL = "parental_control" ATTR_PARENTAL_CONTROL_CATEGORIES = "parental_control_categories" ATTR_PARENTAL_CONTROL_CATEGORY = "parental_control_category" ATTR_PARENTAL_CONTROL_SERVICE = "parental_control_service" ATTR_PARENTAL_CONTROL_SERVICES = "parental_control_services" ATTR_PERFORMANCE = "performance" ATTR_PRIVACY = "privacy" ATTR_PROFILE = "profile" ATTR_PROFILES = "profiles" ATTR_SECURITY = "security" ATTR_SECURITY = "security" ATTR_SETTINGS = "settings" ATTR_TEST = "test" ATTR_ANONYMIZED_ECS = "anonymized_ecs" ATTR_BLOCK_PAGE = "block_page" ATTR_CACHE_BOOST = "cache_boost" ATTR_CNAME_FLATTENING = "cname_flattening" ATTR_LOGS = "logs" ATTR_LOGS_LOCATION = "logs_location" ATTR_LOGS_RETENTION = "logs_retention" ATTR_RETENTION = "retention" ATTR_LOCATION = "location" ATTR_WEB3 = "web3" ATTR_ALLOW_AFFILIATE = "allow_affiliate" ATTR_BLOCK_DISGUISED_TRACKERS = "block_disguised_trackers" ATTR_AI_THREAT_DETECTION = "ai_threat_detection" ATTR_BLOCK_CSAM = "block_csam" ATTR_BLOCK_DDNS = "block_ddns" ATTR_BLOCK_NRD = "block_nrd" ATTR_BLOCK_PARKED_DOMAINS = "block_parked_domains" ATTR_CRYPTOJACKING_PROTECTION = "cryptojacking_protection" ATTR_DGA_PROTECTION = "dga_protection" ATTR_DNS_REBINDING_PROTECTION = "dns_rebinding_protection" ATTR_GOOGLE_SAFE_BROWSING = "google_safe_browsing" ATTR_IDN_HOMOGRAPH_ATTACKS_PROTECTION = "idn_homograph_attacks_protection" ATTR_THREAT_INTELLIGENCE_FEEDS = "threat_intelligence_feeds" ATTR_TYPOSQUATTING_PROTECTION = "typosquatting_protection" ATTR_BLOCK_BYPASS_METHODS = "block_bypass_methods" ATTR_SAFESEARCH = "safesearch" ATTR_YOUTUBE_RESTRICTED_MODE = "youtube_restricted_mode" PARENTAL_CONTROL_CATEGORIES = tuple(item for item in ParentalControlCategoriesAttrs) PARENTAL_CONTROL_SERVICES = tuple(item for item in ParentalControlServicesAttrs) ENDPOINTS = { ATTR_ANALYTICS: "https://api.nextdns.io/profiles/{profile_id}/analytics/{type}", ATTR_CLEAR_LOGS: "https://api.nextdns.io/profiles/{profile_id}/logs", ATTR_GET_LOGS: "https://api.nextdns.io/profiles/{profile_id}/logs/download", ATTR_PROFILE: "https://api.nextdns.io/profiles/{profile_id}", ATTR_PROFILES: "https://api.nextdns.io/profiles", ATTR_TEST: "https://{profile_id}.test.nextdns.io", ATTR_SECURITY: "https://api.nextdns.io/profiles/{profile_id}/security", ATTR_SETTINGS: "https://api.nextdns.io/profiles/{profile_id}/settings", ATTR_PERFORMANCE: "https://api.nextdns.io/profiles/{profile_id}/settings/performance", ATTR_PRIVACY: "https://api.nextdns.io/profiles/{profile_id}/privacy", ATTR_PARENTAL_CONTROL: "https://api.nextdns.io/profiles/{profile_id}/parentalControl", ATTR_PARENTAL_CONTROL_CATEGORY: "https://api.nextdns.io/profiles/{profile_id}/parentalControl/categories/{category}", ATTR_PARENTAL_CONTROL_CATEGORIES: "https://api.nextdns.io/profiles/{profile_id}/parentalControl/categories", ATTR_PARENTAL_CONTROL_SERVICE: "https://api.nextdns.io/profiles/{profile_id}/parentalControl/services/{service}", ATTR_PARENTAL_CONTROL_SERVICES: "https://api.nextdns.io/profiles/{profile_id}/parentalControl/services", ATTR_LOGS: "https://api.nextdns.io/profiles/{profile_id}/settings/logs", ATTR_LOGS_LOCATION: "https://api.nextdns.io/profiles/{profile_id}/settings/logs/location", ATTR_LOGS_RETENTION: "https://api.nextdns.io/profiles/{profile_id}/settings/logs/retention", ATTR_BLOCK_PAGE: "https://api.nextdns.io/profiles/{profile_id}/settings/blockPage", } MAP_DNSSEC = {False: "not_validated_queries", True: "validated_queries"} MAP_ENCRYPTED = {False: "unencrypted_queries", True: "encrypted_queries"} MAP_IP_VERSIONS = {4: "ipv4_queries", 6: "ipv6_queries"} MAP_PROFILE = {"parentalControl": "parental_control"} MAP_PROTOCOLS = { "DNS-over-HTTPS": "doh_queries", "DNS-over-HTTP/3": "doh3_queries", "DNS-over-QUIC": "doq_queries", "DNS-over-TLS": "dot_queries", "TCP": "tcp_queries", "UDP": "udp_queries", } MAP_STATUS = { "allowed": "allowed_queries", "blocked": "blocked_queries", "default": "default_queries", "relayed": "relayed_queries", } MAP_SETTING = { ATTR_BLOCK_PAGE: SettingDescription(ENDPOINTS[ATTR_BLOCK_PAGE], ATTR_ENABLED), ATTR_CACHE_BOOST: SettingDescription( ENDPOINTS[ATTR_PERFORMANCE], ApiNames.CACHE_BOOST ), ATTR_CNAME_FLATTENING: SettingDescription( ENDPOINTS[ATTR_PERFORMANCE], ApiNames.CNAME_FLATTENING ), ATTR_ANONYMIZED_ECS: SettingDescription(ENDPOINTS[ATTR_PERFORMANCE], ApiNames.ECS), ATTR_WEB3: SettingDescription(ENDPOINTS[ATTR_SETTINGS], ATTR_WEB3), ATTR_LOGS: SettingDescription(ENDPOINTS[ATTR_LOGS], ATTR_ENABLED), ATTR_LOGS_LOCATION: SettingDescription(ENDPOINTS[ATTR_LOGS], ATTR_LOCATION), ATTR_LOGS_RETENTION: SettingDescription(ENDPOINTS[ATTR_LOGS], ATTR_RETENTION), ATTR_ALLOW_AFFILIATE: SettingDescription( ENDPOINTS[ATTR_PRIVACY], ApiNames.ALLOW_AFFILIATE ), ATTR_BLOCK_DISGUISED_TRACKERS: SettingDescription( ENDPOINTS[ATTR_PRIVACY], ApiNames.DISGUISED_TRACKERS ), ATTR_AI_THREAT_DETECTION: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.AI_THREAT_TETECTION ), ATTR_BLOCK_CSAM: SettingDescription(ENDPOINTS[ATTR_SECURITY], ApiNames.CSAM), ATTR_BLOCK_DDNS: SettingDescription(ENDPOINTS[ATTR_SECURITY], ApiNames.DDNS), ATTR_BLOCK_NRD: SettingDescription(ENDPOINTS[ATTR_SECURITY], ApiNames.NRD), ATTR_BLOCK_PARKED_DOMAINS: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.PARKING ), ATTR_CRYPTOJACKING_PROTECTION: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.CRYPTOJACKING ), ATTR_DGA_PROTECTION: SettingDescription(ENDPOINTS[ATTR_SECURITY], ApiNames.DGA), ATTR_DNS_REBINDING_PROTECTION: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.DNS_REBINDING ), ATTR_GOOGLE_SAFE_BROWSING: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.GOOGLE_SAFE_BROWSING ), ATTR_IDN_HOMOGRAPH_ATTACKS_PROTECTION: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.IDN_HOMOGRAPHS ), ATTR_THREAT_INTELLIGENCE_FEEDS: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.THREAT_INTELLIGENCE_FEEDS ), ATTR_TYPOSQUATTING_PROTECTION: SettingDescription( ENDPOINTS[ATTR_SECURITY], ApiNames.TYPOSQUATTING ), ATTR_BLOCK_BYPASS_METHODS: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL], ApiNames.BLOCK_BYPASS ), ATTR_SAFESEARCH: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL], ApiNames.SAFESEARCH ), ATTR_YOUTUBE_RESTRICTED_MODE: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL], ApiNames.YOUTUBE_RESTRICTED_MODE ), ParentalControlServicesAttrs.BLOCK_TIKTOK: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.TIKTOK ), ParentalControlServicesAttrs.BLOCK_TINDER: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.TINDER ), ParentalControlServicesAttrs.BLOCK_FACEBOOK: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.FACEBOOK ), ParentalControlServicesAttrs.BLOCK_SNAPCHAT: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.SNAPCHAT ), ParentalControlServicesAttrs.BLOCK_INSTAGRAM: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.INSTAGRAM ), ParentalControlServicesAttrs.BLOCK_FORTNITE: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.FORTNITE ), ParentalControlServicesAttrs.BLOCK_MESSENGER: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.MESSENGER ), ParentalControlServicesAttrs.BLOCK_LEAGUEOFLEGENDS: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.LEAGUEOFLEGENDS, ), ParentalControlServicesAttrs.BLOCK_VK: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.VK ), ParentalControlServicesAttrs.BLOCK_9GAG: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.NINEGAG ), ParentalControlServicesAttrs.BLOCK_TUMBLR: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.TUMBLR ), ParentalControlServicesAttrs.BLOCK_ROBLOX: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.ROBLOX ), ParentalControlServicesAttrs.BLOCK_TWITCH: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.TWITCH ), ParentalControlServicesAttrs.BLOCK_MINECRAFT: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.MINECRAFT ), ParentalControlServicesAttrs.BLOCK_TWITTER: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.TWITTER ), ParentalControlServicesAttrs.BLOCK_DISCORD: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.DISCORD ), ParentalControlServicesAttrs.BLOCK_DAILYMOTION: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.DAILYMOTION ), ParentalControlServicesAttrs.BLOCK_PINTEREST: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.PINTEREST ), ParentalControlServicesAttrs.BLOCK_YOUTUBE: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.YOUTUBE ), ParentalControlServicesAttrs.BLOCK_STEAM: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.STEAM ), ParentalControlServicesAttrs.BLOCK_HULU: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.HULU ), ParentalControlServicesAttrs.BLOCK_WHATSAPP: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.WHATSAPP ), ParentalControlServicesAttrs.BLOCK_REDDIT: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.REDDIT ), ParentalControlServicesAttrs.BLOCK_BLIZZARD: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.BLIZZARD ), ParentalControlServicesAttrs.BLOCK_NETFLIX: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.NETFLIX ), ParentalControlServicesAttrs.BLOCK_IMGUR: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.IMGUR ), ParentalControlServicesAttrs.BLOCK_TELEGRAM: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.TELEGRAM ), ParentalControlServicesAttrs.BLOCK_DISNEYPLUS: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.DISNEYPLUS ), ParentalControlServicesAttrs.BLOCK_VIMEO: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.VIMEO ), ParentalControlServicesAttrs.BLOCK_SKYPE: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.SKYPE, ), ParentalControlServicesAttrs.BLOCK_EBAY: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.EBAY ), ParentalControlServicesAttrs.BLOCK_SPOTIFY: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.SPOTIFY ), ParentalControlServicesAttrs.BLOCK_PRIMEVIDEO: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.PRIMEVIDEO ), ParentalControlServicesAttrs.BLOCK_ZOOM: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.ZOOM ), ParentalControlServicesAttrs.BLOCK_AMAZON: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.AMAZON ), ParentalControlServicesAttrs.BLOCK_XBOXLIVE: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.XBOXLIVE ), ParentalControlServicesAttrs.BLOCK_SIGNAL: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.SIGNAL ), ParentalControlServicesAttrs.BLOCK_BEREAL: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.BEREAL ), ParentalControlServicesAttrs.BLOCK_GOOGLE_CHAT: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.GOOGLE_CHAT ), ParentalControlServicesAttrs.BLOCK_CHATGPT: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.CHATGPT ), ParentalControlServicesAttrs.BLOCK_HBOMAX: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.HBOMAX ), ParentalControlServicesAttrs.BLOCK_MASTODON: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.MASTODON ), ParentalControlServicesAttrs.BLOCK_PLAYSTATION_NETWORK: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICE], ParentalControlServices.PLAYSTATION_NETWORK, ), ParentalControlCategoriesAttrs.BLOCK_DATING: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORY], ParentalControlCategories.DATING ), ParentalControlCategoriesAttrs.BLOCK_GAMBLING: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORY], ParentalControlCategories.GAMBLING ), ParentalControlCategoriesAttrs.BLOCK_PIRACY: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORY], ParentalControlCategories.PIRACY ), ParentalControlCategoriesAttrs.BLOCK_PORN: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORY], ParentalControlCategories.PORN ), ParentalControlCategoriesAttrs.BLOCK_SOCIAL_NETWORKS: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORY], ParentalControlCategories.SOCIAL_NETWORKS, ), ParentalControlCategoriesAttrs.BLOCK_VIDEO_STREAMING: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORY], ParentalControlCategories.VIDEO_STREAMING, ), ParentalControlCategoriesAttrs.BLOCK_ONLINE_GAMING: SettingDescription( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORY], ParentalControlCategories.ONLINE_GAMING, ), } ALLOWED_LOGS_LOCATION = ("ch", "eu", "gb", "us") ALLOWED_LOGS_RETENTION = (1, 6, 24, 168, 720, 2160, 4320, 8760, 17520) TIMEOUT = ClientTimeout(total=5) STOP_AFTER_ATTEMPT = 3 WAIT_INCREMENT = 2 WAIT_START = 2 HTTP_STATUS_TIMEOUT = 524 nextdns-3.3.0/nextdns/exceptions.py000066400000000000000000000013141466755272500174400ustar00rootroot00000000000000"""NextDNS exceptions.""" class NextDnsError(Exception): """Base class for nextdns errors.""" class InvalidApiKeyError(NextDnsError): """Raised to indicate invalid API key error.""" class ApiError(NextDnsError): """Raised to indicate API error.""" def __init__(self, status: str) -> None: """Initialize.""" super().__init__(status) self.status = status class ProfileIdNotFoundError(NextDnsError): """Raised to indicate profile ID not found error.""" class ProfileNameNotFoundError(NextDnsError): """Raised to indicate profile name not found error.""" class SettingNotSupportedError(NextDnsError): """Raised to indicate setting not supported error.""" nextdns-3.3.0/nextdns/model.py000066400000000000000000000260051466755272500163630ustar00rootroot00000000000000"""Type definitions for NextDNS.""" from __future__ import annotations from dataclasses import dataclass from enum import StrEnum from typing import Any @dataclass class NextDnsData: """NextDNS data class.""" @dataclass class AnalyticsStatus(NextDnsData): """AnalyticsStatus class.""" all_queries: int = 0 allowed_queries: int = 0 blocked_queries: int = 0 default_queries: int = 0 relayed_queries: int = 0 blocked_queries_ratio: float = 0 def __post_init__(self) -> None: """Call after initialization.""" self.all_queries = sum( [ self.default_queries, self.blocked_queries, self.allowed_queries, self.relayed_queries, ] ) self.blocked_queries_ratio = ( 0 if not self.all_queries else round(self.blocked_queries / self.all_queries * 100, 1) ) @dataclass class AnalyticsDnssec(NextDnsData): """AnalyticsDnssec class.""" not_validated_queries: int = 0 validated_queries: int = 0 validated_queries_ratio: float = 0 def __post_init__(self) -> None: """Call after initialization.""" all_queries = sum([self.validated_queries, self.not_validated_queries]) self.validated_queries_ratio = ( 0 if not all_queries else round(self.validated_queries / all_queries * 100, 1) ) @dataclass class AnalyticsEncryption(NextDnsData): """AnalyticsEncryption class.""" encrypted_queries: int = 0 unencrypted_queries: int = 0 encrypted_queries_ratio: float = 0 def __post_init__(self) -> None: """Call after initialization.""" all_queries = sum([self.encrypted_queries, self.unencrypted_queries]) self.encrypted_queries_ratio = ( 0 if not all_queries else round(self.encrypted_queries / all_queries * 100, 1) ) @dataclass class AnalyticsIpVersions(NextDnsData): """AnalyticsIpVersions class.""" ipv6_queries: int = 0 ipv4_queries: int = 0 ipv6_queries_ratio: float = 0 def __post_init__(self) -> None: """Call after initialization.""" all_queries = sum([self.ipv6_queries, self.ipv4_queries]) self.ipv6_queries_ratio = ( 0 if not all_queries else round(self.ipv6_queries / all_queries * 100, 1) ) @dataclass class AnalyticsProtocols(NextDnsData): """AnalyticsProtocols class.""" doh_queries: int = 0 doh3_queries: int = 0 doq_queries: int = 0 dot_queries: int = 0 tcp_queries: int = 0 udp_queries: int = 0 doh_queries_ratio: float = 0 doh3_queries_ratio: float = 0 doq_queries_ratio: float = 0 dot_queries_ratio: float = 0 tcp_queries_ratio: float = 0 udp_queries_ratio: float = 0 def __post_init__(self) -> None: """Call after initialization.""" all_queries = sum( [ self.doh_queries, self.doh3_queries, self.doq_queries, self.dot_queries, self.tcp_queries, self.udp_queries, ] ) self.doh_queries_ratio = ( 0 if not all_queries else round(self.doh_queries / all_queries * 100, 1) ) self.doh3_queries_ratio = ( 0 if not all_queries else round(self.doh3_queries / all_queries * 100, 1) ) self.doq_queries_ratio = ( 0 if not all_queries else round(self.doq_queries / all_queries * 100, 1) ) self.dot_queries_ratio = ( 0 if not all_queries else round(self.dot_queries / all_queries * 100, 1) ) self.tcp_queries_ratio = ( 0 if not all_queries else round(self.tcp_queries / all_queries * 100, 1) ) self.udp_queries_ratio = ( 0 if not all_queries else round(self.udp_queries / all_queries * 100, 1) ) @dataclass class AllAnalytics(NextDnsData): """AllAnalytics class.""" dnssec: AnalyticsDnssec encryption: AnalyticsEncryption ip_versions: AnalyticsIpVersions protocols: AnalyticsProtocols status: AnalyticsStatus @dataclass class Profile(NextDnsData): """Profile class.""" allowlist: list[dict[str, Any]] denylist: list[dict[str, Any]] fingerprint: str id: str name: str parental_control: dict[str, Any] privacy: dict[str, Any] rewrites: list security: dict[str, Any] settings: dict[str, Any] setup: dict[str, Any] @dataclass class Settings(NextDnsData): """Settings class.""" block_page: bool cache_boost: bool cname_flattening: bool anonymized_ecs: bool logs: bool logs_location: str logs_retention: int web3: bool allow_affiliate: bool block_disguised_trackers: bool ai_threat_detection: bool block_csam: bool block_ddns: bool block_nrd: bool block_parked_domains: bool cryptojacking_protection: bool dga_protection: bool dns_rebinding_protection: bool google_safe_browsing: bool idn_homograph_attacks_protection: bool threat_intelligence_feeds: bool typosquatting_protection: bool block_bypass_methods: bool safesearch: bool youtube_restricted_mode: bool block_9gag: bool block_amazon: bool block_bereal: bool block_blizzard: bool block_chatgpt: bool block_dailymotion: bool block_discord: bool block_disneyplus: bool block_ebay: bool block_facebook: bool block_fortnite: bool block_google_chat: bool block_hbomax: bool block_hulu: bool block_imgur: bool block_instagram: bool block_leagueoflegends: bool block_mastodon: bool block_messenger: bool block_minecraft: bool block_netflix: bool block_pinterest: bool block_playstation_network: bool block_primevideo: bool block_reddit: bool block_roblox: bool block_signal: bool block_skype: bool block_snapchat: bool block_spotify: bool block_steam: bool block_telegram: bool block_tiktok: bool block_tinder: bool block_tumblr: bool block_twitch: bool block_twitter: bool block_vimeo: bool block_vk: bool block_whatsapp: bool block_xboxlive: bool block_youtube: bool block_zoom: bool block_dating: bool block_gambling: bool block_piracy: bool block_porn: bool block_social_networks: bool block_online_gaming: bool block_video_streaming: bool @dataclass class ProfileInfo(NextDnsData): """ProfileInfo class.""" id: str fingerprint: str name: str @dataclass class ConnectionStatus(NextDnsData): """ConnectionStatus class.""" connected: bool profile_id: str | None = None class ParentalControlServices(StrEnum): """Service type for parental control.""" AMAZON = "amazon" BEREAL = "bereal" BLIZZARD = "blizzard" CHATGPT = "chatgpt" DAILYMOTION = "dailymotion" DISCORD = "discord" DISNEYPLUS = "disneyplus" EBAY = "ebay" FACEBOOK = "facebook" FORTNITE = "fortnite" GOOGLE_CHAT = "google-chat" HBOMAX = "hbomax" HULU = "hulu" IMGUR = "imgur" INSTAGRAM = "instagram" LEAGUEOFLEGENDS = "leagueoflegends" MASTODON = "mastodon" MESSENGER = "messenger" MINECRAFT = "minecraft" NETFLIX = "netflix" NINEGAG = "9gag" PINTEREST = "pinterest" PLAYSTATION_NETWORK = "playstation-network" PRIMEVIDEO = "primevideo" REDDIT = "reddit" ROBLOX = "roblox" SIGNAL = "signal" SKYPE = "skype" SNAPCHAT = "snapchat" SPOTIFY = "spotify" STEAM = "steam" TELEGRAM = "telegram" TIKTOK = "tiktok" TINDER = "tinder" TUMBLR = "tumblr" TWITCH = "twitch" TWITTER = "twitter" VIMEO = "vimeo" VK = "vk" WHATSAPP = "whatsapp" XBOXLIVE = "xboxlive" YOUTUBE = "youtube" ZOOM = "zoom" class ParentalControlServicesAttrs(StrEnum): """Service type attributes for parental control.""" BLOCK_9GAG = "block_9gag" BLOCK_AMAZON = "block_amazon" BLOCK_BEREAL = "block_bereal" BLOCK_BLIZZARD = "block_blizzard" BLOCK_CHATGPT = "block_chatgpt" BLOCK_DAILYMOTION = "block_dailymotion" BLOCK_DISCORD = "block_discord" BLOCK_DISNEYPLUS = "block_disneyplus" BLOCK_EBAY = "block_ebay" BLOCK_FACEBOOK = "block_facebook" BLOCK_FORTNITE = "block_fortnite" BLOCK_GOOGLE_CHAT = "block_google_chat" BLOCK_HBOMAX = "block_hbomax" BLOCK_HULU = "block_hulu" BLOCK_IMGUR = "block_imgur" BLOCK_INSTAGRAM = "block_instagram" BLOCK_LEAGUEOFLEGENDS = "block_leagueoflegends" BLOCK_MASTODON = "block_mastodon" BLOCK_MESSENGER = "block_messenger" BLOCK_MINECRAFT = "block_minecraft" BLOCK_NETFLIX = "block_netflix" BLOCK_PINTEREST = "block_pinterest" BLOCK_PLAYSTATION_NETWORK = "block_playstation_network" BLOCK_PRIMEVIDEO = "block_primevideo" BLOCK_REDDIT = "block_reddit" BLOCK_ROBLOX = "block_roblox" BLOCK_SIGNAL = "block_signal" BLOCK_SKYPE = "block_skype" BLOCK_SNAPCHAT = "block_snapchat" BLOCK_SPOTIFY = "block_spotify" BLOCK_STEAM = "block_steam" BLOCK_TELEGRAM = "block_telegram" BLOCK_TIKTOK = "block_tiktok" BLOCK_TINDER = "block_tinder" BLOCK_TUMBLR = "block_tumblr" BLOCK_TWITCH = "block_twitch" BLOCK_TWITTER = "block_twitter" BLOCK_VIMEO = "block_vimeo" BLOCK_VK = "block_vk" BLOCK_WHATSAPP = "block_whatsapp" BLOCK_XBOXLIVE = "block_xboxlive" BLOCK_YOUTUBE = "block_youtube" BLOCK_ZOOM = "block_zoom" class ParentalControlCategories(StrEnum): """Categories type for parental control.""" DATING = "dating" GAMBLING = "gambling" ONLINE_GAMING = "gaming" PIRACY = "piracy" PORN = "porn" SOCIAL_NETWORKS = "social-networks" VIDEO_STREAMING = "video-streaming" class ParentalControlCategoriesAttrs(StrEnum): """Categories type attributes for parental control.""" BLOCK_VIDEO_STREAMING = "block_video_streaming" BLOCK_SOCIAL_NETWORKS = "block_social_networks" BLOCK_PORN = "block_porn" BLOCK_PIRACY = "block_piracy" BLOCK_ONLINE_GAMING = "block_online_gaming" BLOCK_GAMBLING = "block_gambling" BLOCK_DATING = "block_dating" class ApiNames(StrEnum): """Names type for API.""" AI_THREAT_TETECTION = "aiThreatDetection" ALLOW_AFFILIATE = "allowAffiliate" BLOCK_BYPASS = "blockBypass" CACHE_BOOST = "cacheBoost" CATEGORIES = "categories" CNAME_FLATTENING = "cnameFlattening" CRYPTOJACKING = "cryptojacking" CSAM = "csam" DDNS = "ddns" DGA = "dga" DISGUISED_TRACKERS = "disguisedTrackers" DNS_REBINDING = "dnsRebinding" ECS = "ecs" GOOGLE_SAFE_BROWSING = "googleSafeBrowsing" IDN_HOMOGRAPHS = "idnHomographs" NRD = "nrd" PARKING = "parking" SAFESEARCH = "safeSearch" SERVICES = "services" THREAT_INTELLIGENCE_FEEDS = "threatIntelligenceFeeds" TYPOSQUATTING = "typosquatting" YOUTUBE_RESTRICTED_MODE = "youtubeRestrictedMode" @dataclass class SettingDescription: """SettingDescription class.""" url: str name: str nextdns-3.3.0/nextdns/py.typed000066400000000000000000000000001466755272500163730ustar00rootroot00000000000000nextdns-3.3.0/pyproject.toml000066400000000000000000000037741466755272500161520ustar00rootroot00000000000000[tool.pytest.ini_options] asyncio_mode = "strict" [tool.mypy] python_version = "3.12" show_error_codes = true follow_imports = "silent" ignore_missing_imports = true warn_incomplete_stub = true warn_redundant_casts = true warn_unused_configs = true check_untyped_defs = true disallow_incomplete_defs = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = false disallow_untyped_defs = true no_implicit_optional = true strict_equality = true warn_return_any = true warn_unused_ignores = true warn_unreachable = true [tool.ruff] target-version = "py312" lint.select = ["ALL"] lint.ignore = [ "ANN101", # Missing type annotation for `self` in method "ANN102", # Missing type annotation for `cls` in classmethod "ANN201", # Missing return type annotation for public function "ANN401", # Dynamically typed expressions (typing.Any) are disallowed "COM812", # Trailing comma missing "D203", # 1 blank line required before class docstring "D213", # Multi-line docstring summary should start at the second line "EM101", # Exception must not use a string literal, assign to variable first "EM102", # Exception must not use an f-string literal, assign to variable first "FBT001", # Boolean positional arg in function definition "ISC001", # Single line implicit string concatenation "PLR0915", # Too many statements "TCH002", # Move third-party import into a type-checking block "TCH003", # Move standard library import into a type-checking block "TRY003", # Avoid specifying long messages outside the exception class ] [tool.ruff.lint.per-file-ignores] "tests/*" = [ "FBT003", # Boolean positional value in function call "PLR2004", # Magic value used in comparison "S101", # Use of `assert` detected ] "example.py" = [ "ERA001", # Found commented-out code "T201", # `print` found ] [tool.ruff.lint.mccabe] max-complexity = 25 [tool.coverage.run] source = ["nextdns"] nextdns-3.3.0/requirements-dev.txt000066400000000000000000000001051466755272500172570ustar00rootroot00000000000000-r requirements.txt -r requirements-test.txt pre-commit==3.8.0 -e . nextdns-3.3.0/requirements-test.txt000066400000000000000000000002661466755272500174700ustar00rootroot00000000000000aioresponses==0.7.6 coverage==7.6.1 mypy==1.11.2 pytest-asyncio==0.24.0 pytest-cov==5.0.0 pytest-error-for-skips==2.0.2 pytest-timeout==2.3.1 pytest==8.3.2 ruff==0.6.3 syrupy==4.7.1 nextdns-3.3.0/requirements.txt000066400000000000000000000000301466755272500165000ustar00rootroot00000000000000aiohttp>=3.7.0 tenacity nextdns-3.3.0/scripts/000077500000000000000000000000001466755272500147125ustar00rootroot00000000000000nextdns-3.3.0/scripts/setup-devcontainer-env.sh000077500000000000000000000002321466755272500216530ustar00rootroot00000000000000#!/bin/bash pip install --upgrade pip setuptools wheel pip --disable-pip-version-check --no-cache-dir install -r requirements-dev.txt pre-commit install nextdns-3.3.0/scripts/setup-local-env.sh000077500000000000000000000003621466755272500202700ustar00rootroot00000000000000#!/bin/bash PYTHON_VERSION=3.12 python$PYTHON_VERSION -m pip install uv python$PYTHON_VERSION -m uv venv venv --seed --python=$PYTHON_VERSION source venv/bin/activate pip install uv uv pip install -r requirements-dev.txt pre-commit install nextdns-3.3.0/setup.py000066400000000000000000000021731466755272500147400ustar00rootroot00000000000000"""Setup module for nextdns.""" from pathlib import Path from setuptools import setup PROJECT_DIR = Path(__file__).parent.resolve() README_FILE = PROJECT_DIR / "README.md" VERSION = "3.3.0" setup( name="nextdns", version=VERSION, author="Maciej Bieniek", description="Python wrapper for NextDNS API.", long_description=README_FILE.read_text(encoding="utf-8"), long_description_content_type="text/markdown", include_package_data=True, url="https://github.com/bieniu/nextdns", license="Apache-2.0 License", packages=["nextdns"], package_data={"nextdns": ["py.typed"]}, python_requires=">=3.11", install_requires=["aiohttp>=3.7.0"], classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3 :: Only", "Typing :: Typed", ], ) nextdns-3.3.0/tests/000077500000000000000000000000001466755272500143655ustar00rootroot00000000000000nextdns-3.3.0/tests/__init__.py000066400000000000000000000000411466755272500164710ustar00rootroot00000000000000"""Tests for nextdns package.""" nextdns-3.3.0/tests/conftest.py000066400000000000000000000017531466755272500165720ustar00rootroot00000000000000"""Set up some common test helper things.""" import json from pathlib import Path from typing import Any import pytest from syrupy.assertion import SnapshotAssertion from syrupy.extensions.amber import AmberSnapshotExtension from syrupy.location import PyTestLocation @pytest.fixture def profiles_data() -> dict[str, Any]: """Return the profiles data from the fixture file.""" with Path.open("tests/fixtures/profiles.json", encoding="utf-8") as file: return json.load(file) @pytest.fixture def snapshot(snapshot: SnapshotAssertion) -> SnapshotAssertion: """Return snapshot assertion fixture.""" return snapshot.use_extension(SnapshotExtension) class SnapshotExtension(AmberSnapshotExtension): """Extension for Syrupy.""" @classmethod def dirname(cls, *, test_location: PyTestLocation) -> str: """Return the directory for the snapshot files.""" test_dir = Path(test_location.filepath).parent return str(test_dir.joinpath("snapshots")) nextdns-3.3.0/tests/fixtures/000077500000000000000000000000001466755272500162365ustar00rootroot00000000000000nextdns-3.3.0/tests/fixtures/dnssec.json000066400000000000000000000004151466755272500204100ustar00rootroot00000000000000{ "data": [ { "validated": false, "queries": 793765 }, { "validated": true, "queries": 49451 } ], "meta": { "pagination": { "cursor": null } } } nextdns-3.3.0/tests/fixtures/encryption.json000066400000000000000000000004131466755272500213210ustar00rootroot00000000000000{ "data": [ { "encrypted": true, "queries": 1380260 }, { "encrypted": false, "queries": 40 } ], "meta": { "pagination": { "cursor": null } } } nextdns-3.3.0/tests/fixtures/ip_versions.json000066400000000000000000000004031466755272500214660ustar00rootroot00000000000000{ "data": [ { "version": 4, "queries": 1338183 }, { "version": 6, "queries": 42117 } ], "meta": { "pagination": { "cursor": null } } } nextdns-3.3.0/tests/fixtures/logs.csv000066400000000000000000000007051466755272500177210ustar00rootroot00000000000000timestamp,domain,query_type,dnssec,protocol,client_ip,status,reasons,destination_country,root_domain,device_id,device_name,device_model,device_local_ip,matched_name,client_name 2022-11-14T18:15:04.122893+00:00,sync-1-us-west1-g.sync.services.mozilla.com,A,false,DNS-over-TLS,10.10.10.10,,,US,mozilla.com,8M05S,"Client",,,, 2022-11-14T18:15:04.11827+00:00,profile.accounts.firefox.com,A,false,DNS-over-TLS,10.10.10.10,,,US,firefox.com,8M05S,"Client",,,, nextdns-3.3.0/tests/fixtures/profile.json000066400000000000000000000061171466755272500205760ustar00rootroot00000000000000{ "data": { "id": "fakepr", "fingerprint": "fakeprofile12", "name": "Fake Profile", "setup": { "ipv4": [], "ipv6": [], "linkedIp": { "servers": [ "0.0.0.0", "0.0.0.0" ], "ip": "0.0.0.0", "ddns": null, "updateToken": "xxyyzz12345" }, "dnscrypt": "sdns://zxy123" }, "security": { "threatIntelligenceFeeds": true, "aiThreatDetection": true, "googleSafeBrowsing": true, "cryptojacking": true, "dnsRebinding": true, "idnHomographs": true, "typosquatting": true, "dga": true, "nrd": true, "ddns": true, "parking": true, "csam": true, "tlds": [] }, "privacy": { "disguisedTrackers": true, "allowAffiliate": true, "blocklists": [], "natives": [ { "id": "samsung" }, { "id": "huawei" }, { "id": "alexa" }, { "id": "windows" }, { "id": "apple" }, { "id": "roku" }, { "id": "sonos" } ] }, "parentalControl": { "safeSearch": false, "youtubeRestrictedMode": false, "blockBypass": true, "services": [], "categories": [ { "id": "porn", "recreation": false, "active": true }, { "id": "gambling", "recreation": false, "active": true }, { "id": "dating", "recreation": false, "active": true }, { "id": "piracy", "recreation": false, "active": true } ], "recreation": { "times": {}, "timezone": null } }, "settings": { "logs": { "enabled": true, "drop": { "ip": false, "domain": false }, "retention": 2592000, "location": "ch" }, "blockPage": { "enabled": false }, "performance": { "ecs": true, "cacheBoost": true, "cnameFlattening": true }, "web3": true }, "denylist": [], "allowlist": [], "rewrites": [] } } nextdns-3.3.0/tests/fixtures/profiles.json000066400000000000000000000002271466755272500207550ustar00rootroot00000000000000{ "data": [ { "id": "fakepr", "fingerprint": "fakeprofile12", "name": "Fake Profile" } ] } nextdns-3.3.0/tests/fixtures/protocols.json000066400000000000000000000011721466755272500211560ustar00rootroot00000000000000{ "data": [ { "protocol": "DNS-over-TLS", "queries": 101010 }, { "protocol": "DNS-over-HTTPS", "queries": 99999 }, { "protocol": "DNS-over-HTTP/3", "queries": 88888 }, { "protocol": "DNS-over-QUIC", "queries": 55555 }, { "protocol": "UDP", "queries": 44444 }, { "protocol": "TCP", "queries": 33333 } ], "meta": { "pagination": { "cursor": null } } } nextdns-3.3.0/tests/fixtures/status.json000066400000000000000000000006651466755272500204630ustar00rootroot00000000000000{ "data": [ { "status": "default", "queries": 837764 }, { "status": "blocked", "queries": 530805 }, { "status": "relayed", "queries": 6279 }, { "status": "allowed", "queries": 5452 } ], "meta": { "pagination": { "cursor": null } } } nextdns-3.3.0/tests/fixtures/test.json000066400000000000000000000004461466755272500201140ustar00rootroot00000000000000{ "status": "ok", "protocol": "DOT", "profile": "fakeprofile12", "client": "0.0.0.0", "srcIP": "0.0.0.0", "destIP": "0.0.0.0", "anycast": true, "server": "server-name", "clientName": "unknown-dot", "deviceName": "client-name", "deviceID": "XXYYZZ" } nextdns-3.3.0/tests/snapshots/000077500000000000000000000000001466755272500164075ustar00rootroot00000000000000nextdns-3.3.0/tests/snapshots/test_init.ambr000066400000000000000000000055121466755272500212570ustar00rootroot00000000000000# serializer version: 1 # name: test_valid_data NextDns( profiles=list([ ProfileInfo(id='fakepr', fingerprint='fakeprofile12', name='Fake Profile'), ]), ) # --- # name: test_valid_data.1 AllAnalytics(dnssec=AnalyticsDnssec(not_validated_queries=793765, validated_queries=49451, validated_queries_ratio=5.9), encryption=AnalyticsEncryption(encrypted_queries=1380260, unencrypted_queries=40, encrypted_queries_ratio=100.0), ip_versions=AnalyticsIpVersions(ipv6_queries=42117, ipv4_queries=1338183, ipv6_queries_ratio=3.1), protocols=AnalyticsProtocols(doh_queries=99999, doh3_queries=88888, doq_queries=55555, dot_queries=101010, tcp_queries=33333, udp_queries=44444, doh_queries_ratio=23.6, doh3_queries_ratio=21.0, doq_queries_ratio=13.1, dot_queries_ratio=23.9, tcp_queries_ratio=7.9, udp_queries_ratio=10.5), status=AnalyticsStatus(all_queries=1380300, allowed_queries=5452, blocked_queries=530805, default_queries=837764, relayed_queries=6279, blocked_queries_ratio=38.5)) # --- # name: test_valid_data.2 ConnectionStatus(connected=True, profile_id='fakepr') # --- # name: test_valid_data.3 Settings(block_page=False, cache_boost=True, cname_flattening=True, anonymized_ecs=True, logs=True, logs_location='ch', logs_retention=720, web3=True, allow_affiliate=True, block_disguised_trackers=True, ai_threat_detection=True, block_csam=True, block_ddns=True, block_nrd=True, block_parked_domains=True, cryptojacking_protection=True, dga_protection=True, dns_rebinding_protection=True, google_safe_browsing=True, idn_homograph_attacks_protection=True, threat_intelligence_feeds=True, typosquatting_protection=True, block_bypass_methods=True, safesearch=False, youtube_restricted_mode=False, block_9gag=False, block_amazon=False, block_bereal=False, block_blizzard=False, block_chatgpt=False, block_dailymotion=False, block_discord=False, block_disneyplus=False, block_ebay=False, block_facebook=False, block_fortnite=False, block_google_chat=False, block_hbomax=False, block_hulu=False, block_imgur=False, block_instagram=False, block_leagueoflegends=False, block_mastodon=False, block_messenger=False, block_minecraft=False, block_netflix=False, block_pinterest=False, block_playstation_network=False, block_primevideo=False, block_reddit=False, block_roblox=False, block_signal=False, block_skype=False, block_snapchat=False, block_spotify=False, block_steam=False, block_telegram=False, block_tiktok=False, block_tinder=False, block_tumblr=False, block_twitch=False, block_twitter=False, block_vimeo=False, block_vk=False, block_whatsapp=False, block_xboxlive=False, block_youtube=False, block_zoom=False, block_dating=True, block_gambling=True, block_piracy=True, block_porn=True, block_social_networks=False, block_online_gaming=False, block_video_streaming=False) # --- # name: test_valid_data.4 'Fake Profile' # --- # name: test_valid_data.5 'fakepr' # --- nextdns-3.3.0/tests/test_init.py000066400000000000000000000364531466755272500167540ustar00rootroot00000000000000"""Tests for nextdns package.""" import json import re from http import HTTPStatus from pathlib import Path from typing import Any from unittest.mock import Mock, patch import aiohttp import pytest from aioresponses import aioresponses from syrupy import SnapshotAssertion from tenacity import RetryError from nextdns import ( ATTR_ANALYTICS, ATTR_CLEAR_LOGS, ATTR_GET_LOGS, ATTR_LOGS, ATTR_PARENTAL_CONTROL_CATEGORIES, ATTR_PARENTAL_CONTROL_SERVICES, ATTR_PROFILE, ATTR_PROFILES, ATTR_TEST, ENDPOINTS, MAP_SETTING, ApiError, InvalidApiKeyError, NextDns, ProfileIdNotFoundError, ProfileNameNotFoundError, SettingNotSupportedError, ) from nextdns.const import ATTR_BLOCK_PAGE PROFILE_ID = "fakepr" @pytest.mark.asyncio async def test_valid_data( snapshot: SnapshotAssertion, profiles_data: dict[str, Any] ) -> None: """Test with valid data.""" with Path.open("tests/fixtures/dnssec.json", encoding="utf-8") as file: dnssec_data = json.load(file) with Path.open("tests/fixtures/encryption.json", encoding="utf-8") as file: encryption_data = json.load(file) with Path.open("tests/fixtures/ip_versions.json", encoding="utf-8") as file: ip_versions_data = json.load(file) with Path.open("tests/fixtures/protocols.json", encoding="utf-8") as file: protocols_data = json.load(file) with Path.open("tests/fixtures/status.json", encoding="utf-8") as file: status_data = json.load(file) with Path.open("tests/fixtures/test.json", encoding="utf-8") as file: test_data = json.load(file) with Path.open("tests/fixtures/profile.json", encoding="utf-8") as file: profile_data = json.load(file) session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.get( ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="dnssec"), payload=dnssec_data, ) session_mock.get( ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="encryption"), payload=encryption_data, ) session_mock.get( ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="ipVersions"), payload=ip_versions_data, ) session_mock.get( ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="protocols"), payload=protocols_data, ) session_mock.get( ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="status"), payload=status_data, ) session_mock.get( ENDPOINTS[ATTR_TEST].format(profile_id=PROFILE_ID), payload=test_data ) session_mock.get( ENDPOINTS[ATTR_PROFILE].format(profile_id=PROFILE_ID), payload=profile_data ) nextdns = await NextDns.create(session, "fakeapikey") analytics = await nextdns.get_all_analytics(PROFILE_ID) connection_status = await nextdns.connection_status(PROFILE_ID) settings = await nextdns.get_settings(PROFILE_ID) await session.close() assert nextdns == snapshot assert analytics == snapshot assert connection_status == snapshot assert settings == snapshot assert nextdns.get_profile_name(PROFILE_ID) == snapshot assert nextdns.get_profile_id("Fake Profile") == snapshot @pytest.mark.asyncio async def test_profile_id_not_found(profiles_data: dict[str, Any]) -> None: """Test with wrong profile id.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) nextdns = await NextDns.create(session, "fakeapikey") await session.close() with pytest.raises(ProfileIdNotFoundError): nextdns.get_profile_name("xxyyxx") @pytest.mark.asyncio async def test_profile_name_not_found(profiles_data: dict[str, Any]) -> None: """Test with wrong name id.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) nextdns = await NextDns.create(session, "fakeapikey") await session.close() with pytest.raises(ProfileNameNotFoundError): nextdns.get_profile_id("Profile Name") @pytest.mark.asyncio async def test_clear_logs(profiles_data: dict[str, Any]) -> None: """Test clear_logs() method.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.delete( ENDPOINTS[ATTR_CLEAR_LOGS].format(profile_id=PROFILE_ID), status=HTTPStatus.NO_CONTENT.value, ) nextdns = await NextDns.create(session, "fakeapikey") result = await nextdns.clear_logs(PROFILE_ID) await session.close() assert result is True @pytest.mark.asyncio async def test_get_logs(profiles_data: dict[str, Any]) -> None: """Test get_logs() method.""" with Path.open("tests/fixtures/logs.csv", encoding="utf-8") as file: logs = file.read() session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.get( ENDPOINTS[ATTR_GET_LOGS].format(profile_id=PROFILE_ID), status=HTTPStatus.OK.value, payload=logs, ) nextdns = await NextDns.create(session, "fakeapikey") result = await nextdns.get_logs(PROFILE_ID) await session.close() assert result == logs @pytest.mark.asyncio @pytest.mark.parametrize( ("setting", "url"), [ ("block_page", ENDPOINTS[ATTR_BLOCK_PAGE].format(profile_id=PROFILE_ID)), ( "block_tinder", MAP_SETTING["block_tinder"].url.format( profile_id=PROFILE_ID, service=MAP_SETTING["block_tinder"].name ), ), ( "block_piracy", MAP_SETTING["block_piracy"].url.format( profile_id=PROFILE_ID, category=MAP_SETTING["block_piracy"].name ), ), ], ) async def test_set_setting( setting: str, url: str, profiles_data: dict[str, Any] ) -> None: """Test set_setting() method.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.patch(url, status=HTTPStatus.NO_CONTENT.value) nextdns = await NextDns.create(session, "fakeapikey") result = await nextdns.set_setting(PROFILE_ID, setting, True) await session.close() assert result is True @pytest.mark.asyncio async def test_set_parental_contrl_service(profiles_data: dict[str, Any]) -> None: """Test set_setting() method for parental control service.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.patch( MAP_SETTING["block_tinder"].url.format( profile_id=PROFILE_ID, service=MAP_SETTING["block_tinder"].name ), status=HTTPStatus.NOT_FOUND.value, payload={"errors": [{"code": "notFound"}]}, ) session_mock.post( ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICES].format(profile_id=PROFILE_ID), status=HTTPStatus.NO_CONTENT.value, ) nextdns = await NextDns.create(session, "fakeapikey") result = await nextdns.set_setting(PROFILE_ID, "block_tinder", True) await session.close() assert result is True @pytest.mark.asyncio async def test_set_parental_contrl_category(profiles_data: dict[str, Any]) -> None: """Test set_setting() method for parental control category.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.patch( MAP_SETTING["block_piracy"].url.format( profile_id=PROFILE_ID, category=MAP_SETTING["block_piracy"].name ), status=HTTPStatus.NOT_FOUND.value, payload={"errors": [{"code": "notFound"}]}, ) session_mock.post( ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORIES].format(profile_id=PROFILE_ID), status=HTTPStatus.NO_CONTENT.value, ) nextdns = await NextDns.create(session, "fakeapikey") result = await nextdns.set_setting(PROFILE_ID, "block_piracy", True) await session.close() assert result is True @pytest.mark.asyncio async def test_set_not_supported_setting(profiles_data: dict[str, Any]) -> None: """Test set_setting() method with not supported setting.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) nextdns = await NextDns.create(session, "fakeapikey") with pytest.raises(SettingNotSupportedError): await nextdns.set_setting(PROFILE_ID, "unsupported_setting", True) await session.close() @pytest.mark.asyncio async def test_invalid_api_key() -> None: """Test error when provided API key is invalid.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], status=HTTPStatus.FORBIDDEN.value) with pytest.raises(InvalidApiKeyError): await NextDns.create(session, "fakeapikey") await session.close() @pytest.mark.parametrize( "exception", [TimeoutError, aiohttp.ClientConnectorError(Mock(), Mock())] ) @pytest.mark.asyncio async def test_retry_error(exception: Exception) -> None: """Test retry error.""" session = aiohttp.ClientSession() with aioresponses() as session_mock, patch("asyncio.sleep") as sleep_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], exception=exception, repeat=True) with pytest.raises(RetryError) as exc: await NextDns.create(session, "fakeapikey") assert "RetryError" in str(exc.value) assert sleep_mock.call_count == 2 assert sleep_mock.call_args_list[0][0][0] == 2 assert sleep_mock.call_args_list[1][0][0] == 4 await session.close() @pytest.mark.parametrize( "exception", [TimeoutError, aiohttp.ClientConnectorError(Mock(), Mock())] ) @pytest.mark.asyncio async def test_retry_success( profiles_data: dict[str, Any], exception: Exception ) -> None: """Test retry which succeeded.""" session = aiohttp.ClientSession() with aioresponses() as session_mock, patch("asyncio.sleep") as sleep_mock: session_mock.get( ENDPOINTS[ATTR_PROFILES], exception=exception, ) session_mock.get( ENDPOINTS[ATTR_PROFILES], exception=exception, ) session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) await NextDns.create(session, "fakeapikey") assert sleep_mock.call_count == 2 assert sleep_mock.call_args_list[0][0][0] == 2 assert sleep_mock.call_args_list[1][0][0] == 4 await session.close() @pytest.mark.asyncio async def test_retry_after_524(profiles_data: dict[str, Any]) -> None: """Test retry after HTTP status code 524.""" session = aiohttp.ClientSession() with aioresponses() as session_mock, patch("asyncio.sleep") as sleep_mock: session_mock.get( ENDPOINTS[ATTR_PROFILES], status=524, payload="Timeout Error", ) session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) await NextDns.create(session, "fakeapikey") assert sleep_mock.call_count == 1 assert sleep_mock.call_args_list[0][0][0] == 2 await session.close() @pytest.mark.asyncio async def test_too_many_requests() -> None: """Test too many requests.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( ENDPOINTS[ATTR_PROFILES], status=429, ) with pytest.raises(ApiError, match=re.escape("Too many requests")): await NextDns.create(session, "fakeapikey") await session.close() @pytest.mark.asyncio async def test_error_with_html() -> None: """Test error status code with text/html error response.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( ENDPOINTS[ATTR_PROFILES], status=523, content_type="text/html", payload="origin is unreachable", ) with pytest.raises(ApiError, match=re.escape("Error code: 523")): await NextDns.create(session, "fakeapikey") await session.close() @pytest.mark.asyncio async def test_set_logs_retention(profiles_data: dict[str, Any]) -> None: """Test set_logs_retention() method.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.patch( ENDPOINTS[ATTR_LOGS].format(profile_id=PROFILE_ID), status=HTTPStatus.NO_CONTENT.value, ) nextdns = await NextDns.create(session, "fakeapikey") result = await nextdns.set_logs_retention(PROFILE_ID, 1) await session.close() assert result is True @pytest.mark.asyncio async def test_set_logs_retention_with_invalid_value( profiles_data: dict[str, Any], ) -> None: """Test set_logs_retention() method with invalid value.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) nextdns = await NextDns.create(session, "fakeapikey") await session.close() with pytest.raises( ValueError, match=re.escape( "Invalid logs retention value. " "Allowed values are: (1, 6, 24, 168, 720, 2160, 4320, 8760, 17520)" ), ): await nextdns.set_logs_retention(PROFILE_ID, 999) @pytest.mark.asyncio async def test_set_logs_location(profiles_data: dict[str, Any]) -> None: """Test set_logs_location() method.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) session_mock.patch( ENDPOINTS[ATTR_LOGS].format(profile_id=PROFILE_ID), status=HTTPStatus.NO_CONTENT.value, ) nextdns = await NextDns.create(session, "fakeapikey") result = await nextdns.set_logs_location(PROFILE_ID, "us") await session.close() assert result is True @pytest.mark.asyncio async def test_set_logs_location_with_invalid_value( profiles_data: dict[str, Any], ) -> None: """Test set_logs_location() method with invalid value.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data) nextdns = await NextDns.create(session, "fakeapikey") await session.close() with pytest.raises( ValueError, match=re.escape( "Invalid logs location value. Allowed values are: ('ch', 'eu', 'gb', 'us')" ), ): await nextdns.set_logs_location(PROFILE_ID, "pl") nextdns-3.3.0/tox.ini000066400000000000000000000014011466755272500145320ustar00rootroot00000000000000[tox] envlist = py311, py312, py313, lint, typing, coverage skip_missing_interpreters = True [gh-actions] python = 3.11: py311, lint, typing, coverage 3.12: py312 3.13.0-rc.1: py313 [testenv] commands = pytest --timeout=30 --cov=nextdns --cov-report=xml {posargs} --error-for-skips deps = -rrequirements.txt -rrequirements-test.txt [testenv:lint] basepython = python3 ignore_errors = True commands = ruff check . ruff format --check . deps = -rrequirements.txt -rrequirements-test.txt [testenv:typing] basepython = python3 ignore_errors = True commands = mypy nextdns deps = -rrequirements.txt -rrequirements-test.txt [testenv:coverage] deps = -rrequirements.txt -rrequirements-test.txt commands = coverage report --fail-under=79