This repository has been archived by the owner on Nov 16, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
android-hybrid.js
284 lines (256 loc) · 10.1 KB
/
android-hybrid.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
"use strict";
var logger = require('../../server/logger.js').get('appium')
, _ = require('underscore')
, errors = require('../../server/errors.js')
, UnknownError = errors.UnknownError
, async = require('async')
, Chromedriver = require('appium-chromedriver')
, status = require("../../server/status.js");
var androidHybrid = {};
androidHybrid.chromedriver = null;
androidHybrid.sessionChromedrivers = {};
androidHybrid.listWebviews = function (cb) {
logger.debug("Getting a list of available webviews");
var webviews = [];
var definedDeviceSocket = this.args.androidDeviceSocket;
this.adb.shell("cat /proc/net/unix", function (err, out) {
if (err) return cb(err);
_.each(out.split("\n"), function (line) {
line = line.trim();
var webviewPid = line.match(/@?_devtools_remote_/);
if (definedDeviceSocket) {
if (line.indexOf("@" + definedDeviceSocket) ===
line.length - definedDeviceSocket.length - 1) {
if (webviewPid) {
webviews.push(this.WEBVIEW_BASE + webviewPid[1]);
} else {
webviews.push(this.CHROMIUM_WIN);
}
}
} else if (webviewPid) {
// for multiple webviews a list of 'WEBVIEW_<index>' will be returned
// where <index> is zero based (same is in selendroid)
//webviews.push(this.WEBVIEW_BASE + webviewPid[1]);
webviews.push(this.WEBVIEW_BASE + this.args.appPackage + "_devtools_remote");
}
}.bind(this));
webviews = _.uniq(webviews);
if (definedDeviceSocket) {
return cb(null, webviews);
}
var webviewsTmp = webviews;
webviews = [];
var getProcessNameFromWebview = function (view, cb) {
//this.getProcessNameFromWebview(view, function (err, pkg) {
// if (err) return cb(err);
// webviews.push(this.WEBVIEW_BASE + pkg);
// cb();
//}.bind(this));
webviews.push(this.WEBVIEW_BASE + this.args.appPackage);
cb(null, webviews);
}.bind(this);
async.each(webviewsTmp, getProcessNameFromWebview, function (err) {
if (err) return cb(err);
logger.debug("Available contexts: " + this.contexts);
//logger.debug(JSON.stringify(webviews));
cb(null, webviews);
}.bind(this));
}.bind(this));
};
var previousState = {};
// remember whether we were previously proxying to a chromedriver or not
androidHybrid.rememberProxyState = function () {
previousState.isProxy = this.isProxy;
};
androidHybrid.restoreProxyState = function () {
this.isProxy = previousState.isProxy;
};
androidHybrid.getProcessNameFromWebview = function (webview, cb) {
// webview_devtools_remote_4296 => 4296
var pid = webview.match(/\d+$/);
if (!pid) return cb("No pid for webview " + webview);
pid = pid[0];
logger.debug(webview + " mapped to pid " + pid);
logger.debug("Getting process name for webview");
this.adb.shell("ps", function (err, out) {
if (err) return cb(err);
var pkg = "unknown";
var lines = out.split(/\r?\n/);
/*
USER PID PPID VSIZE RSS WCHAN PC NAME
u0_a136 6248 179 946000 48144 ffffffff 4005903e R com.example.test
*/
var header = lines[0].trim().split(/\s+/);
// the column order may not be identical on all androids
// dynamically locate the pid and name column.
var pidColumn = header.indexOf("PID");
var pkgColumn = header.indexOf("NAME") + 1;
_.find(lines, function (line) {
line = line.trim().split(/\s+/);
if (line[pidColumn].indexOf(pid) !== -1) {
logger.debug("Parsed pid: " + line[pidColumn] + " pkg: " + line[pkgColumn]);
logger.debug("from: " + line);
pkgColumn = line.length - 1;
pkg = line[pkgColumn];
return pkg; // exit from _.find
}
});
logger.debug("returning process name: " + pkg);
cb(null, pkg);
});
};
androidHybrid.startChromedriverProxy = function (context, cb) {
cb = _.once(cb);
logger.debug("Connecting to chrome-backed webview");
if (this.chromedriver !== null) {
return cb(new Error("We already have a chromedriver instance running"));
}
if (this.sessionChromedrivers[context]) {
// in the case where we've already set up a chromedriver for a context,
// we want to reconnect to it, not create a whole new one
this.setupExistingChromedriver(context, cb);
} else {
this.setupNewChromedriver(context, cb);
}
};
androidHybrid.setupNewChromedriver = function (context, cb) {
var chromeArgs = {
port: this.args.chromeDriverPort,
executable: this.args.chromedriverExecutable
};
this.chromedriver = new Chromedriver(chromeArgs);
this.proxyReqRes = this.chromedriver.proxyReq.bind(this.chromedriver);
this.rememberProxyState();
this.isProxy = true;
var caps = {
chromeOptions: {
androidPackage: this.args.appPackage,
androidUseRunningApp: true
}
//,
//xwalkOptions: {
// androidPackage: this.args.appPackage,
// androidUseRunningApp: true
//}
};
if (this.args.enablePerformanceLogging) {
caps.loggingPrefs = {performance: 'ALL'};
}
// For now the only known arg passed this way is androidDeviceSocket used
// by Operadriver (deriving from Chromedriver) // We don't know how other
// Chromium embedders will call this argument so for now it's name needs to
// be configurable. When Google adds the androidDeviceSocket argument to
// the original Chromedriver then we will be sure about its name for all
// Chromium embedders (as their Webdrivers will derive from Chromedriver)
if (this.args.specialChromedriverSessionArgs) {
_.each(this.args.specialChromedriverSessionArgs, function (val, option) {
logger.debug("This method is being deprecated. Apply chromeOptions " +
"normally to pass along options,see sites.google.com/a/" +
"chromium.org/chromedriver/capabilities for more info");
caps.chromeOptions[option] = val;
});
}
caps = this.decorateChromeOptions(caps);
this.chromedriver.on(Chromedriver.EVENT_CHANGED, function (msg) {
if (msg.state === Chromedriver.STATE_STOPPED) {
// bind our stop/exit handler, passing in context so we know which
// one stopped unexpectedly
this.onChromedriverStop(context);
}
}.bind(this));
this.chromedriver.start(caps).then(function () {
// save the chromedriver object under the context
this.sessionChromedrivers[context] = this.chromedriver;
cb();
}.bind(this), cb);
};
androidHybrid.setupExistingChromedriver = function (context, cb) {
logger.debug("Found existing Chromedriver for context '" + context + "'." +
" Using it.");
this.rememberProxyState();
this.chromedriver = this.sessionChromedrivers[context];
this.proxyReqRes = this.chromedriver.proxyReq.bind(this.chromedriver);
this.isProxy = true;
// check the status by sending a simple window-based command to ChromeDriver
// if there is an error, we want to recreate the ChromeDriver session
this.chromedriver.hasWorkingWebview().then(function (works) {
if (works) return cb();
logger.debug("ChromeDriver is not associated with a window. " +
"Re-initializing the session.");
this.chromedriverRestartingContext = context;
this.chromedriver.restart().then(function () {
this.chromedriverRestartingContext = null;
cb();
}.bind(this), cb);
}.bind(this), cb);
};
androidHybrid.onChromedriverStop = function (context) {
logger.warn("Chromedriver for context " + context + " stopped unexpectedly");
if (context === this.curContext) {
// if we don't have a stop callback, we exited unexpectedly and so want
// to shut down the session and respond with an error
// TODO: this kind of thing should be emitted and handled by a higher-level
// controlling function
var error = new UnknownError("Chromedriver quit unexpectedly during session");
logger.error(error.message);
if (typeof this.cbForCurrentCmd === "function") {
this.shutdown(function () {
this.cbForCurrentCmd(error, null);
}.bind(this));
}
} else if (context !== this.chromedriverRestartingContext) {
// if a Chromedriver in the non-active context barfs, we don't really
// care, we'll just make a new one next time we need the context.
// The only time we ignore this is if we know we're in the middle of a
// Chromedriver restart
logger.warn("Chromedriver quit unexpectedly, but it wasn't the active " +
"context, ignoring");
delete this.sessionChromedrivers[context];
}
};
androidHybrid.suspendChromedriverProxy = function (cb) {
this.chromedriver = null;
this.restoreProxyState();
cb();
};
androidHybrid.stopChromedriverProxies = function (ocb) {
async.eachSeries(Object.keys(this.sessionChromedrivers), function (context, cb) {
logger.debug("Stopping chromedriver for context " + context);
// stop listening for the stopped state event
this.sessionChromedrivers[context].removeAllListeners(Chromedriver.EVENT_CHANGED);
var onStop = function (err) {
if (err) logger.warn("Error stopping Chromedriver: " + err.message);
// chromedriver isn't valid anymore, so remove it from context list
delete this.sessionChromedrivers[context];
cb();
}.bind(this);
this.sessionChromedrivers[context].stop().then(function () {
onStop();
}, onStop);
}.bind(this), function (err) {
// if one of these fails, go back to last proxy state and error out
this.restoreProxyState();
ocb(err);
}.bind(this));
};
androidHybrid.defaultWebviewName = function () {
return this.WEBVIEW_BASE + this.appProcess;
};
androidHybrid.initAutoWebview = function (cb) {
if (this.args.autoWebview) {
logger.debug('Setting auto webview');
var viewName = this.defaultWebviewName();
var timeout = (this.args.autoWebviewTimeout) || 2000;
this.setContext(viewName, function (err, res) {
if (err && res.status !== status.codes.NoSuchContext.code) return cb(err);
if (res.status === status.codes.Success.code) return cb();
setTimeout(function () {
logger.debug("Retrying context switch with timeout '" + timeout + "'");
this.setContext(viewName, cb);
}.bind(this), timeout);
}.bind(this));
} else {
cb();
}
};
module.exports = androidHybrid;