-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdriver.js
538 lines (472 loc) · 15.9 KB
/
driver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import {BaseDriver, errors} from 'appium/driver';
import B from 'bluebird';
import _ from 'lodash';
import {
closeApp,
extendDevMode,
getDeviceInfo,
installApp,
launchApp,
uninstallApp,
} from './cli/ares';
import {CAP_CONSTRAINTS, DEFAULT_CAPS} from './constraints';
import {AsyncScripts, SyncScripts} from './scripts';
// @ts-ignore
import Chromedriver from 'appium-chromedriver';
import getPort from 'get-port';
import got from 'got';
import {KEYMAP} from './keys';
import log from './logger';
import {LGRemoteKeys} from './remote/lg-remote-client';
import {LGWSClient} from './remote/lg-socket-client';
// eslint-disable-next-line import/no-unresolved
import {ValueBox} from './remote/valuebox';
export {KEYS} from './keys';
// this is the ID for the 'Developer' application, which we launch after a session ends to ensure
// some app stays running (otherwise the TV might shut off)
const DEV_MODE_ID = 'com.palmdts.devmode';
/**
* A security flag to enable chromedriver auto download feature
*/
const CHROMEDRIVER_AUTODOWNLOAD_FEATURE = 'chromedriver_autodownload';
/**
* To get chrome driver version in the UA
*/
const REGEXP_CHROME_VERSION_IN_UA = new RegExp('Chrome\\/(\\S+)');
// don't proxy any 'appium' routes
/** @type {RouteMatcher[]} */
const NO_PROXY = [
['POST', new RegExp('^/session/[^/]+/appium')],
['GET', new RegExp('^/session/[^/]+/appium')],
['POST', new RegExp('^/session/[^/]+/execute/sync')],
];
export const DEFAULT_PRESS_DURATION_MS = 100;
/**
* @extends {BaseDriver<WebOsConstraints>}
*/
export class WebOSDriver extends BaseDriver {
/** @type {RouteMatcher[]} */
jwpProxyAvoid = _.clone(NO_PROXY); // why clone?
/** @type {boolean} */
jwpProxyActive = false;
/** @type {LGWSClient|undefined} */
socketClient;
/** @type {import('./remote/lg-remote-client').LGRemoteClient|undefined} */
remoteClient;
desiredCapConstraints = CAP_CONSTRAINTS;
/** @type {Chromedriver|undefined} */
#chromedriver;
static executeMethodMap = {
'webos: pressKey': Object.freeze({
command: 'pressKey',
params: {required: ['key'], optional: ['duration']},
}),
'webos: listApps': Object.freeze({
command: 'listApps'
}),
'webos: activeAppInfo': Object.freeze({
command: 'getCurrentForegroundAppInfo'
}),
};
/**
*
* @param {any} name
* @returns {name is ScriptId}
*/
static isExecuteScript(name) {
return name in WebOSDriver.executeMethodMap;
}
/**
* @param {W3CWebOsCaps} w3cCaps1
* @param {W3CWebOsCaps} w3cCaps2
* @param {W3CWebOsCaps} w3cCaps3
* @returns {Promise<[string,WebOsCaps]>}
*/
async createSession(w3cCaps1, w3cCaps2, w3cCaps3) {
w3cCaps3.alwaysMatch = {...DEFAULT_CAPS, ...w3cCaps3.alwaysMatch};
let [sessionId, caps] = await super.createSession(w3cCaps1, w3cCaps2, w3cCaps3);
const {
autoExtendDevMode,
deviceName,
app,
appId,
appLaunchParams,
noReset,
fullReset,
deviceHost,
debuggerPort,
chromedriverExecutable,
chromedriverExecutableDir,
appLaunchCooldown,
remoteOnly,
websocketPort,
websocketPortSecure,
useSecureWebsocket,
keyCooldown,
} = caps;
if (noReset && fullReset) {
throw new Error(`Cannot use both noReset and fullReset`);
}
if (autoExtendDevMode) {
await extendDevMode(deviceName);
}
try {
caps.deviceInfo = await getDeviceInfo(deviceName);
} catch (error) {
throw new Error(
`Could not retrieve device info for device with ` +
`name '${deviceName}'. Are you sure the device is ` +
`connected? (Original error: ${error})`
);
}
if (fullReset) {
try {
await uninstallApp(appId, deviceName);
} catch (err) {
// if the app is not installed, we expect the following error message, so if we get any
// message other than that one, bubble the error up. Otherwise, just ignore!
if (!/FAILED_REMOVE/.test(/** @type {Error} */ (err).message)) {
throw err;
}
}
}
if (app) {
await installApp(app, appId, deviceName);
}
this.valueBox = ValueBox.create('appium-lg-webos-driver');
this.socketClient = new LGWSClient({
valueBox: this.valueBox,
deviceName,
url: `ws://${deviceHost}:${websocketPort}`,
urlSecure: `wss://${deviceHost}:${websocketPortSecure}`,
useSecureWebsocket,
remoteKeyCooldown: keyCooldown,
});
log.info(`Connecting remote; address any prompts on screen now!`);
await this.socketClient.initialize();
this.remoteClient = await this.socketClient.getRemoteClient();
await launchApp(appId, deviceName, appLaunchParams);
const waitMsgInterval = setInterval(() => {
log.info('Waiting for app launch to take effect');
}, 1000);
await B.delay(appLaunchCooldown);
clearInterval(waitMsgInterval);
if (remoteOnly) {
log.info(`Remote-only mode requested, not starting chromedriver`);
// in remote-only mode, we force rcMode to 'rc' instead of 'js'
this.opts.rcMode = caps.rcMode = 'rc';
return [sessionId, caps];
}
await this.startChromedriver({
debuggerHost: deviceHost,
debuggerPort,
executable: /** @type {string} */ (chromedriverExecutable),
executableDir: /** @type {string} */ (chromedriverExecutableDir),
isAutodownloadEnabled: /** @type {Boolean} */ (this.#isChromedriverAutodownloadEnabled()),
});
log.info('Waiting for app launch to take effect');
await B.delay(appLaunchCooldown);
if (!noReset) {
log.info('Clearing app local storage & reloading');
await this.executeChromedriverScript(SyncScripts.reset);
}
return [sessionId, caps];
}
/**
* Use UserAgent info for "Browser" if the chrome response did not include
* browser name properly.
* @param {object} browserVersionInfo
*/
useUAForBrowserIfNotPresent(browserVersionInfo) {
if (!_.isEmpty(browserVersionInfo.Browser)) {
return browserVersionInfo;
}
const ua = browserVersionInfo['User-Agent'];
if (_.isEmpty(ua)) {
return browserVersionInfo;
}
const chromeVersion = ua.match(REGEXP_CHROME_VERSION_IN_UA);
if (_.isEmpty(chromeVersion)) {
return browserVersionInfo;
}
log.info(`The response did not have Browser, thus set the Browser value from UA as ${JSON.stringify(browserVersionInfo)}`);
browserVersionInfo.Browser = chromeVersion[0];
return browserVersionInfo;
}
/**
* Returns whether the session can enable autodownloadd feature.
* @returns {boolean}
*/
#isChromedriverAutodownloadEnabled() {
if (this.isFeatureEnabled(CHROMEDRIVER_AUTODOWNLOAD_FEATURE)) {
return true;
}
this.log.debug(
`Automated Chromedriver download is disabled. ` +
`Use '${CHROMEDRIVER_AUTODOWNLOAD_FEATURE}' server feature to enable it`,
);
return false;
}
/**
* @param {StartChromedriverOptions} opts
*/
async startChromedriver({debuggerHost, debuggerPort, executable, executableDir, isAutodownloadEnabled}) {
const debuggerAddress = `${debuggerHost}:${debuggerPort}`;
let result;
if (executableDir) {
// get the result of chrome info to use auto detection.
try {
result = await got.get(`http://${debuggerAddress}/json/version`).json();
log.info(`The response of http://${debuggerAddress}/json/version was ${JSON.stringify(result)}`);
result = this.useUAForBrowserIfNotPresent(result);
// To respect the executableDir.
executable = undefined;
} catch (err) {
throw new errors.SessionNotCreatedError(
`Could not get the chrome browser information to detect proper chromedriver version. Is it a debiggable build? Error: ${err.message}`
);
}
}
this.#chromedriver = new Chromedriver({
// @ts-ignore bad types
port: await getPort(),
executable,
executableDir,
isAutodownloadEnabled,
// @ts-ignore
details: {info: result}
});
// XXX: goog:chromeOptions in newer versions, chromeOptions in older
await this.#chromedriver.start({
chromeOptions: {
debuggerAddress,
},
});
this.proxyReqRes = this.#chromedriver.proxyReq.bind(this.#chromedriver);
this.jwpProxyActive = true;
}
/**
* Execute some arbitrary JS via Chromedriver.
* @template [TReturn=any]
* @template [TArg=any]
* @param {((...args: any[]) => TReturn)|string} script
* @param {TArg[]} [args]
* @returns {Promise<{value: TReturn}>}
*/
async executeChromedriverScript(script, args = []) {
return await this.#executeChromedriverScript('/execute/sync', script, args);
}
/**
* Given a script of {@linkcode ScriptId} or some arbitrary JS, figure out
* which it is and run it.
*
* @template [TArg=any]
* @template [TReturn=unknown]
* @template {import('type-fest').LiteralUnion<ScriptId, string>} [S=string]
* @param {S} script
* @param {S extends ScriptId ? [Record<string,any>] : TArg[]} args
* @returns {Promise<S extends ScriptId ? import('type-fest').AsyncReturnType<ExecuteMethod<S>> : {value: TReturn}>}
*/
async execute(script, args) {
if (WebOSDriver.isExecuteScript(script)) {
log.debug(`Calling script "${script}" with arg ${JSON.stringify(args[0])}`);
const methodArgs = /** @type {[Record<string,any>]} */ (args);
return await this.executeMethod(script, [methodArgs[0]]);
}
return await /** @type {Promise<S extends ScriptId ? import('type-fest').AsyncReturnType<ExecuteMethod<S>> : {value: TReturn}>} */ (
this.executeChromedriverScript(script, /** @type {TArg[]} */ (args))
);
}
/**
*
* @param {string} sessionId
* @param {import('@appium/types').DriverData[]} [driverData]
*/
async deleteSession(sessionId, driverData) {
// TODO decide if we want to extend at the end of the session too
//if (this.opts.autoExtendDevMode) {
//await extendDevMode(this.opts.deviceName);
//}
if (this.#chromedriver) {
log.debug(`Stopping chromedriver`);
// stop listening for the stopped state event
// @ts-ignore
this.#chromedriver.removeAllListeners(Chromedriver.EVENT_CHANGED);
try {
await this.#chromedriver.stop();
} catch (err) {
log.warn(`Error stopping Chromedriver: ${/** @type {Error} */ (err).message}`);
}
this.#chromedriver = undefined;
}
try {
await closeApp(this.opts.appId, this.opts.deviceName);
} catch (err) {
log.warn(`Error in closing ${this.opts.appId}: ${/** @type {Error} */ (err).message}`);
}
if (this.remoteClient) {
log.info(`Pressing HOME and launching dev app to prevent auto off`);
await this.remoteClient.pressKey(LGRemoteKeys.HOME);
await launchApp(DEV_MODE_ID, this.opts.deviceName);
}
if (this.socketClient) {
log.debug(`Stopping socket clients`);
try {
await this.socketClient.disconnect();
} catch (err) {
log.warn(`Error stopping socket clients: ${err}`);
}
this.socketClient = undefined;
this.remoteClient = undefined;
}
await super.deleteSession(sessionId, driverData);
}
proxyActive() {
return this.jwpProxyActive;
}
getProxyAvoidList() {
return this.jwpProxyAvoid;
}
canProxy() {
return true;
}
/**
* Execute some arbitrary JS via Chromedriver.
* @template [TReturn=unknown]
* @template [TArg=any]
* @param {string} endpointPath - Relative path of the endpoint URL
* @param {((...args: any[]) => TReturn)|string} script
* @param {TArg[]} [args]
* @returns {Promise<{value: TReturn}>}
*/
async #executeChromedriverScript(endpointPath, script, args = []) {
const wrappedScript =
typeof script === 'string' ? script : `return (${script}).apply(null, arguments)`;
// @ts-ignore
return await this.#chromedriver.sendCommand(endpointPath, 'POST', {
script: wrappedScript,
args,
});
}
/**
* Automates a keypress
* @param {import('./keys').KnownKey} key
* @param {number} [duration]
*/
async pressKey(key, duration) {
if (this.opts.rcMode === 'js') {
return await this.#pressKeyViaJs(key, duration);
} else {
if (duration) {
this.log.warn(
`Attempted to send a duration for a remote-based ` + `key press; duration will be ignored`
);
}
return await this.pressKeyViaRemote(key);
}
}
/**
* Automates a press of a button on a remote control.
* @param {string} key
*/
async pressKeyViaRemote(key) {
const sc = /** @type {import('./remote/lg-socket-client').LGWSClient} */ (this.socketClient);
const rc = /** @type {import('./remote/lg-remote-client').LGRemoteClient} */ (
this.remoteClient
);
const keyMap = Object.freeze(
/** @type {const} */ ({
VOL_UP: sc.volumeUp,
VOL_DOWN: sc.volumeDown,
MUTE: sc.mute,
UNMUTE: sc.unmute,
PLAY: sc.play,
STOP: sc.stop,
REWIND: sc.rewind,
FF: sc.fastForward,
CHAN_UP: sc.channelUp,
CHAN_DOWN: sc.channelDown,
})
);
/**
*
* @param {any} key
* @returns {key is keyof typeof keyMap}
*/
const isMappedKey = (key) => key in keyMap;
const knownKeys = [...Object.keys(keyMap), ...Object.keys(LGRemoteKeys)];
if (!knownKeys.includes(_.upperCase(key))) {
this.log.warn(`Unknown key '${key}'; will send to remote as-is`);
return await rc.pressKey(key);
}
key = _.upperCase(key);
if (isMappedKey(key)) {
this.log.info(`Found virtual 'key' to be sent as socket command`);
return await keyMap[key].call(sc);
}
return await rc.pressKey(key);
}
/**
* Press key via Chromedriver.
* @param {import('./keys').KnownKey} key
* @param {number} [duration]
*/
async #pressKeyViaJs(key, duration = DEFAULT_PRESS_DURATION_MS) {
key = /** @type {typeof key} */ (key.toLowerCase());
const [keyCode, keyName] = KEYMAP[key];
if (!keyCode) {
throw new errors.InvalidArgumentError(`Key name '${key}' is not supported`);
}
await this.#executeChromedriverScript('/execute/sync', AsyncScripts.pressKey, [
keyCode,
keyName,
duration,
]);
}
/**
*
* @returns {Promise<[object]>} Return the list of installed applications
*/
async listApps() {
const sc = /** @type {import('./remote/lg-socket-client').LGWSClient} */ (this.socketClient);
if (sc) {
return (await sc.getListApps()).apps;
};
throw new errors.UnknownError('Socket connection to the device might be missed');
}
/**
*
* @returns {Promise<object>} Return current active application information.
*/
async getCurrentForegroundAppInfo() {
const sc = /** @type {import('./remote/lg-socket-client').LGWSClient} */ (this.socketClient);
if (sc) {
// {"returnValue"=>true, "appId"=>"com.your.app", "processId"=>"", "windowId"=>""}
return await sc.getForegroundAppInfo();
};
throw new errors.UnknownError('Socket connection to the device might be missed');
}
}
/**
* @typedef {import('./types').ExtraWebOsCaps} WebOSCapabilities
* @typedef {import('./constraints').WebOsConstraints} WebOsConstraints
* @typedef {import('./keys').KnownKey} Key
* @typedef {import('./types').StartChromedriverOptions} StartChromedriverOptions
*/
/**
* @typedef {import('@appium/types').DriverCaps<WebOsConstraints, WebOSCapabilities>} WebOsCaps
* @typedef {import('@appium/types').W3CDriverCaps<WebOsConstraints, WebOSCapabilities>} W3CWebOsCaps
* @typedef {import('@appium/types').RouteMatcher} RouteMatcher
*/
/**
* @typedef {typeof WebOSDriver.executeMethodMap} WebOSDriverExecuteMethodMap
*/
/**
* A known script identifier (e.g., `tizen: pressKey`)
* @typedef {keyof WebOSDriverExecuteMethodMap} ScriptId
*/
/**
* Lookup a method by its script ID.
* @template {ScriptId} S
* @typedef {WebOSDriver[WebOSDriverExecuteMethodMap[S]['command']]} ExecuteMethod
*/