-
Notifications
You must be signed in to change notification settings - Fork 119
/
receiver.js
266 lines (232 loc) · 8.35 KB
/
receiver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/**
Copyright 2022 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
import { CastQueue } from './queuing.js';
import { MediaFetcher } from './media_fetcher.js';
import { AdsTracker, SenderTracker, ContentTracker } from './cast_analytics.js';
/**
* @fileoverview This sample demonstrates how to build your own Web Receiver for
* use with Google Cast. The main receiver implementation is provided in this
* file which sets up access to the CastReceiverContext and PlayerManager. Some
* added functionality can be enabled by uncommenting some of the code blocks
* below.
*/
/*
* Convenience variables to access the CastReceiverContext and PlayerManager.
*/
const context = cast.framework.CastReceiverContext.getInstance();
const playerManager = context.getPlayerManager();
/*
* Constant to be used for fetching media by entity from sample repository.
*/
const ID_REGEX = '\/?([^\/]+)\/?$';
/**
* Debug Logger
*/
const castDebugLogger = cast.debug.CastDebugLogger.getInstance();
const LOG_RECEIVER_TAG = 'Receiver';
/*
* WARNING: Make sure to turn off debug logger for production release as it
* may expose details of your app.
* Uncomment below line to enable debug logger, show a 'DEBUG MODE' tag at
* top left corner and show debug overlay.
*/
// context.addEventListener(cast.framework.system.EventType.READY, () => {
// if (!castDebugLogger.debugOverlayElement_) {
// /**
// * Enable debug logger and show a 'DEBUG MODE' tag at
// * top left corner.
// */
// castDebugLogger.setEnabled(true);
// /**
// * Show debug overlay.
// */
// castDebugLogger.showDebugLogs(true);
// }
// });
/*
* Set verbosity level for Core events.
*/
castDebugLogger.loggerLevelByEvents = {
'cast.framework.events.category.CORE':
cast.framework.LoggerLevel.INFO,
'cast.framework.events.EventType.MEDIA_STATUS':
cast.framework.LoggerLevel.DEBUG
};
if (!castDebugLogger.loggerLevelByTags) {
castDebugLogger.loggerLevelByTags = {};
}
/*
* Set verbosity level for custom tag.
* Enables log messages for error, warn, info and debug.
*/
castDebugLogger.loggerLevelByTags[LOG_RECEIVER_TAG] =
cast.framework.LoggerLevel.DEBUG;
/*
* Example of how to listen for events on playerManager.
*/
playerManager.addEventListener(
cast.framework.events.EventType.ERROR, (event) => {
castDebugLogger.error(LOG_RECEIVER_TAG,
'Detailed Error Code - ' + event.detailedErrorCode);
if (event && event.detailedErrorCode == 905) {
castDebugLogger.error(LOG_RECEIVER_TAG,
'LOAD_FAILED: Verify the load request is set up ' +
'properly and the media is able to play.');
}
});
/*
* Example analytics tracking implementation. To enable this functionality see
* the implmentation and complete the TODO item in ./google_analytics.js. Once
* complete uncomment the the calls to startTracking below to enable each
* Tracker.
*/
const adTracker = new AdsTracker();
const senderTracker = new SenderTracker();
const contentTracker = new ContentTracker();
// adTracker.startTracking();
// senderTracker.startTracking();
// contentTracker.startTracking();
/**
* Modifies the provided mediaInformation by adding a pre-roll break clip to it.
* @param {cast.framework.messages.MediaInformation} mediaInformation The target
* MediaInformation to be modified.
* @return {Promise} An empty promise.
*/
function addBreaks(mediaInformation) {
castDebugLogger.debug(LOG_RECEIVER_TAG, "addBreaks: " +
JSON.stringify(mediaInformation));
return MediaFetcher.fetchMediaById('fbb_ad')
.then((clip1) => {
mediaInformation.breakClips = [
{
id: 'fbb_ad',
title: clip1.title,
contentUrl: clip1.stream.dash,
contentType: 'application/dash+xml',
whenSkippable: 5
}
];
mediaInformation.breaks = [
{
id: 'pre-roll',
breakClipIds: ['fbb_ad'],
position: 0
}
];
});
}
/*
* Intercept the LOAD request to load and set the contentUrl.
*/
playerManager.setMessageInterceptor(
cast.framework.messages.MessageType.LOAD, loadRequestData => {
castDebugLogger.debug(LOG_RECEIVER_TAG,
`loadRequestData: ${JSON.stringify(loadRequestData)}`);
// If the loadRequestData is incomplete, return an error message.
if (!loadRequestData || !loadRequestData.media) {
const error = new cast.framework.messages.ErrorData(
cast.framework.messages.ErrorType.LOAD_FAILED);
error.reason = cast.framework.messages.ErrorReason.INVALID_REQUEST;
return error;
}
// Check all content source fields for the asset URL or ID.
let source = loadRequestData.media.contentUrl
|| loadRequestData.media.entity || loadRequestData.media.contentId;
// If there is no source or a malformed ID then return an error.
if (!source || source == "" || !source.match(ID_REGEX)) {
let error = new cast.framework.messages.ErrorData(
cast.framework.messages.ErrorType.LOAD_FAILED);
error.reason = cast.framework.messages.ErrorReason.INVALID_REQUEST;
return error;
}
let sourceId = source.match(ID_REGEX)[1];
// Optionally add breaks to the media information and set the contentUrl.
return Promise.resolve()
// .then(() => addBreaks(loadRequestData.media)) // Uncomment to enable ads.
.then(() => {
// If the source is a url that points to an asset don't fetch from the
// content repository.
if (sourceId.includes('.')) {
castDebugLogger.debug(LOG_RECEIVER_TAG,
"Interceptor received full URL");
loadRequestData.media.contentUrl = source;
return loadRequestData;
} else {
// Fetch the contentUrl if provided an ID or entity URL.
castDebugLogger.debug(LOG_RECEIVER_TAG, "Interceptor received ID");
return MediaFetcher.fetchMediaInformationById(sourceId)
.then((mediaInformation) => {
loadRequestData.media = mediaInformation;
return loadRequestData;
})
}
})
.catch((errorMessage) => {
let error = new cast.framework.messages.ErrorData(
cast.framework.messages.ErrorType.LOAD_FAILED);
error.reason = cast.framework.messages.ErrorReason.INVALID_REQUEST;
castDebugLogger.error(LOG_RECEIVER_TAG, errorMessage);
return error;
});
}
);
/*
* Set the control buttons in the UI controls.
*/
const controls = cast.framework.ui.Controls.getInstance();
controls.clearDefaultSlotAssignments();
// Assign buttons to control slots.
controls.assignButton(
cast.framework.ui.ControlsSlot.SLOT_SECONDARY_1,
cast.framework.ui.ControlsButton.QUEUE_PREV
);
controls.assignButton(
cast.framework.ui.ControlsSlot.SLOT_PRIMARY_1,
cast.framework.ui.ControlsButton.CAPTIONS
);
controls.assignButton(
cast.framework.ui.ControlsSlot.SLOT_PRIMARY_2,
cast.framework.ui.ControlsButton.SEEK_FORWARD_15
);
controls.assignButton(
cast.framework.ui.ControlsSlot.SLOT_SECONDARY_2,
cast.framework.ui.ControlsButton.QUEUE_NEXT
);
/*
* Configure the CastReceiverOptions.
*/
const castReceiverOptions = new cast.framework.CastReceiverOptions();
/*
* Set the player configuration.
*/
const playbackConfig = new cast.framework.PlaybackConfig();
playbackConfig.autoResumeDuration = 5;
castReceiverOptions.playbackConfig = playbackConfig;
castDebugLogger.info(LOG_RECEIVER_TAG,
`autoResumeDuration set to: ${playbackConfig.autoResumeDuration}`);
/*
* Set the SupportedMediaCommands.
*/
castReceiverOptions.supportedCommands =
cast.framework.messages.Command.ALL_BASIC_MEDIA |
cast.framework.messages.Command.QUEUE_PREV |
cast.framework.messages.Command.QUEUE_NEXT |
cast.framework.messages.Command.STREAM_TRANSFER
/*
* Optionally enable a custom queue implementation. Custom queues allow the
* receiver app to manage and add content to the playback queue. Uncomment the
* line below to enable the queue.
*/
// castReceiverOptions.queue = new CastQueue();
context.start(castReceiverOptions);