### Install aw-client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Install the aw-client library using pip. ```bash pip install aw-client ``` -------------------------------- ### Settings Dictionary Examples Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Examples of settings dictionaries returned by get_setting(). Shows how to retrieve all settings or a specific setting like 'classes'. ```python # Get all settings all_settings = { "classes": [...], "other_setting": "value" } # Get one setting classes = [ {"name": ["Work"], "rule": {...}}, ... ] ``` -------------------------------- ### AWQuery Example File Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md An example AWQuery file demonstrating how to define and process events, including filtering and aggregation. ```awql events = flood(query_bucket(find_bucket("aw-watcher-afk_myhost"))); not_afk = filter_keyvals(events, "status", ["not-afk"]); RETURN = sum_durations(not_afk); ``` -------------------------------- ### Get All Server Settings Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Retrieves all server settings when no key is provided. Ensure the client is initialized. ```python all_settings = client.get_setting() ``` -------------------------------- ### Bucket Info Dictionary Example Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Example of the bucket information dictionary returned by the get_buckets() function. Each entry represents a data source with its metadata. ```python { "aw-watcher-window_myhost": { "id": "aw-watcher-window_myhost", "client": "aw-watcher-window", "hostname": "myhost", "type": "currentwindow", "created": "2024-01-01T00:00:00+00:00" }, ... } ``` -------------------------------- ### start Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/request-queue.md Starts the background thread and begins the main loop. This is called automatically by ActivityWatchClient.connect(). ```APIDOC ## start ### Description Starts the background thread and begins the main loop. **Note**: Called automatically by `ActivityWatchClient.connect()` ### Signature ```python def start(self) -> None ``` ``` -------------------------------- ### Create Bucket Example Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Demonstrates the creation of a Bucket object, specifying its ID and type. This is used by the RequestQueue to manage bucket creation. ```python from aw_client.client import Bucket bucket = Bucket(id="my-bucket", type="event") ``` -------------------------------- ### GET /buckets/ Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Lists all available buckets on the ActivityWatch server. ```APIDOC ## GET /buckets/ ### Description Lists all buckets on the server. ### Method GET ### Endpoint /api/0/buckets/ ### Request Example ```http GET /api/0/buckets/ Authorization: Bearer {api_key} ``` ### Response #### Success Response (200 OK) - **(object)** - A dictionary where keys are bucket IDs and values are bucket objects. - **id** (string) - The unique identifier for the bucket. - **client** (string) - The name of the client that created the bucket. - **hostname** (string) - The hostname where the bucket was created. - **type** (string) - The type of data the bucket stores. - **created** (string) - The timestamp when the bucket was created. #### Response Example ```json { "aw-watcher-window_myhost": { "id": "aw-watcher-window_myhost", "client": "aw-watcher-window", "hostname": "myhost", "type": "currentwindow", "created": "2024-01-01T00:00:00+00:00" }, "aw-watcher-afk_myhost": { "id": "aw-watcher-afk_myhost", "client": "aw-watcher-afk", "hostname": "myhost", "type": "afkstatus", "created": "2024-01-01T00:00:00+00:00" } } ``` ``` -------------------------------- ### ActivityWatchClient Initialization Examples Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/configuration.md Demonstrates different ways to initialize the ActivityWatchClient, including using default configurations, testing configurations, and overriding configuration with constructor parameters. Shows how to access the commit interval. ```python from aw_client import ActivityWatchClient # Uses config defaults (127.0.0.1:5600) client1 = ActivityWatchClient("app1") # Uses testing config (127.0.0.1:5666) client2 = ActivityWatchClient("app2", testing=True) # Constructor overrides config client3 = ActivityWatchClient("app3", host="custom.host", port=9999) # Commit interval from config (or 10 seconds default) print(client1.commit_interval) # 10 or custom value ``` -------------------------------- ### Workflow Example with Request Queue Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/request-queue.md Demonstrates how to initialize the client with queuing enabled, register a bucket, and queue a heartbeat event. The queue automatically handles retries if the server is unavailable. ```python from aw_client import ActivityWatchClient from aw_core.models import Event from datetime import datetime, timezone # Create client with queuing enabled client = ActivityWatchClient("my-watcher") client.connect() # Register a bucket client.create_bucket("my-bucket", "activity", queued=True) # Queue a heartbeat event = Event(timestamp=datetime.now(timezone.utc), duration=0, data={"app": "myapp"}) client.heartbeat("my-bucket", event, pulsetime=60, queued=True) # If server is down, request is persisted and will retry when available # If server comes back, requests will be sent automatically client.disconnect() # Waits for pending requests and stops queue thread ``` -------------------------------- ### Manage Buckets with aw-client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Provides examples for listing, creating, and deleting buckets using the ActivityWatchClient. Ensure the client is connected before performing these operations. ```python from aw_client import ActivityWatchClient client = ActivityWatchClient("my-app") # List buckets buckets = client.get_buckets() for bucket_id in buckets: print(bucket_id) # Create bucket client.create_bucket("my-bucket", "event") # Delete bucket client.delete_bucket("my-bucket", force=False) ``` -------------------------------- ### Get Specific Server Setting Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Retrieves a specific server setting by its key. Ensure the client is initialized. ```python classes = client.get_setting("classes") ``` -------------------------------- ### Create and Print Event Instance Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Example demonstrating how to instantiate an Event object with timezone-aware datetime, timedelta, and a data dictionary, then printing its attributes. ```python from aw_core.models import Event from datetime import datetime, timedelta, timezone event = Event( timestamp=datetime.now(timezone.utc), duration=timedelta(minutes=5), data={"app": "vim", "title": "main.py"} ) print(event.timestamp) # 2024-01-15 12:00:00+00:00 print(event.duration) # 0:05:00 print(event.data) # {"app": "vim", "title": "main.py"} ``` -------------------------------- ### GET All Server Settings Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieves all server settings. Requires an API key for authorization. ```http GET /api/0/settings/ Authorization: Bearer {api_key} ``` -------------------------------- ### Start Background Thread Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/request-queue.md Starts the background thread, initiating the main loop. This is automatically called by ActivityWatchClient.connect(). ```python def start(self) -> None: pass ``` -------------------------------- ### Example Usage of QueryParams Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/queries.md Instantiate QueryParams with default classes and filtering options. ```python from aw_client.queries import QueryParams, default_classes params = QueryParams( classes=default_classes, filter_afk=True, include_audible=True ) ``` -------------------------------- ### Example Usage of DesktopQueryParams Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/queries.md Instantiate DesktopQueryParams with specific bucket IDs for window, AFK, and browser activity, along with default classes and filtering. ```python from aw_client.queries import DesktopQueryParams, default_classes params = DesktopQueryParams( bid_window="aw-watcher-window_myhost", bid_afk="aw-watcher-afk_myhost", bid_browsers=["aw-watcher-web-firefox_myhost"], classes=default_classes, filter_afk=True ) ``` -------------------------------- ### Get All Settings Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieves all server settings. This operation is used by ActivityWatchClient.get_setting(). ```APIDOC ## GET /settings/ ### Description Retrieves all server settings. ### Method GET ### Endpoint /api/0/settings/ ### Parameters #### Request Headers - **Authorization** (string) - Required - Bearer {api_key} ### Response #### Success Response (200 OK) - **classes** (array) - Description of classes setting. - **other_setting** (string) - Description of other setting. ### Response Example ```json { "classes": [ { "name": ["Work"], "rule": {"type": "regex", "regex": "vim|emacs"} } ], "other_setting": "value" } ``` ``` -------------------------------- ### Get Server Information with aw-client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Retrieve server hostname and testing status using `get_info`. Use `wait_for_start` to pause execution until the server is ready, with an optional timeout. ```python from aw_client import ActivityWatchClient client = ActivityWatchClient("my-app") # Get server info info = client.get_info() print(info["hostname"]) print(info["testing"]) # Wait for server to start client.wait_for_start(timeout=10) ``` -------------------------------- ### GET /info Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieves basic information about the ActivityWatch server. ```APIDOC ## GET /info ### Description Returns basic server information. ### Method GET ### Endpoint /api/0/info ### Request Example ```http GET /api/0/info Authorization: Bearer {api_key} ``` ### Response #### Success Response (200 OK) - **hostname** (string) - The hostname of the server. - **testing** (boolean) - Indicates if the server is in testing mode. #### Response Example ```json { "hostname": "myhost", "testing": false } ``` ``` -------------------------------- ### Get Server Information Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Retrieves basic server information, including hostname and testing status. Returns a dictionary containing server details. ```python info = client.get_info() print(info) ``` -------------------------------- ### Specify Date/Time Formats for Queries Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md The --start and --stop options accept various date and time formats, including ISO, date-only, and relative dates. ```bash --start "2024-01-15T10:30:00" --stop "2024-01-16T18:00:00" ``` ```bash --start "2024-01-15" --stop "2024-01-16" ``` ```bash --start "2024-01-15" ``` -------------------------------- ### Duration Format Examples Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Shows how durations are represented as timedelta objects or total seconds. ```python # As timedelta timedelta(seconds=3661) # 1:01:01 (1 hour, 1 minute, 1 second) ``` ```python # As total seconds (in JSON) 3661.0 ``` -------------------------------- ### Example TOML Configuration for aw-client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md This TOML configuration snippet shows how to specify the server hostname and port for the aw-client. It is loaded from `~/.config/aw-client/aw-client.toml` and can be overridden by command-line options. ```toml [server] hostname = "192.168.1.100" port = "5600" ``` -------------------------------- ### Connect to Activity Watch Client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Starts the request queue thread for offline queuing and asynchronous event submission. Must be called before using queued operations. ```python client = ActivityWatchClient("my-watcher") client.connect() ``` -------------------------------- ### Usage of EnhancedJSONEncoder Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/queries.md Example demonstrating how to use the EnhancedJSONEncoder with json.dumps to serialize dataclass instances. Ensure necessary imports are included. ```python import json from aw_client.queries import DesktopQueryParams, EnhancedJSONEncoder params = DesktopQueryParams(...) json_str = json.dumps(params, cls=EnhancedJSONEncoder) ``` -------------------------------- ### Create QueuedRequest Example Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Illustrates how to instantiate a QueuedRequest object with a specific endpoint and data payload. This is used for persistent storage of failed requests. ```python from aw_client.client import QueuedRequest request = QueuedRequest( endpoint="buckets/my-bucket/heartbeat?pulsetime=60", data={"timestamp": "2024-01-15T12:00:00+00:00", "duration": 0, "data": {...}} ) ``` -------------------------------- ### AWQuery Script Example Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md Define AWQuery statements in a file to perform complex data analysis, such as calculating total active time. ```aw # query.aw # Find total active time events = flood(query_bucket(find_bucket("aw-watcher-afk_myhost"))); not_afk = filter_keyvals(events, "status", ["not-afk"]); RETURN = sum_durations(not_afk); ``` -------------------------------- ### Import/Export Data with aw-client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Use `export_all` to get all data, `export_bucket` for a specific bucket, and `import_bucket` to load data into another client instance. ```python from aw_client import ActivityWatchClient client1 = ActivityWatchClient("app1") client2 = ActivityWatchClient("app2") # Export all buckets all_data = client1.export_all() # Export single bucket bucket_data = client1.export_bucket("my-bucket") # Import bucket client2.import_bucket(bucket_data) ``` -------------------------------- ### connect Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Starts the request queue thread to enable offline queuing and asynchronous event submission. Must be called before using queued operations. ```APIDOC ## connect ### Description Starts the request queue thread to enable offline queuing and asynchronous event submission. Must be called before using queued operations. ### Method connect ### Parameters None ### Returns None ### Example ```python client = ActivityWatchClient("my-watcher") client.connect() # Now queued operations are available client.disconnect() ``` ``` -------------------------------- ### Acquire Single Instance Lock with Unique Client Name Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/errors.md This example shows how to initialize the ActivityWatchClient with a unique name based on the process ID to ensure a single instance lock can be acquired. It includes error handling for SystemExit if the lock cannot be obtained. ```python from aw_client import ActivityWatchClient import os import sys try: # Create client with unique name client = ActivityWatchClient(f"my-app-{os.getpid()}") except SystemExit: print("Could not acquire single instance lock") sys.exit(1) ``` -------------------------------- ### Get Event Count (Python) Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Retrieves the number of events in a bucket. Supports filtering by start and end times. The `limit` parameter is unused. ```python def get_eventcount( self, bucket_id: str, limit: int = -1, start: Optional[datetime] = None, end: Optional[datetime] = None, ) -> int ``` ```python count = client.get_eventcount("my-bucket", start=start, end=end) print(f"Bucket contains {count} events") ``` -------------------------------- ### GET Bucket Event Count Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Use this endpoint to retrieve the total number of events stored in a specific bucket. You can optionally filter by a start and end timestamp to count events within a particular time frame. Requires an API key for authorization. ```http GET /api/0/buckets/aw-watcher-window_myhost/events/count?start=2024-01-15T00:00:00%2B00:00&end=2024-01-15T23:59:59%2B00:00 Authorization: Bearer {api_key} ``` -------------------------------- ### Initialize and Connect to ActivityWatch Client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Demonstrates how to create an ActivityWatchClient instance and connect to the service using both context manager and manual connection methods. ```python from aw_client import ActivityWatchClient from aw_core.models import Event from datetime import datetime, timedelta, timezone # Create client client = ActivityWatchClient("my-app") # Automatic connection with context manager with ActivityWatchClient("my-app") as client: # All operations here pass # Manual connection client = ActivityWatchClient("my-app") client.connect() try: # Operations pass finally: client.disconnect() ``` -------------------------------- ### register_bucket Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/request-queue.md Registers a bucket to be created when the queue thread connects to the server. This method handles the initial setup of buckets, either storing them for future connection or attempting immediate creation. ```APIDOC ## register_bucket ### Description Registers a bucket to be created when the queue thread connects to the server. This method handles the initial setup of buckets, either storing them for future connection or attempting immediate creation. ### Method `register_bucket(self, bucket_id: str, event_type: str) -> None` ### Parameters #### Path Parameters - **bucket_id** (str) - Required - Unique bucket identifier - **event_type** (str) - Required - Type of events (e.g., "activity", "heartbeat") ### Behavior - If queue thread is not yet connected, stores bucket for creation on next connect - If queue thread is already connected, attempts immediate creation - Failed immediate creation sets `self.connected = False`, causing reconnect loop ### Example ```python client.request_queue.register_bucket("my-bucket", "event") ``` ``` -------------------------------- ### Run Query from File with aw-client CLI Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/INDEX.md Execute a query defined in a file using `aw-client query`. Specify start and stop dates for the query range. The query file should contain ActivityWatch query language. ```bash # Run query from file aw-client query query.aw --start "2024-01-15" --stop "2024-01-16" ``` -------------------------------- ### Basic Usage Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Demonstrates how to initialize and connect to the ActivityWatch client, both with and without a context manager. ```python from aw_client import ActivityWatchClient # Create client client = ActivityWatchClient("my-app") # Automatic connection with context manager with ActivityWatchClient("my-app") as client: # All operations here pass # Manual connection client = ActivityWatchClient("my-app") client.connect() try: # Operations pass finally: client.disconnect() ``` -------------------------------- ### Simple Aggregation Result Example Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Example of a simple aggregation result, such as a total duration, returned as a list containing a single float value. ```python # Result from sum_durations query result = [3600.0] # Total seconds ``` -------------------------------- ### Desktop Report Result Example Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Example of a detailed desktop report result, often from a fullDesktopQuery. Includes classified events and aggregated data for window and browser activity. ```python # From fullDesktopQuery result = [ { "events": [...], # All classified events "window": { "app_events": [...], "title_events": [...], "cat_events": [...], "active_events": [...], "duration": 28800.0 }, "browser": { "domains": [...], "urls": [...], "duration": 3600.0 } } ] ``` -------------------------------- ### Typical Desktop Activity Query Workflow Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/queries.md Demonstrates a complete workflow for querying desktop activity using the ActivityWatch client. This includes client initialization, defining query parameters, generating the query, executing it, and processing the results. ```python from aw_client import ActivityWatchClient from aw_client.queries import DesktopQueryParams, fullDesktopQuery, default_classes from datetime import datetime, timedelta, timezone # Create client client = ActivityWatchClient("my-app") # Define query parameters params = DesktopQueryParams( bid_window="aw-watcher-window_myhost", bid_afk="aw-watcher-afk_myhost", bid_browsers=["aw-watcher-web-firefox_myhost", "aw-watcher-web-chromium_myhost"], classes=default_classes, filter_afk=True, filter_classes=[["Comms"]] # Exclude communications category ) # Generate query query = fullDesktopQuery(params) # Execute query now = datetime.now(timezone.utc) yesterday = now - timedelta(days=1) result = client.query(query, [(yesterday, now)])[0] # Process results print(f"Total active time: {result['window']['duration']} seconds") print(f"Top 5 apps:") for event in result['window']['app_events'][:5]: print(f" {event['data']['app']}: {event['duration']} seconds") ``` -------------------------------- ### Example Regex Category Rule Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md An example of a category rule specification using a regular expression to match application or title strings. It includes options for case sensitivity. ```python spec = { "type": "regex", "regex": "vim|emacs|vscode", "ignore_case": False } ``` -------------------------------- ### ActivityWatchClient Initialization Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/module-index.md Demonstrates how to initialize the main client class for server communication. ```APIDOC ## ActivityWatchClient Initialization ### Description Initialize the main client class for ActivityWatch server communication. ### Usage ```python from aw_client import ActivityWatchClient client = ActivityWatchClient("my-app") ``` ``` -------------------------------- ### Initialize and Use ActivityWatchClient Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/INDEX.md Instantiate the main client and manage connection. Use 'with client:' for automatic connection management. All operations are available through the client object. ```python from aw_client import ActivityWatchClient client = ActivityWatchClient("my-app") # Connection management with client: # All operations client.get_buckets() client.insert_event("bucket", event) ``` -------------------------------- ### Event List Result Example Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Example of an event list result, typically returned by RETURN = events queries. It's a list of time periods, where each period contains event dictionaries. ```python # Result from RETURN = events query result = [ [ { "id": 1, "timestamp": "2024-01-15T12:00:00+00:00", "duration": 300, "data": {"app": "vim"} }, ... ] ] # List of time periods, each containing events ``` -------------------------------- ### Initialize ActivityWatchClient with Custom Host and Port Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/INDEX.md Demonstrates how to override the default server hostname and port when initializing the ActivityWatchClient. This is useful for connecting to a server on a non-standard address. ```python # Constructor overrides client = ActivityWatchClient("app", host="custom.host", port=9999) ``` -------------------------------- ### Full Module Import Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/module-index.md Import the entire aw_client module and instantiate the ActivityWatchClient. ```python import aw_client client = aw_client.ActivityWatchClient() ``` -------------------------------- ### ActivityWatch Client Configuration Hierarchy Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/module-index.md Demonstrates how constructor parameters override configuration files, which in turn override default settings. Use constructor parameters for the highest priority overrides. ```python # Constructor overrides everything client = ActivityWatchClient("app", host="custom.host", port=9999) # Config file overrides defaults # ~/.config/aw-client/aw-client.toml: # [server] # hostname = "custom.host" # Defaults if nothing specified # server.hostname = "127.0.0.1" # server.port = "5600" ``` -------------------------------- ### Initialize ActivityWatchClient Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/module-index.md Instantiate the main client class for server communication. This is the primary entry point for interacting with the ActivityWatch server. ```python from aw_client import ActivityWatchClient client = ActivityWatchClient("my-app") ``` -------------------------------- ### Show aw-client CLI help Source: https://github.com/activitywatch/aw-client/blob/master/README.md Use this command to display the help message for the aw-client command-line utility, showing available options and commands. ```bash $ aw-client --help ``` -------------------------------- ### Get All Buckets Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Retrieves all buckets from the server. The returned dictionary maps bucket IDs to their metadata. ```python def get_buckets(self) -> dict ``` ```python buckets = client.get_buckets() for bucket_id, bucket_info in buckets.items(): print(f"{bucket_id}: {bucket_info['type']}") ``` -------------------------------- ### Import ActivityWatchClient Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/module-index.md Import the main ActivityWatchClient class for basic usage. ```python # Main export from aw_client import ActivityWatchClient ``` -------------------------------- ### Get Specific Setting Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieves a specific setting by its key. This operation is used by ActivityWatchClient.get_setting(key). ```APIDOC ## GET /settings/{key} ### Description Retrieves a specific setting by key. ### Method GET ### Endpoint /api/0/settings/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The key of the setting to retrieve. #### Request Headers - **Authorization** (string) - Required - Bearer {api_key} ### Response #### Success Response (200 OK) - **name** (array) - The name of the setting class. - **rule** (object) - The rule associated with the setting. #### Status Codes - 200: Setting found - 404: Setting not found ### Response Example ```json [ { "name": ["Work"], "rule": {"type": "regex", "regex": "vim|emacs"} } ] ``` ``` -------------------------------- ### GET Export All Data Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Exports all buckets and events from the server. Requires an API key for authorization. ```http GET /api/0/export Authorization: Bearer {api_key} ``` -------------------------------- ### aw-client Custom Configuration File Structure Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/configuration.md Illustrates the default file structure for aw-client and aw-server-rust configuration files, including the optional custom configuration. ```text ~/.config/aw-client/ └── aw-client.toml # Optional custom configuration ~/.config/aw-server-rust/ ├── config.toml # Production server config (contains api_key) └── config-testing.toml # Testing server config (contains api_key) ~/.local/share/aw-client/ └── queued/ ├── {client_name}.v1.persistqueue # Production queue └── {client_name}-testing.v1.persistqueue # Testing queue ``` -------------------------------- ### REST API Endpoints Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/MANIFEST.txt Reference for all available REST API endpoints, including methods, parameters, and examples. ```APIDOC ## REST API Endpoints This document provides a complete reference for all ActivityWatch REST API endpoints. ### GET /info #### Description Retrieves general information about the ActivityWatch server. ### GET/POST/DELETE /buckets/ #### Description Manages buckets. GET lists buckets, POST creates a bucket, DELETE removes a bucket. ### GET/POST/DELETE /buckets/{id}/events #### Description Manages events within a specific bucket. GET retrieves events, POST adds events, DELETE removes events. ### POST /buckets/{id}/heartbeat #### Description Sends a heartbeat signal for a specific bucket. ### POST /query/ #### Description Executes a query against the ActivityWatch data. Expects a JSON payload with query parameters. ### GET/POST /settings/ #### Description Manages server settings. GET retrieves settings, POST updates settings. ### GET /export #### Description Exports ActivityWatch data within a specified time range. ### POST /import #### Description Imports data into ActivityWatch. Expects data in a specific format in the request body. ### Request/Response Examples Each endpoint includes detailed JSON examples for requests and responses, along with HTTP status codes and error conditions. ``` -------------------------------- ### Get Server Information Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieves basic information about the ActivityWatch server. Requires an API key for authentication. ```http GET /api/0/info Authorization: Bearer {api_key} ``` -------------------------------- ### GET Specific Server Setting Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieves a specific server setting by its key. Requires an API key for authorization. ```http GET /api/0/settings/classes Authorization: Bearer {api_key} ``` -------------------------------- ### Instantiate ActivityWatch Client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/classes-categories.md Creates an instance of the ActivityWatchClient with a unique name including a random number to prevent conflicts. ```python awc = aw_client.ActivityWatchClient(f"get-setting-{random.randint(0, 10000)}") ``` -------------------------------- ### GET Export Single Bucket Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Exports a single bucket with all its events. Requires the bucket ID and an API key for authorization. ```http GET /api/0/buckets/aw-watcher-window_myhost/export Authorization: Bearer {api_key} ``` -------------------------------- ### Initialize ActivityWatchClient Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/README.md Instantiate the main synchronous API client to interact with the ActivityWatch server. Ensure the client is properly closed after use. ```python from aw_client import ActivityWatchClient with ActivityWatchClient("my-app") as client: buckets = client.get_buckets() ``` -------------------------------- ### Run mypy Type Checking Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Execute mypy to check type definitions in the specified directories. Ensure mypy is installed and configured. ```bash mypy aw_client tests examples ``` -------------------------------- ### Set Server Setting Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Sets a specific server setting with a given key and value. Ensure the client is initialized. ```python client.set_setting(key="some_key", value="some_value") ``` -------------------------------- ### GET /buckets/{bucket_id}/events/count Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieves the total number of events within a specified bucket, with optional filtering by a time range. ```APIDOC ## GET /buckets/{bucket_id}/events/count ### Description Gets the number of events in a bucket within an optional time range. ### Method GET ### Endpoint /api/0/buckets/{bucket_id}/events/count ### Parameters #### Query Parameters - **start** (ISO datetime) - Optional - Inclusive start time - **end** (ISO datetime) - Optional - Inclusive end time ### Request Example ```http GET /api/0/buckets/aw-watcher-window_myhost/events/count?start=2024-01-15T00:00:00%2B00:00&end=2024-01-15T23:59:59%2B00:00 Authorization: Bearer {api_key} ``` ### Response #### Success Response (200 OK) - **Response Format**: Plain text integer ### Response Example ``` 42 ``` ``` -------------------------------- ### List Available Buckets Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md List all available buckets on the ActivityWatch server. This command requires no specific options. ```bash aw-client buckets ``` -------------------------------- ### Test Connection with aw-client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md Use the --testing flag to verify the connection to the ActivityWatch server and list buckets, or run a simple query to check server info. ```bash aw-client --testing buckets ``` ```bash aw-client query -c "print('Connected')" --json ``` -------------------------------- ### Server Information Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Shows how to retrieve server information and wait for the server to become available. ```APIDOC ## Server Information ### Description Retrieves information about the ActivityWatch server and provides a method to wait until the server is ready. ### Method ```python client.get_info() client.wait_for_start(timeout=10) ``` ### Parameters #### wait_for_start - **timeout** (int) - Optional - The maximum time in seconds to wait for the server to start. ### Request Example ```python from aw_client import ActivityWatchClient client = ActivityWatchClient("my-app") # Get server info info = client.get_info() print(info["hostname"]) print(info["testing"]) # Wait for server to start client.wait_for_start(timeout=10) ``` ### Response #### Success Response (get_info) - Returns a dictionary containing server information, including 'hostname' and 'testing' status. #### Success Response (wait_for_start) - Returns None upon successful connection or if the timeout is reached. ``` -------------------------------- ### Configure Python Logging Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/classes-categories.md Sets up basic logging for the ActivityWatch client module to display DEBUG level messages and above. ```python import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Server-Side Classification JSON Format Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/classes-categories.md Example of the JSON structure used by the ActivityWatch server to store custom classifications. This format is converted by `get_classes()`. ```json { "classes": [ { "name": ["Work", "Programming"], "rule": { "type": "regex", "regex": "vim|emacs|vscode" } }, ... ] } ``` -------------------------------- ### AWQuery JSON Output Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md Example of AWQuery results formatted as JSON. This output includes event IDs, timestamps, durations, and data payloads. ```json [ {"id": 1, "timestamp": "2024-01-15T00:00:00Z", "duration": 315, "data": {...}}, ... ] ``` -------------------------------- ### Manage Settings with aw-client Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Retrieve all settings with `get_setting()`, a specific setting with `get_setting("key")`, or update a setting using `set_setting("key", "value")`. ```python from aw_client import ActivityWatchClient client = ActivityWatchClient("my-app") # Get all settings all_settings = client.get_setting() # Get specific setting classes = client.get_setting("classes") # Set setting client.set_setting("my_key", "my_value") ``` -------------------------------- ### Datetime Handling in Python Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/quick-reference.md Demonstrates creating and parsing datetime objects in UTC, local, and specific timezones. Also shows how to calculate differences using timedelta. ```python from datetime import datetime, timedelta, timezone from zoneinfo import ZoneInfo # UTC (recommended) now_utc = datetime.now(timezone.utc) # Local timezone now_local = datetime.now().astimezone() # Specific timezone now_ny = datetime.now(ZoneInfo("America/New_York")) # Parse ISO string from datetime import datetime iso_str = "2024-01-15T12:30:45+00:00" dt = datetime.fromisoformat(iso_str) # Difference one_day_ago = now_utc - timedelta(days=1) ``` -------------------------------- ### Get Activity Classes Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/module-index.md Fetches activity classification rules from the server. If the server fetch fails, it returns a predefined list of default classes. ```python def get_classes() -> List[Tuple[List[str], dict]] ``` -------------------------------- ### POST /query/ Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Executes a server-side query using ActivityWatch Query Language (AWQL) and returns the results. ```APIDOC ## POST /query/ ### Description Executes a server-side query using ActivityWatch Query Language. ### Method POST ### Endpoint /api/0/query/ ### Parameters #### Query Parameters - **name** (string) - Optional - Query name (required if cache=1) - **cache** (boolean) - Optional - Cache results for 24 hours (0 or 1) #### Request Body - **timeperiods** (array[string]) - Required - Time periods in format "start/end" (ISO 8601) - **query** (array[string]) - Required - AWQuery statements, each ending with semicolon ### Request Example ```json { "timeperiods": [ "2024-01-15T00:00:00+00:00/2024-01-16T00:00:00+00:00" ], "query": [ "events = flood(query_bucket(find_bucket(\"aw-watcher-window_myhost\")));", "RETURN = events;" ] } ``` ### Response #### Success Response (200 OK) - **Response Format**: Array of results, one per timeperiod; structure depends on query #### Response Example ```json [ [ { "id": 1, "timestamp": "2024-01-15T12:00:00+00:00", "duration": 300, "data": {"app": "vim"} } ] ] ``` ### Status Codes - **200**: Query executed successfully - **400**: Invalid query syntax - **500**: Query execution error ``` -------------------------------- ### Check Thread Stop Signal Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/request-queue.md Returns whether the thread has been signaled to stop. No setup or specific usage notes beyond its direct purpose. ```python def should_stop(self) -> bool: pass ``` -------------------------------- ### List Buckets with aw-client CLI Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/INDEX.md Use the `aw-client buckets` command to list available buckets on the ActivityWatch server. This is a basic command for server introspection. ```bash # List buckets aw-client buckets ``` -------------------------------- ### Load aw-client Configuration Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/configuration.md Loads aw-client configuration from TOML files, falling back to defaults if keys are missing. Configuration includes server and client settings. ```python from aw_client.config import load_config config = load_config() print(config["server"]["hostname"]) # "127.0.0.1" print(config["client"]["commit_interval"]) # 10 ``` -------------------------------- ### Handle 'Connection refused' Error Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/errors.md This error indicates the ActivityWatch server is not running or is inaccessible. Ensure the server is started or connect to a different host/port if necessary. ```python # Cause: Server not running # Fix: Start aw-server # aw-server # Or check if on different host/port client = ActivityWatchClient(host="example.com", port=5600) ``` -------------------------------- ### Define CategorySpec Type Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/types.md Defines a dictionary structure for a category rule specification. This example shows a rule of type 'regex' for matching event titles. ```python CategorySpec = Dict[str, Any] ``` -------------------------------- ### get_setting Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Retrieves server settings. If a key is provided, it returns the value for that specific setting; otherwise, it returns a dictionary of all settings. ```APIDOC ## get_setting ### Description Retrieves server settings. If a key is provided, it returns the value for that specific setting; otherwise, it returns a dictionary of all settings. ### Method Signature ```python def get_setting(self, key: Optional[str] = None) -> dict ``` ### Parameters #### Path Parameters - **key** (Optional[str]) - Optional - Specific setting key to retrieve; if None, returns all settings ### Returns Dictionary of settings or a single setting value ### Example ```python # Retrieve all settings all_settings = client.get_setting() # Retrieve a specific setting classes = client.get_setting("classes") ``` ``` -------------------------------- ### Register Bucket for Creation Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/request-queue.md Register a bucket to be created when the queue thread connects to the server. If the thread is already connected, it attempts immediate creation. Failed immediate creation will trigger a reconnect. ```python def register_bucket(self, bucket_id: str, event_type: str) -> None ``` ```python client.request_queue.register_bucket("my-bucket", "event") ``` -------------------------------- ### Wait for Server Start Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Blocks until the server responds to a ping request or the specified timeout is reached. Raises an exception if the server does not respond within the timeout period. ```python client.wait_for_start(timeout=10) ``` -------------------------------- ### Use Testing Server Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/cli.md Utilize the testing server ports and configuration by using the --testing flag. This is useful for development and testing purposes. ```bash aw-client --testing buckets ``` -------------------------------- ### JSON Response for Heartbeat Event Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Example of a successful JSON response after sending a heartbeat event. The response includes the ID and details of the processed heartbeat event. ```json { "id": 3, "timestamp": "2024-01-15T12:05:00+00:00", "duration": 0, "data": {"app": "vim", "title": "main.py"} } ``` -------------------------------- ### wait_for_start Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Blocks until the server responds to a ping request or timeout is reached. ```APIDOC ## wait_for_start ### Description Blocks until the server responds to a ping request or timeout is reached. ### Method wait_for_start ### Parameters #### Query Parameters - **timeout** (int) - Optional - Maximum seconds to wait for server startup (Default: 10) ### Returns None ### Raises - `Exception`: If server does not respond within timeout period ``` -------------------------------- ### Handle General Configuration Errors Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/errors.md Catch general exceptions during configuration loading. This can occur due to invalid TOML syntax, missing, or unreadable configuration files. The client logs a warning and uses defaults. ```python from aw_client.config import load_config try: config = load_config() except Exception as e: print(f"Config error: {e}") ``` -------------------------------- ### get_info Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Retrieves basic server information. ```APIDOC ## get_info ### Description Retrieves basic server information. ### Method get_info ### Parameters None ### Returns Dictionary containing at least keys 'hostname' and 'testing' ### Example ```python info = client.get_info() print(info) # Output: {'hostname': 'myhost', 'testing': False, ...} ``` ``` -------------------------------- ### GET Request to Retrieve Single Event Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md Retrieve a specific event by its unique ID from a given bucket. This is useful for fetching details of a single recorded activity. ```http GET /api/0/buckets/aw-watcher-window_myhost/events/1 Authorization: Bearer {api_key} ``` -------------------------------- ### Define Desktop Query Parameters Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/queries.md Parameters for desktop activity analysis. Extends QueryParams with desktop-specific bucket IDs. ```python @dataclass class DesktopQueryParams(QueryParams, _DesktopQueryParamsBase): pass ``` -------------------------------- ### JSON Response for Retrieved Events Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/rest-api.md This is an example of a successful JSON response when retrieving multiple events from a bucket. Each event includes an ID, timestamp, duration, and associated data. ```json [ { "id": 1, "timestamp": "2024-01-15T12:00:00+00:00", "duration": 300, "data": { "app": "vim", "title": "main.py" } }, { "id": 2, "timestamp": "2024-01-15T12:05:00+00:00", "duration": 150, "data": { "app": "firefox", "title": "GitHub" } } ] ``` -------------------------------- ### Initialize ActivityWatchClient Source: https://github.com/activitywatch/aw-client/blob/master/_autodocs/activity-watch-client.md Initializes a client connection to an ActivityWatch server. Can connect to default local, testing, or remote servers. Using a context manager ensures automatic connection and disconnection. ```python from aw_client import ActivityWatchClient # Connect to default local server client = ActivityWatchClient("my-watcher") # Connect to testing server client = ActivityWatchClient("my-watcher", testing=True) # Connect to remote server client = ActivityWatchClient("my-watcher", host="192.168.1.100", port=5600) # Using context manager for automatic connection/disconnection with ActivityWatchClient("my-watcher") as client: buckets = client.get_buckets() ```