forked from GoogleWebComponents/google-youtube-upload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google-youtube-upload.html
executable file
·684 lines (602 loc) · 21.1 KB
/
google-youtube-upload.html
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
<link rel="import" href="../google-apis/google-client-loader.html">
<link rel="import" href="../google-signin/google-signin.html">
<link rel="import" href="../iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../iron-pages/iron-pages.html">
<link rel="import" href="../paper-fab/paper-fab.html">
<link rel="import" href="../paper-styles/color.html">
<link rel="import" href="../paper-styles/typography.html">
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="./google-youtube-upload-icons.html">
<link rel="import" href="./md-gum-polyfill-import.html">
<link rel="import" href="./upload-import.html">
<!--
Element enabling you to upload videos to YouTube.
##### Examples
Manual upload with a `Video Upload` button once a video file is selected:
<google-youtube-upload client-id="..."></google-youtube-upload>
Automatic upload on video file select, with a custom title, and 'unlisted' privacy:
<google-youtube-upload
auto
video-title="My Awesome Video"
privacy-status="unlisted"
client-id="...">
</google-youtube-upload>
@demo
-->
<dom-module id="google-youtube-upload">
<style>
:host {
@apply(--layout-relative);
@apply(--paper-font-common-base);
display: block;
overflow: auto;
}
video {
max-height: 100%;
width: 100%;
}
p {
@apply(--paper-font-body1);
margin: 16px;
}
section {
@apply(--layout-center);
@apply(--layout-center-justified);
@apply(--layout-fit);
@apply(--layout-vertical);
}
section[name="record-video"] {
background-color: black;
}
.fabs {
@apply(--layout-horizontal);
position: absolute;
top: 0;
right: 0;
}
.fabs > paper-fab {
margin: 16px;
}
#profile {
border-radius: 50%;
cursor: pointer;
height: 40px;
left: 16px;
position: absolute;
top: 16px;
width: 40px;
z-index: 1;
}
</style>
<template>
<google-client-loader on-js-api-load="_loadChannels"></google-client-loader>
<template is="dom-if" if="[[_channel]]">
<img id="profile"
src="[[_channel.thumbnail]]"
title="Uploading as [[_channel.name]]"
on-tap="_transitionToLoginLogout">
</template>
<iron-pages attr-for-selected="name"
selected="[[_selectedSection]]">
<section name="no-client-id">
<p>
The developer using this <code><google-youtube-upload></code>
element did not properly set a <code>client-id</code> attribute.
</p>
<p>
Information on registering for an using the client id can be found in
the <a target="_blank" href="https://elements.polymer-project.org/elements/google-youtube-upload#property-clientId"><code><google-youtube-upload></code> documentation</a>.
</p>
</section>
<section name="login-logout">
<google-signin client-id="[[clientId]]"
scopes="https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtube.readonly"
on-google-signin-success="_handleSignedIn"
on-google-signed-out="_handleSignedOut">
</google-signin>
<template is="dom-if" if="[[_channel]]">
<div class="fabs">
<paper-fab icon="google-youtube-upload-icons:theaters"
mini
on-tap="_transitionToUploadFile"
title="Upload File">
</paper-fab>
<paper-fab icon="google-youtube-upload-icons:videocam"
mini
hidden$="[[!recordSupported]]"
on-tap="_transitionToRecordVideo"
title="Record Video">
</paper-fab>
</div>
</template>
</section>
<section name="upload-file">
<input type="file"
accept="video/*"
on-change="_handleFileChanged">
<p id="tos">
By clicking 'upload,' you certify that you own all rights to the
content or that you are authorized by the owner to make the content
publicly available on YouTube, and that it otherwise complies with
the YouTube Terms of Service located at
<a target="_blank" href="http://www.youtube.com/t/terms">http://www.youtube.com/t/terms</a>.
</p>
<div class="fabs">
<paper-fab icon="google-youtube-upload-icons:file-upload"
mini
on-tap="_handleUploadClicked"
disabled$="[[!_selectedFile]]"
hidden$="[[auto]]"
title="Upload to YouTube">
</paper-fab>
</div>
</section>
<section name="record-video">
<video id="get-user-media"
autoplay
muted$="[[!_calculateVideoControls(_recordingState)]]"
controls$="[[_calculateVideoControls(_recordingState)]]">
</video>
<div class="fabs">
<paper-fab icon="google-youtube-upload-icons:stop"
mini
hidden="[[_calculateStopButtonHidden(_recordingState)]]"
on-tap="_handleStopClicked"
title="Stop Recording">
</paper-fab>
<paper-fab icon="google-youtube-upload-icons:brightness-1"
mini
hidden="[[_calculateRecordButtonHidden(_recordingState)]]"
on-tap="_handleRecordClicked"
title="Start Recording">
</paper-fab>
<paper-fab icon="google-youtube-upload-icons:file-upload"
mini
hidden="[[_calculateRecordingUploadButtonHidden(_recordingState)]]"
on-tap="_handleRecordingUploadClicked"
title="Upload to YouTube">
</paper-fab>
</div>
</section>
<section name="thanks">
<p>Your video is being uploaded.</p>
</section>
</iron-pages>
</template>
</dom-module>
<script>
Polymer({
is: 'google-youtube-upload',
/**
* Fired when the upload begins.
*
* `e.detail` is set to the
* [file](https://developer.mozilla.org/en-US/docs/Web/API/File)
* being uploaded.
*
* @event youtube-upload-start
* @param {Object} e Event parameters.
*/
/**
* Fired while the upload is in progress.
*
* `e.detail.progressEvent` is set to the corresponding
* [XMLHttpRequestProgressEvent](http://www.w3.org/TR/progress-events/).
*
* `e.detail.estimatedSecondsRemaining` is set to an estimate of the time remaining
* in the upload, based on the average upload speed so far.
*
* `e.detail.bytesPerSecond` is set to the average number of bytes sent per second
* sent so far.
*
* `e.fractionComplete` is set to the fraction of the upload that's complete, in the range [0, 1].
*
* @event youtube-upload-progress
* @param {Object} e Event parameters.
*/
/**
* Fired when YouTube upload has failed.
*
* Since the actual upload failed, it's not possible for the YouTube server to attempt to
* process the video, and no `youtube-processing-poll` events will be fired.
*
* `e.detail` is set to a string explaining what went wrong.
*
* @event youtube-upload-fail
* @param {Object} e Event parameters
*/
/**
* Fired when video upload has completed, and YouTube has begun processing the video.
*
* At this point, the video is not yet playable, and there is no guarantee that
* the server-side YouTube processing will succeed.
*
* One or more `youtube-processing-poll` events will then be fired after this event,
* followed by either a `youtube-processing-complete` or `youtube-processing-fail`.
*
* `e.detail` is set to the YouTube video id of the video.
*
* @event youtube-upload-complete
* @param {Object} e Event parameters.
*/
/**
* Fired while server-side processing is in progress.
*
* Server-side processing can take an
* [unpredictable amount of time](https://support.google.com/youtube/answer/71674?hl=en&ref_topic=2888603),
* and these events will be periodically fired each time the processing status is polled.
*
* `e.detail` is set to a
* [status](https://developers.google.com/youtube/v3/docs/videos#status)
* object.
*
* @event youtube-processing-poll
* @param {Object} e Event parameters
*/
/**
* Fired when server-side processing is successful and the video is
* available for playback on YouTube.
*
* The video can be played at `https://youtu.be/VIDEO_ID` and can be
* embedded using the
* [`google-youtube`](https://github.com/GoogleWebComponents/google-youtube) element.
*
* `e.detail` is set to the YouTube video id of the video.
*
* @event youtube-processing-complete
* @param {Object} e Event parameters
*/
/**
* Fired when the video
* [failed transcoding](https://support.google.com/youtube/topic/2888603?hl=en&ref_topic=16547)
* and can't be played on YouTube.
*
* `e.detail` is set to a
* [status](https://developers.google.com/youtube/v3/docs/videos#status)
* object which has more details about the failure.
*
* @event youtube-processing-fail
* @param {Object} e Event parameters
*/
properties: {
/**
* An OAuth 2 clientId reference, obtained from the
* [Google Developers Console](https://console.developers.google.com).
*
* Follow
* [the steps](https://developers.google.com/console/help/new/#generatingoauth2)
* for registering for OAuth 2, ensure that the
* [YouTube Data API v3](https://developers.google.com/youtube/registering_an_application)
* is enabled for your API project, and ensure that the JavaScript Origin
* is set to the domain hosting the page on which
* you'll be using this element.
*
* @attribute clientId
* @type string
* @default ''
*/
clientId: {
type: String,
value: ''
},
/**
* Whether files should be automatically uploaded after they're selected.
*
* If false, the upload must be started by calling the uploadFile()
* method and passing in a reference to the selected file.
*/
auto: {
type: Boolean,
value: false
},
/**
* The title for the new YouTube video.
*/
videoTitle: {
type: String,
value: 'Untitled Video'
},
/**
* The description for the new YouTube video.
*/
description: {
type: String,
value: 'Uploaded via a web component! Check out https://github.com/GoogleWebComponents/google-youtube-upload'
},
/**
* The array of tags for the new YouTube video.
*/
tags: {
type: Array,
value: function() {
return ['google-youtube-upload'];
}
},
/**
* The numeric YouTube
* [cateogry id](https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.videoCategories.list?part=snippet®ionCode=us).
*
* The default value, `22`, corresponds to the "People & Blogs" category.
*/
categoryId: {
type: Number,
value: 22
},
/**
* The [privacy setting](https://support.google.com/youtube/answer/157177?hl=en)
* for the new video.
*
* Valid values are 'public', 'private', and 'unlisted'.
*/
privacyStatus: {
type: String,
value: 'unlisted'
},
/**
* The id of the new video.
*
* This is set as soon as a `youtube-upload-complete` event is fired.
*/
videoId: {
notify: true,
readOnly: true,
type: String,
value: ''
},
/**
* Whether the current browser supports recording and uploading video.
*
* This depends on the `MediaRecorder` and `MediaDevices` APIs.
*/
recordSupported: {
readOnly: true,
type: Boolean,
value: Boolean('MediaRecorder' in window &&
'mediaDevices' in navigator &&
'getUserMedia' in navigator.mediaDevices)
}
},
ready: function() {
this._selectedFile = null;
this._STATUS_POLLING_ITERVAL_MILLIS = 60 * 1000;
if (this.clientId) {
this._transitionToLoginLogout();
} else {
this._transitionToNoClientId();
}
},
/**
* Uploads a video file to YouTube.
*
* If the `auto` attribute is set, then this will be called automatically
* once a file is selected. Otherwise, this should be called manually and
* passed a reference to the file (or blob) to be uploaded.
*
* @method uploadFile
* @param {object} file File object corresponding to the video to upload.
*/
uploadFile: function(file) {
var metadata = {
snippet: {
title: this.videoTitle,
description: this.description,
tags: this.tags,
categoryId: this.categoryId
},
status: {
privacyStatus: this.privacyStatus
}
};
var uploader = new MediaUploader({
baseUrl: 'https://www.googleapis.com/upload/youtube/v3/videos',
file: file,
token: this._accessToken,
metadata: metadata,
params: {
part: Object.keys(metadata).join(',')
},
onError: function(data) {
var message = data;
// Assuming the error is raised by the YouTube API, data will be
// a JSON string with error.message set. I am not 100% sure that's the
// only time onError will be raised, though.
try {
var errorResponse = JSON.parse(data);
message = errorResponse.error.message;
} finally {
this.fire('youtube-upload-fail', message);
}
}.bind(this),
onProgress: function(data) {
var currentTime = Date.now();
var bytesUploaded = data.loaded;
var totalBytes = data.total;
// The times are in millis, so we need to divide by 1000 to get seconds.
var bytesPerSecond = bytesUploaded / ((currentTime - this._uploadStartTime) / 1000);
var estimatedSecondsRemaining = (totalBytes - bytesUploaded) / bytesPerSecond;
var fractionComplete = bytesUploaded / totalBytes;
this.fire('youtube-upload-progress', {
progressEvent: data,
bytesPerSecond: bytesPerSecond,
estimatedSecondsRemaining: estimatedSecondsRemaining,
fractionComplete: fractionComplete
});
}.bind(this),
onComplete: function(data) {
var uploadResponse = JSON.parse(data);
// Need to use _setVideoId() because videoId is read-only.
this._setVideoId(uploadResponse.id);
this.fire('youtube-upload-complete', uploadResponse.id);
this._pollForVideoStatus();
}.bind(this)
});
this.fire('youtube-upload-start', file);
// This won't correspond to the *exact* start of the upload, but it should be close enough.
this._uploadStartTime = Date.now();
uploader.upload();
this._transitionToThanks();
},
// Private helper methods.
_initializeMediaRecorder: function() {
if (this._mediaRecorder) {
return Promise.resolve();
}
return navigator.mediaDevices.getUserMedia({
audio: true, video: true
}).then(function(stream) {
this.$$('#get-user-media').src = URL.createObjectURL(stream);
this._recordedBlobs = [];
this._mediaRecorder = new MediaRecorder(stream, {
mimeType: 'video/webm;codecs=vp9,vp8'
});
this._mediaRecorder.addEventListener('dataavailable', function(event) {
if (event.data.size > 0) {
this._recordedBlobs.push(event.data);
}
}.bind(this));
this._mediaRecorder.addEventListener('stop', function() {
this._videoBlob = new Blob(this._recordedBlobs, {
type: this._mediaRecorder.mimeType
});
this.$$('#get-user-media').src = URL.createObjectURL(this._videoBlob);
this._tearDownMediaRecorder();
}.bind(this));
}.bind(this));
},
_tearDownMediaRecorder: function() {
this._recordingState = 'stopped';
if (this._mediaRecorder) {
this._mediaRecorder.stream.getAudioTracks().forEach(function(track) {
track.stop();
});
this._mediaRecorder.stream.getVideoTracks().forEach(function(track) {
track.stop();
});
this._mediaRecorder = null;
this._recordedBlobs = null;
}
},
_loadChannels: function() {
if (gapi && gapi.client && this._accessToken && !this._loadChannelRequested) {
this._loadChannelRequested = true;
gapi.client.request({
path: '/youtube/v3/channels',
params: {
part: 'snippet',
mine: true
},
callback: function(response) {
if (response.error) {
this.fire('youtube-upload-fail', response.error.message);
this._channel = null;
} else {
this._channel = {
name: response.items[0].snippet.title,
thumbnail: response.items[0].snippet.thumbnails.default.url
};
}
}.bind(this)
});
}
},
_pollForVideoStatus: function() {
gapi.client.request({
path: '/youtube/v3/videos',
params: {
part: 'status',
id: this.videoId
},
callback: function(response) {
if (response.error) {
// Not exactly sure how to handle this one, since it means the status polling failed.
setTimeout(this._pollForVideoStatus.bind(this), this._STATUS_POLLING_ITERVAL_MILLIS);
} else {
var status = response.items[0].status;
switch (status.uploadStatus) {
// This is a non-final status, so we need to poll again.
case 'uploaded':
this.fire('youtube-processing-poll', status);
setTimeout(this._pollForVideoStatus.bind(this), this._STATUS_POLLING_ITERVAL_MILLIS);
break;
// The video was successfully transcoded and is available.
case 'processed':
this.fire('youtube-processing-complete', this.videoId);
break;
// All other statuses indicate a permanent transcoding failure.
default:
this.fire('youtube-processing-fail', status);
break;
}
}
}.bind(this)
});
},
// UI event helpers.
_transitionToNoClientId: function() {
this._selectedSection = 'no-client-id';
},
_transitionToLoginLogout: function() {
// This will be a no-op if we don't currently have a MediaRecorder.
this._tearDownMediaRecorder();
this._selectedSection = 'login-logout';
},
_transitionToUploadFile: function() {
this._selectedSection = 'upload-file';
},
_transitionToRecordVideo: function() {
this._selectedSection = 'record-video';
this._initializeMediaRecorder().then(function() {
this._recordingState = 'not-started';
}.bind(this));
},
_transitionToThanks: function() {
this._selectedSection = 'thanks';
},
_handleUploadClicked: function() {
this.uploadFile(this._selectedFile);
},
_handleRecordClicked: function() {
this._initializeMediaRecorder().then(function() {
this._mediaRecorder.start(100);
this._recordingState = 'started';
}.bind(this));
},
_handleStopClicked: function() {
this._mediaRecorder.stop();
},
_handleRecordingUploadClicked: function() {
this.uploadFile(this._videoBlob);
},
_handleFileChanged: function(e) {
this._selectedFile = e.target.files[0];
if (this._selectedFile) {
this._uploadButtonDisabled = false;
if (this.auto) {
this.uploadFile(this._selectedFile);
}
}
},
_handleSignedIn: function() {
this._accessToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;
this._loadChannels();
},
_handleSignedOut: function() {
this._accessToken = null;
this._channel = null;
this._loadChannelRequested = false;
},
// Computed value helpers.
_calculateRecordButtonHidden: function(recordingState) {
return recordingState === 'started';
},
_calculateStopButtonHidden: function(recordingState) {
return recordingState !== 'started';
},
_calculateRecordingUploadButtonHidden: function(recordingState) {
return recordingState !== 'stopped';
},
_calculateVideoControls: function(recordingState) {
return recordingState === 'stopped';
}
});
</script>