### User Login Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Example of how to log in a user, providing callbacks for password and 2FA retrieval using `getpass`. ```python import getpass await controller.login( username="user@proton.me", get_password=getpass.getpass, get_2fa=lambda: getpass.getpass("2FA Token: ") ) ``` -------------------------------- ### Bash Examples for Connecting to VPN Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Provides various examples of how to connect to the Proton VPN using the CLI, including connecting to the fastest server, specific countries/cities, P2P, Secure Core, Tor, or a random server. ```bash # Fastest server globally protonvpn connect # Fastest server in United States protonvpn connect --country US # Fastest server in New York protonvpn connect --city "New York" # Fastest P2P server protonvpn connect --p2p # Fastest Secure Core server in specific country protonvpn connect --country DE --securecore # Random available server protonvpn connect --random # Specific server by ID protonvpn connect IT#23 ``` -------------------------------- ### Proton VPN CLI Integration Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md An example demonstrating the proper usage of core CLI utilities for asynchronous command execution, controller creation, connection, and exception handling. Ensure async event loop management and error reporting. ```python import asyncio from proton.vpn.cli.core.run_async import run_async from proton.vpn.cli.core.exception_handler import ExceptionHandler from proton.vpn.cli.core.controller import Controller @run_async async def cli_command(): try: controller = await Controller.create(params, ctx) result = await controller.connect(server) return result except Exception as e: ExceptionHandler.report_error(e) raise ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/README.md Install all required dependencies for the project within the activated virtual environment. ```shell pip install -r requirements.txt ``` -------------------------------- ### Full Configuration Flow Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Demonstrates initializing the controller, checking user tier, and enabling Kill Switch and NetShield features. ```python from proton.vpn.cli.core.controller import Controller, Params from proton.vpn.cli.commands.feature_setting_definitions import ( KILLSWITCH_FEATURE, NETSHIELD_FEATURE, ) # Initialize controller controller = await Controller.create( params=Params(verbose=True), click_ctx=click_context ) # Check user tier if controller.user_on_free_tier: print("Upgrade for advanced features") else: # Enable Kill Switch await controller.save_feature_setting( KILLSWITCH_FEATURE, KillSwitchState.ON ) # Enable NetShield with full protection await controller.save_feature_setting( NETSHIELD_FEATURE, NetShield.BLOCK_ADS_AND_TRACKING ) # Check current settings settings = await controller.get_settings() print(f"Kill Switch: {settings.features.killswitch}") print(f"NetShield: {settings.features.netshield}") ``` -------------------------------- ### Logging Configuration Setup Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md Illustrates the configuration of the logging system using `ProtonLogging.config`. This setup determines the log file name, directory, and whether to output logs to the console based on verbosity. ```python ProtonLogging.config( filename=LOGGING_FILENAME, logdirpath=LOGGING_DIR_PATH, log_to_console=params.verbose ) ``` -------------------------------- ### Bash Example for Account Info Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Demonstrates how to retrieve and display information about your currently logged-in Proton account using the CLI. ```bash protonvpn info # Output: Account: 'user@proton.me' ``` -------------------------------- ### Bash Example for User Signin Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Demonstrates how to sign in to your Proton account using the CLI. You will be prompted for your password and, if enabled, a 2FA token. ```bash protonvpn signin user@proton.me # Prompts: Enter password: # Prompts (if 2FA enabled): 2FA Token: # Output: Successfully signed in as 'user@proton.me' ``` -------------------------------- ### Bash Example for User Signout Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Shows how to log out of your Proton account and terminate the VPN session using the CLI. ```bash protonvpn signout # Output: You have been successfully signed out. ``` -------------------------------- ### Params Usage Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/types.md Demonstrates how to instantiate the Params data class with specific configurations for verbose logging and GUI concurrency. ```python from proton.vpn.cli.core.controller import Params params = Params(verbose=True, allow_gui_concurrency=False) ``` -------------------------------- ### Feature Usage Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/types.md Shows how to create a Feature instance, specifying the setting path, free tier availability, and whether a restart is needed for changes. ```python from proton.vpn.cli.core.controller import Feature feature = Feature( setting_path="features.killswitch", available_on_free_tier=False, requires_restart=True ) ``` -------------------------------- ### Initialize Controller with Parameters Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Initializes the main controller for the Proton VPN CLI. This example shows how to create a controller instance with specific parameters, including verbose logging and the current Click context. ```python from proton.vpn.cli.core.controller import Controller, Params import click ctx = click.get_current_context() controller = await Controller.create( params=Params(verbose=True), click_ctx=ctx ) ``` -------------------------------- ### CLI Command Invocation Examples Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/main.md Illustrates how to invoke various Proton VPN CLI commands from the command line. ```bash # The CLI is invoked via command line: # protonvpn signin user@proton.me # protonvpn connect --country US # protonvpn config list ``` -------------------------------- ### Main Function Usage Examples Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/main.md Demonstrates how to invoke the `main` function with default settings, custom arguments, or in a testing mode with a mock controller. ```python from proton.vpn.cli import main # Run with default settings main() # Run with custom arguments main(cli_args=['connect', '--country', 'US']) # Run in testing mode with a mock controller custom_controller = MyMockController() main(allow_concurrency=True, controller=custom_controller) ``` -------------------------------- ### ToggleType Examples Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/feature-settings.md Demonstrates the usage of the ToggleType class for converting between string and boolean representations, and for getting human-friendly state strings. ```python ToggleType.from_str("on") # → True ToggleType.from_str("off") # → False ToggleType.to_str(True) # → "on" ToggleType.to_str(False) # → "off" ToggleType.get_human_friendly_state_string(True) # → "enabled" ToggleType.get_human_friendly_state_string(False) # → "disabled" ``` -------------------------------- ### Get Feature Setting Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/feature-settings.md Retrieves the current state of a feature, such as the Kill Switch, using the controller. Requires importing the specific feature definition. ```python from proton.vpn.cli.commands.feature_setting_definitions import KILLSWITCH_FEATURE current_state = await controller.get_feature_setting(KILLSWITCH_FEATURE) print(f"Kill Switch: {KILLSWITCH_FEATURE.click_type.get_human_friendly_state_string(current_state)}") ``` -------------------------------- ### Get All Settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Retrieve a Settings object containing all current configuration values. ```python settings = await controller.get_settings() ``` -------------------------------- ### Get All VPN Settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Retrieve all current configuration settings for the VPN client. ```python # Get all settings settings = await controller.get_settings() ``` -------------------------------- ### Connect with Multiple Filters Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Connects to a server that matches multiple criteria, such as country and P2P optimization. This example connects to the fastest P2P server in the US. ```bash protonvpn connect --country US --p2p ``` -------------------------------- ### ToggleType Example Usage Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/types.md Demonstrates how to instantiate and use the ToggleType methods for string conversions and list retrieval. ```python click_type = ToggleType() print(click_type.to_list_of_str()) # ["off", "on"] print(click_type.from_str("on")) # True print(click_type.to_str(True)) # "on" ``` -------------------------------- ### Example Usage of CLI Constants Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md Demonstrates how to import and use the defined CLI constants, such as `PROGRAM_NAME` and `LOGGING_DIR_PATH`, for displaying program information and log locations. ```python from proton.vpn.cli._cli_constants import PROGRAM_NAME, LOGGING_DIR_PATH print(f"Running: {PROGRAM_NAME}") print(f"Logs at: {LOGGING_DIR_PATH}") ``` -------------------------------- ### CustomDNSType Output Examples Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/feature-settings.md Illustrates the output of CustomDNSType.to_str with different CustomDNS inputs. ```python CustomDNSType.to_str(CustomDNS(True, [])) ``` ```python CustomDNSType.to_str(CustomDNS(True, [IP("1.1.1.1"), IP("8.8.8.8")])) ``` ```python CustomDNSType.to_str(CustomDNS(False, [])) ``` -------------------------------- ### Configuration and Settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/FILES.txt Guide to settings and configuration options for the Proton VPN CLI, including constructor options, CLI options, and feature availability matrices. Essential for customizing the CLI's behavior. ```APIDOC ## Configuration and Settings ### Description This section covers all aspects of configuring the Proton VPN CLI, including available settings, constructor options, CLI arguments, and feature availability based on subscription tiers. It allows users to customize the CLI's behavior to their specific needs. ### Method N/A (Configuration Reference) ### Endpoint N/A ### Parameters Refer to the detailed configuration options in `configuration.md`. ### Request Example ```bash # Example setting a specific configuration via CLI protonvpn-cli config set --dns-mode "ipv6" # Example of programmatic configuration (conceptual) from protonvpn_cli.controller import Controller config_options = { "dns_mode": "ipv6", "protocol": "wireguard" } controller = Controller(config=config_options) ``` ### Response N/A ### Error Handling Refer to `errors.md` for detailed information on exceptions and handling strategies. ``` -------------------------------- ### ClickFeature Usage Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/types.md Demonstrates using a pre-defined ClickFeature instance, such as KILLSWITCH_FEATURE, for CLI command definitions. ```python from proton.vpn.cli.commands.feature_setting_definitions import KILLSWITCH_FEATURE # KILLSWITCH_FEATURE is a pre-defined ClickFeature instance feature = KILLSWITCH_FEATURE ``` -------------------------------- ### CLI Commands Reference Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/FILES.txt Reference for all available CLI commands, including signin, signout, connect, disconnect, and configuration commands. Each command is documented with its syntax, options, behavior, and output examples. ```APIDOC ## CLI Commands Reference ### Description This section provides a comprehensive reference for all command-line interface commands supported by the Proton VPN CLI. It covers command syntax, available options, expected behavior, and examples of command output. ### Method CLI Commands (executed via terminal) ### Endpoint N/A (CLI Interface) ### Parameters Refer to individual command documentation within `api-reference/commands.md`. ### Request Example ```bash protonvpn-cli signin --username "user@example.com" --password "your_password" protonvpn-cli connect --country "United States" protonvpn-cli status protonvpn-cli disconnect ``` ### Response Command output examples are provided in `api-reference/commands.md`. ### Error Handling Refer to `errors.md` for detailed information on error cases and handling strategies. ``` -------------------------------- ### Python Click Command Decorator for Connect Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md This snippet illustrates the Python decorator setup for the 'connect' command using the click library. It defines arguments and options for server selection. ```python import click @click.command(name="connect") @click.argument('server_name', required=False) @click.option('--country', default=None) @click.option('--city', default=None) @click.option('--p2p', is_flag=True) @click.option('-sc', '--securecore', is_flag=True) @click.option('--tor', is_flag=True) @click.option('--random', is_flag=True) @click.pass_context async def connect(ctx, server_name, city, country, p2p, securecore, tor, random) ``` -------------------------------- ### Iterate All Features Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/feature-settings.md Iterates through the ALL_FEATURES list to print the command and human-friendly name of each feature. Useful for displaying available features. ```python from proton.vpn.cli.commands.feature_setting_definitions import ALL_FEATURES for feature in ALL_FEATURES: print(f"{feature.command}: {feature.human_friendly_name}") ``` -------------------------------- ### Save Modified Settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Modify settings from a retrieved Settings object and then save them. This example shows enabling IPv6 and setting the Kill Switch to ON. ```python settings = await controller.get_settings() # Modify settings settings.ipv6 = True settings.features.killswitch = KillSwitchState.ON await controller.save_settings(settings) ``` -------------------------------- ### Save Feature Setting Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/feature-settings.md Saves a new value for a feature, like Netshield, using the controller. Requires importing the feature and its relevant enum. ```python from proton.vpn.cli.commands.feature_setting_definitions import NETSHIELD_FEATURE from proton.vpn.core.settings.features import NetShield await controller.save_feature_setting( feature=NETSHIELD_FEATURE, value=NetShield.BLOCK_ADS_AND_TRACKING ) ``` -------------------------------- ### Check Tier Requirements Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/feature-settings.md Checks if a feature, like the Kill Switch, is available on the free tier. Raises an error if the user is on the free tier and the feature is not available. ```python from proton.vpn.cli.commands.feature_setting_definitions import KILLSWITCH_FEATURE if not KILLSWITCH_FEATURE.available_on_free_tier: if controller.user_on_free_tier: raise RequiresHigherTierError ``` -------------------------------- ### ServerFeatureEnum Usage Example Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/types.md Demonstrates how to import and use ServerFeatureEnum for checking VPN server capabilities like P2P, Secure Core, or Tor support using bitwise operations. ```python from proton.vpn.session.servers.types import ServerFeatureEnum # Find P2P server features = ServerFeatureEnum.P2P # Find server with multiple features features = ServerFeatureEnum.P2P | ServerFeatureEnum.SECURE_CORE # Check if server has feature if server.features & ServerFeatureEnum.P2P: print("P2P is supported") ``` -------------------------------- ### Example Command Error Handling with Custom Exceptions Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/errors.md Illustrates a typical error handling flow within a command handler, converting custom CLI exceptions into user-friendly messages using click exceptions. ```python @click.command() @click.argument('country') @click.pass_context async def connect(ctx, country): controller = await Controller.create(params=ctx.obj, click_ctx=ctx) try: server = await controller.find_logical_server(country=country) await controller.connect(server) except AuthenticationRequiredError: raise click.UsageError( "Authentication required. Please sign in first." ) except CountryCodeError: raise click.UsageError( f"Invalid country code '{country}'." ) except RequiresHigherTierError: raise click.UsageError( "This feature requires a paid Proton VPN subscription." ) except VPNConnectionError: raise click.ClickException( "Connection failed. Try a different server." ) ``` -------------------------------- ### Configure Internal Python Package Registry Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/README.md Set up the internal Python package registry for installing Proton VPN components. Replace placeholders with your GitLab token, instance, and group ID. ```shell pip config set global.index-url https://__token__:{GITLAB_TOKEN}@{GITLAB_INSTANCE}/api/v4/groups/{GROUP_ID}/-/packages/pypi/simple ``` -------------------------------- ### Example Usage of wait_for_current_tasks Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md Demonstrates how to use `wait_for_current_tasks` to ensure background tasks are completed. This is useful in asynchronous main functions to prevent premature exit. ```python from proton.vpn.cli.core.wait_for_current_tasks import wait_for_current_tasks async def main(): # Start some background tasks asyncio.create_task(background_work()) # Wait for them to finish await wait_for_current_tasks() print("All tasks completed") ``` -------------------------------- ### Custom Exception Reporter Implementation Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md An example of a custom class implementing the ExceptionReporter protocol. This class demonstrates how to handle and report errors, printing them to the console. ```python class CustomReporter: def report_error(self, error): # error is either: # - An exception instance # - A (exc_type, exc_value, exc_traceback) tuple print(f"Reporting error: {error}") handler = CustomReporter() ExceptionHandler.enable(exception_reporter=handler) ``` -------------------------------- ### Initialize and Connect with Proton VPN CLI Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Demonstrates how to initialize the controller, find a server in the US, and establish a VPN connection. It also shows how to configure the kill switch feature. ```python import asyncio from proton.vpn.cli.core.controller import Controller, Params import click async def main(): # Initialize ctx = click.get_current_context() controller = await Controller.create( params=Params(verbose=True), click_ctx=ctx ) # Connect server = await controller.find_logical_server(country="US") await controller.connect(server) # Configure from proton.vpn.cli.commands.feature_setting_definitions import KILLSWITCH_FEATURE from proton.vpn.killswitch.interface import KillSwitchState await controller.save_feature_setting( KILLSWITCH_FEATURE, KillSwitchState.ON ) asyncio.run(main()) ``` -------------------------------- ### Initialize Controller and Connect Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Initialize the Controller for programmatic access and establish a VPN connection. Requires parameters and a context object. ```python from proton.vpn.cli.core.controller import Controller, Params controller = await Controller.create(params, ctx) server = await controller.find_logical_server(country="US") await controller.connect(server) ``` -------------------------------- ### Get Program Name Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Retrieves the name of the CLI program, such as 'protonvpn'. ```python @property def program_name(self) -> Optional[str] ``` -------------------------------- ### Initialize Controller with Default Settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Create a Controller instance with default parameters. Requires a click context. ```python from proton.vpn.cli.core.controller import Controller, Params # Create with default settings controller = await Controller.create( params=Params(verbose=False), click_ctx=click_context ) ``` -------------------------------- ### main() Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/main.md The primary entry point for the Proton VPN CLI. It initializes the Click application context, sets up the controller, and handles all top-level exceptions. The function orchestrates command execution and error handling. ```APIDOC ## Function: main Runs the CLI application with optional configuration and custom controller override. ### Signature ```python def main( allow_concurrency: bool = False, cli_args: Optional[List[str]] = None, controller: Optional[Controller] = None ) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | allow_concurrency | bool | No | False | Whether to allow concurrent execution with the GUI app | | cli_args | Optional[List[str]] | No | None | Custom CLI arguments; if None, uses sys.argv | | controller | Optional[Controller] | No | None | Override the default Controller instance for testing | ### Return Type None ### Description This is the primary entry point for the Proton VPN CLI. It initializes the Click application context, sets up the controller, and handles all top-level exceptions. The function orchestrates command execution and error handling. ### Exceptions | Exception | Condition | |-----------|-----------| | ProtonAPIError | API call fails with an error message | | TimeoutError | Network request times out | | ProtonAPINotReachable | Cannot reach Proton API servers | | click.Abort | User aborts the operation (Ctrl+C) | ### Example ```python from proton.vpn.cli import main # Run with default settings main() # Run with custom arguments main(cli_args=['connect', '--country', 'US']) # Run in testing mode with a mock controller custom_controller = MyMockController() main(allow_concurrency=True, controller=custom_controller) ``` ``` -------------------------------- ### Initialize Controller with Verbose Output Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Create a Controller instance with verbose logging enabled. Requires a click context. ```python from proton.vpn.cli.core.controller import Controller, Params # Create with verbose output controller = await Controller.create( params=Params(verbose=True), click_ctx=click_context ) ``` -------------------------------- ### Get VPN Connector Instance Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Retrieves the VPNConnector instance responsible for managing low-level connection operations. ```python async def get_vpn_connector() -> VPNConnector ``` -------------------------------- ### Get Updated Server List Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Fetches the most recent server list from the API to ensure up-to-date information. ```python async def get_updated_server_list() -> ServerList ``` -------------------------------- ### List all configuration settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Display all current configuration settings for the Proton VPN CLI. ```bash protonvpn config list ``` -------------------------------- ### Get Account Name Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Retrieves the username of the currently authenticated user. Raises an exception if the user is not logged in. ```python @property def account_name(self) -> str ``` -------------------------------- ### Get Specific Feature Setting Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Retrieves the current value of a specific feature setting. Requires user to be logged in. ```python await controller.get_feature_setting(feature=Feature.DNS) ``` -------------------------------- ### Catch AuthenticationRequiredError Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/errors.md Catch errors indicating that the user must be logged in to perform an action. This guides the user to sign in. ```python from proton.vpn.cli.core.exceptions import AuthenticationRequiredError try: server = await controller.find_logical_server() except AuthenticationRequiredError: print(f"Please sign in first: {program_name} signin") print("Then try again: protonvpn connect") ``` -------------------------------- ### Initialize Controller with Custom API Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Create a Controller instance with a custom API implementation, typically used for testing. Requires a click context. ```python from proton.vpn.cli.core.controller import Controller, Params # Create with custom API (testing) custom_api = MyProtonVPNAPI() controller = Controller( params=Params(), click_ctx=click_context, api=custom_api ) ``` -------------------------------- ### Get Current VPN Connection Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Retrieves the currently active VPN connection object. Returns None if no connection is active. ```python async def get_current_connection() -> Optional[VPNConnection] ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/README.md Create a Python virtual environment and activate it to manage project dependencies. ```shell python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Controller.connect Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Establishes a VPN connection to a specified server. ```APIDOC ## async connect ### Description Establishes a VPN connection to the specified server. ### Parameters #### Parameters - **server** (LogicalServer) - Required - The target server to connect to ### Return Type Optional[states.State] - Connection state on success, None on failure ``` -------------------------------- ### Connect to Fastest Server Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Initiates a VPN connection to the fastest available server. This is the default behavior when no server is specified. ```bash protonvpn connect ``` -------------------------------- ### Get Current VPN Settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Retrieves the current VPN settings from the API. This method always returns the latest server-side configuration. ```python await controller.get_settings() ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/README.md After cloning the repository, run this command to clone necessary submodules. ```shell git submodule update --init --recursive ``` -------------------------------- ### Get User Subscription Tier Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Returns an integer representing the user's subscription tier. 0 indicates the free tier. ```python @property def user_tier(self) -> int ``` -------------------------------- ### Get Specific Feature Setting Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Retrieve the current value of a specific feature, such as the Kill Switch. Requires importing the feature definition. ```python from proton.vpn.cli.commands.feature_setting_definitions import KILLSWITCH_FEATURE current_value = await controller.get_feature_setting(KILLSWITCH_FEATURE) print(f"Kill Switch: {current_value}") ``` -------------------------------- ### Initialize ProtonVPNAPI Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Instantiate the ProtonVPNAPI for low-level integration with core libraries. This is the lowest level of interaction. ```python from proton.vpn.core.api import ProtonVPNAPI api = ProtonVPNAPI(...) connector = await api.get_vpn_connector() ``` -------------------------------- ### Connect to VPN Server Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Establish a VPN connection to a selected server. Returns the connection state. ```python # Connect state = await controller.connect(server) if state: print("Connected!") ``` -------------------------------- ### Configure Exceptions to Absorb Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Configures the controller to ignore specific exceptions, preventing them from being reported or halting execution. This example sets `CancelledError` to be absorbed. ```python from asyncio import CancelledError controller.set_uncaught_exceptions_to_absorb([CancelledError]) ``` -------------------------------- ### Catching CountryNameError Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/errors.md Demonstrates how to catch the CountryNameError when validating a country name. This example shows how to provide user-friendly feedback and suggest valid alternatives. ```python from proton.vpn.cli.core.exceptions import CountryNameError try: country_code = controller.validate_country_input("Atlantis") except CountryNameError: print("Invalid country name 'Atlantis'. Please use a valid country name or code.") # Show some example countries print("Examples: United States, United Kingdom, Germany") ``` -------------------------------- ### Show help message Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Display the help message for Proton VPN CLI commands. ```bash -h, --help ``` -------------------------------- ### List available servers Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Display a list of available Proton VPN servers, with options to filter the results. ```bash protonvpn servers [OPTIONS] ``` -------------------------------- ### List All Countries Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Display a list of all countries where Proton VPN servers are available. ```bash protonvpn countries list # List all countries ``` -------------------------------- ### Configure Custom DNS Servers Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Enable custom DNS servers by providing a comma-separated list of IP addresses with 'on'. Disable with 'off'. ```bash protonvpn config set custom-dns on --dns 1.1.1.1,8.8.8.8 protonvpn config set custom-dns off ``` -------------------------------- ### Update Version and Build Packages Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/README.md Add versioning information to versions.yml and then run the build script to generate package files. ```shell scripts/build_packages.py ``` -------------------------------- ### Configuration Commands Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/GENERATION-SUMMARY.txt Manages CLI and VPN feature settings. ```APIDOC ## Configuration Commands ### Description Commands for managing CLI settings and VPN feature configurations. ### Commands - **config list**: Displays all current configuration settings. - **config set**: Modifies a specific configuration setting. Supports 8 distinct settings. ``` -------------------------------- ### Create Controller Instance Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Factory method to create a fully initialized Controller instance. It ensures settings are loaded before authentication. ```python @staticmethod async def create(params: Params, click_ctx: ClickContext) -> Controller ``` -------------------------------- ### Handling ProtonAPINotReachable Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/errors.md Shows how to catch ProtonAPINotReachable, an exception indicating network connectivity issues with the Proton API. The example displays a network error message and exits. ```python try: main() except ProtonAPINotReachable: click.echo("Error: Network connectivity issues detected. " "Please check your internet connection and try again.") sys.exit(1) ``` -------------------------------- ### Configure VPN Accelerator Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Enable or disable the VPN Accelerator for performance optimization. ```bash - `vpn-accelerator {on|off}` — Performance optimization ``` -------------------------------- ### Catching InvalidDNS Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/errors.md Shows how to catch the InvalidDNS exception when parsing DNS IP addresses. This example logs the invalid IP and provides guidance on correct formatting. ```python from proton.vpn.cli.core.exceptions import InvalidDNS try: dns_entries = controller.parse_dns_ips(["1.1.1.1", "999.999.999.999"]) except InvalidDNS as e: print(f"Invalid DNS IP '{e.dns}': {e.message}") print("Please provide valid IPv4 or IPv6 addresses.") print("Examples: 1.1.1.1, 8.8.8.8, 2606:4700:4700::1111") ``` -------------------------------- ### Customize Click Context for Help Options Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md This dictionary configures Click to recognize both --help and -h as valid help flags across all commands. ```python _CLICK_CONTEXT_SETTINGS = { "help_option_names": [HELP_OPTION, HELP_OPTION_ABBREVIATED] } ``` -------------------------------- ### Get Specific Feature Setting Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Retrieve the current value of a specific VPN feature setting, like the Kill Switch. Requires importing the feature definition. ```python # Get specific feature from proton.vpn.cli.commands.feature_setting_definitions import KILLSWITCH_FEATURE current = await controller.get_feature_setting(KILLSWITCH_FEATURE) ``` -------------------------------- ### Enable verbose logging Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Enable verbose logging for the Proton VPN CLI commands. ```bash -v, --verbose ``` -------------------------------- ### Connect to a Logical Server Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Connects to a Proton VPN server, optionally specifying a country. This snippet demonstrates finding a server and establishing a connection, then checking the connection state. ```python server = await controller.find_logical_server(country="US") connection_state = await controller.connect(server) if connection_state: print("Connected successfully") ``` -------------------------------- ### Running an Async Operation Synchronously Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md An example of using the @run_async decorator to execute an async function and retrieve its result synchronously. Note that each call creates a new event loop. ```python from proton.vpn.cli.core.run_async import run_async import asyncio @run_async async def async_operation(): await asyncio.sleep(1) return "completed" result = async_operation() # Blocks until async_operation completes print(result) # "completed" ``` -------------------------------- ### Connect to a Server in a Specific City Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Connects to the fastest server within a specified city. Use quotes if the city name contains spaces. ```bash protonvpn connect --city "New York" ``` -------------------------------- ### Connect to a Proton VPN server Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Connect to a Proton VPN server, optionally specifying a server name and connection options. ```bash protonvpn connect [SERVER_NAME] [OPTIONS] ``` -------------------------------- ### Server Discovery Commands Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Commands for discovering available servers, countries, and cities. ```APIDOC ## servers ### Description List available VPN servers. Supports filtering by country, platform, and other criteria. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters - **country** (string) - Optional - Filter servers by country code. - **platform** (string) - Optional - Filter servers by platform (e.g., "linux"). #### Request Body None ### Request Example ```bash protonvpn-cli servers protonvpn-cli servers --country US ``` ### Response #### Success Response A list of available servers is returned. #### Response Example ```json [ { "name": "us-ca-101.protonvpn.com", "country": "US", "platform": "linux" } ] ``` ## countries ### Description Display a list of all countries where Proton VPN servers are available. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash protonvpn-cli countries ``` ### Response #### Success Response A list of countries is returned. #### Response Example ```json [ "US", "NL", "DE" ] ``` ## cities ### Description Display a list of cities available within a specified country. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters - **country** (string) - Required - The country code for which to list cities. #### Request Body None ### Request Example ```bash protonvpn-cli cities --country US ``` ### Response #### Success Response A list of cities in the specified country is returned. #### Response Example ```json [ "Los Angeles", "New York" ] ``` ``` -------------------------------- ### Import and Access Predefined Features Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Imports predefined feature constants and demonstrates how to access their attributes like setting path and human-friendly name. ```python from proton.vpn.cli.commands.feature_setting_definitions import ( VPN_ACCELERATOR_FEATURE, MODERATE_NAT_FEATURE, IPV6_FEATURE, ANON_CRASH_REPORTS_FEATURE, PORT_FORWARDING_FEATURE, CUSTOM_DNS_FEATURE, KILLSWITCH_FEATURE, NETSHIELD_FEATURE, ) # Example: Get kill switch setting path path = KILLSWITCH_FEATURE.setting_path # "features.killswitch" name = KILLSWITCH_FEATURE.human_friendly_name # "Kill Switch" ``` -------------------------------- ### Feature Settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/GENERATION-SUMMARY.txt Documentation for configurable VPN features and their settings. ```APIDOC ## Feature Settings ### Description Details on the 8 configurable VPN features, including their settings, tier availability, and management via CLI or API. ### Features Documented - IPv6 routing - Kill Switch - NetShield (ad/tracker blocking) - VPN Accelerator - Moderate NAT - Port Forwarding - Custom DNS - Anonymous Crash Reports ### Settings Management Settings can be managed using the `config set` command or the `set_setting` method of the Controller class. Each setting may have tier-specific requirements. ``` -------------------------------- ### Configure NetShield (Malware/Ad Blocking) Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Configures the NetShield feature for blocking malware, ads, and trackers. Options include disabling it, blocking only malware, or enabling full protection. ```bash protonvpn config set netshield off protonvpn config set netshield malware-only protonvpn config set netshield malware-ads-trackers ``` -------------------------------- ### Accessing Settings via Dot Notation Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Demonstrates how to access various settings and feature configurations using dot notation in Python. This is useful for checking or modifying application settings programmatically. ```python settings.ipv6 # bool settings.anonymous_crash_reports # bool settings.custom_dns # CustomDNS settings.features.killswitch # KillSwitchState settings.features.netshield # NetShield settings.features.vpn_accelerator # bool settings.features.moderate_nat # bool settings.features.port_forwarding # bool settings.protocol # Protocol enum ``` -------------------------------- ### Connect to VPN Command Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Connect to a Proton VPN server. Supports specifying a server and various connection options. ```bash protonvpn connect [SERVER] [OPTIONS] # Connect to VPN ``` -------------------------------- ### Controller.create Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md A factory method to create and initialize a Controller instance. It ensures that the controller has its settings loaded, even before user authentication. ```APIDOC ## Controller.create ### Description Factory method to create a fully initialized Controller instance. It ensures the controller always has settings loaded, even before authentication. ### Parameters #### Parameters - **params** (Params) - Required - Application parameters - **click_ctx** (ClickContext) - Required - Click command context ### Return Type Controller - A fully initialized controller with settings loaded ### Example ```python from proton.vpn.cli.core.controller import Controller, Params import click ctx = click.get_current_context() controller = await Controller.create( params=Params(verbose=True), click_ctx=ctx ) ``` ``` -------------------------------- ### Sign in to Proton VPN CLI Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Users authenticate with Proton credentials. This command prompts for password and a 2FA token if enabled. ```bash protonvpn signin user@proton.me ``` -------------------------------- ### List Available VPN Servers Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md List all available Proton VPN servers, with options to filter by country, city, or server type. ```bash protonvpn servers [OPTIONS] # List available servers ``` -------------------------------- ### Define Server Feature Flags Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Demonstrates how to use bit flags to specify server features for filtering. ```python from proton.vpn.session.servers.types import ServerFeatureEnum # Single feature features = ServerFeatureEnum.P2P # Multiple features (must have all) features = ServerFeatureEnum.P2P | ServerFeatureEnum.SECURE_CORE # No features (fastest general server) features = 0 ``` -------------------------------- ### Connect to a Server Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Connects to a specified server after finding it. Requires user to be logged in. Automatically refreshes certificates and cleans up state on failure. ```python from proton.vpn.session.servers.types import LogicalServer server = await controller.find_logical_server(country="US") connection_state = await controller.connect(server) if connection_state: print("Connected successfully") ``` -------------------------------- ### Show Account Information Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Display information about the currently signed-in Proton VPN account. ```bash protonvpn info # Show account name ``` -------------------------------- ### Connect to a Random Server Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Initiates a VPN connection to a randomly selected server, bypassing the fastest server selection logic. ```bash protonvpn connect --random ``` -------------------------------- ### List available countries Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Retrieve and display a list of countries where Proton VPN servers are available. ```bash protonvpn countries list ``` -------------------------------- ### List Available VPN Servers Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Lists all available VPN servers. Supports filtering by country, city, and specific features like P2P, Secure Core, or Tor. The output is displayed in a table format. ```bash protonvpn servers # List servers in specific country protonvpn servers --country US # List P2P servers protonvpn servers --p2p ``` -------------------------------- ### Establish VPN Connection Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Establishes a VPN connection to a specified server. Returns the connection state on success or None on failure. ```python async def connect(server: LogicalServer) -> Optional[states.State] ``` -------------------------------- ### Set Custom DNS Servers via CLI Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Configures custom DNS servers using the 'protonvpn config set custom-dns' command. ```bash # Set custom DNS servers protonvpn config set custom-dns on --dns 1.1.1.1,8.8.8.8 # IPv6 support protonvpn config set custom-dns on --dns 2606:4700:4700::1111,2001:4860:4860::8888 # Disable (use Proton's DNS) protonvpn config set custom-dns off ``` -------------------------------- ### Error Reference and Handling Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/FILES.txt Comprehensive reference for all exception classes, including their trigger conditions and recommended handling strategies. Essential for building robust applications using the Proton VPN CLI. ```APIDOC ## Error Reference and Handling ### Description This section provides a detailed reference for all exception classes raised by the Proton VPN CLI. It includes information on when each exception is triggered and guidance on how to effectively catch and handle them. ### Method N/A (Error Handling Reference) ### Endpoint N/A ### Parameters Refer to the detailed definitions in `errors.md`. ### Request Example ```python from protonvpn_cli.errors import ConnectionError try: # Attempt a connection that might fail # controller.connect(server='non-existent-server') pass except ConnectionError as e: print(f"Failed to connect: {e}") # Handle the connection error appropriately except Exception as e: print(f"An unexpected error occurred: {e}") ``` ### Response N/A ### Error Handling Refer to the detailed error handling strategies in `errors.md`. ``` -------------------------------- ### Server Commands Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/GENERATION-SUMMARY.txt Handles connection management and server status retrieval. ```APIDOC ## Server Commands ### Description Commands for managing VPN connections and checking server status. ### Commands - **connect**: Establishes a VPN connection to a selected server. - **disconnect**: Terminates the active VPN connection. - **status**: Shows the current connection status and details. - **servers**: Lists available servers, with options for filtering. ``` -------------------------------- ### Configure Custom DNS Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Enable or disable custom DNS servers and specify the IP addresses. ```bash - `custom-dns {on|off} [--dns IPS]` — Custom DNS servers ``` -------------------------------- ### Connect to Fastest Server in a Specific Country Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/configuration.md Connects to the fastest server within a specified country, identified by its two-letter country code. ```bash protonvpn connect --country US ``` -------------------------------- ### Configure Kill Switch Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Configures the kill switch feature. 'off' disables it, while 'standard' blocks all internet traffic if the VPN connection drops. ```bash protonvpn config set killswitch off protonvpn config set killswitch standard ``` -------------------------------- ### Find Fastest Global Server Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Find the fastest available global VPN server using the controller. This is a common task for quick connections. ```python # Fastest global server server = await controller.find_logical_server() ``` -------------------------------- ### Proton VPN CLI File Organization Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md This snippet outlines the directory structure of the Proton VPN CLI project, showing the location of main entry points, commands, and core modules. ```tree proton/vpn/cli/ ├── __init__.py # Main entry point, app() group ├── _cli_constants.py # Constants (paths, program name) ├── commands/ │ ├── account.py # signin, signout, info commands │ ├── server.py # connect, disconnect, status, servers │ ├── location_discovery.py # countries, cities commands │ ├── settings.py # config (list and set) commands │ ├── feature_setting_definitions.py # Feature definitions & type converters │ └── command_utils.py # Shared command utilities └── core/ ├── controller.py # Controller class (main logic) ├── exceptions.py # Custom exception classes ├── exception_handler.py # Exception handling & reporting ├── click_exception_handler.py # Click-specific error handling ├── run_async.py # Async decorator for Click └── wait_for_current_tasks.py # Task completion waiter ``` -------------------------------- ### Account Commands Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/GENERATION-SUMMARY.txt Manages user authentication and account information through the CLI. ```APIDOC ## Account Commands ### Description Commands for managing user authentication and retrieving account information. ### Commands - **signin**: Authenticates the user with Proton VPN credentials. - **signout**: Logs the user out of the current session. - **info**: Displays information about the current account and subscription status. ``` -------------------------------- ### Set a configuration feature Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/INDEX.md Modify a specific configuration setting. Use the provided feature names and values. ```bash protonvpn config set FEATURE VALUE [OPTIONS] ``` -------------------------------- ### NetShield Usage Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/feature-settings.md Commands to disable NetShield, block only malware, or enable full protection against malware, ads, and trackers using the Proton VPN CLI. ```bash protonvpn config set netshield off # Disabled protonvpn config set netshield malware-only # Block malware only protonvpn config set netshield malware-ads-trackers # Full protection ``` -------------------------------- ### Find Fastest Server in a Country Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Find the fastest VPN server within a specific country. Requires the country code or name. ```python # Fastest in country server = await controller.find_logical_server(country="US") ``` -------------------------------- ### List Cities with Servers in a Country Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/commands.md Lists all cities with Proton VPN servers within a specified country. You can use either the country code or the full country name. The output includes city name, server count, and available features. ```bash protonvpn cities list US protonvpn cities list "United States" ``` -------------------------------- ### get_settings Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Retrieves current VPN settings. Loads the current VPN configuration from the API. Always returns the latest server-side settings. ```APIDOC ## get_settings ### Description Retrieves current VPN settings. Loads the current VPN configuration from the API. Always returns the latest server-side settings. ### Return Type Settings - Complete settings object with protocol, features, DNS, etc. ``` -------------------------------- ### Main Function Signature Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/main.md Defines the primary entry point for the CLI application. It accepts optional arguments for concurrency, custom CLI arguments, and controller overrides. ```python def main( allow_concurrency: bool = False, cli_args: Optional[List[str]] = None, controller: Optional[Controller] = None ) ``` -------------------------------- ### Find Server with Specific Features Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Find a VPN server that supports a particular feature, such as P2P. Requires importing ServerFeatureEnum. ```python # With features from proton.vpn.session.servers.types import ServerFeatureEnum server = await controller.find_logical_server( country="US", features=ServerFeatureEnum.P2P ) ``` -------------------------------- ### Applying run_async Decorator to Click Commands Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md Demonstrates how to use the @run_async decorator on an async Click command handler to make it compatible with Click's synchronous execution model. ```python import click from proton.vpn.cli.core.run_async import run_async @click.command() @click.pass_context @run_async async def my_command(ctx): # Async code here pass ``` -------------------------------- ### Controller Methods API Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/FILES.txt Documentation for the core Controller class API, which includes over 30 methods for managing settings, connection, and other core functionalities. This is the primary interface for integrating the Proton VPN CLI as a library. ```APIDOC ## Controller Methods API ### Description This section details the API exposed by the core Controller class, offering a robust set of methods for managing VPN connections, user settings, and other essential operations. It is designed for programmatic integration of the Proton VPN CLI. ### Method Refer to individual method documentation within `api-reference/controller.md`. ### Endpoint N/A (Library Interface) ### Parameters Refer to individual method documentation within `api-reference/controller.md`. ### Request Example ```python # Example usage (specific methods will vary) from protonvpn_cli.controller import Controller controller = Controller() controller.connect(server='us-ny-1') # ... other operations ... controller.disconnect() ``` ### Response Refer to individual method documentation within `api-reference/controller.md`. ### Error Handling Refer to `errors.md` for detailed information on exceptions and handling strategies. ``` -------------------------------- ### Create Custom DNS Configuration Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/README.md Construct a custom DNS configuration object, specifying whether to use custom DNS and providing the parsed IP entries. ```python # Create DNS object from proton.vpn.cli.commands.feature_setting_definitions import CUSTOM_DNS_FEATURE custom_dns = controller.to_custom_dns(True, dns_entries) ``` -------------------------------- ### connect Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/controller.md Attempts to connect to the specified server. Automatically refreshes certificates before connecting. If connection fails, automatically disconnects to clean up state. ```APIDOC ## connect ### Description Attempts to connect to the specified server. Automatically refreshes certificates before connecting. If connection fails, automatically disconnects to clean up state. ### Raises - **AuthenticationRequiredError**: User is not logged in - **VPNConnection2FARequiredError**: 2FA verification required at connection - **TimeoutError**: Connection attempt times out - **VPNConnectionError**: Generic connection failure ### Example ```python from proton.vpn.session.servers.types import LogicalServer server = await controller.find_logical_server(country="US") connection_state = await controller.connect(server) if connection_state: print("Connected successfully") ``` ``` -------------------------------- ### Enabling Global Exception Handling Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/api-reference/core-utilities.md Shows how to enable global exception handling by providing an optional custom exception reporter. This sets up custom exception hooks for both standard and asyncio exceptions. ```python from proton.vpn.cli.core.exception_handler import ExceptionHandler class MyReporter: def report_error(self, error): send_to_sentry(error) ExceptionHandler.enable(exception_reporter=MyReporter()) ``` -------------------------------- ### Catch Authentication2FAFailedError Source: https://github.com/protonvpn/proton-vpn-cli/blob/stable/_autodocs/errors.md Demonstrates how to catch and handle an Authentication2FAFailedError during the login process. Ensure your device time is synchronized. ```python from proton.vpn.cli.core.exceptions import Authentication2FAFailedError try: await controller.login(username, get_password, get_2fa) except Authentication2FAFailedError: print("2FA Authentication failed. Please try again.") print("Make sure your device time is synchronized.") ```