Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / ui / file_manager / video_player / js / cast / caster.js
1 // Copyright 2014 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 // This hack prevents a bug on the cast extension.
6 // TODO(yoshiki): Remove this once the cast extension supports Chrome apps.
7 // Although localStorage in Chrome app is not supported, but it's used in the
8 // cast extension. This line prevents an exception on using localStorage.
9 window.__defineGetter__('localStorage', function() { return {}; });
10
11 var APPLICATION_ID = '4CCB98DA';
12
13 util.addPageLoadHandler(function() {
14   initialize();
15 }.wrap());
16
17 /**
18  * Starts initialization of cast-related feature.
19  */
20 function initialize() {
21   if (window.loadMockCastExtensionForTest) {
22     // If the test flag is set, the mock extension for test will be laoded by
23     // the test script. Sets the handler to wait for loading.
24     onLoadCastExtension(initializeApi);
25     return;
26   }
27
28   CastExtensionDiscoverer.findInstalledExtension(function(foundId) {
29     if (foundId)
30       loadCastAPI(initializeApi);
31     else
32       console.info('No Google Cast extension is installed.');
33   }.wrap());
34 }
35
36 /**
37  * Loads the cast API extention. If not install, the extension is installed
38  * in background before load. The cast API will load the cast SDK automatically.
39  * The given callback is executes after the cast SDK extension is initialized.
40  *
41  * @param {function} callback Callback (executed asynchronously).
42  * @param {boolean=} opt_secondTry Spericy try if it's second call after
43  *     installation of Cast API extension.
44  */
45 function loadCastAPI(callback, opt_secondTry) {
46   var script = document.createElement('script');
47
48   var onError = function() {
49     script.removeEventListener('error', onError);
50     document.body.removeChild(script);
51
52     if (opt_secondTry) {
53       // Shows error message and exits if it's the 2nd try.
54       console.error('Google Cast API extension load failed.');
55       return;
56     }
57
58     // Installs the Google Cast API extension and retry loading.
59     chrome.fileManagerPrivate.installWebstoreItem(
60         'mafeflapfdfljijmlienjedomfjfmhpd',
61         true,  // Don't use installation prompt.
62         function() {
63           if (chrome.runtime.lastError) {
64             console.error('Google Cast API extension installation error.',
65                           chrome.runtime.lastError.message);
66             return;
67           }
68
69           console.info('Google Cast API extension installed.');
70           // Loads API again.
71           setTimeout(loadCastAPI.bind(null, callback, true));
72         }.wrap());
73   }.wrap();
74
75   // Trys to load the cast API extention which is defined in manifest.json.
76   script.src = '_modules/mafeflapfdfljijmlienjedomfjfmhpd/cast_sender.js';
77   script.addEventListener('error', onError);
78   script.addEventListener('load', onLoadCastExtension.bind(null, callback));
79   document.body.appendChild(script);
80 }
81
82 /**
83  * Loads the cast sdk extension.
84  * @param {function()} callback Callback (executed asynchronously).
85  */
86 function onLoadCastExtension(callback) {
87   if(!chrome.cast || !chrome.cast.isAvailable) {
88     var checkTimer = setTimeout(function() {
89       console.error('Either "Google Cast API" or "Google Cast" extension ' +
90                     'seems not to be installed?');
91     }.wrap(), 5000);
92
93     window['__onGCastApiAvailable'] = function(loaded, errorInfo) {
94       clearTimeout(checkTimer);
95
96       if (loaded)
97         callback();
98       else
99         console.error('Google Cast extension load failed.', errorInfo);
100     }.wrap();
101   } else {
102     setTimeout(callback);  // Runs asynchronously.
103   }
104 }
105
106 /**
107  * Initialize Cast API.
108  */
109 function initializeApi() {
110   var onSession = function() {
111     // TODO(yoshiki): Implement this.
112   };
113
114   var onInitSuccess = function() {
115     // TODO(yoshiki): Implement this.
116   };
117
118   /**
119    * @param {chrome.cast.Error} error
120    */
121   var onError = function(error) {
122     console.error('Error on Cast initialization.', error);
123   };
124
125   var sessionRequest = new chrome.cast.SessionRequest(APPLICATION_ID);
126   var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
127                                             onSession,
128                                             onReceiver);
129   chrome.cast.initialize(apiConfig, onInitSuccess, onError);
130 }
131
132 /**
133  * @param {chrome.cast.ReceiverAvailability} availability Availability of casts.
134  * @param {Array.<Object>} receivers List of casts.
135  */
136 function onReceiver(availability, receivers) {
137   if (availability === chrome.cast.ReceiverAvailability.AVAILABLE) {
138     if (!receivers) {
139       console.error('Receiver list is empty.');
140       receivers = [];
141     }
142
143     player.setCastList(receivers);
144   } else if (availability == chrome.cast.ReceiverAvailability.UNAVAILABLE) {
145     player.setCastList([]);
146   } else {
147     console.error('Unexpected response in onReceiver.', arguments);
148     player.setCastList([]);
149   }
150 }