summaryrefslogtreecommitdiffstats
path: root/remoting/webapp/app_remoting/js/app_remoting_activity.js
blob: ff4fb98a2e0106887d334114460a19c23ba0608d (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
// Copyright 2015 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.

/** @suppress {duplicate} */
var remoting = remoting || {};

/**
 * Type definition for the RunApplicationResponse returned by the API.
 * @typedef {{
 *   status: string,
 *   hostJid: string,
 *   authorizationCode: string,
 *   sharedSecret: string,
 *   host: {
 *     applicationId: string,
 *     hostId: string
 *   }
 * }}
 */
remoting.AppHostResponse;

(function() {

'use strict';

/**
 * @param {Array<string>} appCapabilities Array of application capabilities.
 *
 * @constructor
 * @implements {remoting.Activity}
 */
remoting.AppRemotingActivity = function(appCapabilities) {
  /** @private */
  this.sessionFactory_ = new remoting.ClientSessionFactory(
      document.querySelector('#client-container .client-plugin-container'),
      appCapabilities);

  /** @private {remoting.ClientSession} */
  this.session_ = null;

  /** @private {base.Disposables} */
  this.connectedDisposables_ = null;
};

remoting.AppRemotingActivity.prototype.dispose = function() {
  this.cleanup_();
  remoting.LoadingWindow.close();
};

remoting.AppRemotingActivity.prototype.start = function() {
  remoting.LoadingWindow.show();
  var that = this;
  return remoting.identity.getToken().then(function(/** string */ token) {
    return that.getAppHostInfo_(token);
  }).then(function(/** !remoting.Xhr.Response */ response) {
    that.onAppHostResponse_(response);
  });
};

remoting.AppRemotingActivity.prototype.stop = function() {
  if (this.session_) {
    this.session_.disconnect(remoting.Error.none());
  }
};

/** @private */
remoting.AppRemotingActivity.prototype.cleanup_ = function() {
  base.dispose(this.connectedDisposables_);
  this.connectedDisposables_ = null;
  base.dispose(this.session_);
  this.session_ = null;
};

/**
 * @param {string} token
 * @return {Promise<!remoting.Xhr.Response>}
 * @private
 */
remoting.AppRemotingActivity.prototype.getAppHostInfo_ = function(token) {
  var url = remoting.settings.APP_REMOTING_API_BASE_URL + '/applications/' +
            remoting.settings.getAppRemotingApplicationId() + '/run';
  return new remoting.Xhr({
    method: 'POST',
    url: url,
    oauthToken: token
  }).start();
};

/**
 * @param {!remoting.Xhr.Response} xhrResponse
 * @private
 */
remoting.AppRemotingActivity.prototype.onAppHostResponse_ =
    function(xhrResponse) {
  if (xhrResponse.status == 200) {
    var response = /** @type {remoting.AppHostResponse} */
        (base.jsonParseSafe(xhrResponse.getText()));
    if (response &&
        response.status &&
        response.status == 'done' &&
        response.hostJid &&
        response.authorizationCode &&
        response.sharedSecret &&
        response.host &&
        response.host.hostId) {
      var hostJid = response.hostJid;
      var host = new remoting.Host(response.host.hostId);
      host.jabberId = hostJid;
      host.authorizationCode = response.authorizationCode;
      host.sharedSecret = response.sharedSecret;

      remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);

      /**
       * @param {string} tokenUrl Token-issue URL received from the host.
       * @param {string} hostPublicKey Host public key (DER and Base64
       *     encoded).
       * @param {string} scope OAuth scope to request the token for.
       * @param {function(string, string):void} onThirdPartyTokenFetched
       *     Callback.
       */
      var fetchThirdPartyToken = function(
          tokenUrl, hostPublicKey, scope, onThirdPartyTokenFetched) {
        // Use the authentication tokens returned by the app-remoting server.
        onThirdPartyTokenFetched(host['authorizationCode'],
                                 host['sharedSecret']);
      };

      var credentialsProvider = new remoting.CredentialsProvider(
              {fetchThirdPartyToken: fetchThirdPartyToken});
      var that = this;

      this.sessionFactory_.createSession(this).then(
        function(/** remoting.ClientSession */ session) {
          that.session_ = session;
          session.logHostOfflineErrors(true);
          session.getLogger().setLogEntryMode(
              remoting.ServerLogEntry.VALUE_MODE_APP_REMOTING);
          session.connect(host, credentialsProvider);
      });
    } else if (response && response.status == 'pending') {
      this.onConnectionFailed(new remoting.Error(
          remoting.Error.Tag.SERVICE_UNAVAILABLE));
    }
  } else {
    console.error('Invalid "runApplication" response from server.');
    // The orchestrator returns 403 if the user is not whitelisted to run the
    // app, which gets translated to a generic error message, so pick something
    // a bit more user-friendly.
    var error = xhrResponse.status == 403 ?
        new remoting.Error(remoting.Error.Tag.APP_NOT_AUTHORIZED) :
        remoting.Error.fromHttpStatus(xhrResponse.status);
    this.onConnectionFailed(error);
  }
};

/**
 * @param {remoting.ConnectionInfo} connectionInfo
 */
remoting.AppRemotingActivity.prototype.onConnected = function(connectionInfo) {
  var connectedView = new remoting.AppConnectedView(
      document.getElementById('client-container'), connectionInfo);

  var idleDetector = new remoting.IdleDetector(
      document.getElementById('idle-dialog'), this.stop.bind(this));

  // Map Cmd to Ctrl on Mac since hosts typically use Ctrl for keyboard
  // shortcuts, but we want them to act as natively as possible.
  if (remoting.platformIsMac()) {
    connectionInfo.plugin().setRemapKeys('0x0700e3>0x0700e0,0x0700e7>0x0700e4');
  }

  // Drop the session after 30s of suspension as we cannot recover from a
  // connectivity loss longer than 30s anyways.
  this.session_.dropSessionOnSuspend(30 * 1000);
  this.connectedDisposables_ = new base.Disposables(connectedView);
};

/**
 * @param {remoting.Error} error
 */
remoting.AppRemotingActivity.prototype.onDisconnected = function(error) {
  if (error.isNone()) {
    chrome.app.window.current().close();
  } else {
    this.onConnectionDropped_();
  }
};

/**
 * @param {!remoting.Error} error
 */
remoting.AppRemotingActivity.prototype.onConnectionFailed = function(error) {
  remoting.LoadingWindow.close();
  this.showErrorMessage_(error);
  this.cleanup_();
};

/** @private */
remoting.AppRemotingActivity.prototype.onConnectionDropped_ = function() {
  // Don't dispose the session here to keep the plugin alive so that we can show
  // the last frame of the remote application window.
  base.dispose(this.connectedDisposables_);
  this.connectedDisposables_ = null;

  var rootElement = /** @type {HTMLDialogElement} */ (
      document.getElementById('connection-dropped-dialog'));

  var dialog = new remoting.Html5ModalDialog({
    dialog: rootElement,
    primaryButton: rootElement.querySelector('.restart-button'),
    secondaryButton: rootElement.querySelector('.close-button'),
    closeOnEscape: false
  });

  var that = this;
  dialog.show().then(function(/** remoting.MessageDialog.Result */ result) {
    if (result === remoting.MessageDialog.Result.PRIMARY) {
      // Hide the windows of the remote application with setDesktopRects([])
      // before tearing down the plugin.
      remoting.windowShape.setDesktopRects([]);
      that.cleanup_();
      that.start();
    } else {
      chrome.app.window.current().close();
    }
  });
};

/**
 * @param {!remoting.Error} error The error to be localized and displayed.
 * @private
 */
remoting.AppRemotingActivity.prototype.showErrorMessage_ = function(error) {
  console.error('Connection failed: ' + error.toString());
  remoting.MessageWindow.showErrorMessage(
      remoting.app.getApplicationName(),
      chrome.i18n.getMessage(error.getTag()));
};

})();