.NET용 Google API 클라이언트 라이브러리를 사용하는 다음 코드 샘플은 YouTube Data API에 사용할 수 있습니다. 이 코드 샘플들은 GitHub의 YouTube API 코드 샘플 리포지토리의 dotnet
폴더에서 받으실 수 있습니다.
내 업로드 검색
아래의 코드 샘플은 API의 playlistItems.list
메소드를 호출하여 요청과 관련된 채널에 업로드된 동영상 목록을 검색합니다. 이 코드는 mine
매개변수를 true
로 설정하고 channels.list
메소드를 호출하여 채널에 업로드된 동영상을 식별하는 재생목록 ID도 검색할 수 있습니다.
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; /* * External dependencies, OAuth 2.0 support, and core client libraries are at: * https://developers.google.com/api-client-library/dotnet/apis/ * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at: * https://github.com/youtube/api-samples/tree/master/dotnet */ using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; using Google.Apis.Youtube.v3; using Google.Apis.Youtube.v3.Data; namespace dotnet { class my_uploads { static void Main(string[] args) { CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("YouTube Data API: My Uploads"); var credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); var youtube = new YoutubeService(new BaseClientService.Initializer() { Authenticator = auth }); var channelsListRequest = youtube.Channels.List("contentDetails"); channelsListRequest.Mine = true; var channelsListResponse = channelsListRequest.Fetch(); foreach (var channel in channelsListResponse.Items) { var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads; CommandLine.WriteLine(String.Format("Videos in list {0}", uploadsListId)); var nextPageToken = ""; while (nextPageToken != null) { var playlistItemsListRequest = youtube.PlaylistItems.List("snippet"); playlistItemsListRequest.PlaylistId = uploadsListId; playlistItemsListRequest.MaxResults = 50; playlistItemsListRequest.PageToken = nextPageToken; var playlistItemsListResponse = playlistItemsListRequest.Fetch(); foreach (var playlistItem in playlistItemsListResponse.Items) { CommandLine.WriteLine(String.Format("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId)); } nextPageToken = playlistItemsListResponse.NextPageToken; } } CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString(); var key = "storage_key"; IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key); if (state != null) { client.RefreshToken(state); } else { state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeReadonly.GetStringValue()); AuthorizationMgr.SetCachedRefreshToken(storage, key, state); } return state; } } }
재생목록 만들기
아래의 코드 샘플은 API의 playlists.insert
메소드를 호출하여 요청을 인증하는 채널에서 소유한 비공개 재생목록을 만듭니다.
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; /* * External dependencies, OAuth 2.0 support, and core client libraries are at: * https://developers.google.com/api-client-library/dotnet/apis/ * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at: * https://github.com/youtube/api-samples/tree/master/dotnet */ using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; using Google.Apis.Youtube.v3; using Google.Apis.Youtube.v3.Data; namespace dotnet { class playlist_updates { static void Main(string[] args) { CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Playlist Updates"); var credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); var youtube = new YoutubeService(new BaseClientService.Initializer() { Authenticator = auth }); var newPlaylist = new Playlist(); newPlaylist.Snippet = new PlaylistSnippet(); newPlaylist.Snippet.Title = "Test Playlist"; newPlaylist.Snippet.Description = "A playlist created with the YouTube API v3"; newPlaylist.Status = new PlaylistStatus(); newPlaylist.Status.PrivacyStatus = "public"; newPlaylist = youtube.Playlists.Insert(newPlaylist, "snippet,status").Fetch(); var newPlaylistItem = new PlaylistItem(); newPlaylistItem.Snippet = new PlaylistItemSnippet(); newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id; newPlaylistItem.Snippet.ResourceId = new ResourceId(); newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"; newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI"; newPlaylistItem = youtube.PlaylistItems.Insert(newPlaylistItem, "snippet").Fetch(); CommandLine.WriteLine(String.Format("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id)); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString(); var key = "storage_key"; IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key); if (state != null) { client.RefreshToken(state); } else { state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.Youtube.GetStringValue()); AuthorizationMgr.SetCachedRefreshToken(storage, key, state); } return state; } } }
키워드별 검색
아래의 코드 샘플은 API의 search.list
메소드를 사용하여 특정 키워드와 관련된 검색 결과를 검색합니다.
using System; using System.Collections; using System.Collections.Generic; /* * External dependencies, OAuth 2.0 support, and core client libraries are at: * https://developers.google.com/api-client-library/dotnet/apis/ * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at: * https://github.com/youtube/api-samples/tree/master/dotnet */ using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Youtube.v3; using Google.Apis.Youtube.v3.Data; namespace dotnet { class search { static void Main(string[] args) { CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Search"); SimpleClientCredentials credentials = PromptingClientCredentials.EnsureSimpleClientCredentials(); YoutubeService youtube = new YoutubeService(new BaseClientService.Initializer() { ApiKey = credentials.ApiKey }); SearchResource.ListRequest listRequest = youtube.Search.List("snippet"); listRequest.Q = CommandLine.RequestUserInput<string>("Search term: "); listRequest.Order = SearchResource.Order.Relevance; SearchListResponse searchResponse = listRequest.Fetch(); List<string> videos = new List<string>(); List<string> channels = new List<string>(); List<string> playlists = new List<string>(); foreach (SearchResult searchResult in searchResponse.Items) { switch (searchResult.Id.Kind) { case "youtube#video": videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId)); break; case "youtube#channel": channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId)); break; case "youtube#playlist": playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId)); break; } } CommandLine.WriteLine(String.Format("Videos:\n{0}\n", String.Join("\n", videos.ToArray()))); CommandLine.WriteLine(String.Format("Channels:\n{0}\n", String.Join("\n", channels.ToArray()))); CommandLine.WriteLine(String.Format("Playlists:\n{0}\n", String.Join("\n", playlists.ToArray()))); CommandLine.PressAnyKeyToExit(); } } }
동영상 업로드
아래의 코드 샘플은 API의 videos.insert
메소드를 호출하여 요청과 관련된 채널에 동영상을 업로드합니다.
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; /* * External dependencies, OAuth 2.0 support, and core client libraries are at: * https://developers.google.com/api-client-library/dotnet/apis/ * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at: * https://github.com/youtube/api-samples/tree/master/dotnet */ using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; using Google.Apis.Youtube.v3; using Google.Apis.Youtube.v3.Data; namespace dotnet { class upload_video { static void Main(string[] args) { CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Upload Video"); var credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); var youtube = new YoutubeService(new BaseClientService.Initializer() { Authenticator = auth }); var video = new Video(); video.Snippet = new VideoSnippet(); video.Snippet.Title = CommandLine.RequestUserInput<string>("Video title"); video.Snippet.Description = CommandLine.RequestUserInput<string>("Video description"); video.Snippet.Tags = new string[] { "tag1", "tag2" }; // See https://developers.google.com/youtube/v3/docs/videoCategories/list video.Snippet.CategoryId = "22"; video.Status = new VideoStatus(); video.Status.PrivacyStatus = CommandLine.RequestUserInput<string>("Video privacy (public, private, or unlisted)"); var filePath = CommandLine.RequestUserInput<string>("Path to local video file"); var fileStream = new FileStream(filePath, FileMode.Open); var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", fileStream, "video/*"); videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged; videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived; var uploadThread = new Thread(() => videosInsertRequest.Upload()); uploadThread.Start(); uploadThread.Join(); CommandLine.PressAnyKeyToExit(); } static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress obj) { CommandLine.WriteLine(String.Format("{0} bytes sent.", obj.BytesSent)); } static void videosInsertRequest_ResponseReceived(Video obj) { CommandLine.WriteLine(String.Format("Video id {0} was successfully uploaded.", obj.Id)); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString(); var key = "storage_key"; IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key); if (state != null) { client.RefreshToken(state); } else { state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeUpload.GetStringValue()); AuthorizationMgr.SetCachedRefreshToken(storage, key, state); } return state; } } }