urban-arrow-api 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.apks
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Koen Hendriks
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.5
2
+ Name: urban-arrow-api
3
+ Version: 0.1.0
4
+ Summary: Async Python client for the Urban Arrow (Pon Connected) bike cloud API
5
+ Project-URL: Homepage, https://github.com/koenhendriks/urban-arrow-api
6
+ Project-URL: Issues, https://github.com/koenhendriks/urban-arrow-api/issues
7
+ Project-URL: Changelog, https://github.com/koenhendriks/urban-arrow-api/releases
8
+ Author: Koen Hendriks
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cargo bike,e-bike,home assistant,pon,urban arrow
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Home Automation
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: aiohttp>=3.9
21
+ Description-Content-Type: text/markdown
22
+
23
+ # urban-arrow-api
24
+
25
+ Async Python client for the cloud API behind the Urban Arrow app
26
+ (`com.urbanarrow.connected` 5.2.1). Intended as the library for a Home Assistant
27
+ integration.
28
+
29
+ The API is the shared **Pon Connected** backend (also used by Gazelle and other
30
+ Pon brands); the `Manufacturer-Id: UA` header selects Urban Arrow.
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install urban-arrow-api
36
+ ```
37
+
38
+ ## Quick start
39
+
40
+ ```bash
41
+ uv sync
42
+ uv run urban-arrow login you@example.com # prompts for password, stores ~/.config/urban-arrow/token.json
43
+ uv run urban-arrow browser-login # fallback: manual browser login
44
+ uv run urban-arrow status # bike details + telemetry as JSON
45
+ uv run urban-arrow raw GET v9/bikes
46
+ ```
47
+
48
+ ```python
49
+ from urban_arrow_api import TokenAuth, UrbanArrowClient, login_with_credentials
50
+
51
+ async with aiohttp.ClientSession() as session:
52
+ token = await login_with_credentials("you@example.com", "password", session=session)
53
+ client = UrbanArrowClient(TokenAuth(session, token, on_token_update=save_token))
54
+ for summary in await client.get_bikes():
55
+ telemetry = await client.get_telemetry(summary.id)
56
+ print(telemetry.battery_charge, telemetry.location)
57
+ ```
58
+
59
+ ## Authentication
60
+
61
+ | | |
62
+ |---|---|
63
+ | Auth0 tenant | `consumer.login.pon.bike` |
64
+ | Client ID | `i2ype1HhtU4rg4LKRdBKgldnfVbVwrG6` |
65
+ | Audience | `https://app.connected.pon.bike/` |
66
+ | Scope | `openid profile offline_access email` |
67
+ | Redirect URI | `urbanarrow://consumer.login.pon.bike/android/com.urbanarrow.connected/callback` |
68
+
69
+ The password grant is **disabled** for this client (`unauthorized_client`), so
70
+ there is no direct username/password token call. Instead,
71
+ `login_with_credentials(username, password)` (`login.py`) drives Auth0's hosted
72
+ login pages over plain HTTP, the way a browser without JavaScript would:
73
+
74
+ 1. `GET /authorize` (PKCE) redirects to `/u/login/identifier?state=...`
75
+ 2. `POST` `state` + `username` redirects to `/u/login/password?state=...`
76
+ 3. `POST` `state` + `username` + `password` redirects to `/authorize/resume`,
77
+ which redirects to `urbanarrow://...callback?code=...`
78
+ 4. The code is exchanged at `/oauth/token`, same as the app.
79
+
80
+ This works because the tenant currently has no captcha or MFA on the login
81
+ pages. If Auth0 starts showing a captcha or asks for MFA, it raises
82
+ `UrbanArrowCaptchaRequired` or `UrbanArrowMfaRequired`. The manual flow
83
+ (`create_login_request` + `extract_code` + `exchange_code`, CLI
84
+ `browser-login`) stays available as a fallback: log in in a browser and paste
85
+ the `urbanarrow://...?code=...` URL back.
86
+
87
+ After login the refresh token (`offline_access`) keeps the session alive.
88
+ `UrbanArrowClient` never handles tokens itself: it asks an `AbstractAuth` for
89
+ one via `async_get_access_token()`. `TokenAuth` is the ready-made
90
+ implementation; it refreshes through Auth0 and calls `on_token_update` so the
91
+ new token can be persisted (Auth0 may rotate refresh tokens). Override
92
+ `TokenAuth.async_refresh_token` to add a fallback such as a fresh login.
93
+ `Token.as_dict()` / `Token.from_dict()` give a JSON-serialisable form for
94
+ storage.
95
+
96
+ For Home Assistant: the config flow asks for email + password, and the
97
+ integration stores the token. It also stores the credentials, so if the refresh
98
+ token is ever revoked it can log in again silently, and only start a reauth
99
+ flow when that fails.
100
+
101
+ ## Request headers
102
+
103
+ ```
104
+ Authorization: Bearer <access_token>
105
+ Manufacturer-Id: UA
106
+ Client-Type: ANDROID
107
+ Accept-Language: <lang>
108
+ ```
109
+
110
+ ## Endpoints
111
+
112
+ Base URL: `https://app.connected.pon.bike/api/`. Timestamps are epoch milliseconds.
113
+
114
+ | Method | Path | Notes | Client method |
115
+ |---|---|---|---|
116
+ | GET | `v9/bikes` | List of paired bikes | `get_bikes` |
117
+ | GET | `v11/bikes/{id}` | Details, module, firmware, subscription, notification settings | `get_bike` |
118
+ | GET | `v11/bikes/{id}/telemetry` | Battery %, charging, GPS, odometer, range, assist level, module charge | `get_telemetry` |
119
+ | GET | `v6/bikes/{id}/activity/history?timeUnit=&startDate=&cutoffDate=` | `timeUnit` WEEK/MONTH/QUARTER/YEAR, `startDate` yyyy-MM-dd, `cutoffDate` epoch ms (app uses pairing date). Returns `values: [double]` | `get_activity` |
120
+ | POST | `v1/bikes/{id}/flash-lights` | Blink lights (find my bike) | `flash_lights` |
121
+ | PUT | `v2/bikes/{id}/settings/{SETTING}/enable` / `disable` | `AUTO_PROTECTION`, `MODULE_BATTERY_MANAGEMENT`, `NOTIFICATION_*` | `set_setting` |
122
+ | PUT | `v1/bikes/{id}/theft/detection/mode` | `{"enabled": bool}` | `set_theft_protection` |
123
+ | PUT | `v1/bikes/{id}/nickname` | `{"nickname": str}` | `set_nickname` |
124
+ | GET | `v9/bikes/module/{moduleId}` | Bike by module id | `get_bike_by_module` |
125
+ | GET | `v10/bikes/frame-number/{frameNumber}` | `{isSmart, productionProfileId}` | `check_frame_number` |
126
+ | POST | `v4/bikes/{id}/theft/report` | `{policeReportNumber, customerPhoneNumber}` (PUT updates) | `report_theft` |
127
+ | POST | `v1/bikes/{id}/theft/cancel` | | `cancel_theft_report` |
128
+ | GET | `v4/notifications?version=6` | In-app inbox | `get_notifications` |
129
+ | PUT | `v7/notifications/mark-as-read` / `mark-as-unread` | `{"content": [ids]}` | `mark_notifications_read` |
130
+ | DELETE | `v7/notifications` | `{"content": [ids]}` | `delete_notifications` |
131
+ | GET | `v9/user-preferences` | `{preferredDealerId, theftNotificationSound}` | `get_user_preferences` |
132
+ | GET | `v3/pois` | Dealers / points of interest | `get_points_of_interest` |
133
+ | GET | `health-watcher/v1/health` | Backend status message (no auth needed) | `get_health` |
134
+ | GET | `v1/productionprofiles/{productionProfileId}/image` | Bike image | `image_url` |
135
+
136
+ Not wrapped (account/commerce, not useful for HA): pairing
137
+ (`v10/bikes/pairing/smart|non-smart`, `DELETE v10/bikes/{id}/pairing`),
138
+ insurance (`v9/bikes/{id}/insurance*`), subscription payments
139
+ (`v10/bikes/{id}/subscription/extension/payment/{variantId}`,
140
+ `v7/payments/sessions/*`, `v7/bikes/{id}/subscription/withdraw`), FCM push
141
+ registration (`v4/notifications/fcm/register`, `v1/notifications/fcm/unregister`),
142
+ dealers (`v3/dealers/...`), FAQ (`v4/faq`, `v3/faq/{id}`), route planning
143
+ (`v11/navigation/route`) and version checks (`v3/minimum-version/android`,
144
+ `v3/latest-release-version/ANDROID`). All reachable through `client._request`.
145
+
146
+ ## Observed values (real Family Active Line Plus, BES2 system)
147
+
148
+ - `battery.charge` and `moduleCharge`: percent (72, 22). `moduleCharge` is the
149
+ connectivity module's own backup battery, not the e-bike battery.
150
+ - `odometer`: km with 2 decimals (1705.04). `range`: km (26.0).
151
+ - `assistLevel`: integer (4).
152
+ - Each telemetry value has its own `lastUpdatedOn`; battery and location can be
153
+ hours older than assist level / range, so they come from separate reports.
154
+ - Bike details also include `category` ("Bakfiets") and `isSmart`.
155
+
156
+ ## Open questions
157
+
158
+ - Whether the refresh token rotates, and how long it lives.
159
+ - How often telemetry updates while the bike is parked or asleep.
160
+
161
+ ## Development and releases
162
+
163
+ ```bash
164
+ uv sync
165
+ uv run ruff check . && uv run ruff format --check . && uv run pytest
166
+ ```
167
+
168
+ Releases are published to PyPI by `.github/workflows/release.yaml` when a
169
+ GitHub release is published. The tag (`v0.1.0` or `0.1.0`) must match
170
+ `version` in `pyproject.toml`. PyPI trusted publishing has to be configured once
171
+ for the `pypi` environment of this repository.
172
+
173
+ ## License
174
+
175
+ MIT
@@ -0,0 +1,153 @@
1
+ # urban-arrow-api
2
+
3
+ Async Python client for the cloud API behind the Urban Arrow app
4
+ (`com.urbanarrow.connected` 5.2.1). Intended as the library for a Home Assistant
5
+ integration.
6
+
7
+ The API is the shared **Pon Connected** backend (also used by Gazelle and other
8
+ Pon brands); the `Manufacturer-Id: UA` header selects Urban Arrow.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install urban-arrow-api
14
+ ```
15
+
16
+ ## Quick start
17
+
18
+ ```bash
19
+ uv sync
20
+ uv run urban-arrow login you@example.com # prompts for password, stores ~/.config/urban-arrow/token.json
21
+ uv run urban-arrow browser-login # fallback: manual browser login
22
+ uv run urban-arrow status # bike details + telemetry as JSON
23
+ uv run urban-arrow raw GET v9/bikes
24
+ ```
25
+
26
+ ```python
27
+ from urban_arrow_api import TokenAuth, UrbanArrowClient, login_with_credentials
28
+
29
+ async with aiohttp.ClientSession() as session:
30
+ token = await login_with_credentials("you@example.com", "password", session=session)
31
+ client = UrbanArrowClient(TokenAuth(session, token, on_token_update=save_token))
32
+ for summary in await client.get_bikes():
33
+ telemetry = await client.get_telemetry(summary.id)
34
+ print(telemetry.battery_charge, telemetry.location)
35
+ ```
36
+
37
+ ## Authentication
38
+
39
+ | | |
40
+ |---|---|
41
+ | Auth0 tenant | `consumer.login.pon.bike` |
42
+ | Client ID | `i2ype1HhtU4rg4LKRdBKgldnfVbVwrG6` |
43
+ | Audience | `https://app.connected.pon.bike/` |
44
+ | Scope | `openid profile offline_access email` |
45
+ | Redirect URI | `urbanarrow://consumer.login.pon.bike/android/com.urbanarrow.connected/callback` |
46
+
47
+ The password grant is **disabled** for this client (`unauthorized_client`), so
48
+ there is no direct username/password token call. Instead,
49
+ `login_with_credentials(username, password)` (`login.py`) drives Auth0's hosted
50
+ login pages over plain HTTP, the way a browser without JavaScript would:
51
+
52
+ 1. `GET /authorize` (PKCE) redirects to `/u/login/identifier?state=...`
53
+ 2. `POST` `state` + `username` redirects to `/u/login/password?state=...`
54
+ 3. `POST` `state` + `username` + `password` redirects to `/authorize/resume`,
55
+ which redirects to `urbanarrow://...callback?code=...`
56
+ 4. The code is exchanged at `/oauth/token`, same as the app.
57
+
58
+ This works because the tenant currently has no captcha or MFA on the login
59
+ pages. If Auth0 starts showing a captcha or asks for MFA, it raises
60
+ `UrbanArrowCaptchaRequired` or `UrbanArrowMfaRequired`. The manual flow
61
+ (`create_login_request` + `extract_code` + `exchange_code`, CLI
62
+ `browser-login`) stays available as a fallback: log in in a browser and paste
63
+ the `urbanarrow://...?code=...` URL back.
64
+
65
+ After login the refresh token (`offline_access`) keeps the session alive.
66
+ `UrbanArrowClient` never handles tokens itself: it asks an `AbstractAuth` for
67
+ one via `async_get_access_token()`. `TokenAuth` is the ready-made
68
+ implementation; it refreshes through Auth0 and calls `on_token_update` so the
69
+ new token can be persisted (Auth0 may rotate refresh tokens). Override
70
+ `TokenAuth.async_refresh_token` to add a fallback such as a fresh login.
71
+ `Token.as_dict()` / `Token.from_dict()` give a JSON-serialisable form for
72
+ storage.
73
+
74
+ For Home Assistant: the config flow asks for email + password, and the
75
+ integration stores the token. It also stores the credentials, so if the refresh
76
+ token is ever revoked it can log in again silently, and only start a reauth
77
+ flow when that fails.
78
+
79
+ ## Request headers
80
+
81
+ ```
82
+ Authorization: Bearer <access_token>
83
+ Manufacturer-Id: UA
84
+ Client-Type: ANDROID
85
+ Accept-Language: <lang>
86
+ ```
87
+
88
+ ## Endpoints
89
+
90
+ Base URL: `https://app.connected.pon.bike/api/`. Timestamps are epoch milliseconds.
91
+
92
+ | Method | Path | Notes | Client method |
93
+ |---|---|---|---|
94
+ | GET | `v9/bikes` | List of paired bikes | `get_bikes` |
95
+ | GET | `v11/bikes/{id}` | Details, module, firmware, subscription, notification settings | `get_bike` |
96
+ | GET | `v11/bikes/{id}/telemetry` | Battery %, charging, GPS, odometer, range, assist level, module charge | `get_telemetry` |
97
+ | GET | `v6/bikes/{id}/activity/history?timeUnit=&startDate=&cutoffDate=` | `timeUnit` WEEK/MONTH/QUARTER/YEAR, `startDate` yyyy-MM-dd, `cutoffDate` epoch ms (app uses pairing date). Returns `values: [double]` | `get_activity` |
98
+ | POST | `v1/bikes/{id}/flash-lights` | Blink lights (find my bike) | `flash_lights` |
99
+ | PUT | `v2/bikes/{id}/settings/{SETTING}/enable` / `disable` | `AUTO_PROTECTION`, `MODULE_BATTERY_MANAGEMENT`, `NOTIFICATION_*` | `set_setting` |
100
+ | PUT | `v1/bikes/{id}/theft/detection/mode` | `{"enabled": bool}` | `set_theft_protection` |
101
+ | PUT | `v1/bikes/{id}/nickname` | `{"nickname": str}` | `set_nickname` |
102
+ | GET | `v9/bikes/module/{moduleId}` | Bike by module id | `get_bike_by_module` |
103
+ | GET | `v10/bikes/frame-number/{frameNumber}` | `{isSmart, productionProfileId}` | `check_frame_number` |
104
+ | POST | `v4/bikes/{id}/theft/report` | `{policeReportNumber, customerPhoneNumber}` (PUT updates) | `report_theft` |
105
+ | POST | `v1/bikes/{id}/theft/cancel` | | `cancel_theft_report` |
106
+ | GET | `v4/notifications?version=6` | In-app inbox | `get_notifications` |
107
+ | PUT | `v7/notifications/mark-as-read` / `mark-as-unread` | `{"content": [ids]}` | `mark_notifications_read` |
108
+ | DELETE | `v7/notifications` | `{"content": [ids]}` | `delete_notifications` |
109
+ | GET | `v9/user-preferences` | `{preferredDealerId, theftNotificationSound}` | `get_user_preferences` |
110
+ | GET | `v3/pois` | Dealers / points of interest | `get_points_of_interest` |
111
+ | GET | `health-watcher/v1/health` | Backend status message (no auth needed) | `get_health` |
112
+ | GET | `v1/productionprofiles/{productionProfileId}/image` | Bike image | `image_url` |
113
+
114
+ Not wrapped (account/commerce, not useful for HA): pairing
115
+ (`v10/bikes/pairing/smart|non-smart`, `DELETE v10/bikes/{id}/pairing`),
116
+ insurance (`v9/bikes/{id}/insurance*`), subscription payments
117
+ (`v10/bikes/{id}/subscription/extension/payment/{variantId}`,
118
+ `v7/payments/sessions/*`, `v7/bikes/{id}/subscription/withdraw`), FCM push
119
+ registration (`v4/notifications/fcm/register`, `v1/notifications/fcm/unregister`),
120
+ dealers (`v3/dealers/...`), FAQ (`v4/faq`, `v3/faq/{id}`), route planning
121
+ (`v11/navigation/route`) and version checks (`v3/minimum-version/android`,
122
+ `v3/latest-release-version/ANDROID`). All reachable through `client._request`.
123
+
124
+ ## Observed values (real Family Active Line Plus, BES2 system)
125
+
126
+ - `battery.charge` and `moduleCharge`: percent (72, 22). `moduleCharge` is the
127
+ connectivity module's own backup battery, not the e-bike battery.
128
+ - `odometer`: km with 2 decimals (1705.04). `range`: km (26.0).
129
+ - `assistLevel`: integer (4).
130
+ - Each telemetry value has its own `lastUpdatedOn`; battery and location can be
131
+ hours older than assist level / range, so they come from separate reports.
132
+ - Bike details also include `category` ("Bakfiets") and `isSmart`.
133
+
134
+ ## Open questions
135
+
136
+ - Whether the refresh token rotates, and how long it lives.
137
+ - How often telemetry updates while the bike is parked or asleep.
138
+
139
+ ## Development and releases
140
+
141
+ ```bash
142
+ uv sync
143
+ uv run ruff check . && uv run ruff format --check . && uv run pytest
144
+ ```
145
+
146
+ Releases are published to PyPI by `.github/workflows/release.yaml` when a
147
+ GitHub release is published. The tag (`v0.1.0` or `0.1.0`) must match
148
+ `version` in `pyproject.toml`. PyPI trusted publishing has to be configured once
149
+ for the `pypi` environment of this repository.
150
+
151
+ ## License
152
+
153
+ MIT
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "urban-arrow-api"
3
+ version = "0.1.0"
4
+ description = "Async Python client for the Urban Arrow (Pon Connected) bike cloud API"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Koen Hendriks" }]
9
+ requires-python = ">=3.12"
10
+ dependencies = ["aiohttp>=3.9"]
11
+ keywords = ["urban arrow", "e-bike", "cargo bike", "home assistant", "pon"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Framework :: AsyncIO",
15
+ "Intended Audience :: Developers",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Home Automation",
19
+ "Typing :: Typed",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/koenhendriks/urban-arrow-api"
24
+ Issues = "https://github.com/koenhendriks/urban-arrow-api/issues"
25
+ Changelog = "https://github.com/koenhendriks/urban-arrow-api/releases"
26
+
27
+ [project.scripts]
28
+ urban-arrow = "urban_arrow_api.__main__:main"
29
+
30
+ [dependency-groups]
31
+ dev = ["pytest>=8", "pytest-asyncio>=0.23", "ruff>=0.15"]
32
+
33
+ [build-system]
34
+ requires = ["hatchling"]
35
+ build-backend = "hatchling.build"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/urban_arrow_api"]
39
+
40
+ [tool.hatch.build.targets.sdist]
41
+ include = ["src", "tests", "README.md", "LICENSE"]
42
+
43
+ [tool.pytest.ini_options]
44
+ asyncio_mode = "auto"
45
+ asyncio_default_fixture_loop_scope = "function"
46
+
47
+ [tool.ruff]
48
+ line-length = 100
49
+ target-version = "py312"
50
+
51
+ [tool.ruff.lint]
52
+ select = ["E", "F", "W", "I", "UP", "B", "ASYNC", "SIM", "RUF"]
@@ -0,0 +1,48 @@
1
+ from .auth import (
2
+ AbstractAuth,
3
+ LoginRequest,
4
+ Token,
5
+ TokenAuth,
6
+ create_login_request,
7
+ exchange_code,
8
+ extract_code,
9
+ )
10
+ from .client import UrbanArrowClient
11
+ from .const import ActivityPeriod, BikeSetting
12
+ from .exceptions import (
13
+ UrbanArrowApiError,
14
+ UrbanArrowAuthError,
15
+ UrbanArrowCaptchaRequired,
16
+ UrbanArrowConnectionError,
17
+ UrbanArrowError,
18
+ UrbanArrowMfaRequired,
19
+ )
20
+ from .login import login_with_credentials
21
+ from .models import Activity, Bike, BikeSummary, Location, Notification, Telemetry, TimedValue
22
+
23
+ __all__ = [
24
+ "AbstractAuth",
25
+ "Activity",
26
+ "ActivityPeriod",
27
+ "Bike",
28
+ "BikeSetting",
29
+ "BikeSummary",
30
+ "Location",
31
+ "LoginRequest",
32
+ "Notification",
33
+ "Telemetry",
34
+ "TimedValue",
35
+ "Token",
36
+ "TokenAuth",
37
+ "UrbanArrowApiError",
38
+ "UrbanArrowAuthError",
39
+ "UrbanArrowCaptchaRequired",
40
+ "UrbanArrowClient",
41
+ "UrbanArrowConnectionError",
42
+ "UrbanArrowError",
43
+ "UrbanArrowMfaRequired",
44
+ "create_login_request",
45
+ "exchange_code",
46
+ "extract_code",
47
+ "login_with_credentials",
48
+ ]
@@ -0,0 +1,125 @@
1
+ """Small CLI for exploring the API: ``urban-arrow login`` then ``urban-arrow status``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import getpass
8
+ import json
9
+ import os
10
+ from datetime import date
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import aiohttp
15
+
16
+ from . import ActivityPeriod, BikeSetting, Token, TokenAuth, UrbanArrowClient
17
+ from .auth import create_login_request, exchange_code, extract_code
18
+ from .login import login_with_credentials
19
+
20
+ TOKEN_FILE = Path(
21
+ os.environ.get("URBAN_ARROW_TOKEN_FILE", "~/.config/urban-arrow/token.json")
22
+ ).expanduser()
23
+
24
+
25
+ def _save(token: Token) -> None:
26
+ TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
27
+ TOKEN_FILE.write_text(json.dumps(token.as_dict()))
28
+ TOKEN_FILE.chmod(0o600)
29
+
30
+
31
+ def _dump(data: Any) -> None:
32
+ print(json.dumps(data, indent=2, default=str))
33
+
34
+
35
+ async def _password_login(username: str) -> None:
36
+ password = os.environ.get("URBAN_ARROW_PASSWORD") or await asyncio.to_thread(
37
+ getpass.getpass, "Password: "
38
+ )
39
+ _save(await login_with_credentials(username, password))
40
+ print(f"Saved token to {TOKEN_FILE}")
41
+
42
+
43
+ async def _browser_login() -> None:
44
+ req = create_login_request()
45
+ print("1. Open this URL in a browser and log in with your Urban Arrow account:\n")
46
+ print(req.url)
47
+ print(
48
+ "\n2. After login the browser tries to open an 'urbanarrow://...' URL and fails."
49
+ "\n Copy that URL (DevTools > Network, or the address bar / error page)"
50
+ " and paste it here."
51
+ )
52
+ redirect = await asyncio.to_thread(input, "\nRedirect URL or code: ")
53
+ async with aiohttp.ClientSession() as session:
54
+ token = await exchange_code(session, extract_code(redirect, req.state), req.code_verifier)
55
+ _save(token)
56
+ print(f"Saved token to {TOKEN_FILE}")
57
+
58
+
59
+ async def _run(args: argparse.Namespace) -> None:
60
+ token = Token.from_dict(json.loads(TOKEN_FILE.read_text()))
61
+ async with aiohttp.ClientSession() as session:
62
+ client = UrbanArrowClient(TokenAuth(session, token, _save))
63
+ match args.command:
64
+ case "bikes":
65
+ _dump([b.raw for b in await client.get_bikes()])
66
+ case "status":
67
+ for summary in await client.get_bikes():
68
+ bike = await client.get_bike(summary.id)
69
+ print(f"== {bike.name} ({bike.id})")
70
+ _dump(bike.raw)
71
+ _dump((await client.get_telemetry(bike.id)).raw)
72
+ case "activity":
73
+ bike = await client.get_bike(args.bike_id)
74
+ start = (
75
+ date.fromisoformat(args.start) if args.start else date.today().replace(day=1)
76
+ )
77
+ _dump((await client.get_activity(bike, ActivityPeriod(args.period), start)).raw)
78
+ case "notifications":
79
+ _dump([n.raw for n in await client.get_notifications()])
80
+ case "flash":
81
+ await client.flash_lights(args.bike_id)
82
+ print("ok")
83
+ case "setting":
84
+ await client.set_setting(
85
+ args.bike_id, BikeSetting(args.setting), args.state == "on"
86
+ )
87
+ print("ok")
88
+ case "raw":
89
+ _dump(await client._request(args.method.upper(), args.path))
90
+
91
+
92
+ def main() -> None:
93
+ parser = argparse.ArgumentParser(prog="urban-arrow")
94
+ sub = parser.add_subparsers(dest="command", required=True)
95
+ p = sub.add_parser("login", help="Log in with email + password")
96
+ p.add_argument("username")
97
+ sub.add_parser("browser-login", help="Fallback: log in via browser and paste the redirect URL")
98
+ sub.add_parser("bikes")
99
+ sub.add_parser("status")
100
+ sub.add_parser("notifications")
101
+ p = sub.add_parser("activity")
102
+ p.add_argument("bike_id")
103
+ p.add_argument("--period", default="MONTH", choices=[p.value for p in ActivityPeriod])
104
+ p.add_argument("--start", help="YYYY-MM-DD, defaults to first day of this month")
105
+ p = sub.add_parser("flash")
106
+ p.add_argument("bike_id")
107
+ p = sub.add_parser("setting")
108
+ p.add_argument("bike_id")
109
+ p.add_argument("setting", choices=[s.value for s in BikeSetting])
110
+ p.add_argument("state", choices=["on", "off"])
111
+ p = sub.add_parser("raw", help="Call any endpoint path relative to /api/")
112
+ p.add_argument("method")
113
+ p.add_argument("path")
114
+ args = parser.parse_args()
115
+ match args.command:
116
+ case "login":
117
+ asyncio.run(_password_login(args.username))
118
+ case "browser-login":
119
+ asyncio.run(_browser_login())
120
+ case _:
121
+ asyncio.run(_run(args))
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()