I would like to "authorize" via the .NET framework using my own API keys, secret and Refresh Token, and then pass the Access Token to JavaScript so I can upload a video directly to YouTube with a progress indicator.
I have working code via the .NET API that will accomplish the upload directly to my channel [without authorization], but you get no progress indication (and it can take quite some time) and the file must be uploaded to my server first, then to YouTube server.
Is a server side access code different from a client side access code? If not:
- How can I obtain the access code server side? (get the string)
- ***How can I pass it to Google APIs via JavaScript? (not how to write
<%= access code %>
but where to pass it in?)
I am well aware of the security risk in exposing the access token, but these do expire right? (as a bonus, how can I shorten the expire time). This is also being done inside a password protected web page, and you don't get the 'client secret' or 'refresh token'
***update - I think I found where to pass in the token, in the MediaUploader
object.
var uploader = new MediaUploader({
baseUrl: 'https://www.googleapis.com/upload/youtube/v3/videos',
file: selectedFile,
token: token, // ***RIGHT HERE***
metadata: metadata,
params: params,
onError: function(data) {
Okay, so after weeks of smashing my way through the APIs, .NET, and JavaScript documentation I have built the following solution....
As per the YouTube V3 Developer documentation get your Keys all set up. (choose OAuth, Web Application, and enter URIs for both your Javascript and Redirect code)
Next use the OAuth Playground to obtain your Refresh Code
Once you have your client_id, client_secret, and refresh_token you are ready to rock!
This code makes a simple HTTP/REST call via the code behind to obtain an access_token which is good for 3600 seconds (the default). It then passes this string to the JavaScript code for use ****WARNING****
This does not use any of the .NET or JavaScript Libraries with the exception of one file, the cors_upload.js available on GitHub
Allas, the code
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ApisCallTest.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
<title>YouTube API Uploads via CORS</title>
<style>
#disclaimer {
font-size: 0.75em;
color: #aeaeae;
max-width: 350px;
}
.during-upload { display: none; }
label { display: block; }
input[type="text"],
textarea,
progress {
font-size: 16px;
width: 15em;
margin-bottom: 1em;
padding: 0.5em;
font-family: "Open Sans", sans-serif;
}
</style>
</head>
<body>
<div>
<input input type="file" id="file" class="button" accept="video/*" />
<button id="button">Upload Video</button>
</div>
<div class="during-upload">
<p><span id="percent-transferred"></span>% done (<span id="bytes-transferred"></span>/<span id="total-bytes"></span> bytes)</p>
<progress id="upload-progress" max="1" value="0"></progress>
</div>
<p id="disclaimer">By uploading a video, 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 href="http://www.youtube.com/t/terms" target="_blank">http://www.youtube.com/t/terms</a></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cors_upload.js"></script>
<script>
$('#button').on("click", goForUpload);
function goForUpload() {
if ($('#file').get(0).files[0]) {
$('#button').attr('disabled', true);
var uploadStartTime = 0;
var metadata = {
snippet: {
title: 'PUT YOU TITLE HERE',
description: 'THIS IS YOUR VIDEO DESCRIPTION',
categoryId: '22'
},
status: {
privacyStatus: 'unlisted'
}
};
var uploader = new MediaUploader({
baseUrl: 'https://www.googleapis.com/upload/youtube/v3/videos',
file: $('#file').get(0).files[0],
token: '<%= access_token %>',
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. That may not be the
// only time onError will be raised, though.
try {
var errorResponse = JSON.parse(data);
message = errorResponse.error.message;
} finally {
alert(message);
}
},
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 percentageComplete = (bytesUploaded * 100) / totalBytes;
$('#upload-progress').attr({
value: bytesUploaded,
max: totalBytes
});
$('#percent-transferred').text(percentageComplete);
$('#bytes-transferred').text(bytesUploaded);
$('#total-bytes').text(totalBytes);
$('.during-upload').show();
},
onComplete: function (data) {
var uploadResponse = JSON.parse(data);
alert('all done, you can store this id: ' + uploadResponse.id)
}
});
uploadStartTime = Date.now();
uploader.upload();
}
}
</script>
</body>
</html>
and Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace ApisCallTest
{
public partial class WebForm1 : System.Web.UI.Page
{
private static readonly HttpClient client = new HttpClient();
public string access_token;
protected void Page_Load(object sender, EventArgs e)
{
var values = new Dictionary<string, string>
{
{ "client_id", "REPLACE_ME" },
{ "client_secret", "REPLACE_ME" },
{ "refresh_token", "REPLACE_ME" },
{ "grant_type", "refresh_token" }
};
var content = new FormUrlEncodedContent(values);
var response = client.PostAsync("https://www.googleapis.com/oauth2/v4/token", content);
string json = response.Result.Content.ReadAsStringAsync().Result;
dynamic obj = JObject.Parse(json);
access_token = obj.access_token;
}
}
}
The result... From a password protected web page I can have a user upload a video to MY channel, unlisted, and store the video ID to later embed that video back on my website.
as for the ****WARNING****, this is somewhat of a security concern as you are exposing (very directly) your PERSONAL access key to the "public". It only lasts for 1 hour, but gives whatever "scope" of access you are using to "anyone" It would be a good idea to try and obstuficate the key somewhat, and at the very least, don't do this on a publicly available page.