### Minimal Example: Get Events from a Bucket Source: https://docs.activitywatch.net/en/latest/examples/working-with-data.html This is a minimal example demonstrating how to retrieve all events from a specified bucket. ```activitywatch events = query_bucket("my_bucket"); RETURN = events; ``` -------------------------------- ### Minimal Python Watcher Example Source: https://docs.activitywatch.net/en/latest/examples/writing-watchers.html This minimal client example demonstrates creating a bucket, inserting an event, fetching it, and deleting the bucket. It runs in testing mode, requiring aw-server to also be started with the --testing flag. ```Python #!/usr/bin/env python3 from datetime import datetime, timezone from aw_core.models import Event from aw_client import ActivityWatchClient # We'll run with testing=True so we don't mess up any production instance. # Make sure you've started aw-server with the `--testing` flag as well. client = ActivityWatchClient("test-client", testing=True) bucket_id = "{}_{}".format("test-client-bucket", client.client_hostname) client.create_bucket(bucket_id, event_type="dummydata") shutdown_data = {"label": "some interesting data"} now = datetime.now(timezone.utc) shutdown_event = Event(timestamp=now, data=shutdown_data) inserted_event = client.insert_event(bucket_id, shutdown_event) events = client.get_events(bucket_id=bucket_id, limit=1) print(events) # Should print a single event in a list client.delete_bucket(bucket_id) ``` -------------------------------- ### Install Rust Nightly Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Install the Rust nightly toolchain using rustup. ```bash rustup update ``` -------------------------------- ### Rust Watcher Example Source: https://docs.activitywatch.net/en/latest/examples/writing-watchers.html This comprehensive example shows how to create buckets, send events using heartbeats and direct inserts, perform synchronous and asynchronous requests, fetch events, and delete buckets using the ActivityWatch Rust client. ```rust use aw_client_rust::AwClient; use aw_models::{Bucket, Event}; use chrono::TimeDelta; use serde_json::{Map, Value}; async fn create_bucket( aw_client: &AwClient, bucket_id: String, event_type: String, ) -> Result<(), Box> { let res = aw_client .create_bucket(&Bucket { id: bucket_id, bid: None, _type: event_type, data: Map::new(), metadata: Default::default(), last_updated: None, hostname: "".to_string(), client: "test-client".to_string(), created: None, events: None, }) .await?; Ok(res) } #[tokio::main] async fn main() { let port = 5666; // the testing port let aw_client = AwClient::new("localhost", port, "test-client").unwrap(); let bucket_id = format!("test-client-bucket_{}", aw_client.hostname); let event_type = "dummy_data".to_string(); // Note that in a real application, you would want to handle these errors create_bucket(&aw_client, bucket_id.clone(), event_type) .await .unwrap(); let sleeptime = 1.0; for i in 0..5 { // Create a sample event to send as heartbeat let mut heartbeat_data = Map::new(); heartbeat_data.insert("label".to_string(), Value::String("heartbeat".to_string())); let now = chrono::Utc::now(); let heartbeat_event = Event { id: None, timestamp: now, duration: TimeDelta::seconds(1), data: heartbeat_data, }; println!("Sending heartbeat event {}", i); // The rust client does not support queued heartbeats, or commit intervals aw_client .heartbeat(&bucket_id, &heartbeat_event, sleeptime + 1.0) .await .unwrap(); // Sleep a second until next heartbeat (eventually drifts due to time spent in the loop) // You could use wait on tokio intervals to avoid drift tokio::time::sleep(tokio::time::Duration::from_secs_f64(sleeptime)).await; } // Sleep a bit more to allow the last heartbeat to be sent tokio::time::sleep(tokio::time::Duration::from_secs_f64(sleeptime)).await; // Synchoronous example, insert an event let mut event_data = Map::new(); event_data.insert( "label".to_string(), Value::String("non-heartbeat event".to_string()), ); let now = chrono::Utc::now(); let event = Event { id: None, timestamp: now, duration: TimeDelta::seconds(1), data: event_data, }; aw_client.insert_event(&bucket_id, &event).await.unwrap(); // fetch the last 10 events // should include the first 5 heartbeats and the last event let events = aw_client .get_events(&bucket_id, None, None, Some(10)) .await .unwrap(); println!("Events: {:?}", events); // Delete the bucket aw_client.delete_bucket(&bucket_id).await.unwrap(); } ``` -------------------------------- ### Install Poetry Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Install the Poetry dependency manager using pip. ```bash python3 -m pip install poetry ``` -------------------------------- ### Install PyInstaller and Development Headers Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Install PyInstaller and Python development headers required for packaging. Use the appropriate command for your Linux distribution. ```bash apt install python3-dev # Or equivalent for your Linux distribution pip3 install --user pyinstaller ``` -------------------------------- ### Build ActivityWatch Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Builds and installs all ActivityWatch components into the activated virtual environment. ```bash make build ``` -------------------------------- ### Python Watcher Example Source: https://docs.activitywatch.net/en/latest/examples/writing-watchers.html This comprehensive example demonstrates creating buckets, sending events via heartbeats and direct insertion, performing synchronous and asynchronous requests, and fetching events from an aw-server bucket. It also includes cleanup by deleting the bucket. Ensure aw-server is running with the `--testing` flag. ```Python #!/usr/bin/env python3 from time import sleep from datetime import datetime, timezone from aw_core.models import Event from aw_client import ActivityWatchClient # We'll run with testing=True so we don't mess up any production instance. # Make sure you've started aw-server with the `--testing` flag as well. client = ActivityWatchClient("test-client", testing=True) # Make the bucket_id unique for both the client and host # The convention is to use client-name_hostname as bucket name, # but if you have multiple buckets in one client you can add a # suffix such as client-name-event-type or similar bucket_id = "{}_{}".format("test-client-bucket", client.client_hostname) # A short and descriptive event type name # Will be used by visualizers (such as aw-webui) to detect what type and format the events are in # Can for example be "currentwindow", "afkstatus", "ping" or "currentsong" event_type = "dummydata" # First we need a bucket to send events/heartbeats to. # If the bucket already exists aw-server will simply return 304 NOT MODIFIED, # so run this every time the clients starts up to verify that the bucket exists. # If the client was unable to connect to aw-server or something failed # during the creation of the bucket, an exception will be raised. client.create_bucket(bucket_id, event_type=event_type) # Asynchronous loop example # This context manager starts the queue dispatcher thread and stops it when done, always use it when setting queued=True. # Alternatively you can use client.connect() and client.disconnect() instead if you prefer that with client: # Now we can send some events via heartbeats # This will send one heartbeat every second 5 times sleeptime = 1 for i in range(5): # Create a sample event to send as heartbeat heartbeat_data = {"label": "heartbeat"} now = datetime.now(timezone.utc) heartbeat_event = Event(timestamp=now, data=heartbeat_data) # The duration between the heartbeats will be less than pulsetime, so they will get merged. # The commit_interval=4.0 means that if heartbeats with the same data has a longer duration than 4 seconds it will be forced to be sent to aw-server # TODO: Make a section with an illustration on how heartbeats work and insert a link here print("Sending heartbeat {}".format(i)) client.heartbeat(bucket_id, heartbeat_event, pulsetime=sleeptime+1, queued=True, commit_interval=4.0) # Sleep a second until next heartbeat sleep(sleeptime) # Give the dispatcher thread some time to complete sending the last events. # If we don't do this the events might possibly queue up and be sent the # next time the client starts instead. sleep(1) # Synchronous example, insert an event event_data = {"label": "non-heartbeat event"} now = datetime.now(timezone.utc) event = Event(timestamp=now, data=event_data) inserted_event = client.insert_event(bucket_id, event) # The event returned from insert_event has been assigned an id by aw-server assert inserted_event.id is not None # Fetch last 10 events from bucket # Should be two events in order of newest to oldest # - "shutdown" event with a duration of 0 # - "heartbeat" event with a duration of 5*sleeptime events = client.get_events(bucket_id=bucket_id, limit=10) print(events) # Now lets clean up after us. # You probably don't want this in your watchers though! client.delete_bucket(bucket_id) # If something doesn't work, run aw-server with --verbose to see why some request doesn't go through # Good luck with writing your own watchers :-) ``` -------------------------------- ### Start ActivityWatch Script Source: https://docs.activitywatch.net/en/latest/running-on-gnome.html This bash script starts the ActivityWatch watchers and server. It assumes ActivityWatch is installed in ~/.local/opt/activitywatch. It can optionally exclude window title tracking and send a notification upon startup. ```bash #!/bin/bash cd ~/.local/opt/activitywatch # Put your ActivityWatch install folder here ./aw-watcher-afk/aw-watcher-afk & ./aw-watcher-window/aw-watcher-window & # you can add --exclude-title here to exclude window title tracking for this session only notify-send "ActivityWatch started" # Optional, sends a notification when ActivityWatch is started ./aw-server/aw-server; ``` -------------------------------- ### GNOME Desktop Entry for Starting ActivityWatch Source: https://docs.activitywatch.net/en/latest/running-on-gnome.html This .desktop file configures an application entry in GNOME to launch the ActivityWatch start script. It specifies the name, comment, execution command, and icon. ```desktop [Desktop Entry] Name=Start ActivityWatch Comment=Start AW Exec="~/.local/opt/activitywatch/start.sh" Hidden=false Terminal=false Type=Application Version=1.0 Icon=activitywatch Categories=Utility; ``` -------------------------------- ### Check Make Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that the 'make' command is installed and accessible, particularly for Windows users. ```bash make --version ``` -------------------------------- ### Setup Bucket Source: https://docs.activitywatch.net/en/latest/api/python.html Configures a bucket with a specific ID and event type. This is often a prerequisite for creating or using a bucket. ```python client.setup_bucket('my-bucket-id', 'my-event-type') ``` -------------------------------- ### Hierarchy Example: Create App-Title Hierarchy Source: https://docs.activitywatch.net/en/latest/examples/working-with-data.html This example shows how to group events by both 'app' and 'title' keys to create a hierarchical structure. ```activitywatch events = query_bucket("my_bucket"); events = merge_events_by_keys(events, ["app", "title"]); RETURN = events; ``` -------------------------------- ### Check Node.js Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that Node.js is installed and accessible in the system's PATH. ```bash node --version ``` -------------------------------- ### Run ActivityWatch Tray Icon Manager Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Starts the ActivityWatch tray icon manager, which is the recommended way to run the application for normal use. ```bash aw-qt ``` -------------------------------- ### Check npm Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that npm is installed and accessible in the system's PATH. ```bash npm --version ``` -------------------------------- ### Waiting for Server Initialization Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Polls the server to check if it has started. It retries with increasing delays up to a specified timeout. Raises an exception if the server does not start within the timeout period. ```python def wait_for_start(self, timeout: int = 10) -> None: """Wait for the server to start by trying to get the server info.""" start_time = datetime.now() sleep_time = 0.1 while (datetime.now() - start_time).seconds < timeout: try: self.get_info() break except req.exceptions.ConnectionError: sleep(sleep_time) sleep_time *= 2 else: raise Exception(f"Server at {self.server_address} did not start in time") ``` -------------------------------- ### Check Git Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that Git is installed and accessible in the system's PATH. ```bash git --version ``` -------------------------------- ### Setup Bucket for Queued Operations Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html A convenience method to set up a bucket for queued operations, essentially calling create_bucket with queued=True. ```python [docs] def setup_bucket(self, bucket_id: str, event_type: str): self.create_bucket(bucket_id, event_type, queued=True) ``` -------------------------------- ### Get Server Setting Source: https://docs.activitywatch.net/en/latest/api/python.html Retrieves a specific server setting by its key. If no key is provided, all settings are returned. ```python setting_value = client.get_setting('some_key') ``` -------------------------------- ### Run Individual ActivityWatch Modules Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Starts individual ActivityWatch modules separately, recommended for development purposes. ```bash aw-server ``` ```bash aw-watcher-afk ``` ```bash aw-watcher-window ``` -------------------------------- ### Check Poetry Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that Poetry is installed and accessible in the system's PATH. ```bash poetry --version ``` -------------------------------- ### Getting Server Settings Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Retrieve server settings. If a key is provided, it fetches a specific setting; otherwise, it retrieves all settings. ```python def get_setting(self, key: Optional[str] = None) -> dict: if key: return self._get(f"settings/{key}").json() else: return self._get("settings").json() ``` -------------------------------- ### Check Python Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that Python 3 is installed and accessible in the system's PATH. ```bash python --version ``` -------------------------------- ### Get Server Setting Source: https://docs.activitywatch.net/en/latest/_modules/aw_server/api.html Retrieves a specific server setting by its key. Returns None if the key is not found. ```python def get_setting(self, key): """Get a setting""" return self.settings.get(key, None) ``` -------------------------------- ### Wait for Server Start Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Waits for the ActivityWatch server to become available, with a specified timeout. ```APIDOC ## Wait for Start ### Description Waits for the ActivityWatch server to start by repeatedly attempting to get server info. Raises an exception if the server does not start within the specified timeout. ### Method Client Method ### Endpoint N/A ### Parameters #### Query Parameters - **timeout** (int) - Optional - The maximum time in seconds to wait for the server to start. Defaults to 10 seconds. ### Response #### Success Response - **None** - Indicates the server has started successfully. ``` -------------------------------- ### Wait for Server Start Source: https://docs.activitywatch.net/en/latest/api/python.html Blocks execution until the ActivityWatch server becomes available, by attempting to retrieve server info. Includes a timeout. ```python client.wait_for_start(timeout=30) ``` -------------------------------- ### Export all buckets using wget Source: https://docs.activitywatch.net/en/latest/features/exporting-data.html Use wget to make a GET request to the REST API to export all buckets. Specify the output file path with -O. ```bash wget http://localhost:5600/api/0/export -O path/to/export.json ``` -------------------------------- ### setup_bucket Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Sets up a bucket for queued event handling. ```APIDOC ## POST /buckets/{bucket_id} ### Description Sets up a bucket for queued event handling. This is a convenience method that calls `create_bucket` with `queued=True`. ### Method POST ### Endpoint /buckets/{bucket_id} ### Parameters #### Path Parameters - **bucket_id** (str) - Required - The ID for the new bucket. #### Request Body - **event_type** (str) - Required - The type of events this bucket will store. ### Response #### Success Response (200) Indicates the bucket was created successfully. ``` -------------------------------- ### Main Server Startup Function Source: https://docs.activitywatch.net/en/latest/_modules/aw_server/main.html The main function orchestrates the server startup process. It parses settings, sets up logging, and initiates the server using the parsed configuration. ```python import logging import sys from aw_core.log import setup_logging from aw_datastore import get_storage_methods from . import __version__ from .config import config from .server import _start logger = logging.getLogger(__name__) def main(): """Called from the executable and __main__.py""" settings, storage_method = parse_settings() # FIXME: The LogResource API endpoint relies on the log being in JSON format # at the path specified by aw_core.log.get_log_file_path(). We probably want # to write the LogResource API so that it does not depend on any physical file # but instead add a logging handler that it can use privately. # That is why log_file_json=True currently. # UPDATE: The LogResource API is no longer available so log_file_json is now False. setup_logging( "aw-server", testing=settings.testing, verbose=settings.verbose, log_stderr=True, log_file=True, ) logger.info(f"Using storage method: {settings.storage}") if settings.testing: logger.info("Will run in testing mode") if settings.custom_static: logger.info(f"Using custom_static: {settings.custom_static}") logger.info("Starting up...") _start( host=settings.host, port=settings.port, testing=settings.testing, storage_method=storage_method, cors_origins=settings.cors_origins, custom_static=settings.custom_static, ) ``` -------------------------------- ### Get Event Count with Filters Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Retrieves the total count of events within a bucket, with optional filtering by start and end times. Returns the count as an integer. ```python [docs] def get_eventcount( self, bucket_id: str, limit: int = -1, start: Optional[datetime] = None, end: Optional[datetime] = None, ) -> int: endpoint = f"buckets/{bucket_id}/events/count" params = dict() # type: Dict[str, str] if start is not None: params["start"] = start.isoformat() if end is not None: params["end"] = end.isoformat() response = self._get(endpoint, params=params) return int(response.text) ``` -------------------------------- ### Configure aw-server-rust Autostart Source: https://docs.activitywatch.net/en/latest/migrating.html Set aw-server-rust as the default server by modifying the aw-qt.toml configuration file. Ensure the relevant lines are uncommented for the settings to be applied. ```toml [aw-qt] autostart_modules = ["aw-server-rust", "aw-watcher-afk", "aw-watcher-window"] ``` -------------------------------- ### Get All Buckets Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Retrieves a dictionary containing all available buckets on the server. This is a simple GET request to the buckets endpoint. ```python [docs] def get_buckets(self) -> dict: return self._get("buckets/").json() ``` -------------------------------- ### Minimal Rust ActivityWatch Client Example Source: https://docs.activitywatch.net/en/latest/examples/writing-watchers.html This minimal Rust client demonstrates creating a bucket, inserting an event, fetching an event, and deleting the bucket. It requires the `aw-client-rust` and `aw-models` crates. ```rust use aw_client_rust::AwClient; use aw_models::{Bucket, Event}; use chrono::TimeDelta; use serde_json::{Map, Value}; async fn create_bucket( aw_client: &AwClient, bucket_id: String, ) -> Result<(), Box> { let res = aw_client .create_bucket(&Bucket { id: bucket_id, bid: None, _type: "dummy_data".to_string(), data: Map::new(), metadata: Default::default(), last_updated: None, hostname: "".to_string(), client: "test-client".to_string(), created: None, events: None, }) .await?; Ok(res) } #[tokio::main] async fn main() { let port = 5666; // the testing port let aw_client = AwClient::new("localhost", port, "test-client").unwrap(); let bucket_id = format!("test-client-bucket_{}", aw_client.hostname); create_bucket(&aw_client, bucket_id.clone()).await.unwrap(); let mut shutdown_data = Map::new(); shutdown_data.insert( "label".to_string(), Value::String("some interesting data".to_string()), ); let now = chrono::Utc::now(); let shutdown_event = Event { id: None, timestamp: now, duration: TimeDelta::seconds(420), data: shutdown_data, }; aw_client.insert_event(&bucket_id, &shutdown_event).await.unwrap(); let events = aw_client.get_events(&bucket_id, None, None, Some(1)).await.unwrap(); print!("{:?}", events); // prints a single event aw_client.delete_bucket(&bucket_id).await.unwrap(); } ``` -------------------------------- ### aw_server.main Source: https://docs.activitywatch.net/en/latest/api/python.html Entry point for the ActivityWatch server executable. ```APIDOC ## aw_server.main ### Description Called from the executable and __main__.py to start the ActivityWatch server. ``` -------------------------------- ### Get Events Source: https://docs.activitywatch.net/en/latest/api/rest.html Retrieves events from a specific bucket. ```APIDOC ## GET /api/0/buckets//events ### Description Retrieves events from a specific bucket. ### Method GET ### Endpoint /api/0/buckets//events ### Parameters #### Path Parameters - **bucket_id** (string) - Required - The ID of the bucket from which to retrieve events. ``` -------------------------------- ### Get Setting Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Retrieves a specific setting or all settings from the ActivityWatch server. ```APIDOC ## GET /settings/{key} ### Description Retrieves a specific setting by its key, or all settings if no key is provided. ### Method GET ### Endpoint /settings/{key} or /settings/ ### Parameters #### Path Parameters - **key** (string) - Optional - The key of the setting to retrieve. ### Response #### Success Response (200) - **settings** (dict) - A dictionary containing the requested setting(s). ``` -------------------------------- ### Get Events from Bucket Source: https://docs.activitywatch.net/en/latest/api/rest.html Retrieves events associated with a specific bucket. ```http GET /api/0/buckets//events ``` -------------------------------- ### Query Bucket with Categories and Filtering Source: https://docs.activitywatch.net/en/latest/examples/working-with-data.html This example shows how to query buckets, find relevant buckets using a pattern, filter out non-active periods, apply categorization rules, and filter for specific categories like 'Work'. ```activitywatch events = flood(query_bucket(find_bucket("aw-watcher-window_"))); not_afk = flood(query_bucket(find_bucket("aw-watcher-afk_"))); not_afk = filter_keyvals(not_afk, "status", ["not-afk"]); events = filter_period_intersect(events, not_afk); events = categorize(events, __CATEGORIES__); events = filter_keyvals(events, "$category", [["Work"]]); RETURN = sort_by_duration(events); ``` -------------------------------- ### Setup Logging Source: https://docs.activitywatch.net/en/latest/api/python.html Configures the logging system for an ActivityWatch service. Allows for specifying service name, testing mode, verbosity, and whether to log to stderr or a file. ```python aw_core.log.setup_logging(_name : str_, _testing =False_, _verbose =False_, _log_stderr =True_, _log_file =False_)[source]ΒΆ ``` -------------------------------- ### Check 7-Zip Availability Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that 7-Zip is installed and accessible, which is optional for packaging. ```bash 7z ``` -------------------------------- ### Package ActivityWatch Executables Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Run the 'make package' command to create portable executables for ActivityWatch. The output will be in the ./dist folder. ```bash make package ``` -------------------------------- ### Run Rust Server Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Executes the ActivityWatch Rust server from its build output directory. ```bash aw-server-rust/target/package/aw-server-rust ``` -------------------------------- ### Setup Logging Configuration Source: https://docs.activitywatch.net/en/latest/_modules/aw_core/log.html Configures the root logger to handle log messages. Supports setting log level via environment variable, logging to stderr, and logging to files with rotation. Use `verbose=True` for DEBUG level. ```python import logging import os import sys from datetime import datetime from logging.handlers import RotatingFileHandler from typing import List, Optional from . import dirs from .decorators import deprecated # NOTE: Will be removed in a future version since it's not compatible # with running a multi-service process. # TODO: prefix with `_` log_file_path = None [docs] @deprecated def get_log_file_path() -> Optional[str]: # pragma: no cover """DEPRECATED: Use get_latest_log_file instead.""" return log_file_path [docs] def setup_logging( name: str, testing=False, verbose=False, log_stderr=True, log_file=False, ): root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG if verbose else logging.INFO) root_logger.handlers = [] # run with LOG_LEVEL=DEBUG to customize log level across all AW components log_level = os.environ.get("LOG_LEVEL") if log_level: if hasattr(logging, log_level.upper()): root_logger.setLevel(getattr(logging, log_level.upper())) else: root_logger.warning( f"No logging level called {log_level} (as specified in env var)" ) if log_stderr: root_logger.addHandler(_create_stderr_handler()) if log_file: root_logger.addHandler(_create_file_handler(name, testing=testing)) def excepthook(type_, value, traceback): root_logger.exception("Unhandled exception", exc_info=(type_, value, traceback)) # call the default excepthook if log_stderr isn't true # (otherwise it'll just get duplicated) if not log_stderr: sys.__excepthook__(type_, value, traceback) sys.excepthook = excepthook ``` -------------------------------- ### Get Bucket Metadata Source: https://docs.activitywatch.net/en/latest/api/rest.html Retrieves metadata for a specific bucket. Returns 404 if the bucket does not exist. ```APIDOC ## GET /api/0/buckets/ ### Description Retrieves metadata for a specific bucket. ### Method GET ### Endpoint /api/0/buckets/ ### Parameters #### Path Parameters - **bucket_id** (string) - Required - The ID of the bucket to retrieve metadata for. ``` -------------------------------- ### Create Namespace Source: https://docs.activitywatch.net/en/latest/_modules/aw_query/query2.html Initializes and returns a dictionary representing the query namespace, including boolean values. ```python def create_namespace() -> dict: namespace = { "True": True, "False": False, "true": True, "false": False, } return namespace ``` -------------------------------- ### Get Bucket Metadata Source: https://docs.activitywatch.net/en/latest/api/rest.html Retrieves metadata for a specific bucket. Returns 404 if the bucket does not exist. ```http GET /api/0/buckets/ ``` -------------------------------- ### Run Tests Source: https://docs.activitywatch.net/en/latest/development.html Execute both standard and integration tests. ```bash make test && make test-integration ``` -------------------------------- ### get_eventcount Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Retrieves the total count of events in a bucket, with optional filtering by start and end times. ```APIDOC ## GET /buckets/{bucket_id}/events/count ### Description Retrieves the total count of events in a bucket, with optional filtering by start and end times. ### Method GET ### Endpoint /buckets/{bucket_id}/events/count ### Parameters #### Path Parameters - **bucket_id** (str) - Required - The ID of the bucket to get the event count from. #### Query Parameters - **start** (datetime) - Optional - The start of the time range for the count. - **end** (datetime) - Optional - The end of the time range for the count. ### Response #### Success Response (200) - **count** (int) - The total number of events in the bucket within the specified time range. ### Response Example { "example": "12345" } ``` -------------------------------- ### get_events Source: https://docs.activitywatch.net/en/latest/_modules/aw_client/client.html Retrieves events from a specified bucket, with optional filtering by limit, start, and end times. ```APIDOC ## GET /buckets/{bucket_id}/events ### Description Retrieves events from a specified bucket, with optional filtering by limit, start, and end times. ### Method GET ### Endpoint /buckets/{bucket_id}/events ### Parameters #### Query Parameters - **limit** (int) - Optional - The maximum number of events to retrieve. - **start** (datetime) - Optional - The start of the time range for events. - **end** (datetime) - Optional - The end of the time range for events. ### Response #### Success Response (200) - **events** (list) - A list of event objects. ### Response Example { "example": "[{"timestamp": "2023-10-27T10:00:00Z", "duration": 300, "label": "Example Event", "metadata": {}} ...]" } ``` -------------------------------- ### ServerAPI.create_bucket Source: https://docs.activitywatch.net/en/latest/_modules/aw_server/api.html Creates a new bucket on the server. If hostname is set to '!local', the server's hostname and device ID will be used. ```APIDOC ## ServerAPI.create_bucket ### Description Create a bucket. If hostname is "!local", the hostname and device_id will be set from the server info. This is useful for watchers which are known/assumed to run locally but might not know their hostname (like aw-watcher-web). ### Method POST ### Endpoint /api/1/buckets ### Parameters #### Request Body - **bucket_id** (string) - Required - The ID for the new bucket. - **event_type** (string) - Required - The type of events this bucket will store. - **client** (string) - Required - The client creating the bucket. - **hostname** (string) - Required - The hostname for the bucket. Use "!local" to use the server's hostname. - **created** (string) - Optional - The ISO 8601 formatted creation timestamp for the bucket. If not provided, the current time will be used. - **data** (object) - Optional - Additional metadata for the bucket. ### Request Example ```json { "bucket_id": "new-local-bucket", "event_type": "activity", "client": "aw-watcher-local", "hostname": "!local", "created": "2023-10-27T14:00:00+00:00", "data": {"description": "Bucket for local activity tracking"} } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the bucket was created successfully. ### Response Example ```json { "message": "Bucket 'new-local-bucket' created successfully." } ``` ``` -------------------------------- ### Check Cargo Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that the Cargo build tool is installed and accessible in the system's PATH. ```bash cargo --version ``` -------------------------------- ### ServerAPI.import_all Source: https://docs.activitywatch.net/en/latest/_modules/aw_server/api.html Imports multiple buckets and their events into the server. The input is a dictionary of buckets, where keys are bucket IDs. ```APIDOC ## ServerAPI.import_all ### Description Imports all buckets and their events from a provided dictionary. ### Method POST ### Endpoint /api/1/import ### Parameters #### Request Body - **buckets** (object) - Required - A dictionary where keys are bucket IDs and values are the bucket data objects to be imported. ### Request Example ```json { "buckets": { "bucket-to-import-1": { "id": "bucket-to-import-1", "type": "events", "client": "aw-watcher-import", "hostname": "import-host", "created": "2023-10-27T13:00:00+00:00", "events": [ { "timestamp": "2023-10-27T13:01:00+00:00", "duration": 60, "data": {"status": "imported"} } ] }, "bucket-to-import-2": { "id": "bucket-to-import-2", "type": "events", "client": "aw-watcher-import", "hostname": "import-host", "created": "2023-10-27T13:05:00+00:00", "events": [ { "timestamp": "2023-10-27T13:06:00+00:00", "duration": 120, "data": {"status": "processed"} } ] } } } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating successful import of all buckets. ### Response Example ```json { "message": "All buckets imported successfully." } ``` ``` -------------------------------- ### Check Rust Compiler Version Source: https://docs.activitywatch.net/en/latest/installing-from-source.html Verify that the Rust compiler is installed and accessible in the system's PATH. ```bash rustc --version ```