pyatv-http 0.1.0__py3-none-any.whl

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.
pyatv_http/__init__.py ADDED
File without changes
pyatv_http/app.py ADDED
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+
5
+ from fastapi import Depends, FastAPI, HTTPException
6
+ from pyatv.const import PowerState
7
+ from starlette.requests import Request
8
+ from starlette.responses import JSONResponse
9
+
10
+ from pyatv_http import atv
11
+ from pyatv_http.atv import DeviceUnreachableError
12
+ from pyatv_http.auth import require_token
13
+ from pyatv_http.config import AppConfig
14
+
15
+
16
+ async def _health(_request: Request) -> JSONResponse:
17
+ return JSONResponse({"status": "ok"})
18
+
19
+
20
+ def create_app(config: AppConfig) -> FastAPI:
21
+ app = FastAPI(dependencies=[Depends(require_token(config))])
22
+
23
+ # Added as a raw Starlette route (like FastAPI's own /docs, /openapi.json)
24
+ # so it bypasses the app-wide bearer-token dependency above -- health
25
+ # probes (load balancers, uptime checks) shouldn't need a token.
26
+ app.add_route("/health", _health, methods=["GET"])
27
+
28
+ def _get_device(name: str):
29
+ device = config.get_device(name)
30
+ if device is None:
31
+ raise HTTPException(status_code=404, detail=f"unknown device: {name}")
32
+ return device
33
+
34
+ async def _set_power_state(name: str, desired: PowerState) -> dict[str, str]:
35
+ device = _get_device(name)
36
+ loop = asyncio.get_running_loop()
37
+ try:
38
+ state = await atv.set_power_state(loop, device, desired)
39
+ except DeviceUnreachableError as exc:
40
+ raise HTTPException(status_code=504, detail=str(exc)) from exc
41
+ except Exception as exc:
42
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
43
+
44
+ return {"device": name, "power_state": state.name.lower()}
45
+
46
+ @app.post("/{name}/turnOn")
47
+ async def turn_on(name: str) -> dict[str, str]:
48
+ return await _set_power_state(name, PowerState.On)
49
+
50
+ @app.post("/{name}/turnOff")
51
+ async def turn_off(name: str) -> dict[str, str]:
52
+ return await _set_power_state(name, PowerState.Off)
53
+
54
+ @app.get("/{name}/powerState")
55
+ async def power_state(name: str) -> dict[str, str]:
56
+ device = _get_device(name)
57
+ loop = asyncio.get_running_loop()
58
+ try:
59
+ state = await atv.get_power_state(loop, device)
60
+ except DeviceUnreachableError as exc:
61
+ raise HTTPException(status_code=504, detail=str(exc)) from exc
62
+ except Exception as exc:
63
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
64
+
65
+ return {"device": name, "power_state": state.name.lower()}
66
+
67
+ @app.get("/devices")
68
+ async def list_devices() -> list[dict[str, str]]:
69
+ return [
70
+ {"device": device.key, "name": device.name}
71
+ for device in sorted(config.devices.values(), key=lambda d: d.key)
72
+ ]
73
+
74
+ return app
pyatv_http/atv.py ADDED
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+
5
+ import pyatv
6
+ from pyatv.const import PowerState
7
+ from pyatv.interface import AppleTV
8
+ from pyatv.settings import (
9
+ AirPlaySettings,
10
+ CompanionSettings,
11
+ DmapSettings,
12
+ MrpSettings,
13
+ ProtocolSettings,
14
+ RaopSettings,
15
+ Settings,
16
+ )
17
+ from pyatv.storage import MODEL_VERSION, StorageModel
18
+ from pyatv.storage.memory_storage import MemoryStorage
19
+
20
+ from pyatv_http.config import DeviceConfig, ProtocolCredential
21
+
22
+ SCAN_TIMEOUT_SECONDS = 5
23
+
24
+
25
+ class DeviceUnreachableError(Exception):
26
+ """Raised when the Apple TV cannot be found on the network."""
27
+
28
+
29
+ def _protocol_settings(
30
+ device: DeviceConfig,
31
+ ) -> dict[
32
+ str, AirPlaySettings | CompanionSettings | DmapSettings | MrpSettings | RaopSettings
33
+ ]:
34
+ empty = ProtocolCredential()
35
+ airplay = device.protocols.get("airplay", empty)
36
+ companion = device.protocols.get("companion", empty)
37
+ dmap = device.protocols.get("dmap", empty)
38
+ mrp = device.protocols.get("mrp", empty)
39
+ raop = device.protocols.get("raop", empty)
40
+
41
+ return {
42
+ "airplay": AirPlaySettings(
43
+ identifier=airplay.identifier,
44
+ credentials=airplay.credentials,
45
+ password=airplay.password,
46
+ ),
47
+ "companion": CompanionSettings(
48
+ identifier=companion.identifier, credentials=companion.credentials
49
+ ),
50
+ "dmap": DmapSettings(identifier=dmap.identifier, credentials=dmap.credentials),
51
+ "mrp": MrpSettings(identifier=mrp.identifier, credentials=mrp.credentials),
52
+ "raop": RaopSettings(
53
+ identifier=raop.identifier,
54
+ credentials=raop.credentials,
55
+ password=raop.password,
56
+ ),
57
+ }
58
+
59
+
60
+ def _build_storage(device: DeviceConfig) -> MemoryStorage:
61
+ settings = Settings(protocols=ProtocolSettings(**_protocol_settings(device)))
62
+ storage = MemoryStorage()
63
+ storage.storage_model = StorageModel(version=MODEL_VERSION, devices=[settings])
64
+ return storage
65
+
66
+
67
+ async def connect(loop: asyncio.AbstractEventLoop, device: DeviceConfig) -> AppleTV:
68
+ results = await pyatv.scan(
69
+ loop,
70
+ hosts=[device.address],
71
+ identifier={device.identifier},
72
+ timeout=SCAN_TIMEOUT_SECONDS,
73
+ )
74
+ if not results:
75
+ raise DeviceUnreachableError(
76
+ f"could not find '{device.name}' ({device.identifier}) at {device.address}"
77
+ )
78
+
79
+ storage = _build_storage(device)
80
+ return await pyatv.connect(results[0], loop, storage=storage)
81
+
82
+
83
+ async def get_power_state(
84
+ loop: asyncio.AbstractEventLoop, device: DeviceConfig
85
+ ) -> PowerState:
86
+ atv = await connect(loop, device)
87
+ try:
88
+ return atv.power.power_state
89
+ finally:
90
+ atv.close()
91
+
92
+
93
+ async def set_power_state(
94
+ loop: asyncio.AbstractEventLoop, device: DeviceConfig, desired: PowerState
95
+ ) -> PowerState:
96
+ atv = await connect(loop, device)
97
+ try:
98
+ current = atv.power.power_state
99
+ if current == desired:
100
+ return current
101
+
102
+ # await_new_state=True raises NotImplementedError on pyatv's Companion
103
+ # protocol (pyatv/protocols/companion/__init__.py); we already read the
104
+ # state ourselves above, so we don't need pyatv to wait for it too.
105
+ if desired == PowerState.On:
106
+ await atv.power.turn_on(await_new_state=False)
107
+ else:
108
+ await atv.power.turn_off(await_new_state=False)
109
+ return desired
110
+ finally:
111
+ atv.close()
pyatv_http/auth.py ADDED
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Annotated
4
+
5
+ from fastapi import Depends, HTTPException
6
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
7
+
8
+ from pyatv_http.config import AppConfig
9
+
10
+ _bearer_scheme = HTTPBearer(auto_error=False)
11
+
12
+
13
+ def require_token(config: AppConfig):
14
+ def _verify(
15
+ credentials: Annotated[
16
+ HTTPAuthorizationCredentials | None, Depends(_bearer_scheme)
17
+ ] = None,
18
+ ) -> None:
19
+ if credentials is None or credentials.credentials not in config.auth_tokens:
20
+ raise HTTPException(
21
+ status_code=401,
22
+ detail="missing or invalid bearer token",
23
+ headers={"WWW-Authenticate": "Bearer"},
24
+ )
25
+
26
+ return _verify
pyatv_http/cli.py ADDED
@@ -0,0 +1,94 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import asyncio
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import uvicorn
10
+
11
+ from pyatv_http.app import create_app
12
+ from pyatv_http.config import load_config
13
+ from pyatv_http.gen_config import DeviceNotFoundError, generate_config_block
14
+
15
+ DEFAULT_STORAGE_PATH = Path.home() / ".pyatv.conf"
16
+
17
+
18
+ def default_config_path() -> Path:
19
+ xdg_config_home = os.environ.get("XDG_CONFIG_HOME")
20
+ config_home = Path(xdg_config_home) if xdg_config_home else Path.home() / ".config"
21
+ return config_home / "pyatv-http" / "config.toml"
22
+
23
+
24
+ def _serve(args: argparse.Namespace) -> None:
25
+ config_path = args.config or default_config_path()
26
+ config = load_config(config_path)
27
+ app = create_app(config)
28
+ uvicorn.run(app, host=args.host, port=config.port)
29
+
30
+
31
+ def _gen_config(args: argparse.Namespace) -> None:
32
+ storage_path = args.storage or DEFAULT_STORAGE_PATH
33
+ try:
34
+ block = asyncio.run(
35
+ generate_config_block(
36
+ storage_path=storage_path,
37
+ identifier=args.identifier,
38
+ key=args.key,
39
+ name=args.name,
40
+ address=args.address,
41
+ )
42
+ )
43
+ except DeviceNotFoundError as exc:
44
+ print(str(exc), file=sys.stderr)
45
+ raise SystemExit(1) from exc
46
+
47
+ print(block)
48
+
49
+
50
+ def build_parser() -> argparse.ArgumentParser:
51
+ parser = argparse.ArgumentParser(prog="pyatv-http")
52
+ subparsers = parser.add_subparsers(dest="command", required=True)
53
+
54
+ serve = subparsers.add_parser("serve", help="Run the HTTP server")
55
+ serve.add_argument(
56
+ "--config",
57
+ default=None,
58
+ help=f"Path to the config TOML file (default: {default_config_path()})",
59
+ )
60
+ serve.add_argument("--host", default="0.0.0.0", help="Interface to bind to")
61
+ serve.set_defaults(func=_serve)
62
+
63
+ gen_config = subparsers.add_parser(
64
+ "gen-config",
65
+ help="Generate a [devices.<key>] config block from an atvremote pairing",
66
+ )
67
+ gen_config.add_argument(
68
+ "--storage",
69
+ default=None,
70
+ help=f"Path to atvremote's storage file (default: {DEFAULT_STORAGE_PATH})",
71
+ )
72
+ gen_config.add_argument(
73
+ "--identifier", required=True, help="Device identifier to look up"
74
+ )
75
+ gen_config.add_argument(
76
+ "--key", required=True, help="Config key / URL path segment for this device"
77
+ )
78
+ gen_config.add_argument("--name", default=None, help="Display name (default: key)")
79
+ gen_config.add_argument(
80
+ "--address", required=True, help="IP address or hostname of the Apple TV"
81
+ )
82
+ gen_config.set_defaults(func=_gen_config)
83
+
84
+ return parser
85
+
86
+
87
+ def main(argv: list[str] | None = None) -> None:
88
+ parser = build_parser()
89
+ args = parser.parse_args(argv)
90
+ args.func(args)
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
pyatv_http/config.py ADDED
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ import tomllib
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+
7
+ KNOWN_PROTOCOLS = frozenset({"airplay", "companion", "dmap", "mrp", "raop"})
8
+
9
+
10
+ class ConfigError(Exception):
11
+ """Raised when the config file is missing or invalid."""
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ProtocolCredential:
16
+ identifier: str | None = None
17
+ credentials: str | None = None
18
+ password: str | None = None
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class DeviceConfig:
23
+ key: str
24
+ name: str
25
+ address: str
26
+ identifier: str
27
+ protocols: dict[str, ProtocolCredential] = field(default_factory=dict)
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class AppConfig:
32
+ port: int
33
+ devices: dict[str, DeviceConfig]
34
+ auth_tokens: frozenset[str]
35
+
36
+ def get_device(self, key: str) -> DeviceConfig | None:
37
+ return self.devices.get(key)
38
+
39
+
40
+ def _parse_protocol(device_key: str, proto_name: str, raw: dict) -> ProtocolCredential:
41
+ if proto_name not in KNOWN_PROTOCOLS:
42
+ raise ConfigError(
43
+ f"devices.{device_key}.protocols.{proto_name}: unknown protocol "
44
+ f"(expected one of {sorted(KNOWN_PROTOCOLS)})"
45
+ )
46
+ return ProtocolCredential(
47
+ identifier=raw.get("identifier"),
48
+ credentials=raw.get("credentials"),
49
+ password=raw.get("password"),
50
+ )
51
+
52
+
53
+ def _parse_device(key: str, raw: dict) -> DeviceConfig:
54
+ name = raw.get("name")
55
+ if not name:
56
+ raise ConfigError(f"devices.{key}: missing required field 'name'")
57
+
58
+ identifier = raw.get("identifier")
59
+ if not identifier:
60
+ raise ConfigError(f"devices.{key}: missing required field 'identifier'")
61
+
62
+ address = raw.get("address")
63
+ if not address:
64
+ raise ConfigError(f"devices.{key}: missing required field 'address'")
65
+
66
+ raw_protocols = raw.get("protocols", {})
67
+ protocols = {
68
+ proto_name: _parse_protocol(key, proto_name, proto_raw)
69
+ for proto_name, proto_raw in raw_protocols.items()
70
+ }
71
+
72
+ return DeviceConfig(
73
+ key=key,
74
+ name=name,
75
+ address=address,
76
+ identifier=identifier,
77
+ protocols=protocols,
78
+ )
79
+
80
+
81
+ def _parse_auth_tokens(data: dict) -> frozenset[str]:
82
+ raw_auth = data.get("auth")
83
+ if not raw_auth:
84
+ raise ConfigError("missing or empty required table 'auth'")
85
+
86
+ tokens = raw_auth.get("tokens")
87
+ if not tokens:
88
+ raise ConfigError("missing or empty required field 'auth.tokens'")
89
+
90
+ return frozenset(tokens)
91
+
92
+
93
+ def load_config(path: str | Path) -> AppConfig:
94
+ path = Path(path)
95
+ if not path.is_file():
96
+ raise ConfigError(f"config file not found: {path}")
97
+
98
+ data = tomllib.loads(path.read_text())
99
+
100
+ port = data.get("port")
101
+ if not isinstance(port, int):
102
+ raise ConfigError("missing or invalid required field 'port'")
103
+
104
+ raw_devices = data.get("devices")
105
+ if not raw_devices:
106
+ raise ConfigError("missing or empty required table 'devices'")
107
+
108
+ devices = {
109
+ key: _parse_device(key, raw_device) for key, raw_device in raw_devices.items()
110
+ }
111
+
112
+ auth_tokens = _parse_auth_tokens(data)
113
+
114
+ return AppConfig(port=port, devices=devices, auth_tokens=auth_tokens)
@@ -0,0 +1,106 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from pathlib import Path
5
+
6
+ from pyatv.settings import Settings
7
+ from pyatv.storage.file_storage import FileStorage
8
+
9
+ PROTOCOL_NAMES = ("airplay", "companion", "dmap", "mrp", "raop")
10
+
11
+
12
+ class DeviceNotFoundError(Exception):
13
+ """Raised when no stored device matches the given identifier."""
14
+
15
+
16
+ def _escape_toml_string(value: str) -> str:
17
+ return value.replace("\\", "\\\\").replace('"', '\\"')
18
+
19
+
20
+ def _toml_string(value: str) -> str:
21
+ return f'"{_escape_toml_string(value)}"'
22
+
23
+
24
+ def _settings_identifiers(settings: Settings) -> set[str]:
25
+ identifiers = set()
26
+ for proto_name in PROTOCOL_NAMES:
27
+ proto_identifier = getattr(settings.protocols, proto_name).identifier
28
+ if proto_identifier is not None:
29
+ identifiers.add(proto_identifier)
30
+ return identifiers
31
+
32
+
33
+ def _find_settings(devices: list[Settings], identifier: str) -> Settings | None:
34
+ for settings in devices:
35
+ if identifier in _settings_identifiers(settings):
36
+ return settings
37
+ return None
38
+
39
+
40
+ def render_toml_block(
41
+ *,
42
+ key: str,
43
+ name: str,
44
+ address: str,
45
+ identifier: str,
46
+ protocols: dict[str, dict[str, str | None]],
47
+ ) -> str:
48
+ lines = [
49
+ f"[devices.{key}]",
50
+ f"name = {_toml_string(name)}",
51
+ f"identifier = {_toml_string(identifier)}",
52
+ f"address = {_toml_string(address)}",
53
+ ]
54
+
55
+ for proto_name in PROTOCOL_NAMES:
56
+ proto = protocols.get(proto_name)
57
+ if not proto:
58
+ continue
59
+ if not proto.get("identifier") and not proto.get("credentials"):
60
+ continue
61
+
62
+ lines.append("")
63
+ lines.append(f"[devices.{key}.protocols.{proto_name}]")
64
+ for field_name in ("identifier", "credentials", "password"):
65
+ value = proto.get(field_name)
66
+ if value is not None:
67
+ lines.append(f"{field_name} = {_toml_string(value)}")
68
+
69
+ return "\n".join(lines) + "\n"
70
+
71
+
72
+ async def generate_config_block(
73
+ *,
74
+ storage_path: str | Path,
75
+ identifier: str,
76
+ key: str,
77
+ name: str | None,
78
+ address: str,
79
+ ) -> str:
80
+ loop = asyncio.get_running_loop()
81
+ storage = FileStorage(str(storage_path), loop)
82
+ await storage.load()
83
+
84
+ devices = list(storage.settings)
85
+ settings = _find_settings(devices, identifier)
86
+ if settings is None:
87
+ available = sorted(
88
+ {i for device in devices for i in _settings_identifiers(device)}
89
+ )
90
+ raise DeviceNotFoundError(
91
+ f"no paired device found with identifier '{identifier}'. "
92
+ f"Available identifiers: {available}"
93
+ )
94
+
95
+ protocols = {
96
+ proto_name: dict(getattr(settings.protocols, proto_name))
97
+ for proto_name in PROTOCOL_NAMES
98
+ }
99
+
100
+ return render_toml_block(
101
+ key=key,
102
+ name=name or key,
103
+ address=address,
104
+ identifier=identifier,
105
+ protocols=protocols,
106
+ )
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyatv-http
3
+ Version: 0.1.0
4
+ Summary: HTTP interface for controlling Apple TVs via pyatv
5
+ Project-URL: Homepage, https://github.com/hugoh/pyatv-http
6
+ Project-URL: Repository, https://github.com/hugoh/pyatv-http
7
+ Project-URL: Issues, https://github.com/hugoh/pyatv-http/issues
8
+ Author: Hugo Haas
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Home Automation
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: fastapi>=0.121.0
21
+ Requires-Dist: pyatv>=0.16.0
22
+ Requires-Dist: uvicorn>=0.38.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # pyatv-http
26
+
27
+ An HTTP interface for controlling Apple TVs, built on top of
28
+ [pyatv](https://github.com/postlund/pyatv).
29
+
30
+ ## Features
31
+
32
+ - `POST /<name>/turnOn` and `POST /<name>/turnOff` — checks the Apple TV's current
33
+ power state and only sends a command if it differs from the desired state.
34
+ - `GET /<name>/powerState` — reads the current power state without changing it.
35
+ - `GET /devices` — lists the devices available in the config file.
36
+ - `GET /health` — unauthenticated liveness check, for load balancers/uptime
37
+ monitors.
38
+ - Every other request requires a bearer token, configured as a list of
39
+ accepted tokens in the config file.
40
+ - Config-driven: one TOML file lists the port to listen on, accepted API
41
+ tokens, and the paired devices.
42
+ - Pairing stays out-of-band, via pyatv's own `atvremote` CLI; a `pyatv-http gen-config`
43
+ helper turns a paired device's stored credentials into a config snippet.
44
+
45
+ ## Setup
46
+
47
+ ### 1. Find your Apple TV
48
+
49
+ ```sh
50
+ uvx --from pyatv atvremote scan
51
+ ```
52
+
53
+ This lists every Apple TV on the network along with its identifiers, IP
54
+ address, and which protocols it supports (AirPlay, Companion, etc).
55
+
56
+ ### 2. Pair with `atvremote`
57
+
58
+ Power control uses the **Companion** protocol, and pyatv-http talks to the
59
+ device over **AirPlay** for the initial handshake, so pair both:
60
+
61
+ ```sh
62
+ uvx --from pyatv atvremote --id <device-identifier> pair --protocol airplay
63
+ uvx --from pyatv atvremote --id <device-identifier> pair --protocol companion
64
+ ```
65
+
66
+ Follow the on-screen PIN prompt for each. Credentials are stored in pyatv's
67
+ storage file (default `~/.pyatv.conf`).
68
+
69
+ ### 3. Generate a config entry
70
+
71
+ ```sh
72
+ uv run pyatv-http gen-config \
73
+ --identifier <device-identifier> \
74
+ --address <device-ip-or-hostname> \
75
+ --key living_room
76
+ ```
77
+
78
+ `<device-identifier>` and `<device-ip-or-hostname>` come from the `scan`
79
+ output in step 1; `--key` is whatever short name you want to use in URLs
80
+ (`--name` sets the human-readable display name too, defaulting to `--key`).
81
+
82
+ This prints a `[devices.living_room]` TOML block built from the stored
83
+ pairing. Paste it into your config file (see below). If the identifier
84
+ doesn't match any paired device, the command lists the identifiers it does
85
+ have on file.
86
+
87
+ ### 4. Write the config file
88
+
89
+ ```toml
90
+ port = 8080
91
+
92
+ [auth]
93
+ tokens = ["a-long-random-token"]
94
+
95
+ [devices.living_room]
96
+ name = "Living Room"
97
+ identifier = "AA:BB:CC:DD:EE:FF"
98
+ address = "10.0.0.5"
99
+
100
+ [devices.living_room.protocols.airplay]
101
+ identifier = "AA:BB:CC:DD:EE:FF"
102
+ credentials = "..."
103
+
104
+ [devices.living_room.protocols.companion]
105
+ identifier = "11:22:33:44:55:66"
106
+ credentials = "..."
107
+ ```
108
+
109
+ - `port` — port the HTTP server listens on.
110
+ - `[auth].tokens` — required, non-empty list of bearer tokens accepted on every
111
+ request (see [API](#api) below). Generate one with e.g.
112
+ `python3 -c "import secrets; print(secrets.token_urlsafe(32))"`.
113
+ - The `[devices.<key>]` table key (`living_room` above) is the URL path
114
+ segment used in requests, e.g. `POST /living_room/turnOn`.
115
+ - `identifier` — the device's main pyatv identifier (from `atvremote scan`).
116
+ - `address` — the Apple TV's IP address or hostname; used to connect
117
+ directly instead of relying on mDNS discovery at request time.
118
+ - `[devices.<key>.protocols.<protocol>]` — one block per paired protocol,
119
+ exactly as generated by `gen-config`. Supported protocol names: `airplay`,
120
+ `companion`, `dmap`, `mrp`, `raop`.
121
+
122
+ ### 5. Run the server
123
+
124
+ ```sh
125
+ uv run pyatv-http serve --config config.toml
126
+ ```
127
+
128
+ `--config` is optional; if omitted, it defaults to
129
+ `$XDG_CONFIG_HOME/pyatv-http/config.toml`, falling back to
130
+ `~/.config/pyatv-http/config.toml` when `$XDG_CONFIG_HOME` isn't set.
131
+
132
+ By default the server binds `0.0.0.0`; pass `--host` to bind a specific
133
+ interface.
134
+
135
+ ## API
136
+
137
+ Every request must include one of the configured tokens as a bearer token:
138
+
139
+ ```sh
140
+ TOKEN=a-long-random-token
141
+
142
+ curl -X POST http://localhost:8080/living_room/turnOn \
143
+ -H "Authorization: Bearer $TOKEN"
144
+
145
+ curl -X POST http://localhost:8080/living_room/turnOff \
146
+ -H "Authorization: Bearer $TOKEN"
147
+
148
+ curl http://localhost:8080/living_room/powerState \
149
+ -H "Authorization: Bearer $TOKEN"
150
+
151
+ curl http://localhost:8080/devices \
152
+ -H "Authorization: Bearer $TOKEN"
153
+
154
+ curl http://localhost:8080/health
155
+ ```
156
+
157
+ `turnOn`/`turnOff`/`powerState` return a JSON body:
158
+ `{"device": "living_room", "power_state": "on"}`.
159
+
160
+ `GET /devices` returns the devices available in the config file:
161
+
162
+ ```json
163
+ [{"device": "living_room", "name": "Living Room"}]
164
+ ```
165
+
166
+ `GET /health` (no token required) returns `{"status": "ok"}`.
167
+
168
+ | Status | Meaning |
169
+ | ------ | ------------------------------------------------------------------ |
170
+ | 200 | Command sent (or no-op, if the device was already in that state) |
171
+ | 401 | Missing or invalid bearer token |
172
+ | 404 | No device configured under that name |
173
+ | 504 | Device could not be found/reached on the network |
174
+ | 502 | pyatv raised an error while connecting or sending the command |
175
+
176
+ ### Interactive API docs
177
+
178
+ FastAPI auto-generates interactive documentation for the running server:
179
+
180
+ - `GET /docs` — Swagger UI (use the "Authorize" button to set your bearer
181
+ token, then try requests directly from the browser).
182
+ - `GET /redoc` — ReDoc view of the same schema.
183
+ - `GET /openapi.json` — the raw OpenAPI schema.
184
+
185
+ These three routes are not themselves behind the bearer-token check.
186
+
187
+ ## Notes
188
+
189
+ - Each request opens a fresh connection to the Apple TV, checks its current
190
+ power state, and only sends `turnOn`/`turnOff` if it differs from the
191
+ desired state — there's no persistent connection or background polling.
192
+ - Pairing is entirely out-of-band via `atvremote`; this project never
193
+ performs the pairing handshake itself.
194
+
195
+ ## Development
196
+
197
+ ```sh
198
+ uv sync
199
+ uv run pytest
200
+ hk check --all
201
+ ```
@@ -0,0 +1,12 @@
1
+ pyatv_http/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ pyatv_http/app.py,sha256=-NMn_GPo1dEfU12fM50GO4zFTzUpKnO_lf33jJBBKaM,2705
3
+ pyatv_http/atv.py,sha256=bhMOyup1UJtHm5XIoexewKLvTNs6HoROBqrOY5i2Gf0,3439
4
+ pyatv_http/auth.py,sha256=sF3js3joyfO4ydUqrXwm0gLJLjcgVmuqf1llWVPA9po,761
5
+ pyatv_http/cli.py,sha256=WuzL0VOOt75Aufs7FLj0MaO2LrGxbOlXFOtVjR-wJxY,2831
6
+ pyatv_http/config.py,sha256=ViINn8vO3DTB5dGi6J0AfjMEUTNhDMakxlUw4SfJbnk,3152
7
+ pyatv_http/gen_config.py,sha256=A66dFuMASPa8luMMrZTx44fr4FDtaL4bX_gsIGy1Hn0,2920
8
+ pyatv_http-0.1.0.dist-info/METADATA,sha256=pcz_BWIdRjSsWm5KjqKEN--O3sUvJ1fjCa3vlwojs0g,6786
9
+ pyatv_http-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
10
+ pyatv_http-0.1.0.dist-info/entry_points.txt,sha256=qd70JeIvePekCQdNLKwdJTS7rASr5O7qDiGFIw9xJD0,51
11
+ pyatv_http-0.1.0.dist-info/licenses/LICENSE,sha256=qCv-aayDkFcB09IGjnNETtrZ31NOA1tdCq4IJ7nZObc,1066
12
+ pyatv_http-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyatv-http = pyatv_http.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hugo Haas
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.