This repository has been archived by the owner on Jul 15, 2019. It is now read-only.
forked from proverma/arrow
/
session_request_handler.js
545 lines (481 loc) · 22 KB
/
session_request_handler.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
539
540
541
542
543
544
545
/*
This file is part of the GhostDriver project from Neustar inc.
Copyright (c) 2012, Ivan De Marino <ivan.de.marino@gmail.com> - Neustar inc.
Copyright (c) 2012, Alex Anderson <@alxndrsn>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var ghostdriver = ghostdriver || {};
ghostdriver.SessionReqHand = function(session) {
// private:
var
_protoParent = ghostdriver.SessionReqHand.prototype,
_session = session,
_locator = new ghostdriver.WebElementLocator(_session),
_const = {
URL : "url",
ELEMENT : "element",
ELEMENTS : "elements",
ELEMENT_DIR : "/element/",
TITLE : "title",
WINDOW : "window",
CURRENT : "current",
SIZE : "size",
FORWARD : "forward",
BACK : "back",
REFRESH : "refresh",
EXECUTE : "execute",
EXECUTE_ASYNC : "execute_async",
SCREENSHOT : "screenshot",
TIMEOUTS : "timeouts",
TIMEOUTS_DIR : "/timeouts/",
ASYNC_SCRIPT : "async_script",
IMPLICIT_WAIT : "implicit_wait",
WINDOW_HANDLE : "window_handle",
WINDOW_HANDLES : "window_handles",
FRAME : "frame",
SOURCE : "source",
COOKIE : "cookie"
},
_errors = require("./errors.js"),
_handle = function(req, res) {
var element;
_protoParent.handle.call(this, req, res);
// console.log("Request => " + JSON.stringify(req, null, ' '));
// Handle "/url" GET and POST
if (req.urlParsed.file === _const.URL) { //< ".../url"
if (req.method === "GET") {
_getUrlCommand(req, res);
} else if (req.method === "POST") {
_postUrlCommand(req, res);
}
return;
} else if (req.urlParsed.file === _const.TITLE && req.method === "GET") { //< ".../title"
// Get the current Page title
_getTitleCommand(req, res);
return;
} else if (req.urlParsed.file === _const.SCREENSHOT && req.method === "GET") {
_getScreenshotCommand(req, res);
return;
} else if (req.urlParsed.file === _const.WINDOW) { //< ".../window"
if (req.method === "DELETE") {
_deleteWindowCommand(req, res); //< close window
} else if (req.method === "POST") {
_postWindowCommand(req, res); //< change focus to the given window
}
return;
} else if (req.urlParsed.chunks[0] === _const.WINDOW) {
_handleWindow(req, res);
return;
} else if (req.urlParsed.file === _const.ELEMENT && req.method === "POST" && req.urlParsed.chunks.length == 1) { //< ".../element"
_postElementCommand(req, res);
return;
} else if (req.urlParsed.file === _const.ELEMENTS && req.method === "POST" && req.urlParsed.chunks.length == 1) { //< ".../elements"
_postElementsCommand(req, res);
return;
} else if (req.urlParsed.directory === _const.ELEMENT_DIR) { //< ".../element/:elementId" or ".../element/active"
// TODO
} else if (req.urlParsed.chunks[0] === _const.ELEMENT) { //< ".../element/:elementId/COMMAND"
// Get the WebElementRH and, if found, re-route request to it
element = _locator.getElement(decodeURIComponent(req.urlParsed.chunks[1]));
if (element !== null) {
_protoParent.reroute.call(element, req, res, _const.ELEMENT_DIR + req.urlParsed.chunks[1]);
} else {
throw _errors.createInvalidReqVariableResourceNotFoundEH(req);
}
return;
} else if (req.urlParsed.file === _const.FORWARD && req.method === "POST") {
_forwardCommand(req, res);
return;
} else if (req.urlParsed.file === _const.BACK && req.method === "POST") {
_backCommand(req, res);
return;
} else if (req.urlParsed.file === _const.REFRESH && req.method === "POST") {
_refreshCommand(req, res);
return;
} else if (req.urlParsed.file === _const.EXECUTE && req.method === "POST") {
_executeCommand(req, res);
return;
} else if (req.urlParsed.file === _const.EXECUTE_ASYNC && req.method === "POST") {
_executeAsyncCommand(req, res);
return;
} else if ((req.urlParsed.file === _const.TIMEOUTS || req.urlParsed.directory === _const.TIMEOUTS_DIR) && req.method === "POST") {
_postTimeout(req, res);
return;
} else if (req.urlParsed.file === _const.WINDOW_HANDLE && req.method === "GET") {
_getWindowHandle(req, res);
return;
} else if (req.urlParsed.file === _const.WINDOW_HANDLES && req.method === "GET") {
_getWindowHandles(req, res);
return;
} else if (req.urlParsed.file === _const.FRAME && req.method === "POST") {
_postFrameCommand(req, res);
return;
} else if (req.urlParsed.file === _const.SOURCE && req.method === "GET") {
_getSourceCommand(req, res);
return;
} else if (req.urlParsed.file === _const.COOKIE) {
if(req.method === "DELETE") {
_deleteCookieCommand(req, res);
return;
}
}
throw _errors.createInvalidReqInvalidCommandMethodEH(req);
},
_createOnSuccessHandler = function(res) {
return function (status) {
res.success(_session.getId());
};
},
_handleWindow = function(req, res) {
var windowHandle = req.urlParsed.chunks[1],
command = req.urlParsed.chunks[2];
// TODO - We need support for multiple windows:
// instead of checking request is for "current", we should
// check if it's not, and if not then apply to specific window instead
// of _session.getCurrentWindow().
// TODO handle NoSuchWindow - If the specified window cannot be found.
if(windowHandle === _const.CURRENT) {
if(command === _const.SIZE && req.method === "POST") {
_postWindowSizeCommand(req, res);
return;
} else if(command === _const.SIZE && req.method === "GET") {
_getWindowSizeCommand(req, res);
return;
}
}
},
_refreshCommand = function(req, res) {
var successHand = _createOnSuccessHandler(res);
_session.getCurrentWindow().evaluateAndWaitForLoad(
function() { window.location.reload(true); }, //< 'reload(true)' force reload from the server
successHand,
successHand); //< We don't care if 'refresh' fails
},
_backCommand = function(req, res) {
var successHand = _createOnSuccessHandler(res);
_session.getCurrentWindow().evaluateAndWaitForLoad(
require("./webdriver_atoms.js").get("back"),
successHand,
successHand); //< We don't care if 'back' fails
},
_forwardCommand = function(req, res) {
var successHand = _createOnSuccessHandler(res);
_session.getCurrentWindow().evaluateAndWaitForLoad(
require("./webdriver_atoms.js").get("forward"),
successHand,
successHand); //< We don't care if 'forward' fails
},
_executeCommand = function(req, res) {
var postObj = JSON.parse(req.post),
result,
timer,
scriptTimeout = _session.getTimeout(_session.timeoutNames().SCRIPT),
timedOut = false;
if (typeof(postObj) === "object" && postObj.script && postObj.args) {
// Execute script, but within a limited timeframe
timer = setTimeout(function() {
// The script didn't return within the expected timeframe
timedOut = true;
_errors.handleFailedCommandEH(
_errors.FAILED_CMD_STATUS.TIMEOUT,
"Script didn't return within "+scriptTimeout+"ms",
req,
res,
_session,
"SessionReqHand");
}, scriptTimeout);
// Launch the actual script
result = _session.getCurrentWindow().evaluate(
require("./webdriver_atoms.js").get("execute_script"),
postObj.script,
postObj.args,
true);
// If we are here, we don't need the timer anymore
clearTimeout(timer);
// Respond with result ONLY if this hasn't ALREADY timed-out
if (!timedOut) {
res.respondBasedOnResult(_session, req, result);
}
} else {
throw _errors.createInvalidReqMissingCommandParameterEH(req);
}
},
_executeAsyncCommand = function(req, res) {
var postObj = JSON.parse(req.post);
if (typeof(postObj) === "object" && postObj.script && postObj.args) {
_session.getCurrentWindow().setOneShotCallback("onCallback", function() {
res.respondBasedOnResult(_session, req, arguments[0]);
});
_session.getCurrentWindow().evaluate(
"function(script, args, timeout) { " +
"return (" + require("./webdriver_atoms.js").get("execute_async_script") + ")( " +
"script, args, timeout, callPhantom, true); " +
"}",
postObj.script,
postObj.args,
_session.getTimeout(_session.timeoutNames().ASYNC_SCRIPT));
} else {
throw _errors.createInvalidReqMissingCommandParameterEH(req);
}
},
_getWindowHandle = function(req, res) {
res.success(_session.getId(), _session.getCurrentWindowHandle());
},
_getWindowHandles = function(req, res) {
res.success(_session.getId(), _session.getWindowHandles());
},
_getScreenshotCommand = function(req, res) {
var rendering = _session.getCurrentWindow().renderBase64("png");
res.success(_session.getId(), rendering);
},
_getUrlCommand = function(req, res) {
// Get the URL at which the Page currently is
var result = _session.getCurrentWindow().evaluate(
require("./webdriver_atoms.js").get("execute_script"),
"return location.toString()",
[]);
res.respondBasedOnResult(_session, res, result);
},
_postUrlCommand = function(req, res) {
// Load the given URL in the Page
var postObj = JSON.parse(req.post),
pageOpenTimeout = _session.getTimeout(_session.timeoutNames().PAGE_LOAD),
pageOpenTimedout = false,
timer;
if (typeof(postObj) === "object" && postObj.url) {
// Open the given URL and, when done, return "HTTP 200 OK"
_session.getCurrentWindow().open(postObj.url, function(status) {
if (!pageOpenTimedout) {
// Callback received: don't need the timer anymore
clearTimeout(timer);
if (status === "success") {
res.success(_session.getId());
} else {
_errors.handleInvalidReqInvalidCommandMethodEH(req, res);
}
}
});
timer = setTimeout(function() {
// Command Failed (Timed-out)
pageOpenTimedout = true;
_errors.handleFailedCommandEH(
_errors.FAILED_CMD_STATUS.TIMEOUT,
"URL '"+postObj.url+"' didn't load within "+pageOpenTimeout+"ms",
req,
res,
_session,
"SessionReqHand");
}, pageOpenTimeout);
} else {
throw _errors.createInvalidReqMissingCommandParameterEH(req);
}
},
_postTimeout = function(req, res) {
var postObj = JSON.parse(req.post);
// Normalize the call: the "type" is read from the URL, not a POST parameter
if (req.urlParsed.file === _const.IMPLICIT_WAIT) {
postObj["type"] = _session.timeoutNames().IMPLICIT;
} else if (req.urlParsed.file === _const.ASYNC_SCRIPT) {
postObj["type"] = _session.timeoutNames().ASYNC_SCRIPT;
}
if (typeof(postObj["type"]) !== "undefined" && typeof(postObj["ms"]) !== "undefined") {
_session.setTimeout(postObj["type"], postObj["ms"]);
res.success(_session.getId());
} else {
throw _errors.createInvalidReqMissingCommandParameterEH(req);
}
},
_postFrameCommand = function(req, res) {
var postObj = JSON.parse(req.post),
frameElement = null,
result;
if (typeof(postObj) === "object" && typeof(postObj.id) !== "undefined") {
if(postObj.id === null) {
// Reset focus on the topmost (main) Frame
_session.getCurrentWindow().evaluate(
require("./webdriver_atoms.js").get("execute_script"),
"return top.focus();");
res.success(_session.getId());
return; //< we are done here: no need go further
}
if (typeof(postObj.id) === "number") {
// Search frame by "index" within the "window.frames" array
result = _session.getCurrentWindow().evaluate(
require("./webdriver_atoms.js").get("execute_script"),
"var el = null; " +
"if (typeof(window.frames[arguments[0]]) !== 'undefined') { " +
"el = window.frames[arguments[0]].frameElement; " +
"} " +
"return el; ",
[postObj.id]);
// Check if the Frame was found
if (result.status === 0 && typeof(result.value) === "object") {
frameElement = result.value;
}
} else if (typeof(postObj.id) === "string") {
// Search frame by "name" and, if not found, by "id"
result = _session.getCurrentWindow().evaluate(
require("./webdriver_atoms.js").get("execute_script"),
"var el = null; " +
"el = document.querySelector(\"[name='\"+arguments[0]+\"']\"); " +
"if (el === null) { " +
"el = document.querySelector('#'+arguments[0]); " +
"} " +
"return el; ",
[postObj.id]);
// Check if the Frame was found
if (result.status === 0 && typeof(result.value) === "object") {
frameElement = result.value;
}
} else if (typeof(postObj.id) === "object" && typeof(postObj.id["ELEMENT"]) === "string") {
// Search frame by "{ELEMENT : id}" object
result = _locator.getElement(decodeURIComponent(postObj.id["ELEMENT"]));
// Check if the Frame was found
if (result !== null && typeof(result) === "object") {
frameElement = result.getJSON();
}
} else {
throw _errors.createInvalidReqInvalidCommandMethodEH(req);
}
// Send a positive response if the element was found...
if (frameElement !== null) {
result = _session.getCurrentWindow().evaluate(
require("./webdriver_atoms.js").get("execute_script"),
"return arguments[0].focus();",
[frameElement]);
res.success(_session.getId());
} else {
// ... otherwise, throw the appropriate exception
_errors.handleFailedCommandEH(
_errors.FAILED_CMD_STATUS.NO_SUCH_FRAME, //< error name
"Frame not found", //< error message
req, //< request
res,
_session, //< session
"SessionReqHand"); //< class name
}
} else {
throw _errors.createInvalidReqMissingCommandParameterEH(req);
}
},
_getSourceCommand = function(req, res) {
var source = _session.getCurrentWindow().content;
res.success(_session.getId(), source);
},
_deleteCookieCommand = function(req, res) {
// Delete all cookies visible to the current page.
_session.getCurrentWindow().evaluate(function() {
var p = document.cookie.split(";"),
i, key;
for(i = p.length -1; i >= 0; --i) {
key = p[i].split("=");
document.cookie = key + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
});
res.success(_session.getId());
},
_deleteWindowCommand = function(req, res) {
// TODO An optional JSON parameter "name" might be given
_session.closeCurrentWindow();
res.success(_session.getId());
},
_postWindowCommand = function(req, res) {
// TODO
// TODO An optional JSON parameter "name" might be given
},
_postWindowSizeCommand = function(req, res) {
var params = JSON.parse(req.post),
newWidth = params.width,
newHeight = params.height;
// If width/height are passed in string, force them to numbers
if (typeof(params.width) === "string") {
newWidth = parseInt(params.width, 10);
}
if (typeof(params.height) === "string") {
newHeight = parseInt(params.height, 10);
}
// If a number was not found, the command is
if (isNaN(newWidth) || isNaN(newHeight)) {
throw _errors.createInvalidReqInvalidCommandMethodEH(req);
}
_session.getCurrentWindow().viewportSize = {
width : newWidth,
height : newHeight
};
res.success(_session.getId());
},
_getWindowSizeCommand = function(req, res) {
// Returns response in the format "{width: number, height: number}"
res.success(_session.getId(), _session.getCurrentWindow().viewportSize);
},
_getTitleCommand = function(req, res) {
var result = _session.getCurrentWindow().evaluate(function() { return document.title; });
res.success(_session.getId(), result);
},
_postElementCommand = function(req, res) {
// Search for a WebElement on the Page
var element,
searchStartTime = new Date().getTime();
// Try to find the element
// and retry if "startTime + implicitTimeout" is
// greater (or equal) than current time
do {
element = _locator.locateElement(JSON.parse(req.post));
if (element) {
res.success(_session.getId(), element.getJSON());
return;
}
} while(searchStartTime + _session.getTimeout(_session.timeoutNames().IMPLICIT) >= new Date().getTime());
throw _errors.createInvalidReqVariableResourceNotFoundEH(req);
};
_postElementsCommand = function(req, res) {
// Search for a WebElement on the Page
var elements,
searchStartTime = new Date().getTime(),
elementsResponse = "";
// Try to find at least one element
// and retry if "startTime + implicitTimeout" is
// greater (or equal) than current time
do {
elements = _locator.locateElements(JSON.parse(req.post));
if (elements.length > 0) {
// Manually construct the JSON response, since the return
// from locateElements is an array of WebElementReqHand
// objects.
for (var i = 0; i < elements.length; i++) {
if (elementsResponse.length > 0) {
elementsResponse += ", ";
}
elementsResponse += JSON.stringify(elements[i].getJSON());
}
break;
}
} while(searchStartTime + _session.getTimeout(_session.timeoutNames().IMPLICIT) >= new Date().getTime());
res.success(_session.getId(), JSON.parse("[" + elementsResponse + "]"));
};
// public:
return {
handle : _handle,
setSession : function(s) { _session = s; },
getSessionId : function() { return _session.getId(); }
};
};
// prototype inheritance:
ghostdriver.SessionReqHand.prototype = new ghostdriver.RequestHandler();