Skip to content

FirebaseClient

chad63e edited this page Jan 29, 2024 · 1 revision

FirebaseClient

Table of Contents

Class Description

FirebaseClient is a comprehensive class designed for managing Firebase functionalities in Python applications, with a focus on web push notifications, device token management, and topic subscriptions for messaging. This class is primarily used on the client side of Anvil applications, enabling seamless integration of Firebase services within the Anvil environment.

Constructor

__init__(self, config, public_vapid_key=None, service_worker_url=DEFAULT_SERVICE_WORKER, message_handler=None, save_token_handler=None, subscribe_handler=None, unsubscribe_handler=None, allow_notification_str="Please allow notification!", topics=None, action_maps=None, with_logging=False)

Initializes a new instance of the FirebaseClient class. It configures Firebase with the necessary settings and handlers for web push notifications, messaging, and service worker interactions.

Parameters:

  • config (FirebaseConfig): Configuration for the Firebase project.
  • public_vapid_key (str, optional): Public VAPID key for web push notifications.
  • service_worker_url (str, optional): URL to the custom service worker script.
  • message_handler (callable, optional): Handler function for incoming messages.
  • save_token_handler (callable, optional): Handler function for saving device tokens.
  • subscribe_handler (callable, optional): Handler function for subscribing to topics.
  • unsubscribe_handler (callable, optional): Handler function for unsubscribing from topics.
  • allow_notification_str (str, optional): Message prompt for requesting notification permissions.
  • topics (list, optional): List of topics to subscribe to upon initialization.
  • action_maps (list[ActionMap], optional): List of action maps for the service worker.
  • with_logging (bool, optional): Flag to enable logging for debugging purposes.

Public Methods

initialize_app()

Initializes the Firebase application with the provided configuration settings. This includes setting up Firebase messaging and registering the service worker.

request_notification_permission() -> bool

Requests permission from the user for sending notifications. Returns True if permission is granted, False otherwise.

subscribe_to_topic(topic: str)

Subscribes the client to a specified messaging topic.

unsubscribe_from_topic(topic: str)

Unsubscribes the client from a specified messaging topic.

add_action_map(action_map: ActionMap) -> bool

Adds a specified ActionMap to the service worker for handling specific actions.

Handler Examples

Message Handler

def message_handler(payload):
    print("New message:", payload)

Save Token Handler

def save_token_handler(token):
    print("Saving token:", token)

    # Implement token saving logic here

Subscribe Handler

def subscribe_handler(topic, token):
    print(f"Subscribing to {topic} with token {token}")

    # Invoke a server-side function that, in turn, calls the `subscribe_to_topic()` method of a `FirebaseServer` instance.
    anvil.server.call("your_subscribe_func", topic, token)

Unsubscribe Handler

def unsubscribe_handler(topic, token):
    print(f"Unsubscribing from {topic} with token {token}")

    # Invoke a server-side function that, in turn, calls the `unsubscribe_from_topic()` method of a `FirebaseServer` instance.
    anvil.server.call("your_unsubscribe_func", topic, token)

Obtaining a VAPID Key

To acquire a VAPID key for web push notifications in Firebase, follow these steps:

  1. Navigate to the Firebase console.
  2. Select your project.
  3. Click on the gear icon next to 'Project Overview' and select 'Project settings'.
  4. Go to the 'Cloud Messaging' tab.
  5. Here, you'll find your 'Web Push certificates' section. If you haven't generated a key pair yet, click on 'Generate Key Pair'. This will generate a new VAPID key.
  6. Once the key pair is generated, the public key is your VAPID key. You can click on the 'Copy' button to copy it to your clipboard.

Remember to keep your PRIVATE VAPID key secure and do not share it publicly.

Code Examples

Initializing FirebaseClient

The initialize_app method is essential and must be called to set up Firebase functionalities. However, it is crucial to invoke this method after the DomWindow has fully loaded, typically within an Anvil Form's show event. This ensures that the service worker and other configurations are properly loaded.

from Firebase.client import FirebaseClient

# Initialize Firebase Client
firebase_client = FirebaseClient(
    config=firebase_config,
    public_vapid_key="your_public_vapid_key",
    service_worker_url="/service_worker.js",
    message_handler=message_handler,
    save_token_handler=save_token_handler,
    subscribe_handler=subscribe_handler,
    unsubscribe_handler=unsubscribe_handler,
    with_logging=True
)

# Initialize Client App
firebase_client.initialize_app()

Requesting Notification Permission

Before Web Push Notifications can function, your browser client must have been granted the necessary permissions.

if firebase_client.request_notification_permission():
    print("Notification permission granted.")
else:
    print("Notification permission denied.")

Adding an Action Map

Action maps are useful for defining specific actions that the service worker should perform in response to different events. This example demonstrates adding an action map to the Firebase client.

from Firebase.client import ActionMap

# Define an action map
action_map = ActionMap(
    action_name="open_url",
    full_url="https://example.com",
    params={"param1": "value1", "param2": "value2"}
)

# Add the action map to FirebaseClient
if firebase_client.add_action_map(action_map):
    print("Action map added successfully.")
else:
    print("Failed to add action map.")

In this example, an ActionMap is created and added to the FirebaseClient. The action map defines how the service worker should respond to specific actions, such as opening a URL with given parameters. The add_action_map method of FirebaseClient facilitates this addition.

Clone this wiki locally