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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview
* Functions related to the 'client screen' for Chromoting.
*/
'use strict';
/** @suppress {duplicate} */
var remoting = remoting || {};
(function() {
/**
* @type {boolean} Whether or not the plugin should scale itself.
*/
remoting.scaleToFit = false;
/**
* @type {remoting.ClientSession} The client session object, set once the
* access code has been successfully verified.
*/
remoting.clientSession = null;
/**
* @type {string} The normalized access code.
*/
remoting.accessCode = '';
/**
* @type {string} The host's JID, returned by the server.
*/
remoting.hostJid = '';
/**
* @type {string} The host's public key, returned by the server.
*/
remoting.hostPublicKey = '';
/**
* @type {XMLHttpRequest} The XHR object corresponding to the current
* support-hosts request, if there is one outstanding.
*/
remoting.supportHostsXhr_ = null;
/**
* Entry point for the 'connect' functionality. This function checks for the
* existence of an OAuth2 token, and either requests one asynchronously, or
* calls through directly to tryConnectWithAccessToken_.
*/
remoting.tryConnect = function() {
document.getElementById('cancel-button').disabled = false;
if (remoting.oauth2.needsNewAccessToken()) {
remoting.oauth2.refreshAccessToken(function(xhr) {
if (remoting.oauth2.needsNewAccessToken()) {
// Failed to get access token
remoting.debug.log('tryConnect: OAuth2 token fetch failed');
showConnectError_(remoting.Error.AUTHENTICATION_FAILED);
return;
}
tryConnectWithAccessToken_();
});
} else {
tryConnectWithAccessToken_();
}
}
/**
* Cancel an incomplete connect operation.
*
* @return {void} Nothing.
*/
remoting.cancelConnect = function() {
if (remoting.supportHostsXhr_) {
remoting.supportHostsXhr_.abort();
remoting.supportHostsXhr_ = null;
}
if (remoting.clientSession) {
remoting.clientSession.removePlugin();
remoting.clientSession = null;
}
remoting.setMode(remoting.AppMode.HOME);
}
/**
* Enable or disable scale-to-fit.
*
* @param {Element} button The scale-to-fit button. The style of this button is
* updated to reflect the new scaling state.
* @return {void} Nothing.
*/
remoting.toggleScaleToFit = function(button) {
remoting.scaleToFit = !remoting.scaleToFit;
if (remoting.scaleToFit) {
addClass(button, 'toggle-button-active');
} else {
removeClass(button, 'toggle-button-active');
}
remoting.clientSession.updateDimensions();
}
/**
* Update the remoting client layout in response to a resize event.
*
* @return {void} Nothing.
*/
remoting.onResize = function() {
if (remoting.clientSession)
remoting.clientSession.onWindowSizeChanged();
recenterToolbar_();
}
/**
* Disconnect the remoting client.
*
* @return {void} Nothing.
*/
remoting.disconnect = function() {
if (remoting.clientSession) {
remoting.clientSession.disconnect();
remoting.clientSession = null;
remoting.debug.log('Disconnected.');
remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED);
}
}
/**
* Second stage of the 'connect' functionality. Once an access token is
* available, load the WCS widget asynchronously and call through to
* tryConnectWithWcs_ when ready.
*/
function tryConnectWithAccessToken_() {
if (!remoting.wcsLoader) {
remoting.wcsLoader = new remoting.WcsLoader();
}
/** @param {function(string):void} setToken The callback function. */
var callWithToken = function(setToken) {
remoting.oauth2.callWithToken(setToken);
};
remoting.wcsLoader.start(
remoting.oauth2.getAccessToken(),
callWithToken,
tryConnectWithWcs_);
}
/**
* Final stage of the 'connect' functionality, called when the wcs widget has
* been loaded, or on error.
*
* @param {boolean} success True if the script was loaded successfully.
*/
function tryConnectWithWcs_(success) {
if (success) {
var accessCode = document.getElementById('access-code-entry').value;
remoting.accessCode = normalizeAccessCode_(accessCode);
// At present, only 12-digit access codes are supported, of which the first
// 7 characters are the supportId.
var kSupportIdLen = 7;
var kHostSecretLen = 5;
var kAccessCodeLen = kSupportIdLen + kHostSecretLen;
if (remoting.accessCode.length != kAccessCodeLen) {
remoting.debug.log('Bad access code length');
showConnectError_(remoting.Error.INVALID_ACCESS_CODE);
} else {
var supportId = remoting.accessCode.substring(0, kSupportIdLen);
remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
resolveSupportId(supportId);
}
} else {
showConnectError_(remoting.Error.AUTHENTICATION_FAILED);
}
}
/**
* Callback function called when the state of the client plugin changes. The
* current state is available via the |state| member variable.
*
* @param {number} oldState The previous state of the plugin.
*/
// TODO(jamiewalch): Make this pass both the current and old states to avoid
// race conditions.
function onClientStateChange_(oldState) {
if (!remoting.clientSession) {
// If the connection has been cancelled, then we no longer have a reference
// to the session object and should ignore any state changes.
return;
}
var state = remoting.clientSession.state;
if (state == remoting.ClientSession.State.CREATED) {
remoting.debug.log('Created plugin');
} else if (state == remoting.ClientSession.State.BAD_PLUGIN_VERSION) {
showConnectError_(remoting.Error.BAD_PLUGIN_VERSION);
} else if (state == remoting.ClientSession.State.CONNECTING) {
remoting.debug.log('Connecting as ' + remoting.oauth2.getCachedEmail());
} else if (state == remoting.ClientSession.State.INITIALIZING) {
remoting.debug.log('Initializing connection');
} else if (state == remoting.ClientSession.State.CONNECTED) {
if (remoting.clientSession) {
remoting.setMode(remoting.AppMode.IN_SESSION);
recenterToolbar_();
showToolbarPreview_();
updateStatistics_();
}
} else if (state == remoting.ClientSession.State.CLOSED) {
if (oldState == remoting.ClientSession.State.CONNECTED) {
remoting.clientSession.removePlugin();
remoting.clientSession = null;
remoting.debug.log('Connection closed by host');
remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED);
} else {
// The transition from CONNECTING to CLOSED state may happen
// only with older client plugins. Current version should go the
// FAILED state when connection fails.
showConnectError_(remoting.Error.INVALID_ACCESS_CODE);
}
} else if (state == remoting.ClientSession.State.CONNECTION_FAILED) {
remoting.debug.log('Client plugin reported connection failed: ' +
remoting.clientSession.error);
if (remoting.clientSession.error ==
remoting.ClientSession.ConnectionError.HOST_IS_OFFLINE) {
showConnectError_(remoting.Error.HOST_IS_OFFLINE);
} else if (remoting.clientSession.error ==
remoting.ClientSession.ConnectionError.SESSION_REJECTED) {
showConnectError_(remoting.Error.INVALID_ACCESS_CODE);
} else if (remoting.clientSession.error ==
remoting.ClientSession.ConnectionError.INCOMPATIBLE_PROTOCOL) {
showConnectError_(remoting.Error.INCOMPATIBLE_PROTOCOL);
} else if (remoting.clientSession.error ==
remoting.ClientSession.ConnectionError.NETWORK_FAILURE) {
showConnectError_(remoting.Error.GENERIC);
} else {
showConnectError_(remoting.Error.GENERIC);
}
} else {
remoting.debug.log('Unexpected client plugin state: ' + state);
// This should only happen if the web-app and client plugin get out of
// sync, and even then the version check should allow compatibility.
showConnectError_(remoting.Error.MISSING_PLUGIN);
}
}
/**
* Create the client session object and initiate the connection.
*
* @return {void} Nothing.
*/
function startSession_() {
remoting.debug.log('Starting session...');
var accessCode = document.getElementById('access-code-entry');
accessCode.value = ''; // The code has been validated and won't work again.
remoting.clientSession =
new remoting.ClientSession(
remoting.hostJid, remoting.hostPublicKey,
remoting.accessCode,
/** @type {string} */ (remoting.oauth2.getCachedEmail()),
onClientStateChange_);
/** @param {string} token The auth token. */
var createPluginAndConnect = function(token) {
remoting.clientSession.createPluginAndConnect(
document.getElementById('session-mode'),
token);
};
remoting.oauth2.callWithToken(createPluginAndConnect);
}
/**
* Show a client-side error message.
*
* @param {remoting.Error} errorTag The error to be localized and
* displayed.
* @return {void} Nothing.
*/
function showConnectError_(errorTag) {
remoting.debug.log('Connection failed: ' + errorTag);
var errorDiv = document.getElementById('connect-error-message');
l10n.localizeElementFromTag(errorDiv, /** @type {string} */ (errorTag));
remoting.accessCode = '';
if (remoting.clientSession) {
remoting.clientSession.disconnect();
remoting.clientSession = null;
}
remoting.setMode(remoting.AppMode.CLIENT_CONNECT_FAILED);
}
/**
* Parse the response from the server to a request to resolve a support id.
*
* @param {XMLHttpRequest} xhr The XMLHttpRequest object.
* @return {void} Nothing.
*/
function parseServerResponse_(xhr) {
remoting.supportHostsXhr_ = null;
remoting.debug.log('parseServerResponse: status = ' + xhr.status);
if (xhr.status == 200) {
var host = /** @type {{data: {jabberId: string, publicKey: string}}} */
JSON.parse(xhr.responseText);
if (host.data && host.data.jabberId && host.data.publicKey) {
remoting.hostJid = host.data.jabberId;
remoting.hostPublicKey = host.data.publicKey;
var split = remoting.hostJid.split('/');
document.getElementById('connected-to').innerText = split[0];
startSession_();
return;
}
}
var errorMsg = remoting.Error.GENERIC;
if (xhr.status == 404) {
errorMsg = remoting.Error.INVALID_ACCESS_CODE;
} else if (xhr.status == 0) {
errorMsg = remoting.Error.NO_RESPONSE;
} else {
remoting.debug.log('The server responded: ' + xhr.responseText);
}
showConnectError_(errorMsg);
}
/**
* Normalize the access code entered by the user.
*
* @param {string} accessCode The access code, as entered by the user.
* @return {string} The normalized form of the code (whitespace removed).
*/
function normalizeAccessCode_(accessCode) {
// Trim whitespace.
// TODO(sergeyu): Do we need to do any other normalization here?
return accessCode.replace(/\s/g, '');
}
/**
* Initiate a request to the server to resolve a support ID.
*
* @param {string} supportId The canonicalized support ID.
*/
function resolveSupportId(supportId) {
var headers = {
'Authorization': 'OAuth ' + remoting.oauth2.getAccessToken()
};
remoting.supportHostsXhr_ = remoting.xhr.get(
'https://www.googleapis.com/chromoting/v1/support-hosts/' +
encodeURIComponent(supportId),
parseServerResponse_,
'',
headers);
}
/**
* Timer callback to update the statistics panel.
*/
function updateStatistics_() {
if (!remoting.clientSession ||
remoting.clientSession.state != remoting.ClientSession.State.CONNECTED) {
return;
}
remoting.debug.updateStatistics(remoting.clientSession.stats());
// Update the stats once per second.
window.setTimeout(updateStatistics_, 1000);
}
/**
* Force-show the tool-bar for three seconds to aid discoverability.
*/
function showToolbarPreview_() {
var toolbar = document.getElementById('session-toolbar');
addClass(toolbar, 'toolbar-preview');
window.setTimeout(removeClass, 3000, toolbar, 'toolbar-preview');
}
/**
* Update the horizontal position of the tool-bar to center it.
*/
function recenterToolbar_() {
var toolbar = document.getElementById('session-toolbar');
var toolbarX = (window.innerWidth - toolbar.clientWidth) / 2;
toolbar.style['left'] = toolbarX + 'px';
}
/**
* Query the Remoting Directory for the user's list of hosts.
*
* @return {void} Nothing.
*/
remoting.refreshHostList = function() {
// Fetch a new Access Token for the user, if necessary.
if (remoting.oauth2.needsNewAccessToken()) {
remoting.oauth2.refreshAccessToken(function(xhr) {
if (remoting.oauth2.needsNewAccessToken()) {
// Failed to get access token
remoting.debug.log('tryConnect: OAuth2 token fetch failed');
showConnectError_(remoting.Error.AUTHENTICATION_FAILED);
return;
}
remoting.refreshHostList();
});
return;
}
var headers = {
'Authorization': 'OAuth ' + remoting.oauth2.getAccessToken()
};
var xhr = remoting.xhr.get(
'https://www.googleapis.com/chromoting/v1/@me/hosts',
parseHostListResponse_,
'',
headers);
}
/**
* Handle the results of the host list request. A success response will
* include a JSON-encoded list of host descriptions, which we display if we're
* able to successfully parse it.
*
* @param {XMLHttpRequest} xhr The XHR object for the host list request.
* @return {void} Nothing.
*/
function parseHostListResponse_(xhr) {
// Ignore host list responses if we're not on the Home screen. This mainly
// ensures that errors don't cause an unexpected mode switch.
if (remoting.currentMode != remoting.AppMode.HOME) {
return;
}
if (xhr.readyState != 4) {
return;
}
try {
if (xhr.status == 200) {
var parsed_response =
/** @type {{data: {items: Array}}} */ JSON.parse(xhr.responseText);
if (parsed_response.data && parsed_response.data.items) {
replaceHostList_(parsed_response.data.items);
}
} else {
// Some other error. Log for now, pretty-print in future.
remoting.debug.log('Error: Bad status on host list query: ' +
xhr.status + ' ' + xhr.statusText);
var errorResponse =
/** @type {{error: {code: *, message: *}}} */
JSON.parse(xhr.responseText);
if (errorResponse.error &&
errorResponse.error.code &&
errorResponse.error.message) {
remoting.debug.log('Error code ' + errorResponse.error.code);
remoting.debug.log('Error message ' + errorResponse.error.message);
} else {
remoting.debug.log('Error response: ' + xhr.responseText);
}
// For most errors in the 4xx range, tell the user to re-authorize us.
if (xhr.status == 403) {
// The user's account is not enabled for Me2Me, so fail silently.
} else if (xhr.status >= 400 && xhr.status <= 499) {
// TODO(wez): We need to replace this with a more general showError_().
showConnectError_(remoting.Error.GENERIC);
}
}
} catch(er) {
// Error parsing response...
remoting.debug.log('Error: Error processing response: "' +
xhr.status + ' ' + xhr.statusText);
remoting.debug.log(xhr.responseText);
}
}
/**
* Cache of the latest host list and status information.
*
* @type {Array.<{hostName: string, hostId: string, status: string,
* jabberId: string, publicKey: string}>}
*
*/
remoting.hostList_ = new Array();
/**
* Refresh the host list display with up to date host details.
*
* @param {Array.<{hostName: string, hostId: string, status: string,
* jabberId: string, publicKey: string}>} hostList
* The new list of registered hosts.
* @return {void} Nothing.
*/
function replaceHostList_(hostList) {
var hostListDiv = document.getElementById('host-list-div');
var hostListTable = document.getElementById('host-list');
remoting.hostList_ = hostList;
// Clear the table before adding the host info.
hostListTable.innerHTML = '';
// Show/hide the div depending on whether there are hosts to list.
hostListDiv.hidden = (hostList.length == 0);
for (var i = 0; i < hostList.length; ++i) {
var host = hostList[i];
if (!host.hostName || !host.hostId || !host.status || !host.jabberId ||
!host.publicKey)
continue;
var hostEntry = document.createElement('tr');
var hostName = document.createElement('td');
hostName.setAttribute('class', 'mode-select-label');
hostName.appendChild(document.createTextNode(host.hostName));
hostEntry.appendChild(hostName);
var hostStatus = document.createElement('td');
if (host.status == 'ONLINE') {
var connectButton = document.createElement('button');
connectButton.setAttribute('class', 'mode-select-button');
connectButton.setAttribute('type', 'button');
connectButton.setAttribute('onclick',
'remoting.connectHost("'+host.hostId+'")');
connectButton.innerHTML =
chrome.i18n.getMessage(/*i18n-content*/'CONNECT_BUTTON');
hostStatus.appendChild(connectButton);
} else {
hostStatus.innerHTML = chrome.i18n.getMessage(/*i18n-content*/'OFFLINE');
}
hostEntry.appendChild(hostStatus);
hostListTable.appendChild(hostEntry);
}
}
/**
* Start a connection to the specified host, using the stored details.
*
* @param {string} hostId The Id of the host to connect to.
* @return {void} Nothing.
*/
remoting.connectHost = function(hostId) {
var hostList = remoting.hostList_;
for (var i = 0; i < hostList.length; ++i) {
var host = remoting.hostList_[i];
if (host.hostId != hostId)
continue;
remoting.hostJid = host.jabberId;
remoting.hostPublicKey = host.publicKey;
document.getElementById('connected-to').innerText = host.hostName;
remoting.debug.log('Connecting to host...');
if (!remoting.wcsLoader) {
remoting.wcsLoader = new remoting.WcsLoader();
}
/** @param {function(string):void} setToken The callback function. */
var callWithToken = function(setToken) {
remoting.oauth2.callWithToken(setToken);
};
remoting.wcsLoader.start(
remoting.oauth2.getAccessToken(),
callWithToken,
remoting.connectHostWithWcs);
break;
}
}
/**
* Continue making the connection to a host, once WCS has initialized.
*
* @return {void} Nothing.
*/
remoting.connectHostWithWcs = function() {
remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
remoting.clientSession =
new remoting.ClientSession(
remoting.hostJid, remoting.hostPublicKey,
'', /** @type {string} */ (remoting.oauth2.getCachedEmail()),
onClientStateChange_);
/** @param {string} token The auth token. */
var createPluginAndConnect = function(token) {
remoting.clientSession.createPluginAndConnect(
document.getElementById('session-mode'),
token);
};
remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
remoting.oauth2.callWithToken(createPluginAndConnect);
}
// Don't delete this!
}());
|