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