c# - I want to upload video on youtube using client side login. without open web page permission -


when upload video youtube using client side login. first time redirect ui permissions.

i want upload without redirect web page. need execute code on server.

here code.

    private async task<string> run(string title, string description, string filepath)         {              var videoid = string.empty;             try             {                 logger.info(string.format("[uploading file on youtube title: {0}, description: {1}, filepath: {2}]", title, description, filepath));                 usercredential credential;                 using (var stream = new filestream("client_secret.json", filemode.open, fileaccess.read))                 {                     logger.info("[load credentials google start]");                     credential = await googlewebauthorizationbroker.authorizeasync(                         googleclientsecrets.load(stream).secrets,                         // oauth 2.0 access scope allows application upload files                         // authenticated user's youtube channel, doesn't allow other types of access.                         new[] { youtubeservice.scope.youtubeupload },                         "user",                         cancellationtoken.none                     );                     logger.info("[load credentials google end]");                  }                 logger.info("youtubeapikey {0}", system.configuration.configurationmanager.appsettings["youtubeapikey"]);                 var youtubeservice = new youtubeservice(new baseclientservice.initializer()                   {                       httpclientinitializer = credential,                       apikey = system.configuration.configurationmanager.appsettings["youtubeapikey"],                       applicationname = system.configuration.configurationmanager.appsettings["applicationname"]                   });                  logger.info("applicationname {0}", system.configuration.configurationmanager.appsettings["applicationname"]);                   var video = new video();                 video.snippet = new videosnippet();                 video.snippet.title = title;                 video.snippet.description = description;                 //video.snippet.tags = new string[] { "tag1", "tag2" };                 // video.snippet.categoryid = "22"; // see https://developers.google.com/youtube/v3/docs/videocategories/list                 video.status = new videostatus();                 video.status.privacystatus = "public"; // or "private" or "public"                 var filepath = filepath; // replace path actual movie file.                    using (var filestream = new filestream(filepath, filemode.open))             {                 var videosinsertrequest = youtubeservice.videos.insert(video, "snippet,status", filestream, "video/*");                 videosinsertrequest.progresschanged += videosinsertrequest_progresschanged;                 videosinsertrequest.responsereceived += videosinsertrequest_responsereceived;                  await videosinsertrequest.uploadasync();              }                 return videoid;             }             catch (exception e)             {                 logger.errorexception("[error occurred in run ]", e);             }             return videoid;   }          void videosinsertrequest_progresschanged(google.apis.upload.iuploadprogress progress)         {             switch (progress.status)             {                 case uploadstatus.uploading:                     console.writeline("{0} bytes sent.", progress.bytessent);                     break;                  case uploadstatus.failed:                     console.writeline("an error prevented upload completing.\n{0}", progress.exception);                     break;             }         }          void videosinsertrequest_responsereceived(video video)         {             console.writeline("video id '{0}' uploaded.", video.id);         } 

your code doing doing correctly. youtube api doesn't allow pure server authentication (service account). option available upload files use oauth2 , authenticate code first time.

i sugest make 1 small change add filedatastore. store authentication you. once have authenticated via web browser wont need again.

/// <summary>         /// authenticate google using oauth2         /// documentation https://developers.google.com/accounts/docs/oauth2         /// </summary>         /// <param name="clientid">from google developer console https://console.developers.google.com</param>         /// <param name="clientsecret">from google developer console https://console.developers.google.com</param>         /// <param name="username">a string used identify user.</param>         /// <returns></returns>         public static youtubeservice authenticateoauth(string clientid, string clientsecret, string username)         {              string[] scopes = new string[] { youtubeservice.scope.youtube,  // view , manage youtube account                                              youtubeservice.scope.youtubeforcessl,                                              youtubeservice.scope.youtubepartner,                                              youtubeservice.scope.youtubepartnerchannelaudit,                                              youtubeservice.scope.youtubereadonly,                                              youtubeservice.scope.youtubeupload};               try             {                 // here request user give access, or use refresh token stored in %appdata%                 usercredential credential = googlewebauthorizationbroker.authorizeasync(new clientsecrets { clientid = clientid, clientsecret = clientsecret }                                                                                              , scopes                                                                                              , username                                                                                              , cancellationtoken.none                                                                                              , new filedatastore("daimto.youtube.auth.store")).result;                  youtubeservice service = new youtubeservice(new youtubeservice.initializer()                 {                     httpclientinitializer = credential,                     applicationname = "youtube data api sample",                 });                 return service;             }             catch (exception ex)             {                 console.writeline(ex.innerexception);                 return null;              }          } 

call above method this:

// authenticate oauth2             string client_id = "xxxxxx-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com";             string client_secret = "ndmlunftguk6wgmy7cfo64rv";             var service = authentication.authenticateoauth(client_id, client_secret, "singleuser"); 

your code need authenticated first time. once authenticated filedatastore stores file in %appdata% on machine. every time runs after use refresh token stored in %appdata% gain access again.

code ripped youtube api sample project


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -