### Create VoIP Notification for Incoming Calls Source: https://context7.com/fatal1ty/aioapns/llms.txt This example demonstrates creating a `NotificationRequest` for a VoIP notification. It specifies the `PushType.VOIP` and includes custom payload keys like `caller_id`, `caller_name`, and `call_type`. It also shows how to override the default APNs topic for VoIP services. ```python from aioapns import NotificationRequest, PRIORITY_HIGH, PushType voip_request = NotificationRequest( device_token='voip_device_token_64_hex_chars_0123456789abcdef01234567890123', message={ "aps": {}, "caller_id": "user123", "caller_name": "John Doe", "call_type": "video" }, push_type=PushType.VOIP, priority=PRIORITY_HIGH, apns_topic='com.example.myapp.voip', # Override default topic for VoIP ) ``` -------------------------------- ### Define Push Notification Types with PushType Enum Source: https://context7.com/fatal1ty/aioapns/llms.txt This snippet showcases the `PushType` enum in `aioapns`, which defines different categories of push notifications. It provides examples for `ALERT`, `BACKGROUND`, `VOIP`, `COMPLICATION`, and `FILEPROVIDER` push types, illustrating their intended use cases and how to specify them in a `NotificationRequest`. ```python from aioapns import NotificationRequest, PushType # Available push types and their use cases: # ALERT - Standard visible notifications alert = NotificationRequest( device_token='token', message={"aps": {"alert": "Hello!"}}, push_type=PushType.ALERT, ) # BACKGROUND - Silent notifications for content refresh background = NotificationRequest( device_token='token', message={"aps": {"content-available": 1}}, push_type=PushType.BACKGROUND, ) # VOIP - Voice over IP incoming call notifications voip = NotificationRequest( device_token='voip_token', message={"aps": {}, "caller": "John"}, push_type=PushType.VOIP, ) # COMPLICATION - watchOS complication updates complication = NotificationRequest( device_token='watch_token', message={"aps": {}}, push_type=PushType.COMPLICATION, ) # FILEPROVIDER - File provider extension updates fileprovider = NotificationRequest( device_token='token', message={"aps": {}}, push_type=PushType.FILEPROVIDER, ) ``` -------------------------------- ### Send iOS Notification with Certificate Authentication (Python) Source: https://context7.com/fatal1ty/aioapns/llms.txt Demonstrates how to initialize the APNs client using certificate-based authentication and send a push notification. This method requires a .pem file containing the certificate and private key. The function sends an alert notification and prints the result. ```Python import asyncio from uuid import uuid4 from aioapns import APNs, NotificationRequest, PushType async def send_with_certificate(): # Initialize APNs client with certificate authentication apns_client = APNs( client_cert='/path/to/apns-cert.pem', # Combined cert + key file use_sandbox=False, # Use production server max_connections=10, # Connection pool size max_connection_attempts=5, # Retry attempts on failure ) # Create notification request request = NotificationRequest( device_token='a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd', message={ "aps": { "alert": { "title": "New Message", "body": "You have a new message from John" }, "badge": 1, "sound": "default" }, "custom_data": {"message_id": "12345"} }, notification_id=str(uuid4()), time_to_live=3600, # Expires in 1 hour push_type=PushType.ALERT, ) # Send notification and handle response result = await apns_client.send_notification(request) if result.is_successful: print(f"Notification {result.notification_id} sent successfully") else: print(f"Failed: {result.status} - {result.description}") return result # Run the async function asyncio.run(send_with_certificate()) ``` -------------------------------- ### APNs Client Initialization Source: https://context7.com/fatal1ty/aioapns/llms.txt Methods for initializing the APNs client using either certificate-based (.pem) or token-based (.p8) authentication. ```APIDOC ## APNs Client Initialization ### Description The APNs client is the primary interface for interacting with Apple's push notification service. It supports two authentication modes: certificate-based (using a .pem file) and token-based (using a .p8 private key). ### Method N/A (Class Constructor) ### Parameters #### Certificate-Based - **client_cert** (string) - Required - Path to the .pem certificate file. - **use_sandbox** (boolean) - Optional - Whether to use the APNs sandbox environment. #### Token-Based - **key** (string) - Required - The content of the .p8 private key file. - **key_id** (string) - Required - 10-character Key ID from Apple Developer Portal. - **team_id** (string) - Required - 10-character Team ID from Apple Developer Portal. - **topic** (string) - Required - The Bundle ID of the application. ### Request Example # Certificate Auth apns_client = APNs(client_cert='/path/to/cert.pem') # Token Auth apns_client = APNs(key=auth_key, key_id='KEYID', team_id='TEAMID', topic='com.app.id') ``` -------------------------------- ### Batch Sending Notifications with Connection Pooling Source: https://context7.com/fatal1ty/aioapns/llms.txt Demonstrates how to utilize the aioapns connection pool to send thousands of notifications concurrently. It showcases configuring max_connections and using asyncio.gather to manage high-throughput tasks. ```python import asyncio import time from aioapns import APNs, NotificationRequest async def batch_send_notifications(): apns = APNs( client_cert='/path/to/cert.pem', max_connections=20, max_connection_attempts=5, ) device_tokens = [ f'token_{i:064x}' for i in range(1000) ] async def send_single(token: str, index: int): request = NotificationRequest( device_token=token, message={ "aps": { "alert": f"Batch notification #{index}", "badge": 1 } }, collapse_key='batch-update', ) try: result = await apns.send_notification(request) return result.is_successful except Exception as e: print(f"Error sending to {token[:20]}: {e}") return False start_time = time.time() tasks = [ send_single(token, i) for i, token in enumerate(device_tokens) ] results = await asyncio.gather(*tasks, return_exceptions=True) elapsed = time.time() - start_time successful = sum(1 for r in results if r is True) print(f"Sent {len(device_tokens)} notifications in {elapsed:.2f}s") print(f"Success rate: {successful}/{len(device_tokens)}") print(f"Throughput: {len(device_tokens)/elapsed:.0f} notifications/sec") asyncio.run(batch_send_notifications()) ``` -------------------------------- ### Send iOS Notification with Token Authentication (Python) Source: https://context7.com/fatal1ty/aioapns/llms.txt Demonstrates how to initialize the APNs client using token-based (JWT) authentication and send a background notification. This method requires a .p8 private key file, key ID, and team ID. The function sends a silent background notification and prints the result. ```Python import asyncio from aioapns import APNs, NotificationRequest, PushType async def send_with_token(): # Read the private key file with open('/path/to/AuthKey_ABCD1234.p8', 'r') as f: auth_key = f.read() # Initialize APNs client with token-based authentication apns_client = APNs( key=auth_key, # Contents of .p8 file key_id='ABCD1234', # 10-character Key ID from Apple team_id='TEAMID1234', # 10-character Team ID from Apple topic='com.example.myapp', # Bundle ID (required for token auth) use_sandbox=True, # Use sandbox for development max_connections=20, ) # Send a silent background notification request = NotificationRequest( device_token='a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd', message={ "aps": { "content-available": 1 }, "refresh_type": "messages" }, push_type=PushType.BACKGROUND, priority=5, # Use normal priority for background ) result = await apns_client.send_notification(request) print(f"Status: {result.status}, Success: {result.is_successful}") return result asyncio.run(send_with_token()) ``` -------------------------------- ### Create Standard Alert Notification with Rich Content Source: https://context7.com/fatal1ty/aioapns/llms.txt This snippet shows how to construct a `NotificationRequest` for a standard alert notification. It includes rich content such as title, subtitle, body, badge count, sound, category, and thread ID. It also demonstrates setting a unique notification ID, time-to-live, priority, and collapse key. ```python from aioapns import NotificationRequest, PRIORITY_HIGH, PushType from uuid import uuid4 alert_request = NotificationRequest( device_token='device_token_hex_string_64_characters_long_0123456789abcdef', message={ "aps": { "alert": { "title": "Breaking News", "subtitle": "Technology", "body": "Apple announces new features for iOS developers" }, "badge": 5, "sound": "news.aiff", "category": "NEWS_CATEGORY", "thread-id": "news-thread" }, "article_id": "news-2024-001", "url": "https://example.com/article/001" }, notification_id=str(uuid4()), # Unique ID for tracking time_to_live=86400, # 24 hours expiration priority=PRIORITY_HIGH, # Send immediately (10) collapse_key='news-updates', # Replace previous with same key push_type=PushType.ALERT, ) ``` -------------------------------- ### Create Live Activity Update Notification Source: https://context7.com/fatal1ty/aioapns/llms.txt This snippet illustrates how to create a `NotificationRequest` for a Live Activity update. It uses `PushType.LIVEACTIVITY` and includes a specific `content-state` within the `aps` dictionary to convey real-time information, such as game scores or event progress. ```python from aioapns import NotificationRequest, PushType live_activity_request = NotificationRequest( device_token='live_activity_token_64_hex_chars_0123456789abcdef0123456789', message={ "aps": { "timestamp": 1699000000, "event": "update", "content-state": { "score": "3-2", "time_remaining": "15:30" } } }, push_type=PushType.LIVEACTIVITY, apns_topic='com.example.myapp.push-type.liveactivity', ) ``` -------------------------------- ### Send APNs Notifications with aioapns Source: https://github.com/fatal1ty/aioapns/blob/master/README.rst Demonstrates how to send push notifications to iOS devices using aioapns. It shows initialization of APNs clients with both certificate and token-based authentication, and sending a notification request with optional parameters like TTL and push type. Requires Python 3.8+ and the aioapns library. ```python import asyncio from uuid import uuid4 from aioapns import APNs, NotificationRequest, PushType async def run(): apns_cert_client = APNs( client_cert='/path/to/apns-cert.pem', use_sandbox=False, ) with open('/path/to/apns-key.p8', 'r') as key: apns_key_client = APNs( key=key.read(), key_id='', team_id='', topic='', # Bundle ID use_sandbox=False, ) request = NotificationRequest( device_token='', message = { ``` ```python "aps": { "alert": "Hello from APNs", "badge": "1", } }, notification_id=str(uuid4()), # optional time_to_live=3, # optional push_type=PushType.ALERT, # optional ) await apns_cert_client.send_notification(request) await apns_key_client.send_notification(request) loop = asyncio.get_event_loop() loop.run_until_complete(run()) ``` -------------------------------- ### Create APNs NotificationRequest Payload (Python) Source: https://context7.com/fatal1ty/aioapns/llms.txt Illustrates the creation of a `NotificationRequest` object, which encapsulates the data for a push notification. This includes the device token, message payload adhering to APNs format, and optional delivery parameters like time-to-live and priority. ```Python from uuid import uuid4 from aioapns import NotificationRequest, PushType, PRIORITY_HIGH, PRIORITY_NORMAL # Example usage (assuming apns_client is initialized): # request = NotificationRequest( # device_token='YOUR_DEVICE_TOKEN', # message={ # "aps": { # "alert": { # "title": "Example Title", # "body": "This is an example notification." # }, # "badge": 1 # } # }, # notification_id=str(uuid4()), # time_to_live=300, # push_type=PushType.ALERT, # priority=PRIORITY_HIGH # ) # await apns_client.send_notification(request) ``` -------------------------------- ### POST /send_notification Source: https://context7.com/fatal1ty/aioapns/llms.txt Sends a push notification request to a specific device token using the configured APNs client. ```APIDOC ## POST /send_notification ### Description Sends a notification payload to a specific device token. The request includes the message payload, push type, and delivery parameters. ### Method POST ### Parameters #### Request Body - **device_token** (string) - Required - The target device token. - **message** (object) - Required - The APNs payload dictionary. - **push_type** (enum) - Required - Type of push (ALERT, BACKGROUND, VOIP, etc.). - **time_to_live** (integer) - Optional - Expiration time in seconds. ### Request Example { "device_token": "a1b2c3d4...", "message": {"aps": {"alert": "Hello!"}}, "push_type": "alert" } ### Response #### Success Response (200) - **is_successful** (boolean) - Indicates if the notification was accepted by APNs. - **notification_id** (string) - Unique identifier for the request. #### Response Example { "is_successful": true, "notification_id": "uuid-string" } ``` -------------------------------- ### Handle APNs Responses and Errors in Python Source: https://context7.com/fatal1ty/aioapns/llms.txt This asynchronous Python function demonstrates how to send a notification using `aioapns` and handle the response from APNs. It checks for success and provides specific error handling for common APNs response codes like `GONE`, `BAD_REQUEST`, `TOO_MANY_REQUESTS`, and `FORBIDDEN`, including extracting error descriptions and timestamps. ```python import asyncio from aioapns import APNs, NotificationRequest from aioapns.common import APNS_RESPONSE_CODE async def handle_notification_results(): apns = APNs(client_cert='/path/to/cert.pem') request = NotificationRequest( device_token='potentially_invalid_token_64_hex_chars_0123456789abcdef', message={"aps": {"alert": "Test notification"}} ) result = await apns.send_notification(request) # Check if notification was successful if result.is_successful: print(f"Success! Notification ID: {result.notification_id}") else: # Handle specific error codes if result.status == APNS_RESPONSE_CODE.GONE: # Device token is no longer valid - remove from database print(f"Token invalid since timestamp: {result.timestamp}") # delete_device_token(request.device_token, result.timestamp) elif result.status == APNS_RESPONSE_CODE.BAD_REQUEST: print(f"Bad request: {result.description}") elif result.status == APNS_RESPONSE_CODE.TOO_MANY_REQUESTS: print("Rate limited - implement backoff") elif result.status == APNS_RESPONSE_CODE.FORBIDDEN: print(f"Authentication error: {result.description}") else: print(f"Error {result.status}: {result.description}") return result asyncio.run(handle_notification_results()) ``` -------------------------------- ### HTTP Proxy Support for APNs Notifications Source: https://context7.com/fatal1ty/aioapns/llms.txt Configure aioapns to send notifications through an HTTP proxy. This is useful for network configurations requiring specific routing. The client supports both certificate-based and token-based authentication when using a proxy, with configurable proxy host and port. ```python import asyncio from aioapns import APNs, NotificationRequest async def send_via_proxy(): # Certificate auth with proxy apns_cert = APNs( client_cert='/path/to/cert.pem', proxy_host='proxy.corporate.com', proxy_port=8080, use_sandbox=False, ) # Token auth with proxy with open('/path/to/AuthKey.p8', 'r') as f: auth_key = f.read() apns_token = APNs( key=auth_key, key_id='KEY123', team_id='TEAM123', topic='com.example.app', proxy_host='10.0.0.1', proxy_port=3128, ) request = NotificationRequest( device_token='device_token_64_hex_characters_0123456789abcdef012345678901', message={"aps": {"alert": "Sent via proxy"}} ) result = await apns_cert.send_notification(request) print(f"Via proxy: {result.is_successful}") asyncio.run(send_via_proxy()) ``` -------------------------------- ### Handling APNs Exceptions Source: https://context7.com/fatal1ty/aioapns/llms.txt Provides a pattern for catching specific aioapns exceptions like ConnectionError and MaxAttemptsExceeded. This ensures applications can gracefully handle network failures and retry exhaustion. ```python import asyncio from aioapns import APNs, NotificationRequest from aioapns.exceptions import ConnectionError, ConnectionClosed, MaxAttemptsExceeded async def send_with_error_handling(): apns = APNs( client_cert='/path/to/cert.pem', max_connection_attempts=3, ) request = NotificationRequest( device_token='valid_device_token_64_hex_characters_0123456789abcdef0123', message={"aps": {"alert": "Important update"}} ) try: result = await apns.send_notification(request) if result.is_successful: print("Notification delivered successfully") else: print(f"APNs rejected: {result.description}") except ConnectionError: print("Could not connect to APNs servers") except ConnectionClosed: print("Connection closed unexpectedly") except MaxAttemptsExceeded: print("Failed after maximum retry attempts") except Exception as e: print(f"Unexpected error: {type(e).__name__}: {e}") asyncio.run(send_with_error_handling()) ``` -------------------------------- ### Custom Error Handler for APNs Notifications Source: https://context7.com/fatal1ty/aioapns/llms.txt Implement a custom error handler function to manage failed APNs notification deliveries. This handler is invoked when a notification fails, allowing for centralized logging and actions like removing invalid device tokens from a database. It processes results based on status codes, such as GONE for unregistered tokens or TOO_MANY_REQUESTS for rate limiting. ```python import asyncio from aioapns import APNs, NotificationRequest, NotificationResult from aioapns.common import APNS_RESPONSE_CODE # Database simulation invalid_tokens = [] async def custom_error_handler( request: NotificationRequest, result: NotificationResult ) -> None: """Custom handler called when notification delivery fails.""" print(f"Notification {result.notification_id} failed!") print(f"Status: {result.status}, Reason: {result.description}") # Handle unregistered/invalid tokens if result.status == APNS_RESPONSE_CODE.GONE: invalid_tokens.append({ 'token': request.device_token, 'invalid_since': result.timestamp }) print(f"Marked token for removal: {request.device_token[:20]}...") # Log other errors for monitoring elif result.status == APNS_RESPONSE_CODE.TOO_MANY_REQUESTS: print("Rate limit hit - consider reducing send rate") async def main(): apns = APNs( client_cert='/path/to/cert.pem', err_func=custom_error_handler, # Set custom error handler ) # Send notifications - errors handled automatically tokens = ['valid_token_64_hex', 'invalid_token_64_hex'] for token in tokens: request = NotificationRequest( device_token=token, message={"aps": {"alert": "Test"}} ) await apns.send_notification(request) print(f"Invalid tokens collected: {len(invalid_tokens)}") asyncio.run(main()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.