airabox 0.1.2__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.
- airabox/__init__.py +33 -0
- airabox/client.py +139 -0
- airabox/constants.py +6 -0
- airabox/desktop/__init__.py +11 -0
- airabox/desktop/desktop_asynb.py +507 -0
- airabox/desktop/desktop_sync.py +398 -0
- airabox/mobile/__init__.py +6 -0
- airabox/mobile/mobile_async.py +325 -0
- airabox/mobile/mobile_sync.py +254 -0
- airabox-0.1.2.dist-info/METADATA +254 -0
- airabox-0.1.2.dist-info/RECORD +13 -0
- airabox-0.1.2.dist-info/WHEEL +5 -0
- airabox-0.1.2.dist-info/top_level.txt +1 -0
airabox/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Airabox Python SDK."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from e2b import * # noqa: F401,F403
|
|
6
|
+
from e2b import __all__ as _E2B_EXPORTS
|
|
7
|
+
|
|
8
|
+
from e2b_code_interpreter import AsyncSandbox as AsyncCodeInterpreter
|
|
9
|
+
from e2b_code_interpreter import Sandbox as CodeInterpreter
|
|
10
|
+
from e2b_code_interpreter import models as CodeInterpreterModels
|
|
11
|
+
|
|
12
|
+
from .client import AiraBox, E2B, E2BClientParams
|
|
13
|
+
|
|
14
|
+
from .desktop import AsyncDesktopSandbox, AsyncVNCStream, DesktopSandbox, VNCStream
|
|
15
|
+
from .mobile import AsyncMobileSandbox, MobileSandbox
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"E2B",
|
|
20
|
+
"E2BClientParams",
|
|
21
|
+
"AiraBox",
|
|
22
|
+
"DesktopSandbox",
|
|
23
|
+
"VNCStream",
|
|
24
|
+
"AsyncDesktopSandbox",
|
|
25
|
+
"AsyncVNCStream",
|
|
26
|
+
"MobileSandbox",
|
|
27
|
+
"AsyncMobileSandbox",
|
|
28
|
+
"CodeInterpreter",
|
|
29
|
+
"AsyncCodeInterpreter",
|
|
30
|
+
"CodeInterpreterModels",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
__all__ = [*_E2B_EXPORTS, *__all__]
|
airabox/client.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Dict, Type, TypeVar, Unpack, cast
|
|
3
|
+
|
|
4
|
+
from e2b import ApiParams, E2BClientParams
|
|
5
|
+
from e2b import E2B as CoreE2B
|
|
6
|
+
from e2b_code_interpreter import AsyncSandbox as AsyncCodeInterpreter
|
|
7
|
+
from e2b_code_interpreter import Sandbox as CodeInterpreter
|
|
8
|
+
from .constants import DEFAULT_CODE_INTERPRETER_TEMPLATE
|
|
9
|
+
from .desktop.desktop_asynb import AsyncDesktopSandbox
|
|
10
|
+
from .desktop.desktop_sync import DesktopSandbox
|
|
11
|
+
from .mobile.mobile_async import AsyncMobileSandbox
|
|
12
|
+
from .mobile.mobile_sync import MobileSandbox
|
|
13
|
+
|
|
14
|
+
from .constants import DEFAULT_E2B_DOMAIN
|
|
15
|
+
os.environ.setdefault("E2B_DOMAIN", DEFAULT_E2B_DOMAIN)
|
|
16
|
+
|
|
17
|
+
T = TypeVar("T")
|
|
18
|
+
|
|
19
|
+
__all__ = ["AiraBox", "E2B", "E2BClientParams"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _bind(
|
|
23
|
+
cls: Type[T],
|
|
24
|
+
api_params: ApiParams,
|
|
25
|
+
class_attrs: Dict[str, object] | None = None,
|
|
26
|
+
) -> Type[T]:
|
|
27
|
+
"""Generate a subclass of ``cls`` carrying ``api_params`` as its bound params."""
|
|
28
|
+
attrs = {"_bound_api_params": api_params}
|
|
29
|
+
if class_attrs:
|
|
30
|
+
attrs.update(class_attrs)
|
|
31
|
+
return cast(
|
|
32
|
+
Type[T],
|
|
33
|
+
type(cls.__name__, (cls,), attrs),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class E2B:
|
|
38
|
+
"""
|
|
39
|
+
E2B client with an explicitly bound connection configuration.
|
|
40
|
+
|
|
41
|
+
The resource classes exposed by the client (`Sandbox`, `Volume`,
|
|
42
|
+
`AsyncVolume`, `Template`, `AsyncTemplate`, `Secret`, `AsyncSecret`) behave
|
|
43
|
+
exactly like the top-level exports of the same name, except the params
|
|
44
|
+
passed to the client are used as the defaults instead of the environment
|
|
45
|
+
variables.
|
|
46
|
+
Per-call params still take precedence over the client's params.
|
|
47
|
+
|
|
48
|
+
Multiple clients are fully isolated from each other and from the top-level
|
|
49
|
+
env-configured exports.
|
|
50
|
+
|
|
51
|
+
Example:
|
|
52
|
+
```python
|
|
53
|
+
from airabox import E2B
|
|
54
|
+
|
|
55
|
+
client = E2B(api_key="e2b_...", domain="e2b.dev")
|
|
56
|
+
|
|
57
|
+
desktop = client.Sandbox.create()
|
|
58
|
+
desktop.stream.start()
|
|
59
|
+
```
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, **opts: Unpack[E2BClientParams]):
|
|
63
|
+
"""
|
|
64
|
+
Create a new client with the API params bound to it.
|
|
65
|
+
|
|
66
|
+
:param opts: API params used as the defaults for every call made
|
|
67
|
+
through this client's resource classes.
|
|
68
|
+
"""
|
|
69
|
+
# Params are copied so later mutations of the caller's dicts cannot
|
|
70
|
+
# change the bound configuration.
|
|
71
|
+
api_params = cast(ApiParams, dict(cast(Dict[str, object], opts)))
|
|
72
|
+
|
|
73
|
+
headers = api_params.get("headers")
|
|
74
|
+
if headers is not None:
|
|
75
|
+
api_params["headers"] = dict(headers)
|
|
76
|
+
|
|
77
|
+
api_headers = api_params.get("api_headers")
|
|
78
|
+
if api_headers is not None:
|
|
79
|
+
api_params["api_headers"] = dict(api_headers)
|
|
80
|
+
|
|
81
|
+
self.AsyncMobileSandbox = _bind(AsyncMobileSandbox, api_params)
|
|
82
|
+
"""Mobile `Sandbox` class bound to this client's connection configuration."""
|
|
83
|
+
|
|
84
|
+
self.AsyncDesktopSandbox = _bind(AsyncDesktopSandbox, api_params)
|
|
85
|
+
"""Desktop `Sandbox` class bound to this client's connection configuration."""
|
|
86
|
+
|
|
87
|
+
self.Mobile = _bind(MobileSandbox, api_params)
|
|
88
|
+
"""Synchronous mobile sandbox bound to this client's configuration."""
|
|
89
|
+
|
|
90
|
+
self.Desktop = _bind(DesktopSandbox, api_params)
|
|
91
|
+
"""Synchronous desktop sandbox bound to this client's configuration."""
|
|
92
|
+
|
|
93
|
+
# Code Interpreter uses the official E2B implementation while sharing
|
|
94
|
+
# this client's connection settings and Airabox-specific template.
|
|
95
|
+
self.CodeInterpreter = _bind(
|
|
96
|
+
CodeInterpreter,
|
|
97
|
+
api_params,
|
|
98
|
+
{"default_template": DEFAULT_CODE_INTERPRETER_TEMPLATE},
|
|
99
|
+
)
|
|
100
|
+
"""Synchronous code interpreter bound to this client's configuration."""
|
|
101
|
+
|
|
102
|
+
self.AsyncCodeInterpreter = _bind(
|
|
103
|
+
AsyncCodeInterpreter,
|
|
104
|
+
api_params,
|
|
105
|
+
{"default_template": DEFAULT_CODE_INTERPRETER_TEMPLATE},
|
|
106
|
+
)
|
|
107
|
+
"""Asynchronous code interpreter bound to this client's configuration."""
|
|
108
|
+
|
|
109
|
+
# The resources that are not specific to the Desktop are bound by the
|
|
110
|
+
# core client.
|
|
111
|
+
core = CoreE2B(**api_params)
|
|
112
|
+
|
|
113
|
+
self.Sandbox = core.Sandbox
|
|
114
|
+
"""`Sandbox` class bound to this client's connection configuration."""
|
|
115
|
+
|
|
116
|
+
self.AsyncSandbox = core.AsyncSandbox
|
|
117
|
+
"""`Sandbox` class bound to this client's connection configuration."""
|
|
118
|
+
|
|
119
|
+
self.Volume = core.Volume
|
|
120
|
+
"""`Volume` class bound to this client's connection configuration."""
|
|
121
|
+
|
|
122
|
+
self.AsyncVolume = core.AsyncVolume
|
|
123
|
+
"""`AsyncVolume` class bound to this client's connection configuration."""
|
|
124
|
+
|
|
125
|
+
self.Template = core.Template
|
|
126
|
+
"""`Template` class bound to this client's connection configuration."""
|
|
127
|
+
|
|
128
|
+
self.AsyncTemplate = core.AsyncTemplate
|
|
129
|
+
"""`AsyncTemplate` class bound to this client's connection configuration."""
|
|
130
|
+
|
|
131
|
+
self.Secret = core.Secret
|
|
132
|
+
"""`Secret` class bound to this client's connection configuration."""
|
|
133
|
+
|
|
134
|
+
self.AsyncSecret = core.AsyncSecret
|
|
135
|
+
"""`AsyncSecret` class bound to this client's connection configuration."""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# Keep the product-branded name exactly equivalent to the existing E2B client.
|
|
139
|
+
AiraBox = E2B
|
airabox/constants.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Synchronous and asynchronous desktop sandbox controls."""
|
|
2
|
+
|
|
3
|
+
from .desktop_asynb import AsyncDesktopSandbox, AsyncVNCStream
|
|
4
|
+
from .desktop_sync import DesktopSandbox, VNCStream
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"AsyncDesktopSandbox",
|
|
8
|
+
"AsyncVNCStream",
|
|
9
|
+
"DesktopSandbox",
|
|
10
|
+
"VNCStream",
|
|
11
|
+
]
|
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
"""Native asynchronous controls for an E2B Desktop sandbox."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import secrets
|
|
7
|
+
import string
|
|
8
|
+
from re import search as re_search
|
|
9
|
+
from shlex import quote as quote_string
|
|
10
|
+
from typing import Any, Callable, Literal, Self
|
|
11
|
+
from uuid import uuid4
|
|
12
|
+
|
|
13
|
+
from e2b import AsyncSandbox, CommandExitException, TimeoutException
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
from ..constants import DEFAULT_DESKTOP_TEMPLATE
|
|
17
|
+
except ImportError: # Support loading the module directly from sdk/python.
|
|
18
|
+
from constants import DEFAULT_DESKTOP_TEMPLATE
|
|
19
|
+
|
|
20
|
+
MOUSE_BUTTONS = {"left": 1, "right": 3, "middle": 2}
|
|
21
|
+
KEYS = {
|
|
22
|
+
"alt" : "Alt_L",
|
|
23
|
+
"alt_left" : "Alt_L",
|
|
24
|
+
"alt_right" : "Alt_R",
|
|
25
|
+
"backspace" : "BackSpace",
|
|
26
|
+
"break" : "Pause",
|
|
27
|
+
"caps_lock" : "Caps_Lock",
|
|
28
|
+
"cmd" : "Super_L",
|
|
29
|
+
"command" : "Super_L",
|
|
30
|
+
"control" : "Control_L",
|
|
31
|
+
"control_left" : "Control_L",
|
|
32
|
+
"control_right" : "Control_R",
|
|
33
|
+
"ctrl" : "Control_L",
|
|
34
|
+
"del" : "Delete",
|
|
35
|
+
"delete" : "Delete",
|
|
36
|
+
"down" : "Down",
|
|
37
|
+
"end" : "End",
|
|
38
|
+
"enter" : "Return",
|
|
39
|
+
"esc" : "Escape",
|
|
40
|
+
"escape" : "Escape",
|
|
41
|
+
"home" : "Home",
|
|
42
|
+
"insert" : "Insert",
|
|
43
|
+
"left" : "Left",
|
|
44
|
+
"menu" : "Menu",
|
|
45
|
+
"meta" : "Meta_L",
|
|
46
|
+
"num_lock" : "Num_Lock",
|
|
47
|
+
"page_down" : "Page_Down",
|
|
48
|
+
"page_up" : "Page_Up",
|
|
49
|
+
"pause" : "Pause",
|
|
50
|
+
"print" : "Print",
|
|
51
|
+
"right" : "Right",
|
|
52
|
+
"scroll_lock" : "Scroll_Lock",
|
|
53
|
+
"shift" : "Shift_L",
|
|
54
|
+
"shift_left" : "Shift_L",
|
|
55
|
+
"shift_right" : "Shift_R",
|
|
56
|
+
"space" : "space",
|
|
57
|
+
"super" : "Super_L",
|
|
58
|
+
"super_left" : "Super_L",
|
|
59
|
+
"super_right" : "Super_R",
|
|
60
|
+
"tab" : "Tab",
|
|
61
|
+
"up" : "Up",
|
|
62
|
+
"win" : "Super_L",
|
|
63
|
+
"windows" : "Super_L",
|
|
64
|
+
**{f"f{number}": f"F{number}" for number in range(1, 13)},
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def map_key(key: str) -> str:
|
|
69
|
+
"""Map a friendly key name to its X11 keysym."""
|
|
70
|
+
lower_key = key.lower()
|
|
71
|
+
return KEYS.get(lower_key, lower_key)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class AsyncVNCStream:
|
|
75
|
+
"""Manage x11vnc and noVNC through an asynchronous Desktop client."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, desktop: "AsyncDesktopSandbox") -> None:
|
|
78
|
+
self._desktop = desktop
|
|
79
|
+
self._novnc_handle: Any = None
|
|
80
|
+
self._vnc_port = 5900
|
|
81
|
+
self._port = 6080
|
|
82
|
+
self._novnc_password: str | None = None
|
|
83
|
+
self._url = f"https://{desktop.get_host(self._port)}/vnc.html"
|
|
84
|
+
|
|
85
|
+
async def _check_vnc_running(self) -> bool:
|
|
86
|
+
try:
|
|
87
|
+
await self._desktop.commands.run("pgrep -x x11vnc")
|
|
88
|
+
except CommandExitException:
|
|
89
|
+
return False
|
|
90
|
+
return True
|
|
91
|
+
|
|
92
|
+
async def _wait_for_port(self, port: int) -> bool:
|
|
93
|
+
return await self._desktop._wait_and_verify(
|
|
94
|
+
f'netstat -tuln | grep ":{port} "',
|
|
95
|
+
lambda result: bool(result.stdout.strip()),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
@staticmethod
|
|
99
|
+
def _generate_password(length: int = 16) -> str:
|
|
100
|
+
characters = string.ascii_letters + string.digits
|
|
101
|
+
return "".join(secrets.choice(characters) for _ in range(length))
|
|
102
|
+
|
|
103
|
+
def get_url(
|
|
104
|
+
self,
|
|
105
|
+
auto_connect: bool = True,
|
|
106
|
+
view_only: bool = False,
|
|
107
|
+
resize: str = "scale",
|
|
108
|
+
auth_key: str | None = None,
|
|
109
|
+
) -> str:
|
|
110
|
+
"""Build a noVNC URL from the current local stream state."""
|
|
111
|
+
params: list[str] = []
|
|
112
|
+
if auto_connect:
|
|
113
|
+
params.append("autoconnect=true")
|
|
114
|
+
if view_only:
|
|
115
|
+
params.append("view_only=true")
|
|
116
|
+
if resize:
|
|
117
|
+
params.append(f"resize={resize}")
|
|
118
|
+
if auth_key:
|
|
119
|
+
params.append(f"password={auth_key}")
|
|
120
|
+
return f"{self._url}?{'&'.join(params)}" if params else self._url
|
|
121
|
+
|
|
122
|
+
def get_auth_key(self) -> str:
|
|
123
|
+
"""Return the password generated by an authenticated start."""
|
|
124
|
+
if self._novnc_password is None:
|
|
125
|
+
raise RuntimeError(
|
|
126
|
+
"Unable to retrieve stream auth key, check if require_auth is enabled",
|
|
127
|
+
)
|
|
128
|
+
return self._novnc_password
|
|
129
|
+
|
|
130
|
+
async def start(
|
|
131
|
+
self,
|
|
132
|
+
vnc_port: int | None = None,
|
|
133
|
+
port: int | None = None,
|
|
134
|
+
require_auth: bool = False,
|
|
135
|
+
window_id: str | None = None,
|
|
136
|
+
) -> None:
|
|
137
|
+
"""Start x11vnc and noVNC for the full display or one window."""
|
|
138
|
+
if await self._check_vnc_running():
|
|
139
|
+
raise RuntimeError("Stream is already running")
|
|
140
|
+
|
|
141
|
+
self._vnc_port = vnc_port or self._vnc_port
|
|
142
|
+
self._port = port or self._port
|
|
143
|
+
self._novnc_password = self._generate_password() if require_auth else None
|
|
144
|
+
self._url = f"https://{self._desktop.get_host(self._port)}/vnc.html"
|
|
145
|
+
password_flag = "-nopw"
|
|
146
|
+
|
|
147
|
+
if require_auth:
|
|
148
|
+
await self._desktop.commands.run("mkdir -p ~/.vnc")
|
|
149
|
+
await self._desktop.commands.run(
|
|
150
|
+
f"x11vnc -storepasswd {self._novnc_password} ~/.vnc/passwd",
|
|
151
|
+
)
|
|
152
|
+
password_flag = "-usepw"
|
|
153
|
+
|
|
154
|
+
window_flag = f"-id {window_id}" if window_id else ""
|
|
155
|
+
vnc_command = (
|
|
156
|
+
f"x11vnc -bg -display {self._desktop._display} -forever -wait 50 "
|
|
157
|
+
f"-shared -rfbport {self._vnc_port} {password_flag} "
|
|
158
|
+
f"2>/tmp/x11vnc_stderr.log {window_flag}"
|
|
159
|
+
)
|
|
160
|
+
novnc_command = (
|
|
161
|
+
"cd /opt/noVNC/utils && ./novnc_proxy "
|
|
162
|
+
f"--vnc localhost:{self._vnc_port} --listen {self._port} "
|
|
163
|
+
"--web /opt/noVNC > /tmp/novnc.log 2>&1"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
try:
|
|
167
|
+
await self._desktop.commands.run(vnc_command)
|
|
168
|
+
self._novnc_handle = await self._desktop.commands.run(
|
|
169
|
+
novnc_command,
|
|
170
|
+
background=True,
|
|
171
|
+
timeout=0,
|
|
172
|
+
)
|
|
173
|
+
if not await self._wait_for_port(self._port):
|
|
174
|
+
raise TimeoutException("Could not start noVNC server")
|
|
175
|
+
except BaseException:
|
|
176
|
+
try:
|
|
177
|
+
await self.stop()
|
|
178
|
+
except BaseException:
|
|
179
|
+
pass
|
|
180
|
+
raise
|
|
181
|
+
|
|
182
|
+
async def stop(self) -> None:
|
|
183
|
+
"""Stop x11vnc and the saved noVNC command handle."""
|
|
184
|
+
if await self._check_vnc_running():
|
|
185
|
+
await self._desktop.commands.run("pkill x11vnc")
|
|
186
|
+
if self._novnc_handle is not None:
|
|
187
|
+
await self._novnc_handle.kill()
|
|
188
|
+
self._novnc_handle = None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class AsyncDesktopSandbox(AsyncSandbox):
|
|
192
|
+
"""Extend E2B's asynchronous Sandbox with desktop controls."""
|
|
193
|
+
|
|
194
|
+
default_template = DEFAULT_DESKTOP_TEMPLATE
|
|
195
|
+
|
|
196
|
+
@classmethod
|
|
197
|
+
async def create(
|
|
198
|
+
cls,
|
|
199
|
+
template: str | None = None,
|
|
200
|
+
resolution: tuple[int, int] | None = None,
|
|
201
|
+
dpi: int | None = None,
|
|
202
|
+
display: str | None = None,
|
|
203
|
+
timeout: int | None = None,
|
|
204
|
+
metadata: dict[str, str] | None = None,
|
|
205
|
+
envs: dict[str, str] | None = None,
|
|
206
|
+
**opts: Any,
|
|
207
|
+
) -> Self:
|
|
208
|
+
"""Create a sandbox and initialize its X11 desktop session."""
|
|
209
|
+
display = display or ":0"
|
|
210
|
+
sandbox = await super().create(
|
|
211
|
+
template = template or cls.default_template,
|
|
212
|
+
timeout = timeout,
|
|
213
|
+
metadata = metadata,
|
|
214
|
+
envs = {**(envs or {}), "DISPLAY": display},
|
|
215
|
+
**opts,
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
# print(f"沙箱环境变量 {await sandbox.commands.run('env')}")
|
|
219
|
+
|
|
220
|
+
try:
|
|
221
|
+
sandbox._display = display
|
|
222
|
+
await sandbox._start_Xvfb(display, resolution, dpi)
|
|
223
|
+
sandbox._vnc_stream = AsyncVNCStream(sandbox)
|
|
224
|
+
await sandbox._start_xfce4()
|
|
225
|
+
except BaseException:
|
|
226
|
+
try:
|
|
227
|
+
await sandbox.kill()
|
|
228
|
+
except BaseException:
|
|
229
|
+
pass
|
|
230
|
+
raise
|
|
231
|
+
|
|
232
|
+
return sandbox
|
|
233
|
+
|
|
234
|
+
@classmethod
|
|
235
|
+
async def connect(
|
|
236
|
+
cls,
|
|
237
|
+
sandbox_id: str,
|
|
238
|
+
timeout: int | None = None,
|
|
239
|
+
display: str = ":0",
|
|
240
|
+
resolution: tuple[int, int] | None = None,
|
|
241
|
+
dpi: int | None = None,
|
|
242
|
+
**opts: Any,
|
|
243
|
+
) -> Self:
|
|
244
|
+
"""Connect to an existing sandbox and restore local Desktop state."""
|
|
245
|
+
sandbox = await super().connect(
|
|
246
|
+
sandbox_id = sandbox_id,
|
|
247
|
+
timeout = timeout,
|
|
248
|
+
**opts,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
sandbox._display = display
|
|
252
|
+
await sandbox.commands.run(
|
|
253
|
+
"pkill -x x11vnc || true; pkill -f '[n]ovnc_proxy' || true",
|
|
254
|
+
)
|
|
255
|
+
if not await sandbox._check_ready(
|
|
256
|
+
f"xdpyinfo -display {display}",
|
|
257
|
+
lambda result: result.exit_code == 0,
|
|
258
|
+
):
|
|
259
|
+
await sandbox._start_Xvfb(display, resolution, dpi)
|
|
260
|
+
|
|
261
|
+
sandbox._vnc_stream = AsyncVNCStream(sandbox)
|
|
262
|
+
await sandbox._start_xfce4()
|
|
263
|
+
return sandbox
|
|
264
|
+
|
|
265
|
+
@property
|
|
266
|
+
def stream(self) -> AsyncVNCStream:
|
|
267
|
+
"""Return the stream controller bound to this desktop."""
|
|
268
|
+
return self._vnc_stream
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
async def _check_ready(self, command: str, on_result: Callable[[Any], bool]) -> bool:
|
|
272
|
+
"""Check service readiness once without waiting for retries."""
|
|
273
|
+
try:
|
|
274
|
+
return on_result(await self.commands.run(command))
|
|
275
|
+
except CommandExitException:
|
|
276
|
+
return False
|
|
277
|
+
|
|
278
|
+
async def _wait_and_verify(
|
|
279
|
+
self,
|
|
280
|
+
command: str,
|
|
281
|
+
on_result: Callable[[Any], bool],
|
|
282
|
+
timeout: int = 10,
|
|
283
|
+
interval: float = 0.5,
|
|
284
|
+
) -> bool:
|
|
285
|
+
"""Poll a remote command until its result satisfies a predicate."""
|
|
286
|
+
elapsed = 0.0
|
|
287
|
+
while elapsed < timeout:
|
|
288
|
+
if await self._check_ready(command, on_result):
|
|
289
|
+
return True
|
|
290
|
+
await asyncio.sleep(interval)
|
|
291
|
+
elapsed += interval
|
|
292
|
+
return False
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
async def _start_Xvfb(
|
|
296
|
+
self,
|
|
297
|
+
display: str,
|
|
298
|
+
resolution: tuple[int, int] | None,
|
|
299
|
+
dpi: int | None,
|
|
300
|
+
) -> None:
|
|
301
|
+
"""Start Xvfb and wait until the display accepts connections."""
|
|
302
|
+
width, height = resolution or (1024, 768)
|
|
303
|
+
handle = await self.commands.run(
|
|
304
|
+
f"Xvfb {display} -ac -screen 0 {width}x{height}x24 "
|
|
305
|
+
f"-retro -dpi {dpi or 96} -nolisten tcp -nolisten unix",
|
|
306
|
+
background = True,
|
|
307
|
+
timeout = 0,
|
|
308
|
+
)
|
|
309
|
+
await handle.disconnect()
|
|
310
|
+
if not await self._wait_and_verify(
|
|
311
|
+
f"xdpyinfo -display {display}",
|
|
312
|
+
lambda result: result.exit_code == 0,
|
|
313
|
+
):
|
|
314
|
+
raise TimeoutException("Could not start Xvfb")
|
|
315
|
+
|
|
316
|
+
async def _start_xfce4(self) -> None:
|
|
317
|
+
"""Start XFCE only when its desktop processes are missing."""
|
|
318
|
+
check_cmd = (
|
|
319
|
+
"pgrep -x xfce4-session >/dev/null && pgrep -x xfwm4 >/dev/null "
|
|
320
|
+
"&& pgrep -x xfdesktop >/dev/null"
|
|
321
|
+
)
|
|
322
|
+
if not await self._check_ready(check_cmd, lambda result: result.exit_code == 0):
|
|
323
|
+
handle = await self.commands.run(
|
|
324
|
+
"startxfce4",
|
|
325
|
+
background = True,
|
|
326
|
+
timeout = 0,
|
|
327
|
+
)
|
|
328
|
+
await handle.disconnect()
|
|
329
|
+
|
|
330
|
+
ready = await self._wait_and_verify(
|
|
331
|
+
check_cmd,
|
|
332
|
+
lambda result: result.exit_code == 0,
|
|
333
|
+
timeout = 60,
|
|
334
|
+
)
|
|
335
|
+
if not ready:
|
|
336
|
+
raise TimeoutException("Could not start XFCE")
|
|
337
|
+
|
|
338
|
+
async def screenshot(
|
|
339
|
+
self,
|
|
340
|
+
format: Literal["bytes", "stream"] = "bytes",
|
|
341
|
+
) -> bytes:
|
|
342
|
+
"""Capture the remote desktop and remove its temporary image."""
|
|
343
|
+
screenshot_path = f"/tmp/screenshot-{uuid4()}.png"
|
|
344
|
+
await self.commands.run(f"scrot --pointer {screenshot_path}")
|
|
345
|
+
try:
|
|
346
|
+
screenshot = await self.files.read(screenshot_path, format=format)
|
|
347
|
+
except BaseException:
|
|
348
|
+
try:
|
|
349
|
+
await self.files.remove(screenshot_path)
|
|
350
|
+
except BaseException:
|
|
351
|
+
pass
|
|
352
|
+
raise
|
|
353
|
+
else:
|
|
354
|
+
await self.files.remove(screenshot_path)
|
|
355
|
+
return screenshot
|
|
356
|
+
|
|
357
|
+
async def move_mouse(self, x: int, y: int) -> None:
|
|
358
|
+
"""Move the pointer to an absolute desktop coordinate."""
|
|
359
|
+
await self.commands.run(f"xdotool mousemove --sync {x} {y}")
|
|
360
|
+
|
|
361
|
+
async def _click(
|
|
362
|
+
self,
|
|
363
|
+
command: str,
|
|
364
|
+
x: int | None,
|
|
365
|
+
y: int | None,
|
|
366
|
+
) -> None:
|
|
367
|
+
"""Optionally move the pointer, then execute one click command."""
|
|
368
|
+
if (x is None) != (y is None):
|
|
369
|
+
raise ValueError("Both x and y must be provided together")
|
|
370
|
+
if x is not None and y is not None:
|
|
371
|
+
await self.move_mouse(x, y)
|
|
372
|
+
await self.commands.run(command)
|
|
373
|
+
|
|
374
|
+
async def left_click(self, x: int | None = None, y: int | None = None) -> None:
|
|
375
|
+
"""Click the left mouse button."""
|
|
376
|
+
await self._click("xdotool click 1", x, y)
|
|
377
|
+
|
|
378
|
+
async def double_click(
|
|
379
|
+
self,
|
|
380
|
+
x: int | None = None,
|
|
381
|
+
y: int | None = None,
|
|
382
|
+
) -> None:
|
|
383
|
+
"""Double-click the left mouse button."""
|
|
384
|
+
await self._click("xdotool click --repeat 2 1", x, y)
|
|
385
|
+
|
|
386
|
+
async def right_click(self, x: int | None = None, y: int | None = None) -> None:
|
|
387
|
+
"""Click the right mouse button."""
|
|
388
|
+
await self._click("xdotool click 3", x, y)
|
|
389
|
+
|
|
390
|
+
async def middle_click(
|
|
391
|
+
self,
|
|
392
|
+
x: int | None = None,
|
|
393
|
+
y: int | None = None,
|
|
394
|
+
) -> None:
|
|
395
|
+
"""Click the middle mouse button."""
|
|
396
|
+
await self._click("xdotool click 2", x, y)
|
|
397
|
+
|
|
398
|
+
async def scroll(
|
|
399
|
+
self,
|
|
400
|
+
direction: Literal["up", "down"] = "down",
|
|
401
|
+
amount: int = 1,
|
|
402
|
+
) -> None:
|
|
403
|
+
"""Scroll the mouse wheel by the requested number of steps."""
|
|
404
|
+
button = 4 if direction == "up" else 5
|
|
405
|
+
await self.commands.run(f"xdotool click --repeat {amount} {button}")
|
|
406
|
+
|
|
407
|
+
async def mouse_press(
|
|
408
|
+
self,
|
|
409
|
+
button: Literal["left", "right", "middle"] = "left",
|
|
410
|
+
) -> None:
|
|
411
|
+
"""Press a mouse button without releasing it."""
|
|
412
|
+
await self.commands.run(f"xdotool mousedown {MOUSE_BUTTONS[button]}")
|
|
413
|
+
|
|
414
|
+
async def mouse_release(
|
|
415
|
+
self,
|
|
416
|
+
button: Literal["left", "right", "middle"] = "left",
|
|
417
|
+
) -> None:
|
|
418
|
+
"""Release a pressed mouse button."""
|
|
419
|
+
await self.commands.run(f"xdotool mouseup {MOUSE_BUTTONS[button]}")
|
|
420
|
+
|
|
421
|
+
async def drag(self, fr: tuple[int, int], to: tuple[int, int]) -> None:
|
|
422
|
+
"""Drag from one absolute desktop coordinate to another."""
|
|
423
|
+
await self.move_mouse(fr[0], fr[1])
|
|
424
|
+
await self.mouse_press()
|
|
425
|
+
await self.move_mouse(to[0], to[1])
|
|
426
|
+
await self.mouse_release()
|
|
427
|
+
|
|
428
|
+
async def write(
|
|
429
|
+
self,
|
|
430
|
+
text: str,
|
|
431
|
+
*,
|
|
432
|
+
chunk_size: int = 25,
|
|
433
|
+
delay_in_ms: int = 75,
|
|
434
|
+
) -> None:
|
|
435
|
+
"""Type text sequentially in bounded chunks."""
|
|
436
|
+
for start in range(0, len(text), chunk_size):
|
|
437
|
+
chunk = quote_string(text[start : start + chunk_size])
|
|
438
|
+
await self.commands.run(
|
|
439
|
+
f"xdotool type --delay {delay_in_ms} -- {chunk}",
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
async def press(self, key: str | list[str]) -> None:
|
|
443
|
+
"""Press one key or a key chord."""
|
|
444
|
+
mapped = (
|
|
445
|
+
"+".join(map_key(item) for item in key)
|
|
446
|
+
if isinstance(key, list)
|
|
447
|
+
else map_key(key)
|
|
448
|
+
)
|
|
449
|
+
await self.commands.run(f"xdotool key {mapped}")
|
|
450
|
+
|
|
451
|
+
async def get_cursor_position(self) -> tuple[int, int]:
|
|
452
|
+
"""Return the current pointer coordinate."""
|
|
453
|
+
result = await self.commands.run("xdotool getmouselocation")
|
|
454
|
+
match = re_search(r"x:(\d+)\s+y:(\d+)", result.stdout)
|
|
455
|
+
if match is None:
|
|
456
|
+
raise RuntimeError(
|
|
457
|
+
f"Failed to parse cursor position from output: {result.stdout}",
|
|
458
|
+
)
|
|
459
|
+
return int(match.group(1)), int(match.group(2))
|
|
460
|
+
|
|
461
|
+
async def get_screen_size(self) -> tuple[int, int]:
|
|
462
|
+
"""Return the active X11 screen dimensions."""
|
|
463
|
+
result = await self.commands.run("xrandr")
|
|
464
|
+
match = re_search(r"(\d+x\d+)", result.stdout)
|
|
465
|
+
if match is None:
|
|
466
|
+
raise RuntimeError(
|
|
467
|
+
f"Failed to parse screen size from output: {result.stdout}",
|
|
468
|
+
)
|
|
469
|
+
width, height = match.group(1).split("x")
|
|
470
|
+
return int(width), int(height)
|
|
471
|
+
|
|
472
|
+
async def get_current_window_id(self) -> str:
|
|
473
|
+
"""Return the focused X11 window ID."""
|
|
474
|
+
result = await self.commands.run("xdotool getwindowfocus")
|
|
475
|
+
return result.stdout.strip()
|
|
476
|
+
|
|
477
|
+
async def get_application_windows(self, application: str) -> list[str]:
|
|
478
|
+
"""Return visible X11 window IDs for an application class."""
|
|
479
|
+
result = await self.commands.run(
|
|
480
|
+
"xdotool search --onlyvisible --class " + quote_string(application),
|
|
481
|
+
)
|
|
482
|
+
return result.stdout.split()
|
|
483
|
+
|
|
484
|
+
async def get_window_title(self, window_id: str) -> str:
|
|
485
|
+
"""Return an X11 window title."""
|
|
486
|
+
result = await self.commands.run(
|
|
487
|
+
"xdotool getwindowname " + quote_string(window_id),
|
|
488
|
+
)
|
|
489
|
+
return result.stdout.strip()
|
|
490
|
+
|
|
491
|
+
async def wait(self, ms: int) -> None:
|
|
492
|
+
"""Yield to the event loop for the requested number of milliseconds."""
|
|
493
|
+
await asyncio.sleep(ms / 1000)
|
|
494
|
+
|
|
495
|
+
async def open(self, file_or_url: str) -> None:
|
|
496
|
+
"""Open a file or URL in the default desktop application."""
|
|
497
|
+
command = f"xdg-open {quote_string(file_or_url)}"
|
|
498
|
+
handle = await self.commands.run(command, background=True)
|
|
499
|
+
await handle.disconnect()
|
|
500
|
+
|
|
501
|
+
async def launch(self, application: str, uri: str | None = None) -> None:
|
|
502
|
+
"""Launch a named desktop application and optionally pass a URI."""
|
|
503
|
+
command = f"gtk-launch {quote_string(application)}"
|
|
504
|
+
if uri:
|
|
505
|
+
command += f" {quote_string(uri)}"
|
|
506
|
+
handle = await self.commands.run(command, background=True, timeout=0)
|
|
507
|
+
await handle.disconnect()
|