summaryrefslogtreecommitdiffstats
path: root/remoting/webapp/me2mom/remoting.js
blob: aedac36af7edfdbdb54ab5bca478ff44442ef320 (plain)
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// 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.

var remoting = remoting || {};

(function() {
'use strict';

window.addEventListener('blur', pluginLostFocus_, false);

function pluginLostFocus_() {
  // If the plug loses input focus, release all keys as a precaution against
  // leaving them 'stuck down' on the host.
  if (remoting.session && remoting.session.plugin) {
    remoting.session.plugin.releaseAllKeys();
  }
}

/** @enum {string} */
remoting.AppMode = {
  UNAUTHENTICATED: 'auth',
  CLIENT: 'client',
    CLIENT_UNCONNECTED: 'client.unconnected',
    CLIENT_CONNECTING: 'client.connecting',
    CLIENT_CONNECT_FAILED: 'client.connect-failed',
    CLIENT_SESSION_FINISHED: 'client.session-finished',
  HOST: 'host',
    HOST_UNSHARED: 'host.unshared',
    HOST_WAITING_FOR_CODE: 'host.waiting-for-code',
    HOST_WAITING_FOR_CONNECTION: 'host.waiting-for-connection',
    HOST_SHARED: 'host.shared',
    HOST_SHARE_FAILED: 'host.share-failed',
  IN_SESSION: 'in-session'
};

remoting.EMAIL = 'email';
remoting.HOST_PLUGIN_ID = 'host-plugin-id';

/** @enum {string} */
remoting.ClientError = {
  NO_RESPONSE: 'errorNoResponse',
  INVALID_ACCESS_CODE: 'errorInvalidAccessCode',
  MISSING_PLUGIN: 'errorMissingPlugin',
  OAUTH_FETCH_FAILED: 'errorOAuthFailed',
  OTHER_ERROR: 'errorGeneric'
};

/**
 * Whether or not the plugin should scale itself.
 * @type {boolean}
 */
remoting.scaleToFit = false;

// Constants representing keys used for storing persistent application state.
var KEY_APP_MODE_ = 'remoting-app-mode';
var KEY_EMAIL_ = 'remoting-email';

// Some constants for pretty-printing the access code.
var kSupportIdLen = 7;
var kHostSecretLen = 5;
var kAccessCodeLen = kSupportIdLen + kHostSecretLen;
var kDigitsPerGroup = 4;

function hasClass(classes, cls) {
  return classes.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(element, cls) {
  if (!hasClass(element.className, cls))
    element.className = element.className + ' ' + cls;
}

function removeClass(element, cls) {
  element.className =
      element.className.replace(new RegExp('\\b' + cls + '\\b', 'g'), '');
}

function retrieveEmail_(access_token) {
  var headers = {
    'Authorization': 'OAuth ' + remoting.oauth2.getAccessToken()
  };

  var onResponse = function(xhr) {
    if (xhr.status != 200) {
      // TODO(ajwong): Have a better way of showing an error.
      remoting.debug.log('Unable to get email');
      document.getElementById('current-email').innerText = '???';
      return;
    }

    // TODO(ajwong): See if we can't find a JSON endpoint.
    setEmail(xhr.responseText.split('&')[0].split('=')[1]);
  };

  // TODO(ajwong): Update to new v2 API.
  remoting.xhr.get('https://www.googleapis.com/userinfo/email',
                   onResponse, '', headers);
}

function refreshEmail_() {
  if (!getEmail() && remoting.oauth2.isAuthenticated()) {
    remoting.oauth2.callWithToken(retrieveEmail_);
  }
}

function setEmail(value) {
  window.localStorage.setItem(KEY_EMAIL_, value);
  document.getElementById('current-email').innerText = value;
}

/**
 * @return {string} The email address associated with the auth credentials.
 */
function getEmail() {
  return window.localStorage.getItem(KEY_EMAIL_);
}

function exchangedCodeForToken_() {
  if (!remoting.oauth2.isAuthenticated()) {
    alert('Your OAuth2 token was invalid. Please try again.');
  }
  remoting.oauth2.callWithToken(function(token) {
      retrieveEmail_(token);
  });
}

remoting.clearOAuth2 = function() {
  remoting.oauth2.clear();
  window.localStorage.removeItem(KEY_EMAIL_);
  remoting.setMode(remoting.AppMode.UNAUTHENTICATED);
}

remoting.toggleDebugLog = function() {
  var debugLog = document.getElementById('debug-log');
  if (debugLog.hidden) {
    debugLog.hidden = false;
  } else {
    debugLog.hidden = true;
  }
}

remoting.init = function() {
  l10n.localize();
  // Create global objects.
  remoting.oauth2 = new remoting.OAuth2();
  remoting.debug =
      new remoting.DebugLog(document.getElementById('debug-messages'));

  refreshEmail_();
  var email = getEmail();
  if (email) {
    document.getElementById('current-email').innerText = email;
  }
  remoting.setMode(getAppStartupMode());
  if (isHostModeSupported()) {
    var unsupported = document.getElementById('client-footer-text-cros');
    unsupported.parentNode.removeChild(unsupported);
  } else {
    var footer = document.getElementById('client-footer-text');
    footer.parentNode.removeChild(footer);
    document.getElementById('client-footer-text-cros').id =
        'client-footer-text';
  }
}

/**
 * Change the app's modal state to |mode|, which is considered to be a dotted
 * hierachy of modes. For example, setMode('host.shared') will show any modal
 * elements with an data-ui-mode attribute of 'host' or 'host.shared' and hide
 * all others.
 *
 * @param {string} mode The new modal state, expressed as a dotted hiearchy.
 */
remoting.setMode = function(mode) {
  var modes = mode.split('.');
  for (var i = 1; i < modes.length; ++i)
    modes[i] = modes[i - 1] + '.' + modes[i];
  var elements = document.querySelectorAll('[data-ui-mode]');
  for (var i = 0; i < elements.length; ++i) {
    var element = elements[i];
    var hidden = true;
    for (var m = 0; m < modes.length; ++m) {
      if (hasClass(element.getAttribute('data-ui-mode'), modes[m])) {
        hidden = false;
        break;
      }
    }
    element.hidden = hidden;
  }
  remoting.debug.log('App mode: ' + mode);
  remoting.currentMode = mode;
}

/**
 * Get the major mode that the app is running in.
 * @return {remoting.Mode} The app's current major mode.
 */
remoting.getMajorMode = function(mode) {
  return remoting.currentMode.split('.')[0];
}

remoting.tryShare = function() {
  remoting.debug.log('Attempting to share...');
  if (remoting.oauth2.needsNewAccessToken()) {
    remoting.debug.log('Refreshing token...');
    remoting.oauth2.refreshAccessToken(function() {
      if (remoting.oauth2.needsNewAccessToken()) {
        // If we still need it, we're going to infinite loop.
        showShareError_('unable-to-get-token');
        throw 'Unable to get access token';
      }
      remoting.tryShare();
    });
    return;
  }

  remoting.setMode(remoting.AppMode.HOST_WAITING_FOR_CODE);
  document.getElementById('cancel-button').disabled = false;
  disableTimeoutCountdown_();

  var div = document.getElementById('host-plugin-container');
  var plugin = document.createElement('embed');
  plugin.type = remoting.PLUGIN_MIMETYPE;
  plugin.id = remoting.HOST_PLUGIN_ID;
  // Hiding the plugin means it doesn't load, so make it size zero instead.
  plugin.width = 0;
  plugin.height = 0;
  div.appendChild(plugin);
  plugin.onStateChanged = onStateChanged_;
  plugin.logDebugInfo = debugInfoCallback_;
  plugin.connect(getEmail(),
                 'oauth2:' + remoting.oauth2.getAccessToken());
}

function disableTimeoutCountdown_() {
  if (remoting.timerRunning) {
    clearInterval(remoting.accessCodeTimerId);
    remoting.timerRunning = false;
    updateTimeoutStyles_();
  }
}

var ACCESS_CODE_TIMER_DISPLAY_THRESHOLD = 30;
var ACCESS_CODE_RED_THRESHOLD = 10;

/**
 * Show/hide or restyle various elements, depending on the remaining countdown
 * and timer state.
 *
 * @return {bool} True if the timeout is in progress, false if it has expired.
 */
function updateTimeoutStyles_() {
  if (remoting.timerRunning) {
    if (remoting.accessCodeExpiresIn <= 0) {
      remoting.cancelShare();
      return false;
    }
    if (remoting.accessCodeExpiresIn <= ACCESS_CODE_RED_THRESHOLD) {
      addClass(document.getElementById('access-code-display'), 'expiring');
    } else {
      removeClass(document.getElementById('access-code-display'), 'expiring');
    }
  }
  document.getElementById('access-code-countdown').hidden =
      (remoting.accessCodeExpiresIn > ACCESS_CODE_TIMER_DISPLAY_THRESHOLD) ||
      !remoting.timerRunning;
  return true;
}

remoting.decrementAccessCodeTimeout_ = function() {
  --remoting.accessCodeExpiresIn;
  remoting.updateAccessCodeTimeoutElement_();
}

remoting.updateAccessCodeTimeoutElement_ = function() {
  var pad = (remoting.accessCodeExpiresIn < 10) ? '0' : '';
  document.getElementById('seconds-remaining').innerText =
      pad + remoting.accessCodeExpiresIn;
  if (!updateTimeoutStyles_()) {
    disableTimeoutCountdown_();
  }
}

function onStateChanged_() {
  var plugin = document.getElementById(remoting.HOST_PLUGIN_ID);
  var state = plugin.state;
  if (state == plugin.REQUESTED_ACCESS_CODE) {
    // Nothing to do here.
  } else if (state == plugin.RECEIVED_ACCESS_CODE) {
    var accessCode = plugin.accessCode;
    var accessCodeDisplay = document.getElementById('access-code-display');
    accessCodeDisplay.innerText = '';
    // Display the access code in groups of four digits for readability.
    for (var i = 0; i < accessCode.length; i += kDigitsPerGroup) {
      var nextFourDigits = document.createElement('span');
      nextFourDigits.className = 'access-code-digit-group';
      nextFourDigits.innerText = accessCode.substring(i, i + kDigitsPerGroup);
      accessCodeDisplay.appendChild(nextFourDigits);
    }
    remoting.accessCodeExpiresIn = plugin.accessCodeLifetime;
    if (remoting.accessCodeExpiresIn > 0) {  // Check it hasn't expired.
      remoting.accessCodeTimerId = setInterval(
          'remoting.decrementAccessCodeTimeout_()', 1000);
      remoting.timerRunning = true;
      remoting.updateAccessCodeTimeoutElement_();
      updateTimeoutStyles_();
      remoting.setMode(remoting.AppMode.HOST_WAITING_FOR_CONNECTION);
    } else {
      // This can only happen if the access code takes more than 5m to get from
      // the cloud to the web-app, so we don't care how clean this UX is.
      remoting.debug.log('Access code already invalid on receipt!');
      remoting.cancelShare();
    }
  } else if (state == plugin.CONNECTED) {
    var element = document.getElementById('host-shared-message');
    var client = plugin.client;
    l10n.localizeElement(element, client);
    remoting.setMode(remoting.AppMode.HOST_SHARED);
    disableTimeoutCountdown_();
  } else if (state == plugin.DISCONNECTED) {
    remoting.setMode(remoting.AppMode.HOST_UNSHARED);
    plugin.parentNode.removeChild(plugin);
  } else {
    remoting.debug.log('Unknown state -> ' + state);
  }
}

/**
* This is that callback that the host plugin invokes to indicate that there
* is additional debug log info to display.
*/
function debugInfoCallback_(msg) {
  remoting.debug.log('plugin: ' + msg);
}

function showShareError_(errorCode) {
  var errorDiv = document.getElementById(errorCode);
  errorDiv.style.display = 'block';
  remoting.debug.log('Sharing error: ' + errorCode);
  remoting.setMode(remoting.AppMode.HOST_SHARE_FAILED);
}

remoting.cancelShare = function() {
  remoting.debug.log('Canceling share...');
  var plugin = document.getElementById(remoting.HOST_PLUGIN_ID);
  plugin.disconnect();
  disableTimeoutCountdown_();
}

function updateStatistics() {
  if (remoting.session.state != remoting.ClientSession.State.CONNECTED)
    return;
  var stats = remoting.session.stats();

  var units = '';
  var videoBandwidth = stats['video_bandwidth'];
  if (videoBandwidth < 1024) {
    units = 'Bps';
  } else if (videoBandwidth < 1048576) {
    units = 'KiBps';
    videoBandwidth = videoBandwidth / 1024;
  } else if (videoBandwidth < 1073741824) {
    units = 'MiBps';
    videoBandwidth = videoBandwidth / 1048576;
  } else {
    units = 'GiBps';
    videoBandwidth = videoBandwidth / 1073741824;
  }

  var statistics = document.getElementById('statistics');
  statistics.innerText =
      'Bandwidth: ' + videoBandwidth.toFixed(2) + units +
      ', Capture: ' + stats['capture_latency'].toFixed(2) + 'ms' +
      ', Encode: ' + stats['encode_latency'].toFixed(2) + 'ms' +
      ', Decode: ' + stats['decode_latency'].toFixed(2) + 'ms' +
      ', Render: ' + stats['render_latency'].toFixed(2) + 'ms' +
      ', Latency: ' + stats['roundtrip_latency'].toFixed(2) + 'ms';

  // Update the stats once per second.
  window.setTimeout(updateStatistics, 1000);
}

function onClientStateChange_(oldState) {
  var state = remoting.session.state;
  if (state == remoting.ClientSession.State.CREATED) {
    remoting.debug.log('Created plugin');
  } else if (state == remoting.ClientSession.State.BAD_PLUGIN_VERSION) {
    showConnectError_(remoting.ClientError.MISSING_PLUGIN);
  } else if (state == remoting.ClientSession.State.CONNECTING) {
    remoting.debug.log('Connecting as ' + remoting.username);
  } else if (state == remoting.ClientSession.State.INITIALIZING) {
    remoting.debug.log('Initializing connection');
  } else if (state == remoting.ClientSession.State.CONNECTED) {
    remoting.setMode(remoting.AppMode.IN_SESSION);
    updateStatistics();
    var accessCode = document.getElementById('access-code-entry');
    accessCode.value = '';
  } else if (state == remoting.ClientSession.State.CLOSED) {
    if (oldState == remoting.ClientSession.State.CONNECTED) {
      remoting.session.removePlugin();
      remoting.session = null;
      remoting.debug.log('Connection closed by host');
      remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED);
    } else {
      // TODO(jamiewalch): This is not quite correct, as it will report
      // "Invalid access code", regardless of what actually went wrong.
      // Fix this up by having the host send a suitable error code.
      showConnectError_(remoting.ClientError.INVALID_ACCESS_CODE);
    }
  } else if (state == remoting.ClientSession.State.CONNECTION_FAILED) {
    remoting.debug.log('Client plugin reported connection failed');
    showConnectError_(remoting.ClientError.OTHER_ERROR);
  } else {
    remoting.debug.log('Unexpected client plugin state: ' + state);
    showConnectError_(remoting.ClientError.OTHER_ERROR);
  }
}

function startSession_() {
  remoting.debug.log('Starting session...');
  remoting.username = getEmail();
  remoting.session =
      new remoting.ClientSession(remoting.hostJid, remoting.hostPublicKey,
                                 remoting.accessCode, getEmail(),
                                 onClientStateChange_);
  remoting.oauth2.callWithToken(function(token) {
    remoting.session.createPluginAndConnect(
        document.getElementById('session-mode'),
        token);
  });
}

/**
 * @param {ClientError} errorMsg The error to be localized and displayed.
 * @return {void} Nothing.
 */
function showConnectError_(errorMsg) {
  remoting.debug.log('Connection failed: ' + errorMsg);
  var translation = chrome.i18n.getMessage(errorMsg);
  if (translation) {
    var errorNode = document.getElementById('connect-error-message');
    errorNode.innerText = translation;
  } else {
    remoting.debug.error('Missing translation for ' + errorMsg);
  }
  remoting.accessCode = '';
  if (remoting.session) {
    remoting.session.disconnect();
    remoting.session = null;
  }
  remoting.setMode(remoting.AppMode.CLIENT_CONNECT_FAILED);
}

function parseServerResponse_(xhr) {
  remoting.debug.log('parseServerResponse: status = ' + xhr.status);
  if (xhr.status == 200) {
    var host = JSON.parse(xhr.responseText);
    if (host.data && host.data.jabberId) {
      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.ClientError.OTHER_ERROR;
  if (xhr.status == 404) {
    errorMsg = remoting.ClientError.INVALID_ACCESS_CODE;
  } else if (xhr.status == 0) {
    errorMsg = remoting.ClientError.NO_RESPONSE;
  } else {
    remoting.debug.log('The server responded: ' + xhr.responseText);
  }
  showConnectError_(errorMsg);
}

function normalizeAccessCode_(accessCode) {
  // Trim whitespace.
  // TODO(sergeyu): Do we need to do any other normalization here?
  return accessCode.replace(/\s/g, '');
}

function resolveSupportId(supportId) {
  var headers = {
    'Authorization': 'OAuth ' + remoting.oauth2.getAccessToken()
  };

  remoting.xhr.get(
      'https://www.googleapis.com/chromoting/v1/support-hosts/' +
          encodeURIComponent(supportId),
      parseServerResponse_,
      '',
      headers);
}

remoting.doTryConnect = function() {
  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.
  if (remoting.accessCode.length != kAccessCodeLen) {
    remoting.debug.log('Bad access code length');
    showConnectError_(remoting.ClientError.INVALID_ACCESS_CODE);
  } else {
    var supportId = remoting.accessCode.substring(0, kSupportIdLen);
    remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
    resolveSupportId(supportId);
  }
}

remoting.tryConnect = function() {
  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.ClientError.OAUTH_FETCH_FAILED);
        return;
      }
      remoting.doTryConnect();
    });
  } else {
    remoting.doTryConnect();
  }
}

remoting.cancelPendingOperation = function() {
  document.getElementById('cancel-button').disabled = true;
  if (remoting.getMajorMode() == remoting.AppMode.HOST) {
    remoting.cancelShare();
  }
}

/**
 * Changes the major-mode of the application (Eg., client or host).
 *
 * @param {remoting.AppMode} mode The mode to shift the application into.
 * @return {void} Nothing.
 */
remoting.setAppMode = function(mode) {
  window.localStorage.setItem(KEY_APP_MODE_, mode);
  remoting.setMode(getAppStartupMode());
}

/**
 * Gets the major-mode that this application should start up in.
 *
 * @return {remoting.AppMode} The mode (client or host) to start in.
 */
function getAppStartupMode() {
  if (!remoting.oauth2.isAuthenticated()) {
    return remoting.AppMode.UNAUTHENTICATED;
  }
  if (isHostModeSupported()) {
    var mode = window.localStorage.getItem(KEY_APP_MODE_);
    if (mode == remoting.AppMode.CLIENT) {
      return remoting.AppMode.CLIENT_UNCONNECTED;
    }
    return remoting.AppMode.HOST_UNSHARED;
  } else {
    return remoting.AppMode.CLIENT_UNCONNECTED;
  }
}

/**
 * Returns whether Host mode is supported on this platform.
 *
 * @return {boolean} True if Host mode is supported.
 */
function isHostModeSupported() {
  // Currently, ChromeOS is not supported.
  return !navigator.userAgent.match(/\bCrOS\b/);
}

/**
 * Enable or disable scale-to-fit.
 *
 * @return {void} Nothing.
 */
remoting.toggleScaleToFit = function() {
  remoting.scaleToFit = !remoting.scaleToFit;
  remoting.session.toggleScaleToFit(remoting.scaleToFit);
}

/**
 * Disconnect the remoting client.
 *
 * @return {void} Nothing.
 */
remoting.disconnect = function() {
  if (remoting.session) {
    remoting.session.disconnect();
    remoting.session = null;
    remoting.debug.log('Disconnected.');
    remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED);
  }
}

/** If the client is connected, or the host is shared, prompt before closing.
 *
 * @return {(string|void)} The prompt string if a connection is active.
 */
remoting.promptClose = function() {
  var messageId = null;
  if (remoting.getMajorMode() == remoting.AppMode.HOST &&
      remoting.currentMode != remoting.AppMode.HOST_UNSHARED) {
    messageId = 'closePromptHost';
  } else if (remoting.getMajorMode() == remoting.AppMode.IN_SESSION ||
             remoting.currentMode == remoting.AppMode.CLIENT_CONNECTING) {
    messageId = 'closePromptClient';
  }
  if (messageId) {
    var result = chrome.i18n.getMessage(messageId);
    return result;
  }
}

}());