@midscene/android 0.14.2 → 0.14.3-beta-20250409031306.0
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.
- package/bin/playground +3 -0
- package/dist/es/index.js +4 -0
- package/dist/es/playground.d.ts +2 -0
- package/dist/es/playground.js +852 -0
- package/dist/lib/index.js +4 -0
- package/dist/lib/playground.d.ts +2 -0
- package/dist/lib/playground.js +872 -0
- package/dist/types/playground.d.ts +2 -0
- package/package.json +25 -4
- package/static/index.html +1 -0
- package/static/scripts/htmlElement.js +5 -0
- package/static/scripts/htmlElement.js.LICENSE.txt +12 -0
- package/static/scripts/htmlElementDebug.js +2 -0
- package/static/scripts/htmlElementDebug.js.LICENSE.txt +12 -0
- package/static/scripts/stop-water-flow.js +2 -0
- package/static/scripts/stop-water-flow.js.map +1 -0
- package/static/scripts/water-flow.js +54 -0
- package/static/scripts/water-flow.js.map +1 -0
- package/static/static/css/index.fa8491ca.css +2 -0
- package/static/static/css/index.fa8491ca.css.map +1 -0
- package/static/static/js/792.8ac93205.js +467 -0
- package/static/static/js/792.8ac93205.js.LICENSE.txt +1673 -0
- package/static/static/js/792.8ac93205.js.map +1 -0
- package/static/static/js/async/166.208adb78.js +2 -0
- package/static/static/js/async/166.208adb78.js.map +1 -0
- package/static/static/js/index.906d88a4.js +504 -0
- package/static/static/js/index.906d88a4.js.map +1 -0
- package/static/static/js/lib-polyfill.c3257577.js +2 -0
- package/static/static/js/lib-polyfill.c3257577.js.map +1 -0
- package/static/static/js/lib-react.bac2292c.js +3 -0
- package/static/static/js/lib-react.bac2292c.js.LICENSE.txt +39 -0
- package/static/static/js/lib-react.bac2292c.js.map +1 -0
- package/LICENSE +0 -21
|
@@ -0,0 +1,852 @@
|
|
|
1
|
+
// src/playground/bin.ts
|
|
2
|
+
import path2 from "path";
|
|
3
|
+
import PlaygroundServer from "@midscene/web/midscene-server";
|
|
4
|
+
import open from "open";
|
|
5
|
+
|
|
6
|
+
// src/page/index.ts
|
|
7
|
+
import assert from "assert";
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
import path from "path";
|
|
10
|
+
import { getTmpFile } from "@midscene/core/utils";
|
|
11
|
+
import { resizeImg } from "@midscene/shared/img";
|
|
12
|
+
import { getDebug } from "@midscene/shared/logger";
|
|
13
|
+
import { ADB } from "appium-adb";
|
|
14
|
+
var androidScreenshotPath = "/data/local/tmp/midscene_screenshot.png";
|
|
15
|
+
var debugPage = getDebug("android:device");
|
|
16
|
+
var AndroidDevice = class {
|
|
17
|
+
constructor(deviceId) {
|
|
18
|
+
this.screenSize = null;
|
|
19
|
+
this.yadbPushed = false;
|
|
20
|
+
this.deviceRatio = 1;
|
|
21
|
+
this.adb = null;
|
|
22
|
+
this.connectingAdb = null;
|
|
23
|
+
this.pageType = "android";
|
|
24
|
+
assert(deviceId, "deviceId is required for AndroidDevice");
|
|
25
|
+
this.deviceId = deviceId;
|
|
26
|
+
}
|
|
27
|
+
async connect() {
|
|
28
|
+
return this.getAdb();
|
|
29
|
+
}
|
|
30
|
+
async getAdb() {
|
|
31
|
+
if (this.adb) {
|
|
32
|
+
return this.adb;
|
|
33
|
+
}
|
|
34
|
+
if (this.connectingAdb) {
|
|
35
|
+
return this.connectingAdb;
|
|
36
|
+
}
|
|
37
|
+
this.connectingAdb = (async () => {
|
|
38
|
+
let error = null;
|
|
39
|
+
debugPage(`Initializing ADB with device ID: ${this.deviceId}`);
|
|
40
|
+
try {
|
|
41
|
+
this.adb = await ADB.createADB({
|
|
42
|
+
udid: this.deviceId,
|
|
43
|
+
adbExecTimeout: 6e4
|
|
44
|
+
});
|
|
45
|
+
debugPage("ADB initialized successfully");
|
|
46
|
+
return this.adb;
|
|
47
|
+
} catch (e) {
|
|
48
|
+
debugPage(`Failed to initialize ADB: ${e}`);
|
|
49
|
+
error = new Error(`Unable to connect to device ${this.deviceId}: ${e}`);
|
|
50
|
+
} finally {
|
|
51
|
+
this.connectingAdb = null;
|
|
52
|
+
}
|
|
53
|
+
if (error) {
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
throw new Error("ADB initialization failed unexpectedly");
|
|
57
|
+
})();
|
|
58
|
+
return this.connectingAdb;
|
|
59
|
+
}
|
|
60
|
+
async launch(uri) {
|
|
61
|
+
const adb = await this.getAdb();
|
|
62
|
+
try {
|
|
63
|
+
if (uri.startsWith("http://") || uri.startsWith("https://") || uri.includes("://")) {
|
|
64
|
+
await adb.startUri(uri);
|
|
65
|
+
} else if (uri.includes("/")) {
|
|
66
|
+
const [appPackage, appActivity] = uri.split("/");
|
|
67
|
+
await adb.startApp({
|
|
68
|
+
pkg: appPackage,
|
|
69
|
+
activity: appActivity
|
|
70
|
+
});
|
|
71
|
+
} else {
|
|
72
|
+
await adb.startApp({
|
|
73
|
+
pkg: uri
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
debugPage(`Successfully launched: ${uri}`);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
debugPage(`Error launching ${uri}: ${error}`);
|
|
79
|
+
throw new Error(`Failed to launch ${uri}: ${error}`, { cause: error });
|
|
80
|
+
}
|
|
81
|
+
return this;
|
|
82
|
+
}
|
|
83
|
+
async execYadb(keyboardContent) {
|
|
84
|
+
await this.ensureYadb();
|
|
85
|
+
const adb = await this.getAdb();
|
|
86
|
+
await adb.shell(
|
|
87
|
+
`app_process -Djava.class.path=/data/local/tmp/yadb /data/local/tmp com.ysbing.yadb.Main -keyboard "${keyboardContent}"`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
async getElementsInfo() {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
async getElementsNodeTree() {
|
|
94
|
+
return {
|
|
95
|
+
node: null,
|
|
96
|
+
children: []
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async size() {
|
|
100
|
+
if (this.screenSize) {
|
|
101
|
+
return this.screenSize;
|
|
102
|
+
}
|
|
103
|
+
const adb = await this.getAdb();
|
|
104
|
+
const screenSize = await adb.getScreenSize();
|
|
105
|
+
let width;
|
|
106
|
+
let height;
|
|
107
|
+
if (typeof screenSize === "string") {
|
|
108
|
+
const match = screenSize.match(/(\d+)x(\d+)/);
|
|
109
|
+
if (!match || match.length < 3) {
|
|
110
|
+
throw new Error(`Unable to parse screen size: ${screenSize}`);
|
|
111
|
+
}
|
|
112
|
+
width = Number.parseInt(match[1], 10);
|
|
113
|
+
height = Number.parseInt(match[2], 10);
|
|
114
|
+
} else if (typeof screenSize === "object" && screenSize !== null) {
|
|
115
|
+
const sizeObj = screenSize;
|
|
116
|
+
if ("width" in sizeObj && "height" in sizeObj) {
|
|
117
|
+
width = Number(sizeObj.width);
|
|
118
|
+
height = Number(sizeObj.height);
|
|
119
|
+
} else {
|
|
120
|
+
throw new Error(
|
|
121
|
+
`Invalid screen size object: ${JSON.stringify(screenSize)}`
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
} else {
|
|
125
|
+
throw new Error(`Invalid screen size format: ${screenSize}`);
|
|
126
|
+
}
|
|
127
|
+
const densityNum = await adb.getScreenDensity();
|
|
128
|
+
this.deviceRatio = Number(densityNum) / 160;
|
|
129
|
+
const { x: logicalWidth, y: logicalHeight } = this.reverseAdjustCoordinates(
|
|
130
|
+
width,
|
|
131
|
+
height
|
|
132
|
+
);
|
|
133
|
+
this.screenSize = {
|
|
134
|
+
width: logicalWidth,
|
|
135
|
+
height: logicalHeight
|
|
136
|
+
};
|
|
137
|
+
return this.screenSize;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Convert logical coordinates to physical coordinates, handling device ratio
|
|
141
|
+
* @param x Logical X coordinate
|
|
142
|
+
* @param y Logical Y coordinate
|
|
143
|
+
* @returns Physical coordinate point
|
|
144
|
+
*/
|
|
145
|
+
adjustCoordinates(x, y) {
|
|
146
|
+
const ratio = this.deviceRatio;
|
|
147
|
+
return {
|
|
148
|
+
x: Math.round(x * ratio),
|
|
149
|
+
y: Math.round(y * ratio)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Convert physical coordinates to logical coordinates, handling device ratio
|
|
154
|
+
* @param x Physical X coordinate
|
|
155
|
+
* @param y Physical Y coordinate
|
|
156
|
+
* @returns Logical coordinate point
|
|
157
|
+
*/
|
|
158
|
+
reverseAdjustCoordinates(x, y) {
|
|
159
|
+
const ratio = this.deviceRatio;
|
|
160
|
+
return {
|
|
161
|
+
x: Math.round(x / ratio),
|
|
162
|
+
y: Math.round(y / ratio)
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
async screenshotBase64() {
|
|
166
|
+
debugPage("screenshotBase64 begin");
|
|
167
|
+
const { width, height } = await this.size();
|
|
168
|
+
const adb = await this.getAdb();
|
|
169
|
+
let screenshotBuffer;
|
|
170
|
+
try {
|
|
171
|
+
screenshotBuffer = await adb.takeScreenshot(null);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
const screenshotPath = getTmpFile("png");
|
|
174
|
+
try {
|
|
175
|
+
await adb.shell(`screencap -p ${androidScreenshotPath}`);
|
|
176
|
+
} catch (error2) {
|
|
177
|
+
await this.forceScreenshot(androidScreenshotPath);
|
|
178
|
+
}
|
|
179
|
+
await adb.pull(androidScreenshotPath, screenshotPath);
|
|
180
|
+
screenshotBuffer = await fs.promises.readFile(screenshotPath);
|
|
181
|
+
}
|
|
182
|
+
const resizedScreenshotBuffer = await resizeImg(screenshotBuffer, {
|
|
183
|
+
width,
|
|
184
|
+
height
|
|
185
|
+
});
|
|
186
|
+
const result = `data:image/jpeg;base64,${resizedScreenshotBuffer.toString("base64")}`;
|
|
187
|
+
debugPage("screenshotBase64 end");
|
|
188
|
+
return result;
|
|
189
|
+
}
|
|
190
|
+
get mouse() {
|
|
191
|
+
return {
|
|
192
|
+
click: (x, y) => this.mouseClick(x, y),
|
|
193
|
+
wheel: (deltaX, deltaY) => this.mouseWheel(deltaX, deltaY),
|
|
194
|
+
move: (x, y) => this.mouseMove(x, y),
|
|
195
|
+
drag: (from, to) => this.mouseDrag(from, to)
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
get keyboard() {
|
|
199
|
+
return {
|
|
200
|
+
type: (text) => this.keyboardType(text),
|
|
201
|
+
press: (action) => this.keyboardPressAction(action)
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
async clearInput(element) {
|
|
205
|
+
if (!element) {
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
await this.ensureYadb();
|
|
209
|
+
const adb = await this.getAdb();
|
|
210
|
+
await this.mouse.click(element.center[0], element.center[1]);
|
|
211
|
+
await adb.shell(
|
|
212
|
+
'app_process -Djava.class.path=/data/local/tmp/yadb /data/local/tmp com.ysbing.yadb.Main -keyboard "~CLEAR~"'
|
|
213
|
+
);
|
|
214
|
+
await this.mouse.click(element.center[0], element.center[1]);
|
|
215
|
+
}
|
|
216
|
+
async forceScreenshot(path3) {
|
|
217
|
+
await this.ensureYadb();
|
|
218
|
+
const adb = await this.getAdb();
|
|
219
|
+
await adb.shell(
|
|
220
|
+
`app_process -Djava.class.path=/data/local/tmp/yadb /data/local/tmp com.ysbing.yadb.Main -screenshot ${path3}`
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
async url() {
|
|
224
|
+
const adb = await this.getAdb();
|
|
225
|
+
const { appPackage, appActivity } = await adb.getFocusedPackageAndActivity();
|
|
226
|
+
return `${appPackage}/${appActivity}`;
|
|
227
|
+
}
|
|
228
|
+
async scrollUntilTop(startPoint) {
|
|
229
|
+
if (startPoint) {
|
|
230
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
231
|
+
const end = { x: start.x, y: 0 };
|
|
232
|
+
await this.mouseDrag(start, end);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
await this.mouseWheel(0, 9999999, 100);
|
|
236
|
+
}
|
|
237
|
+
async scrollUntilBottom(startPoint) {
|
|
238
|
+
if (startPoint) {
|
|
239
|
+
const { height } = await this.size();
|
|
240
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
241
|
+
const end = { x: start.x, y: height };
|
|
242
|
+
await this.mouseDrag(start, end);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
await this.mouseWheel(0, -9999999, 100);
|
|
246
|
+
}
|
|
247
|
+
async scrollUntilLeft(startPoint) {
|
|
248
|
+
if (startPoint) {
|
|
249
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
250
|
+
const end = { x: 0, y: start.y };
|
|
251
|
+
await this.mouseDrag(start, end);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
await this.mouseWheel(9999999, 0, 100);
|
|
255
|
+
}
|
|
256
|
+
async scrollUntilRight(startPoint) {
|
|
257
|
+
if (startPoint) {
|
|
258
|
+
const { width } = await this.size();
|
|
259
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
260
|
+
const end = { x: width, y: start.y };
|
|
261
|
+
await this.mouseDrag(start, end);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
await this.mouseWheel(-9999999, 0, 100);
|
|
265
|
+
}
|
|
266
|
+
async scrollUp(distance, startPoint) {
|
|
267
|
+
const { height } = await this.size();
|
|
268
|
+
const scrollDistance = distance || height;
|
|
269
|
+
if (startPoint) {
|
|
270
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
271
|
+
const endY = Math.max(0, start.y - scrollDistance);
|
|
272
|
+
const end = { x: start.x, y: endY };
|
|
273
|
+
await this.mouseDrag(start, end);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
await this.mouseWheel(0, scrollDistance, 1e3);
|
|
277
|
+
}
|
|
278
|
+
async scrollDown(distance, startPoint) {
|
|
279
|
+
const { height } = await this.size();
|
|
280
|
+
const scrollDistance = distance || height;
|
|
281
|
+
if (startPoint) {
|
|
282
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
283
|
+
const endY = Math.min(height, start.y + scrollDistance);
|
|
284
|
+
const end = { x: start.x, y: endY };
|
|
285
|
+
await this.mouseDrag(start, end);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
await this.mouseWheel(0, -scrollDistance, 1e3);
|
|
289
|
+
}
|
|
290
|
+
async scrollLeft(distance, startPoint) {
|
|
291
|
+
const { width } = await this.size();
|
|
292
|
+
const scrollDistance = distance || width;
|
|
293
|
+
if (startPoint) {
|
|
294
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
295
|
+
const endX = Math.max(0, start.x - scrollDistance);
|
|
296
|
+
const end = { x: endX, y: start.y };
|
|
297
|
+
await this.mouseDrag(start, end);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
await this.mouseWheel(scrollDistance, 0, 1e3);
|
|
301
|
+
}
|
|
302
|
+
async scrollRight(distance, startPoint) {
|
|
303
|
+
const { width } = await this.size();
|
|
304
|
+
const scrollDistance = distance || width;
|
|
305
|
+
if (startPoint) {
|
|
306
|
+
const start = { x: startPoint.left, y: startPoint.top };
|
|
307
|
+
const endX = Math.min(width, start.x + scrollDistance);
|
|
308
|
+
const end = { x: endX, y: start.y };
|
|
309
|
+
await this.mouseDrag(start, end);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
await this.mouseWheel(-scrollDistance, 0, 1e3);
|
|
313
|
+
}
|
|
314
|
+
async ensureYadb() {
|
|
315
|
+
if (!this.yadbPushed) {
|
|
316
|
+
const adb = await this.getAdb();
|
|
317
|
+
const yadbBin = path.join(__dirname, "../../bin/yadb");
|
|
318
|
+
await adb.push(yadbBin, "/data/local/tmp");
|
|
319
|
+
this.yadbPushed = true;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async keyboardType(text) {
|
|
323
|
+
if (!text)
|
|
324
|
+
return;
|
|
325
|
+
const adb = await this.getAdb();
|
|
326
|
+
const isChinese = /[\p{Script=Han}\p{sc=Hani}]/u.test(text);
|
|
327
|
+
if (!isChinese) {
|
|
328
|
+
await adb.inputText(text);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
await this.execYadb(text);
|
|
332
|
+
}
|
|
333
|
+
async keyboardPress(key) {
|
|
334
|
+
const keyCodeMap = {
|
|
335
|
+
Enter: 66,
|
|
336
|
+
Backspace: 67,
|
|
337
|
+
Tab: 61,
|
|
338
|
+
ArrowUp: 19,
|
|
339
|
+
ArrowDown: 20,
|
|
340
|
+
ArrowLeft: 21,
|
|
341
|
+
ArrowRight: 22,
|
|
342
|
+
Escape: 111,
|
|
343
|
+
Home: 3,
|
|
344
|
+
End: 123
|
|
345
|
+
};
|
|
346
|
+
const adb = await this.getAdb();
|
|
347
|
+
const keyCode = keyCodeMap[key];
|
|
348
|
+
if (keyCode !== void 0) {
|
|
349
|
+
await adb.keyevent(keyCode);
|
|
350
|
+
} else {
|
|
351
|
+
if (key.length === 1) {
|
|
352
|
+
const asciiCode = key.toUpperCase().charCodeAt(0);
|
|
353
|
+
if (asciiCode >= 65 && asciiCode <= 90) {
|
|
354
|
+
await adb.keyevent(asciiCode - 36);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
async keyboardPressAction(action) {
|
|
360
|
+
if (Array.isArray(action)) {
|
|
361
|
+
for (const act of action) {
|
|
362
|
+
await this.keyboardPress(act.key);
|
|
363
|
+
}
|
|
364
|
+
} else {
|
|
365
|
+
await this.keyboardPress(action.key);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
async mouseClick(x, y) {
|
|
369
|
+
const adb = await this.getAdb();
|
|
370
|
+
const { x: adjustedX, y: adjustedY } = this.adjustCoordinates(x, y);
|
|
371
|
+
await adb.shell(`input tap ${adjustedX} ${adjustedY}`);
|
|
372
|
+
}
|
|
373
|
+
async mouseMove(x, y) {
|
|
374
|
+
return Promise.resolve();
|
|
375
|
+
}
|
|
376
|
+
async mouseDrag(from, to) {
|
|
377
|
+
const adb = await this.getAdb();
|
|
378
|
+
const { x: fromX, y: fromY } = this.adjustCoordinates(from.x, from.y);
|
|
379
|
+
const { x: toX, y: toY } = this.adjustCoordinates(to.x, to.y);
|
|
380
|
+
await adb.shell(`input swipe ${fromX} ${fromY} ${toX} ${toY} 300`);
|
|
381
|
+
}
|
|
382
|
+
async mouseWheel(deltaX, deltaY, duration = 1e3) {
|
|
383
|
+
const { width, height } = await this.size();
|
|
384
|
+
const n = 4;
|
|
385
|
+
const startX = deltaX < 0 ? (n - 1) * (width / n) : width / n;
|
|
386
|
+
const startY = deltaY < 0 ? (n - 1) * (height / n) : height / n;
|
|
387
|
+
const maxNegativeDeltaX = startX;
|
|
388
|
+
const maxPositiveDeltaX = (n - 1) * (width / n);
|
|
389
|
+
const maxNegativeDeltaY = startY;
|
|
390
|
+
const maxPositiveDeltaY = (n - 1) * (height / n);
|
|
391
|
+
deltaX = Math.max(-maxNegativeDeltaX, Math.min(deltaX, maxPositiveDeltaX));
|
|
392
|
+
deltaY = Math.max(-maxNegativeDeltaY, Math.min(deltaY, maxPositiveDeltaY));
|
|
393
|
+
const endX = startX + deltaX;
|
|
394
|
+
const endY = startY + deltaY;
|
|
395
|
+
const { x: adjustedStartX, y: adjustedStartY } = this.adjustCoordinates(
|
|
396
|
+
startX,
|
|
397
|
+
startY
|
|
398
|
+
);
|
|
399
|
+
const { x: adjustedEndX, y: adjustedEndY } = this.adjustCoordinates(
|
|
400
|
+
endX,
|
|
401
|
+
endY
|
|
402
|
+
);
|
|
403
|
+
const adb = await this.getAdb();
|
|
404
|
+
await adb.shell(
|
|
405
|
+
`input swipe ${adjustedStartX} ${adjustedStartY} ${adjustedEndX} ${adjustedEndY} ${duration}`
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
async destroy() {
|
|
409
|
+
try {
|
|
410
|
+
const adb = await this.getAdb();
|
|
411
|
+
await adb.shell(`rm -f ${androidScreenshotPath}`);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
console.error("Error during cleanup:", error);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
// src/agent/index.ts
|
|
419
|
+
import { PageAgent } from "@midscene/web/agent";
|
|
420
|
+
|
|
421
|
+
// src/utils/index.ts
|
|
422
|
+
import { ADB as ADB2 } from "appium-adb";
|
|
423
|
+
|
|
424
|
+
// src/agent/index.ts
|
|
425
|
+
var AndroidAgent = class extends PageAgent {
|
|
426
|
+
async launch(uri) {
|
|
427
|
+
const device = this.page;
|
|
428
|
+
await device.launch(uri);
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
// src/playground/scrcpy-server.ts
|
|
433
|
+
import { exec } from "child_process";
|
|
434
|
+
import { createReadStream } from "fs";
|
|
435
|
+
import { createServer } from "http";
|
|
436
|
+
import { promisify } from "util";
|
|
437
|
+
import { Adb, AdbServerClient } from "@yume-chan/adb";
|
|
438
|
+
import { AdbScrcpyClient, AdbScrcpyOptions2_1 } from "@yume-chan/adb-scrcpy";
|
|
439
|
+
import { AdbServerNodeTcpConnector } from "@yume-chan/adb-server-node-tcp";
|
|
440
|
+
import { BIN } from "@yume-chan/fetch-scrcpy-server";
|
|
441
|
+
import {
|
|
442
|
+
DefaultServerPath,
|
|
443
|
+
ScrcpyOptions3_1,
|
|
444
|
+
ScrcpyVideoCodecId
|
|
445
|
+
} from "@yume-chan/scrcpy";
|
|
446
|
+
import { ReadableStream } from "@yume-chan/stream-extra";
|
|
447
|
+
import cors from "cors";
|
|
448
|
+
import express from "express";
|
|
449
|
+
import { Server } from "socket.io";
|
|
450
|
+
var promiseExec = promisify(exec);
|
|
451
|
+
var ScrcpyServer = class {
|
|
452
|
+
// 用于保存上次设备列表的JSON字符串,用于比较变化
|
|
453
|
+
constructor() {
|
|
454
|
+
this.defaultPort = 5700;
|
|
455
|
+
this.adbClient = null;
|
|
456
|
+
this.currentDeviceId = null;
|
|
457
|
+
this.devicePollInterval = null;
|
|
458
|
+
this.lastDeviceList = "";
|
|
459
|
+
this.app = express();
|
|
460
|
+
this.httpServer = createServer(this.app);
|
|
461
|
+
this.io = new Server(this.httpServer, {
|
|
462
|
+
cors: {
|
|
463
|
+
origin: [
|
|
464
|
+
/^http:\/\/localhost(:\d+)?$/,
|
|
465
|
+
/^http:\/\/127\.0\.0\.1(:\d+)?$/
|
|
466
|
+
],
|
|
467
|
+
methods: ["GET", "POST"],
|
|
468
|
+
credentials: true
|
|
469
|
+
}
|
|
470
|
+
});
|
|
471
|
+
this.app.use(
|
|
472
|
+
cors({
|
|
473
|
+
origin: "*",
|
|
474
|
+
credentials: true
|
|
475
|
+
})
|
|
476
|
+
);
|
|
477
|
+
this.setupSocketHandlers();
|
|
478
|
+
this.setupApiRoutes();
|
|
479
|
+
}
|
|
480
|
+
// setup API routes
|
|
481
|
+
setupApiRoutes() {
|
|
482
|
+
this.app.get("/api/devices", async (req, res) => {
|
|
483
|
+
try {
|
|
484
|
+
const devices = await this.getDevicesList();
|
|
485
|
+
res.json({ devices, currentDeviceId: this.currentDeviceId });
|
|
486
|
+
} catch (error) {
|
|
487
|
+
res.status(500).json({ error: error.message || "Failed to get devices list" });
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
// get devices list
|
|
492
|
+
async getDevicesList() {
|
|
493
|
+
try {
|
|
494
|
+
debugPage("start to get devices list");
|
|
495
|
+
const client = await this.getAdbClient();
|
|
496
|
+
if (!client) {
|
|
497
|
+
console.warn("failed to get adb client");
|
|
498
|
+
return [];
|
|
499
|
+
}
|
|
500
|
+
debugPage("success to get adb client, start to request devices list");
|
|
501
|
+
let devices;
|
|
502
|
+
try {
|
|
503
|
+
devices = await client.getDevices();
|
|
504
|
+
debugPage("original devices list:", devices);
|
|
505
|
+
} catch (error) {
|
|
506
|
+
console.error("failed to get devices list:", error);
|
|
507
|
+
return [];
|
|
508
|
+
}
|
|
509
|
+
if (!devices || devices.length === 0) {
|
|
510
|
+
return [];
|
|
511
|
+
}
|
|
512
|
+
const formattedDevices = devices.map((device) => {
|
|
513
|
+
const result = {
|
|
514
|
+
id: device.serial,
|
|
515
|
+
name: device.product || device.model || device.serial,
|
|
516
|
+
status: device.state || "device"
|
|
517
|
+
};
|
|
518
|
+
return result;
|
|
519
|
+
});
|
|
520
|
+
return formattedDevices;
|
|
521
|
+
} catch (error) {
|
|
522
|
+
console.error("failed to get devices list:", error);
|
|
523
|
+
return [];
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
// get adb client
|
|
527
|
+
async getAdbClient() {
|
|
528
|
+
try {
|
|
529
|
+
if (!this.adbClient) {
|
|
530
|
+
await promiseExec("adb start-server");
|
|
531
|
+
debugPage("adb server started");
|
|
532
|
+
debugPage("initialize adb client");
|
|
533
|
+
this.adbClient = new AdbServerClient(
|
|
534
|
+
new AdbServerNodeTcpConnector({
|
|
535
|
+
host: "localhost",
|
|
536
|
+
port: 5037
|
|
537
|
+
})
|
|
538
|
+
);
|
|
539
|
+
await debugPage("success to initialize adb client");
|
|
540
|
+
} else {
|
|
541
|
+
debugPage("use existing adb client");
|
|
542
|
+
}
|
|
543
|
+
return this.adbClient;
|
|
544
|
+
} catch (error) {
|
|
545
|
+
console.error("failed to get adb client:", error);
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
// get adb object
|
|
550
|
+
async getAdb(deviceId) {
|
|
551
|
+
try {
|
|
552
|
+
const client = await this.getAdbClient();
|
|
553
|
+
if (!client) {
|
|
554
|
+
return null;
|
|
555
|
+
}
|
|
556
|
+
if (deviceId) {
|
|
557
|
+
this.currentDeviceId = deviceId;
|
|
558
|
+
return new Adb(await client.createTransport({ serial: deviceId }));
|
|
559
|
+
}
|
|
560
|
+
const devices = await client.getDevices();
|
|
561
|
+
if (devices.length === 0) {
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
this.currentDeviceId = devices[0].serial;
|
|
565
|
+
return new Adb(await client.createTransport(devices[0]));
|
|
566
|
+
} catch (error) {
|
|
567
|
+
console.error("failed to get adb client:", error);
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
// start scrcpy
|
|
572
|
+
async startScrcpy(adb, options = {}) {
|
|
573
|
+
try {
|
|
574
|
+
await AdbScrcpyClient.pushServer(
|
|
575
|
+
adb,
|
|
576
|
+
ReadableStream.from(createReadStream(BIN))
|
|
577
|
+
);
|
|
578
|
+
const scrcpyOptions = new ScrcpyOptions3_1({
|
|
579
|
+
// default options
|
|
580
|
+
audio: false,
|
|
581
|
+
control: true,
|
|
582
|
+
maxSize: 1024,
|
|
583
|
+
// use videoBitRate as property name
|
|
584
|
+
videoBitRate: 2e6,
|
|
585
|
+
// override default values with user provided options
|
|
586
|
+
...options
|
|
587
|
+
});
|
|
588
|
+
return await AdbScrcpyClient.start(
|
|
589
|
+
adb,
|
|
590
|
+
DefaultServerPath,
|
|
591
|
+
new AdbScrcpyOptions2_1(scrcpyOptions)
|
|
592
|
+
);
|
|
593
|
+
} catch (error) {
|
|
594
|
+
console.error("failed to start scrcpy:", error);
|
|
595
|
+
throw error;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
// setup Socket.IO connection handlers
|
|
599
|
+
setupSocketHandlers() {
|
|
600
|
+
this.io.on("connection", async (socket) => {
|
|
601
|
+
debugPage(
|
|
602
|
+
"client connected, id: %s, client address: %s",
|
|
603
|
+
socket.id,
|
|
604
|
+
socket.handshake.address
|
|
605
|
+
);
|
|
606
|
+
let scrcpyClient = null;
|
|
607
|
+
let adb = null;
|
|
608
|
+
const sendDevicesList = async () => {
|
|
609
|
+
try {
|
|
610
|
+
debugPage("Socket request to get devices list");
|
|
611
|
+
const devices = await this.getDevicesList();
|
|
612
|
+
debugPage("send devices list to client:", devices);
|
|
613
|
+
socket.emit("devices-list", {
|
|
614
|
+
devices,
|
|
615
|
+
currentDeviceId: this.currentDeviceId
|
|
616
|
+
});
|
|
617
|
+
} catch (error) {
|
|
618
|
+
console.error("failed to send devices list:", error);
|
|
619
|
+
socket.emit("error", { message: "failed to get devices list" });
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
await sendDevicesList();
|
|
623
|
+
socket.on("get-devices", async () => {
|
|
624
|
+
debugPage("received client request to get devices list");
|
|
625
|
+
await sendDevicesList();
|
|
626
|
+
});
|
|
627
|
+
socket.on("switch-device", async (deviceId) => {
|
|
628
|
+
debugPage("received client request to switch device:", deviceId);
|
|
629
|
+
try {
|
|
630
|
+
if (scrcpyClient) {
|
|
631
|
+
await scrcpyClient.close();
|
|
632
|
+
scrcpyClient = null;
|
|
633
|
+
}
|
|
634
|
+
this.currentDeviceId = deviceId;
|
|
635
|
+
debugPage("device switched to:", deviceId);
|
|
636
|
+
socket.emit("device-switched", { deviceId });
|
|
637
|
+
this.io.emit("global-device-switched", {
|
|
638
|
+
deviceId,
|
|
639
|
+
timestamp: Date.now()
|
|
640
|
+
});
|
|
641
|
+
} catch (error) {
|
|
642
|
+
console.error("failed to switch device:", error);
|
|
643
|
+
socket.emit("error", {
|
|
644
|
+
message: `Failed to switch device: ${error?.message || "Unknown error"}`
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
});
|
|
648
|
+
socket.on("connect-device", async (options) => {
|
|
649
|
+
try {
|
|
650
|
+
debugPage(
|
|
651
|
+
"received device connection request, options: %s, client id: %s",
|
|
652
|
+
options,
|
|
653
|
+
socket.id
|
|
654
|
+
);
|
|
655
|
+
adb = await this.getAdb(this.currentDeviceId || void 0);
|
|
656
|
+
if (!adb) {
|
|
657
|
+
console.error("no available device found");
|
|
658
|
+
socket.emit("error", { message: "No device found" });
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
debugPage(
|
|
662
|
+
"starting scrcpy service, device id: %s",
|
|
663
|
+
this.currentDeviceId
|
|
664
|
+
);
|
|
665
|
+
scrcpyClient = await this.startScrcpy(adb, options);
|
|
666
|
+
debugPage("scrcpy service started successfully");
|
|
667
|
+
debugPage(
|
|
668
|
+
"check scrcpyClient object structure: %s",
|
|
669
|
+
Object.getOwnPropertyNames(scrcpyClient).map((name) => {
|
|
670
|
+
const type = typeof scrcpyClient[name];
|
|
671
|
+
const isPromise = type === "object" && scrcpyClient[name] && typeof scrcpyClient[name].then === "function";
|
|
672
|
+
return `${name}: ${type}${isPromise ? " (Promise)" : ""}`;
|
|
673
|
+
})
|
|
674
|
+
);
|
|
675
|
+
try {
|
|
676
|
+
if (scrcpyClient.videoStream) {
|
|
677
|
+
debugPage(
|
|
678
|
+
"videoStream exists, type: %s",
|
|
679
|
+
typeof scrcpyClient.videoStream
|
|
680
|
+
);
|
|
681
|
+
let videoStream;
|
|
682
|
+
if (typeof scrcpyClient.videoStream === "object" && typeof scrcpyClient.videoStream.then === "function") {
|
|
683
|
+
debugPage(
|
|
684
|
+
"videoStream is a Promise, waiting for resolution..."
|
|
685
|
+
);
|
|
686
|
+
videoStream = await scrcpyClient.videoStream;
|
|
687
|
+
} else {
|
|
688
|
+
debugPage("videoStream is not a Promise, directly use");
|
|
689
|
+
videoStream = scrcpyClient.videoStream;
|
|
690
|
+
}
|
|
691
|
+
debugPage(
|
|
692
|
+
"video stream fetched successfully, metadata: %s",
|
|
693
|
+
videoStream.metadata
|
|
694
|
+
);
|
|
695
|
+
const metadata = videoStream.metadata || {};
|
|
696
|
+
debugPage("original metadata: %s", metadata);
|
|
697
|
+
if (!metadata.codec) {
|
|
698
|
+
debugPage(
|
|
699
|
+
"metadata does not have codec field, use H264 by default"
|
|
700
|
+
);
|
|
701
|
+
metadata.codec = ScrcpyVideoCodecId.H264;
|
|
702
|
+
}
|
|
703
|
+
if (!metadata.width || !metadata.height) {
|
|
704
|
+
debugPage(
|
|
705
|
+
"metadata does not have width or height field, use default values"
|
|
706
|
+
);
|
|
707
|
+
metadata.width = metadata.width || 1080;
|
|
708
|
+
metadata.height = metadata.height || 1920;
|
|
709
|
+
}
|
|
710
|
+
debugPage(
|
|
711
|
+
"prepare to send video-metadata event to client, data: %s",
|
|
712
|
+
JSON.stringify(metadata)
|
|
713
|
+
);
|
|
714
|
+
socket.emit("video-metadata", metadata);
|
|
715
|
+
debugPage(
|
|
716
|
+
"video-metadata event sent to client, id: %s",
|
|
717
|
+
socket.id
|
|
718
|
+
);
|
|
719
|
+
const { stream } = videoStream;
|
|
720
|
+
const reader = stream.getReader();
|
|
721
|
+
const processStream = async () => {
|
|
722
|
+
try {
|
|
723
|
+
while (true) {
|
|
724
|
+
const { done, value } = await reader.read();
|
|
725
|
+
if (done)
|
|
726
|
+
break;
|
|
727
|
+
const frameType = value.type || "data";
|
|
728
|
+
socket.emit("video-data", {
|
|
729
|
+
data: Array.from(value.data),
|
|
730
|
+
type: frameType,
|
|
731
|
+
timestamp: Date.now(),
|
|
732
|
+
// fix keyframe access
|
|
733
|
+
keyFrame: value.keyFrame
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
} catch (error) {
|
|
737
|
+
console.error("error processing video stream:", error);
|
|
738
|
+
socket.emit("error", {
|
|
739
|
+
message: "video stream processing error"
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
processStream();
|
|
744
|
+
} else {
|
|
745
|
+
console.error(
|
|
746
|
+
"scrcpyClient object does not have videoStream property"
|
|
747
|
+
);
|
|
748
|
+
socket.emit("error", {
|
|
749
|
+
message: "Video stream not available in scrcpy client"
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
} catch (error) {
|
|
753
|
+
console.error("error processing video stream:", error);
|
|
754
|
+
socket.emit("error", {
|
|
755
|
+
message: `Video stream processing error: ${error.message}`
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
if (scrcpyClient?.controller) {
|
|
759
|
+
socket.emit("control-ready");
|
|
760
|
+
}
|
|
761
|
+
} catch (error) {
|
|
762
|
+
console.error("failed to connect device:", error);
|
|
763
|
+
socket.emit("error", {
|
|
764
|
+
message: `Failed to connect device: ${error?.message || "Unknown error"}`
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
socket.on("disconnect", async (reason) => {
|
|
769
|
+
debugPage("client disconnected, id: %s, reason: %s", socket.id, reason);
|
|
770
|
+
if (scrcpyClient) {
|
|
771
|
+
try {
|
|
772
|
+
debugPage("closing scrcpy client");
|
|
773
|
+
await scrcpyClient.close();
|
|
774
|
+
} catch (error) {
|
|
775
|
+
console.error("failed to close scrcpy client:", error);
|
|
776
|
+
}
|
|
777
|
+
scrcpyClient = null;
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
// launch server
|
|
783
|
+
async launch(port) {
|
|
784
|
+
this.port = port || this.defaultPort;
|
|
785
|
+
return new Promise((resolve) => {
|
|
786
|
+
this.httpServer.listen(this.port, () => {
|
|
787
|
+
console.log(`Scrcpy server running at: http://localhost:${this.port}`);
|
|
788
|
+
this.startDeviceMonitoring();
|
|
789
|
+
resolve(this);
|
|
790
|
+
});
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
// start device monitoring
|
|
794
|
+
startDeviceMonitoring() {
|
|
795
|
+
this.devicePollInterval = setInterval(async () => {
|
|
796
|
+
try {
|
|
797
|
+
const devices = await this.getDevicesList();
|
|
798
|
+
const currentDevicesJson = JSON.stringify(devices);
|
|
799
|
+
if (this.lastDeviceList !== currentDevicesJson) {
|
|
800
|
+
debugPage("devices list changed, push to all connected clients");
|
|
801
|
+
this.lastDeviceList = currentDevicesJson;
|
|
802
|
+
if (!this.currentDeviceId && devices.length > 0) {
|
|
803
|
+
const onlineDevices = devices.filter(
|
|
804
|
+
(device) => device.status.toLowerCase() === "device"
|
|
805
|
+
);
|
|
806
|
+
if (onlineDevices.length > 0) {
|
|
807
|
+
this.currentDeviceId = onlineDevices[0].id;
|
|
808
|
+
debugPage(
|
|
809
|
+
"auto select the first online device:",
|
|
810
|
+
this.currentDeviceId
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
this.io.emit("devices-list", {
|
|
815
|
+
devices,
|
|
816
|
+
currentDeviceId: this.currentDeviceId
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
} catch (error) {
|
|
820
|
+
console.error("device monitoring error:", error);
|
|
821
|
+
}
|
|
822
|
+
}, 3e3);
|
|
823
|
+
}
|
|
824
|
+
// close server
|
|
825
|
+
close() {
|
|
826
|
+
if (this.devicePollInterval) {
|
|
827
|
+
clearInterval(this.devicePollInterval);
|
|
828
|
+
this.devicePollInterval = null;
|
|
829
|
+
}
|
|
830
|
+
if (this.httpServer) {
|
|
831
|
+
return this.httpServer.close();
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
|
|
836
|
+
// src/playground/bin.ts
|
|
837
|
+
var staticDir = path2.join(__dirname, "../../static");
|
|
838
|
+
var playgroundServer = new PlaygroundServer(
|
|
839
|
+
AndroidDevice,
|
|
840
|
+
AndroidAgent,
|
|
841
|
+
staticDir
|
|
842
|
+
);
|
|
843
|
+
var scrcpyServer = new ScrcpyServer();
|
|
844
|
+
Promise.all([playgroundServer.launch(5800), scrcpyServer.launch(5700)]).then(() => {
|
|
845
|
+
console.log(
|
|
846
|
+
`Midscene playground server is running on http://localhost:${playgroundServer.port}`
|
|
847
|
+
);
|
|
848
|
+
open(`http://localhost:${playgroundServer.port}`);
|
|
849
|
+
}).catch((error) => {
|
|
850
|
+
console.error("Failed to start servers:", error);
|
|
851
|
+
process.exit(1);
|
|
852
|
+
});
|