Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / remoting / webapp / client_screen.js
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.
4
5 /**
6  * @fileoverview
7  * Functions related to the 'client screen' for Chromoting.
8  */
9
10 'use strict';
11
12 /** @suppress {duplicate} */
13 var remoting = remoting || {};
14
15 /**
16  * @type {remoting.SessionConnector} The connector object, set when a connection
17  *     is initiated.
18  */
19 remoting.connector = null;
20
21 /**
22  * @type {remoting.ClientSession} The client session object, set once the
23  *     connector has invoked its onOk callback.
24  */
25 remoting.clientSession = null;
26
27 /**
28  * Initiate an IT2Me connection.
29  */
30 remoting.connectIT2Me = function() {
31   remoting.ensureSessionConnector_();
32   var accessCode = document.getElementById('access-code-entry').value;
33   remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
34   remoting.connector.connectIT2Me(accessCode);
35 };
36
37 /**
38  * Update the remoting client layout in response to a resize event.
39  *
40  * @return {void} Nothing.
41  */
42 remoting.onResize = function() {
43   if (remoting.clientSession) {
44     remoting.clientSession.onResize();
45   }
46 };
47
48 /**
49  * Handle changes in the visibility of the window, for example by pausing video.
50  *
51  * @return {void} Nothing.
52  */
53 remoting.onVisibilityChanged = function() {
54   if (remoting.clientSession) {
55     remoting.clientSession.pauseVideo(
56       ('hidden' in document) ? document.hidden : document.webkitHidden);
57   }
58 }
59
60 /**
61  * Disconnect the remoting client.
62  *
63  * @return {void} Nothing.
64  */
65 remoting.disconnect = function() {
66   if (!remoting.clientSession) {
67     return;
68   }
69   if (remoting.clientSession.getMode() == remoting.ClientSession.Mode.IT2ME) {
70     remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED_IT2ME);
71   } else {
72     remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED_ME2ME);
73   }
74   remoting.clientSession.disconnect(true);
75   remoting.clientSession = null;
76   console.log('Disconnected.');
77 };
78
79 /**
80  * Sends a Ctrl-Alt-Del sequence to the remoting client.
81  *
82  * @return {void} Nothing.
83  */
84 remoting.sendCtrlAltDel = function() {
85   if (remoting.clientSession) {
86     console.log('Sending Ctrl-Alt-Del.');
87     remoting.clientSession.sendCtrlAltDel();
88   }
89 };
90
91 /**
92  * Sends a Print Screen keypress to the remoting client.
93  *
94  * @return {void} Nothing.
95  */
96 remoting.sendPrintScreen = function() {
97   if (remoting.clientSession) {
98     console.log('Sending Print Screen.');
99     remoting.clientSession.sendPrintScreen();
100   }
101 };
102
103 /**
104  * Callback function called when the state of the client plugin changes. The
105  * current state is available via the |state| member variable.
106  *
107  * @param {number} oldState The previous state of the plugin.
108  * @param {number} newState The current state of the plugin.
109  */
110 function onClientStateChange_(oldState, newState) {
111   switch (newState) {
112     case remoting.ClientSession.State.CLOSED:
113       console.log('Connection closed by host');
114       if (remoting.clientSession.getMode() ==
115           remoting.ClientSession.Mode.IT2ME) {
116         remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED_IT2ME);
117       } else {
118         remoting.setMode(remoting.AppMode.CLIENT_SESSION_FINISHED_ME2ME);
119       }
120       break;
121
122     case remoting.ClientSession.State.FAILED:
123       var error = remoting.clientSession.getError();
124       console.error('Client plugin reported connection failed: ' + error);
125       if (error == null) {
126         error = remoting.Error.UNEXPECTED;
127       }
128       showConnectError_(error);
129       break;
130
131     default:
132       console.error('Unexpected client plugin state: ' + newState);
133       // This should only happen if the web-app and client plugin get out of
134       // sync, so MISSING_PLUGIN is a suitable error.
135       showConnectError_(remoting.Error.MISSING_PLUGIN);
136       break;
137   }
138   remoting.clientSession.disconnect(false);
139   remoting.clientSession.removePlugin();
140   remoting.clientSession = null;
141 }
142
143 /**
144  * Show a client-side error message.
145  *
146  * @param {remoting.Error} errorTag The error to be localized and
147  *     displayed.
148  * @return {void} Nothing.
149  */
150 function showConnectError_(errorTag) {
151   console.error('Connection failed: ' + errorTag);
152   var errorDiv = document.getElementById('connect-error-message');
153   l10n.localizeElementFromTag(errorDiv, /** @type {string} */ (errorTag));
154   remoting.accessCode = '';
155   var mode = remoting.clientSession ? remoting.clientSession.getMode()
156                                     : remoting.connector.getConnectionMode();
157   if (mode == remoting.ClientSession.Mode.IT2ME) {
158     remoting.setMode(remoting.AppMode.CLIENT_CONNECT_FAILED_IT2ME);
159   } else {
160     remoting.setMode(remoting.AppMode.CLIENT_CONNECT_FAILED_ME2ME);
161   }
162 }
163
164 /**
165  * Set the text on the buttons shown under the error message so that they are
166  * easy to understand in the case where a successful connection failed, as
167  * opposed to the case where a connection never succeeded.
168  */
169 function setConnectionInterruptedButtonsText_() {
170   var button1 = document.getElementById('client-reconnect-button');
171   l10n.localizeElementFromTag(button1, /*i18n-content*/'RECONNECT');
172   button1.removeAttribute('autofocus');
173   var button2 = document.getElementById('client-finished-me2me-button');
174   l10n.localizeElementFromTag(button2, /*i18n-content*/'OK');
175   button2.setAttribute('autofocus', 'autofocus');
176 }
177
178 /**
179  * Timer callback to update the statistics panel.
180  */
181 function updateStatistics_() {
182   if (!remoting.clientSession ||
183       remoting.clientSession.getState() !=
184       remoting.ClientSession.State.CONNECTED) {
185     return;
186   }
187   var perfstats = remoting.clientSession.getPerfStats();
188   remoting.stats.update(perfstats);
189   remoting.clientSession.logStatistics(perfstats);
190   // Update the stats once per second.
191   window.setTimeout(updateStatistics_, 1000);
192 }
193
194 /**
195  * Entry-point for Me2Me connections, handling showing of the host-upgrade nag
196  * dialog if necessary.
197  *
198  * @param {string} hostId The unique id of the host.
199  * @return {void} Nothing.
200  */
201 remoting.connectMe2Me = function(hostId) {
202   var host = remoting.hostList.getHostForId(hostId);
203   if (!host) {
204     showConnectError_(remoting.Error.HOST_IS_OFFLINE);
205     return;
206   }
207   var webappVersion = chrome.runtime.getManifest().version;
208   if (remoting.Host.needsUpdate(host, webappVersion)) {
209     var needsUpdateMessage =
210         document.getElementById('host-needs-update-message');
211     l10n.localizeElementFromTag(needsUpdateMessage,
212                                 /*i18n-content*/'HOST_NEEDS_UPDATE_TITLE',
213                                 host.hostName);
214     /** @type {Element} */
215     var connect = document.getElementById('host-needs-update-connect-button');
216     /** @type {Element} */
217     var cancel = document.getElementById('host-needs-update-cancel-button');
218     /** @param {Event} event */
219     var onClick = function(event) {
220       connect.removeEventListener('click', onClick, false);
221       cancel.removeEventListener('click', onClick, false);
222       if (event.target == connect) {
223         remoting.connectMe2MeHostVersionAcknowledged_(host);
224       } else {
225         remoting.setMode(remoting.AppMode.HOME);
226       }
227     }
228     connect.addEventListener('click', onClick, false);
229     cancel.addEventListener('click', onClick, false);
230     remoting.setMode(remoting.AppMode.CLIENT_HOST_NEEDS_UPGRADE);
231   } else {
232     remoting.connectMe2MeHostVersionAcknowledged_(host);
233   }
234 };
235
236 /**
237  * Shows PIN entry screen localized to include the host name, and registers
238  * a host-specific one-shot event handler for the form submission.
239  *
240  * @param {remoting.Host} host The Me2Me host to which to connect.
241  * @return {void} Nothing.
242  */
243 remoting.connectMe2MeHostVersionAcknowledged_ = function(host) {
244   remoting.ensureSessionConnector_();
245   remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
246
247   /**
248    * @param {string} tokenUrl Token-issue URL received from the host.
249    * @param {string} scope OAuth scope to request the token for.
250    * @param {string} hostPublicKey Host public key (DER and Base64 encoded).
251    * @param {function(string, string):void} onThirdPartyTokenFetched Callback.
252    */
253   var fetchThirdPartyToken = function(
254       tokenUrl, hostPublicKey, scope, onThirdPartyTokenFetched) {
255     var thirdPartyTokenFetcher = new remoting.ThirdPartyTokenFetcher(
256         tokenUrl, hostPublicKey, scope, host.tokenUrlPatterns,
257         onThirdPartyTokenFetched);
258     thirdPartyTokenFetcher.fetchToken();
259   };
260
261   /**
262    * @param {boolean} supportsPairing
263    * @param {function(string):void} onPinFetched
264    */
265   var requestPin = function(supportsPairing, onPinFetched) {
266     /** @type {Element} */
267     var pinForm = document.getElementById('pin-form');
268     /** @type {Element} */
269     var pinCancel = document.getElementById('cancel-pin-entry-button');
270     /** @type {Element} */
271     var rememberPin = document.getElementById('remember-pin');
272     /** @type {Element} */
273     var rememberPinCheckbox = document.getElementById('remember-pin-checkbox');
274     /**
275      * Event handler for both the 'submit' and 'cancel' actions. Using
276      * a single handler for both greatly simplifies the task of making
277      * them one-shot. If separate handlers were used, each would have
278      * to unregister both itself and the other.
279      *
280      * @param {Event} event The click or submit event.
281      */
282     var onSubmitOrCancel = function(event) {
283       pinForm.removeEventListener('submit', onSubmitOrCancel, false);
284       pinCancel.removeEventListener('click', onSubmitOrCancel, false);
285       var pinField = document.getElementById('pin-entry');
286       var pin = pinField.value;
287       pinField.value = '';
288       if (event.target == pinForm) {
289         event.preventDefault();
290
291         // Set the focus away from the password field. This has to be done
292         // before the password field gets hidden, to work around a Blink
293         // clipboard-handling bug - http://crbug.com/281523.
294         document.getElementById('pin-connect-button').focus();
295
296         remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
297         onPinFetched(pin);
298         if (/** @type {boolean} */(rememberPinCheckbox.checked)) {
299           remoting.connector.pairingRequested = true;
300         }
301       } else {
302         remoting.setMode(remoting.AppMode.HOME);
303       }
304     };
305     pinForm.addEventListener('submit', onSubmitOrCancel, false);
306     pinCancel.addEventListener('click', onSubmitOrCancel, false);
307     rememberPin.hidden = !supportsPairing;
308     rememberPinCheckbox.checked = false;
309     var message = document.getElementById('pin-message');
310     l10n.localizeElement(message, host.hostName);
311     remoting.setMode(remoting.AppMode.CLIENT_PIN_PROMPT);
312   };
313
314   /** @param {Object} settings */
315   var connectMe2MeHostSettingsRetrieved = function(settings) {
316     /** @type {string} */
317     var clientId = '';
318     /** @type {string} */
319     var sharedSecret = '';
320     var pairingInfo = /** @type {Object} */ (settings['pairingInfo']);
321     if (pairingInfo) {
322       clientId = /** @type {string} */ (pairingInfo['clientId']);
323       sharedSecret = /** @type {string} */ (pairingInfo['sharedSecret']);
324     }
325     remoting.connector.connectMe2Me(host, requestPin, fetchThirdPartyToken,
326                                     clientId, sharedSecret);
327   }
328
329   remoting.HostSettings.load(host.hostId, connectMe2MeHostSettingsRetrieved);
330 };
331
332 /** @param {remoting.ClientSession} clientSession */
333 remoting.onConnected = function(clientSession) {
334   remoting.clientSession = clientSession;
335   remoting.clientSession.setOnStateChange(onClientStateChange_);
336   setConnectionInterruptedButtonsText_();
337   var connectedTo = document.getElementById('connected-to');
338   connectedTo.innerText = remoting.connector.getHostDisplayName();
339   document.getElementById('access-code-entry').value = '';
340   remoting.setMode(remoting.AppMode.IN_SESSION);
341   remoting.toolbar.center();
342   remoting.toolbar.preview();
343   remoting.clipboard.startSession();
344   updateStatistics_();
345   if (remoting.connector.pairingRequested) {
346     /**
347      * @param {string} clientId
348      * @param {string} sharedSecret
349      */
350     var onPairingComplete = function(clientId, sharedSecret) {
351       var pairingInfo = {
352         pairingInfo: {
353           clientId: clientId,
354           sharedSecret: sharedSecret
355         }
356       };
357       remoting.HostSettings.save(remoting.connector.getHostId(), pairingInfo);
358       remoting.connector.updatePairingInfo(clientId, sharedSecret);
359     };
360     // Use the platform name as a proxy for the local computer name.
361     // TODO(jamiewalch): Use a descriptive name for the local computer, for
362     // example, its Chrome Sync name.
363     var clientName = '';
364     if (navigator.platform.indexOf('Mac') != -1) {
365       clientName = 'Mac';
366     } else if (navigator.platform.indexOf('Win32') != -1) {
367       clientName = 'Windows';
368     } else if (navigator.userAgent.match(/\bCrOS\b/)) {
369       clientName = 'ChromeOS';
370     } else if (navigator.platform.indexOf('Linux') != -1) {
371       clientName = 'Linux';
372     } else {
373       console.log('Unrecognized client platform. Using navigator.platform.');
374       clientName = navigator.platform;
375     }
376     clientSession.requestPairing(clientName, onPairingComplete);
377   }
378 };
379
380 /**
381  * Extension message handler.
382  *
383  * @param {string} type The type of the extension message.
384  * @param {string} data The payload of the extension message.
385  * @return {boolean} Return true if the extension message was recognized.
386  */
387 remoting.onExtensionMessage = function(type, data) {
388   return false;
389 };
390
391 /**
392  * Create a session connector if one doesn't already exist.
393  */
394 remoting.ensureSessionConnector_ = function() {
395   if (!remoting.connector) {
396     remoting.connector = new remoting.SessionConnector(
397         document.getElementById('client-plugin-container'),
398         remoting.onConnected,
399         showConnectError_, remoting.onExtensionMessage);
400   }
401 };