Updating XTBs based on .GRDs from branch master
[chromium-blink-merge.git] / remoting / webapp / crd / js / host_controller.js
blob613396946471ca1a6c624bbc5d211e4e388de721
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.
5 'use strict';
7 /** @suppress {duplicate} */
8 var remoting = remoting || {};
10 /** @constructor */
11 remoting.HostController = function() {
12   /** @type {remoting.HostDaemonFacade} @private */
13   this.hostDaemonFacade_ = new remoting.HostDaemonFacade();
15   /** @param {string} version */
16   var printVersion = function(version) {
17     if (version == '') {
18       console.log('Host not installed.');
19     } else {
20       console.log('Host version: ' + version);
21     }
22   };
24   this.getLocalHostVersion()
25       .then(printVersion)
26       .catch(function() {
27         console.log('Host version not available.');
28       });
31 // The values in the enums below are duplicated in daemon_controller.h except
32 // for NOT_INSTALLED.
33 /** @enum {number} */
34 remoting.HostController.State = {
35   NOT_IMPLEMENTED: 0,
36   NOT_INSTALLED: 1,
37   STOPPED: 2,
38   STARTING: 3,
39   STARTED: 4,
40   STOPPING: 5,
41   UNKNOWN: 6
44 /**
45  * @param {string} state The host controller state name.
46  * @return {remoting.HostController.State} The state enum value.
47  */
48 remoting.HostController.State.fromString = function(state) {
49   if (!remoting.HostController.State.hasOwnProperty(state)) {
50     throw "Invalid HostController.State: " + state;
51   }
52   return remoting.HostController.State[state];
55 /** @enum {number} */
56 remoting.HostController.AsyncResult = {
57   OK: 0,
58   FAILED: 1,
59   CANCELLED: 2,
60   FAILED_DIRECTORY: 3
63 /**
64  * @param {string} result The async result name.
65  * @return {remoting.HostController.AsyncResult} The result enum value.
66  */
67 remoting.HostController.AsyncResult.fromString = function(result) {
68   if (!remoting.HostController.AsyncResult.hasOwnProperty(result)) {
69     throw "Invalid HostController.AsyncResult: " + result;
70   }
71   return remoting.HostController.AsyncResult[result];
74 /**
75  * Set of features for which hasFeature() can be used to test.
76  *
77  * @enum {string}
78  */
79 remoting.HostController.Feature = {
80   PAIRING_REGISTRY: 'pairingRegistry',
81   OAUTH_CLIENT: 'oauthClient'
84 /**
85  * Information relating to user consent to collect usage stats.  The
86  * fields are:
87  *
88  *   supported: True if crash dump reporting is supported by the host.
89  *
90  *   allowed: True if crash dump reporting is allowed.
91  *
92  *   setByPolicy: True if crash dump reporting is controlled by policy.
93  *
94  * @typedef {{
95  *   supported:boolean,
96  *   allowed:boolean,
97  *   setByPolicy:boolean
98  * }}
99  */
100 remoting.UsageStatsConsent;
103  * @typedef {{
104  *   userEmail:string,
105  *   refreshToken:string
106  * }}
107  */
108 remoting.XmppCredentials;
111  * @typedef {{
112  *   privateKey:string,
113  *   publicKey:string
114  * }}
115  */
116 remoting.KeyPair;
119  * @param {remoting.HostController.Feature} feature The feature to test for.
120  * @return {!Promise<boolean>} A promise that always resolves.
121  */
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>}
130  */
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.
141  */
142 remoting.HostController.prototype.start = function(hostPin, consent) {
143   /** @type {remoting.HostController} */
144   var that = this;
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) {
152     if (hasOauth) {
153       return that.hostDaemonFacade_.getHostClientId();
154     } else {
155       return null;
156     }
157   });
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([
164     hostClientIdPromise,
165     hostNamePromise,
166     keyPairPromise
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);
174   });
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;
180   });
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);
186   });
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) {
195             return {
196               userEmail: registerResult.email,
197               refreshToken: token
198             };
199           });
200     } else {
201       // Use auth code supplied by Chromoting registry.
202       return that.hostDaemonFacade_.getCredentialsFromAuthCode(
203           registerResult.authCode);
204     }
205   });
207   // Build the host configuration.
208   /** @type {!Promise<!Object>} */
209   var hostConfigPromise = Promise.all([
210     hostNamePromise,
211     pinHashPromise,
212     xmppCredsPromise,
213     keyPairPromise,
214     hostOwnerPromise,
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]);
224     var registerResult =
225         /** @type {remoting.HostListApi.RegisterResult} */ (a[6]);
226     var hostConfig = {
227       xmpp_login: xmppCreds.userEmail,
228       oauth_refresh_token: xmppCreds.refreshToken,
229       host_name: hostName,
230       host_secret_hash: hostSecretHash,
231       private_key: keyPair.privateKey,
232       host_owner: hostOwner
233     };
234     if (hostOwnerEmail != hostOwner) {
235       hostConfig['host_owner_email'] = hostOwnerEmail;
236     }
237     hostConfig['host_id'] = registerResult.hostId;
238     return hostConfig;
239   });
241   // Start the daemon.
242   /** @type {!Promise<remoting.HostController.AsyncResult>} */
243   var startDaemonResultPromise =
244       hostConfigPromise.then(function(hostConfig) {
245         return that.hostDaemonFacade_.startDaemon(hostConfig, consent);
246       });
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);
256           });
257         });
258       } else if (result == remoting.HostController.AsyncResult.CANCELLED) {
259         throw new remoting.Error(remoting.Error.Tag.CANCELLED);
260       } else {
261         throw remoting.Error.unexpected();
262       }
263     }).catch(function(error) {
264       remoting.hostList.unregisterHostById(hostId);
265       throw error;
266     });
267   });
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
274  *     error.
275  * @return {void} Nothing.
276  */
277 remoting.HostController.prototype.stop = function(onDone, onError) {
278   /** @type {remoting.HostController} */
279   var that = this;
281   /** @param {string?} hostId The host id of the local host. */
282   function unregisterHost(hostId) {
283     if (hostId) {
284       remoting.hostList.unregisterHostById(hostId, onDone);
285       return;
286     }
287     onDone();
288   }
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));
296     } else {
297       onError(remoting.Error.unexpected());
298     }
299   }
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.
310  */
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
320  *     error.
321  * @return {void} Nothing.
322  */
323 remoting.HostController.prototype.updatePin = function(newPin, onDone,
324                                                        onError) {
325   /** @type {remoting.HostController} */
326   var that = this;
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));
334     } else {
335       onError(remoting.Error.unexpected());
336     }
337   }
339   /** @param {string} pinHash */
340   function updateDaemonConfigWithHash(pinHash) {
341     var newConfig = {
342       host_secret_hash: pinHash
343     };
344     that.hostDaemonFacade_.updateDaemonConfig(newConfig).then(
345         onConfigUpdated, remoting.Error.handler(onError));
346   }
348   /** @param {Object} config */
349   function onConfig(config) {
350     if (!isHostConfigValid_(config)) {
351       onError(remoting.Error.unexpected());
352       return;
353     }
354     /** @type {string} */
355     var hostId = base.getStringAttr(config, 'host_id');
356     that.hostDaemonFacade_.getPinHash(hostId, newPin).then(
357         updateDaemonConfigWithHash, remoting.Error.handler(onError));
358   }
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
370  *     callback.
371  */
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);
378   }
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.
387  */
388 remoting.HostController.prototype.getLocalHostId = function(onDone) {
389   /** @type {remoting.HostController} */
390   var that = this;
391   /** @param {Object} config */
392   function onConfig(config) {
393     var hostId = null;
394     if (isHostConfigValid_(config)) {
395       hostId = base.getStringAttr(config, 'host_id');
396     }
397     onDone(hostId);
398   };
400   this.hostDaemonFacade_.getDaemonConfig().then(onConfig, function(error) {
401     onDone(null);
402   });
406  * @return {Promise<string>} Promise that resolves with the host version, if
407  *     installed, or rejects otherwise.
408  */
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
418  * @return {void}
419  */
420 remoting.HostController.prototype.getPairedClients = function(onDone,
421                                                               onError) {
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.
432  * @return {void}
433  */
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.
445  * @return {void}
446  */
447 remoting.HostController.prototype.clearPairedClients = function(
448     onDone, onError) {
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.
458  * @private
459  * @return {!Promise<string>}
460  */
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) {
468       switch (state) {
469         case remoting.SignalStrategy.State.CONNECTED:
470         var jid = signalStrategy.getJid().split('/')[0].toLowerCase();
471         base.dispose(signalStrategy);
472         signalStrategy = null;
473         resolve(jid);
474         break;
476         case remoting.SignalStrategy.State.FAILED:
477         var error = signalStrategy.getError();
478         base.dispose(signalStrategy);
479         signalStrategy = null;
480         reject(error);
481         break;
482       }
483     };
485     signalStrategy = remoting.SignalStrategy.create();
486     signalStrategy.setStateChangedCallback(onState);
487   });
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);
494     });
495   });
497   return result;
500 /** @type {remoting.HostController} */
501 remoting.hostController = null;