How to convert Youtube API upload code into an Azure Blob function?

Leam 6 Reputation points
2020-03-17T19:54:52.873+00:00

I have implemented an Azure function, and this function will upload a video to my YouTube channel when there is new video in my 'video' container. I am using the sample YouTubeAPI upload code that was provided by Google: https://developers.google.com/youtube/v3/docs/videos/insert . The problem I am having is that, when I run my function it compiles fine(I have shared the console output below), but videos are not getting uploaded to my YouTube channel. I am not sure if I am missing anything else in the code, If it is an authentication issue or if it needs to re-factored? Could you please have a look at code? Here is the code, along with other files:

Function1.cs:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace YoutubeUploadFunction
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run([BlobTrigger("video/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, Microsoft.Azure.WebJobs.ExecutionContext context, ILogger log)
        {
            UserCredential credential;
            using (var stream = new FileStream(System.IO.Path.Combine(context.FunctionDirectory, "client_secrets.json"), FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { YouTubeService.Scope.YoutubeUpload },
                "user",
                CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22";
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted";
            var VideoInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", myBlob, "video/*");
            await VideoInsertRequest.UploadAsync();
        }
    }
}

client_secrets.json:

{
"installed": {
    "client_id": "147300761218-dl0rhktkoj8arh0ebu5pu56es06hje5p.apps.googleusercontent.com",
    "project_id": "mytestproj",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxxxxxxxxxxxxxxxx",
    "redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob"]
  }
}

Local.Setting.Json:

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=uploadvideotoyoutube;AccountKey=xxxxxxxxxxxxxxxxxxxxxx==;EndpointSuffix=core.windows.net",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
6,875 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. ajkuma 22,401 Reputation points Microsoft Employee
    2020-03-19T16:47:51.977+00:00

    Leam, Welcome to Microsoft Q&A! Thanks for posting this question.

    Firstly, I have checked on this issue and also noticed that you have raised multiple threads on MSDN, Q&A and also on SO. I completely understand the importance and urgency with this matter. We apologies for all the inconvenience and frustration you had with this scenario.

    On one of your MSDN thread, I see that Pramod Valavala (we discussed on this internally) has shared the right guidance.
    “You need a different way to authorize and get the required access token since the code you have will try to open a browser for upload. On Azure, you would have to first perform an authorization code flow to get the required access token and then use that for your upload.”

    Just to isolate, blob upload vs YouTube upload (fiddler trace) , the Azure Functions runtime uses the storage account connection string for all functions except for HTTP triggered functions. The storage account must be a general-purpose. Instead of larger data upload, test with smaller data file upload to the blob storage.

    As a side note and you’re probably already aware that we're migrating from MSDN to Microsoft Q&A as our new forums.
    Azure Functions, Azure Storage and other MSDN forums have not yet been migrated to Q&A. Based on the integration scenario you’re trying to accomplish, the Azure services involved, you can continue to ask questions related to Azure Function & Azure Storage on respective MSDN forums until all the MSDN forums are migrated to Q&A.

    We are actively working to onboard remaining Azure services on Microsoft Q&A.
    We will make a public announcement once complete.

    Want to learn more about new platform and the services which are currently onboarded, kindly checkout this FAQ- Microsoft Q&A Getting Started: https://learn.microsoft.com/answers/articles/388/microsoft-qa-frequently-asked-questions.html

    1 person found this answer helpful.
    0 comments No comments