ha-whodid
Get userid from context objects, even if the context itself does not have a userid provided.
How it works
After creating the WhoDid instance, all events will be monitored. \
For every event, the context id is stored together with its user id and parent id (in a bounded cache, oldest entries are dropped first). \
Automations and scripts create a new context whose parent id points to the context that triggered them. getUserId follows this parent chain back to its root, so a user is found even through several automations/scripts in a row. \
If the root has neither a user nor a parent, the change came from a device or integration and None is returned right away.
getOrigin(context) returns the full picture: kind ("user", "system" for device/integration, or "unknown" if the chain could not be followed), user_id, and chain, the automations/scripts that were passed through.
All integrations using this package will share a single instance. \
This is done to save memory.
Example code
from hawhodid import WhoDid
async def handle_servicecall(call: ServiceCall):
whodidInstance = WhoDid(hass=call.hass)
userid = await whodidInstance.getUserId(context=call.context)
if userid == None:
return
origin = await whodidInstance.getOrigin(context=call.context)
# Origin(kind="user", user_id="...", chain=["automation.b", "script.s"])
This best to put WhoDid(hass=hass) into the setup or async_setup function of your integration to ensure that all events from the beginning are accounted for.
Work in progress
This is a bare bones implementation, that i made for my own integrations. \
I only made this to prevent code duplication and reduce memory usage. \
If you need something for you or any bugs, just create an issue or provide a solution with a PR. \
Both are appreciated.
Releasing
- Bump
version in pyproject.toml and merge to main.
- Either run the Tag main workflow (Actions tab, run on
main), which tags main as v<version> and publishes it, or create a branch/tag named v<version> (e.g. v0.0.2) yourself.
The Publish to PyPI workflow runs only for those two cases, never on pushes or merges to main. It fails if the ref name does not match the pyproject.toml version. It uses the PYPI_PASSWORD secret (a PyPI API token).