1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 /** @suppress {duplicate} */
8 var remoting
= remoting
|| {};
11 remoting
.HostController = function() {
12 /** @type {remoting.HostDaemonFacade} @private */
13 this.hostDaemonFacade_
= new remoting
.HostDaemonFacade();
15 /** @param {string} version */
16 var printVersion = function(version
) {
18 console
.log('Host not installed.');
20 console
.log('Host version: ' + version
);
24 this.getLocalHostVersion()
27 console
.log('Host version not available.');
31 // The values in the enums below are duplicated in daemon_controller.h except
34 remoting
.HostController
.State
= {
45 * @param {string} state The host controller state name.
46 * @return {remoting.HostController.State} The state enum value.
48 remoting
.HostController
.State
.fromString = function(state
) {
49 if (!remoting
.HostController
.State
.hasOwnProperty(state
)) {
50 throw "Invalid HostController.State: " + state
;
52 return remoting
.HostController
.State
[state
];
56 remoting
.HostController
.AsyncResult
= {
64 * @param {string} result The async result name.
65 * @return {remoting.HostController.AsyncResult} The result enum value.
67 remoting
.HostController
.AsyncResult
.fromString = function(result
) {
68 if (!remoting
.HostController
.AsyncResult
.hasOwnProperty(result
)) {
69 throw "Invalid HostController.AsyncResult: " + result
;
71 return remoting
.HostController
.AsyncResult
[result
];
75 * Set of features for which hasFeature() can be used to test.
79 remoting
.HostController
.Feature
= {
80 PAIRING_REGISTRY
: 'pairingRegistry',
81 OAUTH_CLIENT
: 'oauthClient'
85 * Information relating to user consent to collect usage stats. The
88 * supported: True if crash dump reporting is supported by the host.
90 * allowed: True if crash dump reporting is allowed.
92 * setByPolicy: True if crash dump reporting is controlled by policy.
100 remoting
.UsageStatsConsent
;
105 * refreshToken:string
108 remoting
.XmppCredentials
;
119 * @param {remoting.HostController.Feature} feature The feature to test for.
120 * @return {!Promise<boolean>} A promise that always resolves.
122 remoting
.HostController
.prototype.hasFeature = function(feature
) {
123 // TODO(rmsousa): This could synchronously return a boolean, provided it were
124 // only called after native messaging is completely initialized.
125 return this.hostDaemonFacade_
.hasFeature(feature
);
129 * @return {!Promise<remoting.UsageStatsConsent>}
131 remoting
.HostController
.prototype.getConsent = function() {
132 return this.hostDaemonFacade_
.getUsageStatsConsent();
136 * Registers and starts the host.
138 * @param {string} hostPin Host PIN.
139 * @param {boolean} consent The user's consent to crash dump reporting.
140 * @return {!Promise<void>} A promise resolved once the host is started.
142 remoting
.HostController
.prototype.start = function(hostPin
, consent
) {
143 /** @type {remoting.HostController} */
146 // Start a bunch of requests with no side-effects.
147 var hostNamePromise
= this.hostDaemonFacade_
.getHostName();
148 var hasOauthPromise
=
149 this.hasFeature(remoting
.HostController
.Feature
.OAUTH_CLIENT
);
150 var keyPairPromise
= this.hostDaemonFacade_
.generateKeyPair();
151 var hostClientIdPromise
= hasOauthPromise
.then(function(hasOauth
) {
153 return that
.hostDaemonFacade_
.getHostClientId();
158 var hostOwnerPromise
= this.getClientBaseJid_();
160 // Register the host and extract an auth code from the host response
161 // and, optionally an email address for the robot account.
162 /** @type {!Promise<remoting.HostListApi.RegisterResult>} */
163 var registerResultPromise
= Promise
.all([
167 ]).then(function(/** Array */ a
) {
168 var hostClientId
= /** @type {string} */ (a
[0]);
169 var hostName
= /** @type {string} */ (a
[1]);
170 var keyPair
= /** @type {remoting.KeyPair} */ (a
[2]);
172 return remoting
.HostListApi
.getInstance().register(
173 hostName
, keyPair
.publicKey
, hostClientId
);
176 // For convenience, make the host ID available as a separate promise.
177 /** @type {!Promise<string>} */
178 var hostIdPromise
= registerResultPromise
.then(function(registerResult
) {
179 return registerResult
.hostId
;
182 // Get the PIN hash based on the host ID.
183 /** @type {!Promise<string>} */
184 var pinHashPromise
= hostIdPromise
.then(function(hostId
) {
185 return that
.hostDaemonFacade_
.getPinHash(hostId
, hostPin
);
188 // Get XMPP creditials.
189 var xmppCredsPromise
= registerResultPromise
.then(function(registerResult
) {
190 console
.assert(registerResult
.authCode
!= '', '|authCode| is empty.');
191 if (registerResult
.email
) {
192 // Use auth code and email supplied by GCD.
193 return that
.hostDaemonFacade_
.getRefreshTokenFromAuthCode(
194 registerResult
.authCode
).then(function(token
) {
196 userEmail
: registerResult
.email
,
201 // Use auth code supplied by Chromoting registry.
202 return that
.hostDaemonFacade_
.getCredentialsFromAuthCode(
203 registerResult
.authCode
);
207 // Build the host configuration.
208 /** @type {!Promise<!Object>} */
209 var hostConfigPromise
= Promise
.all([
215 remoting
.identity
.getEmail(),
216 registerResultPromise
217 ]).then(function(/** Array */ a
) {
218 var hostName
= /** @type {string} */ (a
[0]);
219 var hostSecretHash
= /** @type {string} */ (a
[1]);
220 var xmppCreds
= /** @type {remoting.XmppCredentials} */ (a
[2]);
221 var keyPair
= /** @type {remoting.KeyPair} */ (a
[3]);
222 var hostOwner
= /** @type {string} */ (a
[4]);
223 var hostOwnerEmail
= /** @type {string} */ (a
[5]);
225 /** @type {remoting.HostListApi.RegisterResult} */ (a
[6]);
227 xmpp_login
: xmppCreds
.userEmail
,
228 oauth_refresh_token
: xmppCreds
.refreshToken
,
230 host_secret_hash
: hostSecretHash
,
231 private_key
: keyPair
.privateKey
,
232 host_owner
: hostOwner
234 if (hostOwnerEmail
!= hostOwner
) {
235 hostConfig
['host_owner_email'] = hostOwnerEmail
;
237 hostConfig
['host_id'] = registerResult
.hostId
;
242 /** @type {!Promise<remoting.HostController.AsyncResult>} */
243 var startDaemonResultPromise
=
244 hostConfigPromise
.then(function(hostConfig
) {
245 return that
.hostDaemonFacade_
.startDaemon(hostConfig
, consent
);
248 // Update the UI or report an error.
249 return hostIdPromise
.then(function(hostId
) {
250 return startDaemonResultPromise
.then(function(result
) {
251 if (result
== remoting
.HostController
.AsyncResult
.OK
) {
252 return hostNamePromise
.then(function(hostName
) {
253 return keyPairPromise
.then(function(keyPair
) {
254 remoting
.hostList
.onLocalHostStarted(
255 hostName
, hostId
, keyPair
.publicKey
);
258 } else if (result
== remoting
.HostController
.AsyncResult
.CANCELLED
) {
259 throw new remoting
.Error(remoting
.Error
.Tag
.CANCELLED
);
261 throw remoting
.Error
.unexpected();
263 }).catch(function(error
) {
264 remoting
.hostList
.unregisterHostById(hostId
);
271 * Stop the daemon process.
272 * @param {function():void} onDone Callback to be called when done.
273 * @param {function(!remoting.Error):void} onError Callback to be called on
275 * @return {void} Nothing.
277 remoting
.HostController
.prototype.stop = function(onDone
, onError
) {
278 /** @type {remoting.HostController} */
281 /** @param {string?} hostId The host id of the local host. */
282 function unregisterHost(hostId
) {
284 remoting
.hostList
.unregisterHostById(hostId
, onDone
);
290 /** @param {remoting.HostController.AsyncResult} result */
291 function onStopped(result
) {
292 if (result
== remoting
.HostController
.AsyncResult
.OK
) {
293 that
.getLocalHostId(unregisterHost
);
294 } else if (result
== remoting
.HostController
.AsyncResult
.CANCELLED
) {
295 onError(new remoting
.Error(remoting
.Error
.Tag
.CANCELLED
));
297 onError(remoting
.Error
.unexpected());
301 this.hostDaemonFacade_
.stopDaemon().then(
302 onStopped
, remoting
.Error
.handler(onError
));
306 * Check the host configuration is valid (non-null, and contains both host_id
307 * and xmpp_login keys).
308 * @param {Object} config The host configuration.
309 * @return {boolean} True if it is valid.
311 function isHostConfigValid_(config
) {
312 return !!config
&& typeof config
['host_id'] == 'string' &&
313 typeof config
['xmpp_login'] == 'string';
317 * @param {string} newPin The new PIN to set
318 * @param {function():void} onDone Callback to be called when done.
319 * @param {function(!remoting.Error):void} onError Callback to be called on
321 * @return {void} Nothing.
323 remoting
.HostController
.prototype.updatePin = function(newPin
, onDone
,
325 /** @type {remoting.HostController} */
328 /** @param {remoting.HostController.AsyncResult} result */
329 function onConfigUpdated(result
) {
330 if (result
== remoting
.HostController
.AsyncResult
.OK
) {
331 that
.clearPairedClients(onDone
, onError
);
332 } else if (result
== remoting
.HostController
.AsyncResult
.CANCELLED
) {
333 onError(new remoting
.Error(remoting
.Error
.Tag
.CANCELLED
));
335 onError(remoting
.Error
.unexpected());
339 /** @param {string} pinHash */
340 function updateDaemonConfigWithHash(pinHash
) {
342 host_secret_hash
: pinHash
344 that
.hostDaemonFacade_
.updateDaemonConfig(newConfig
).then(
345 onConfigUpdated
, remoting
.Error
.handler(onError
));
348 /** @param {Object} config */
349 function onConfig(config
) {
350 if (!isHostConfigValid_(config
)) {
351 onError(remoting
.Error
.unexpected());
354 /** @type {string} */
355 var hostId
= base
.getStringAttr(config
, 'host_id');
356 that
.hostDaemonFacade_
.getPinHash(hostId
, newPin
).then(
357 updateDaemonConfigWithHash
, remoting
.Error
.handler(onError
));
360 // TODO(sergeyu): When crbug.com/121518 is fixed: replace this call
361 // with an unprivileged version if that is necessary.
362 this.hostDaemonFacade_
.getDaemonConfig().then(
363 onConfig
, remoting
.Error
.handler(onError
));
367 * Get the state of the local host.
369 * @param {function(remoting.HostController.State):void} onDone Completion
372 remoting
.HostController
.prototype.getLocalHostState = function(onDone
) {
373 /** @param {!remoting.Error} error */
374 function onError(error
) {
375 onDone((error
.hasTag(remoting
.Error
.Tag
.MISSING_PLUGIN
)) ?
376 remoting
.HostController
.State
.NOT_INSTALLED
:
377 remoting
.HostController
.State
.UNKNOWN
);
379 this.hostDaemonFacade_
.getDaemonState().then(
380 onDone
, remoting
.Error
.handler(onError
));
384 * Get the id of the local host, or null if it is not registered.
386 * @param {function(string?):void} onDone Completion callback.
388 remoting
.HostController
.prototype.getLocalHostId = function(onDone
) {
389 /** @type {remoting.HostController} */
391 /** @param {Object} config */
392 function onConfig(config
) {
394 if (isHostConfigValid_(config
)) {
395 hostId
= base
.getStringAttr(config
, 'host_id');
400 this.hostDaemonFacade_
.getDaemonConfig().then(onConfig
, function(error
) {
406 * @return {Promise<string>} Promise that resolves with the host version, if
407 * installed, or rejects otherwise.
409 remoting
.HostController
.prototype.getLocalHostVersion = function() {
410 return this.hostDaemonFacade_
.getDaemonVersion();
414 * Fetch the list of paired clients for this host.
416 * @param {function(Array<remoting.PairedClient>):void} onDone
417 * @param {function(!remoting.Error):void} onError
420 remoting
.HostController
.prototype.getPairedClients = function(onDone
,
422 this.hostDaemonFacade_
.getPairedClients().then(
423 onDone
, remoting
.Error
.handler(onError
));
427 * Delete a single paired client.
429 * @param {string} client The client id of the pairing to delete.
430 * @param {function():void} onDone Completion callback.
431 * @param {function(!remoting.Error):void} onError Error callback.
434 remoting
.HostController
.prototype.deletePairedClient = function(
435 client
, onDone
, onError
) {
436 this.hostDaemonFacade_
.deletePairedClient(client
).then(
437 onDone
, remoting
.Error
.handler(onError
));
441 * Delete all paired clients.
443 * @param {function():void} onDone Completion callback.
444 * @param {function(!remoting.Error):void} onError Error callback.
447 remoting
.HostController
.prototype.clearPairedClients = function(
449 this.hostDaemonFacade_
.clearPairedClients().then(
450 onDone
, remoting
.Error
.handler(onError
));
454 * Gets the host owner's base JID, used by the host for client authorization.
455 * In most cases this is the same as the owner's email address, but for
456 * non-Gmail accounts, it may be different.
459 * @return {!Promise<string>}
461 remoting
.HostController
.prototype.getClientBaseJid_ = function() {
462 /** @type {remoting.SignalStrategy} */
463 var signalStrategy
= null;
465 var result
= new Promise(function(resolve
, reject
) {
466 /** @param {remoting.SignalStrategy.State} state */
467 var onState = function(state
) {
469 case remoting
.SignalStrategy
.State
.CONNECTED
:
470 var jid
= signalStrategy
.getJid().split('/')[0].toLowerCase();
471 base
.dispose(signalStrategy
);
472 signalStrategy
= null;
476 case remoting
.SignalStrategy
.State
.FAILED
:
477 var error
= signalStrategy
.getError();
478 base
.dispose(signalStrategy
);
479 signalStrategy
= null;
485 signalStrategy
= remoting
.SignalStrategy
.create();
486 signalStrategy
.setStateChangedCallback(onState
);
489 var tokenPromise
= remoting
.identity
.getToken();
490 var emailPromise
= remoting
.identity
.getEmail();
491 tokenPromise
.then(function(/** string */ token
) {
492 emailPromise
.then(function(/** string */ email
) {
493 signalStrategy
.connect(remoting
.settings
.XMPP_SERVER
, email
, token
);
500 /** @type {remoting.HostController} */
501 remoting
.hostController
= null;