public IList<Video> GetVideoFor(string videoName)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = API_KEY,
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q = PREFIX+videoName;
            searchListRequest.MaxResults = MAX_RESULTS;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = searchListRequest.Execute();

            IList<Video> videos = new List<Video>();

            foreach (var searchResult in searchListResponse.Items)
            {

                if (searchResult.Id.Kind == "youtube#video")
                {
                    videos.Add(new Video( EMBEBED_BASE_URL + searchResult.Id.VideoId , new Image(searchResult.Snippet.Thumbnails.Default__.Url)) );
                }
            }
            return videos;
        }
Beispiel #2
0
        public static List<YoutubeChanelObject> GetChanelByUser(string username)
        {
            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = WebConfigurationManager.AppSettings["ApiKey"],
                ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
            });

            var searchListRequest = youtubeService.Channels.List("snippet");
            searchListRequest.ForUsername = username;
            searchListRequest.MaxResults = 50;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = searchListRequest.Execute();//.ExecuteAsync();
            List<YoutubeChanelObject> ListChanel = new List<YoutubeChanelObject>();
            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            foreach (var searchResult in searchListResponse.Items)
            {
                YoutubeChanelObject Chanel = new YoutubeChanelObject();
                Chanel.UChanelID = searchResult.Id;
                Chanel.UTitle = searchResult.Snippet.Title;
                ListChanel.Add(Chanel);
            }
            return ListChanel;
        }
        public static YouTubeService AuthenticateOauthService(string clientId, string clientSecret, string userName)
        {
            string[] scopes = new string[] { YouTubeService.Scope.Youtube};

            try
            {
                UserCredential credential =
                    GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new ClientSecrets
                        {
                            ClientId = clientId,
                            ClientSecret = clientSecret
                        },
                        scopes,
                        userName,
                        CancellationToken.None,
                        new FileDataStore("dtuit.YouTube.Auth.Store")).Result;

                YouTubeService service = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "YouTube Data Api Wrapper"
                });

                return service;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return null;
            }
        }
        private async void HomePage_Loaded(object sender, RoutedEventArgs e)
        {
            if (_activityReq == null)
            {
                var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new Uri("ms-appx:///client_id.json"),
                    new[] { YouTubeService.Scope.Youtube },
                    "user",
                    CancellationToken.None);

                var youtube = new YouTubeService(new BaseClientService.Initializer()
                {
                    //ApiKey = "AIzaSyC7enbf9xtdebb4EDHXeeqHXk2qUuLfeuc",
                    HttpClientInitializer = userCredential,
                    ApplicationName = "ProTube"
                });

                _activityReq = youtube.Activities.List("snippet,contentDetails");
                _activityReq.Home = true;
                _activityReq.MaxResults = 50;
                _activityReq.PublishedAfter = DateTime.Now.AddDays(-14);
            }

            if (_activityRes == null)
            {
                _activityRes = await _activityReq.ExecuteAsync();
                VideosList.ItemsSource = _activityRes.Items;
                NextButton.IsEnabled = true;
            }
        }
Beispiel #5
0
        public async Task AuthenticateWithGoogle()
        {
            if (_googleCredential != null)
            {
                await _googleCredential.RefreshTokenAsync(CancellationToken.None);
            }
            else
            {
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    _googleCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { YouTubeService.Scope.Youtube },
                        "user",
                        CancellationToken.None,
                        new FileDataStore(StringConstants.ApplicationName));
                }
            }

            if (Service == null)
            {
                Service = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = _googleCredential,
                    ApplicationName = StringConstants.ApplicationName
                });
            }
        }
Beispiel #6
0
        public async void OAuthConnect()
        {
            UserCredential credientials;
            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credientials = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.Youtube },
                    "Blissea",
                    CancellationToken.None);
            }

            YouTubeService service = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credientials,
                ApplicationName = "YoutubeOrganizer"
            });

            PlaylistsResource.ListRequest listRequest = service.Playlists.List("id");
            listRequest.MaxResults = 50;
            listRequest.Mine = true;

            PlaylistListResponse listResponse = await listRequest.ExecuteAsync();

            var count = listResponse.Items.Count;

            Debug.WriteLine(count);
        }
        public async Task UploadFileToYouTube(PodcastEpisode episode)
        {
            try
            {
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = await BuildAccountCredentialFromClientSecret(),
                    ApplicationName = "PodcastUploader"
                });

                var video = BuildVideo(episode);
                using (var fileStream = new FileStream(episode.LocalVideoFile, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ResponseReceived += (v) => videosInsertRequest_ResponseReceived(v, episode);

                    var chunkSize = 256 * 0x400 * 4;
                    videosInsertRequest.ChunkSize = chunkSize;
                    videosInsertRequest.Upload();
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
Beispiel #8
0
 public void Disconnect()
 {
     IsAuthorized = false;
     _credential = null;
     _youtubeService.Dispose();
     _youtubeService = null;
 }
Beispiel #9
0
        public async void Load()
        {
            Items.Clear();

            YouTubeService service = new YouTubeService(
                new BaseClientService.Initializer() {
                    HttpClientInitializer = await _authenticationService.GetUserCredential()
                });

            var activititiesRequest = service.Activities.List("snippet");
            activititiesRequest.Home = true;

            ItemsGroup activities = new ItemsGroup(
                new IncLoadingCollection(d => activititiesRequest.ExecuteAsync(d)),
                "Recent activities");
            await activities.Items.LoadMoreItemsAsync(8);

            Items.Add(activities);

            var videosRequest = service.Videos.List("snippet");
            videosRequest.Chart = VideosResource.ListRequest.ChartEnum.MostPopular;

            ItemsGroup videos = new ItemsGroup(
                new IncLoadingCollection(d => videosRequest.ExecuteAsync(d)),
                "Popular videos");
            await videos.Items.LoadMoreItemsAsync(8);

            Items.Add(videos);
        }
Beispiel #10
0
        public async Task<Dictionary<string, PostAnalysisResults>> Analyze( List<rs.Post> posts ) {
            var toReturn = new Dictionary<string, PostAnalysisResults>();
            var youTubePosts = new Dictionary<string, List<rs.Post>>();
            var amWrangler = new BotFunctions.AutoModWrangler( Program.Client.GetSubreddit( Program.Subreddit ) );
            var bannedChannels = amWrangler.GetBannedList( Models.BannedEntity.EntityType.Channel );
            foreach ( var post in posts ) { //TODO error handling
                toReturn.Add( post.Id, new PostAnalysisResults( post, ModuleEnum ) );
                string postYTID = YouTubeHelpers.ExtractVideoId( post.Url.ToString() );

                if ( !string.IsNullOrWhiteSpace( postYTID ) ) {
                    if ( !youTubePosts.ContainsKey( postYTID ) ) youTubePosts.Add( postYTID, new List<rs.Post>() );
                    youTubePosts[postYTID].Add( post );
                }
            }
            var yt = new YouTubeService( new BaseClientService.Initializer { ApiKey = YouTubeAPIKey } );
            var req = yt.Videos.List( "snippet" );
            for ( var i = 0; i < youTubePosts.Keys.Count; i += 50 ) {
                req.Id = string.Join( ",", youTubePosts.Keys.Skip( i ).Take( 50 ) );
                var response = req.ExecuteAsync();
                await Task.WhenAll( response, bannedChannels );
                foreach ( var vid in response.Result.Items ) {
                    //if the channel is banned
                    var chan = bannedChannels.Result.Where( c => c.EntityString == vid.Snippet.ChannelId ).FirstOrDefault();
                    if ( chan != null ) {
                        foreach ( var ytPost in youTubePosts[vid.Id] ) {
                            //ring 'er up
                            toReturn[ytPost.Id].Scores.Add( new AnalysisScore( 9999, $"Channel ID: {chan.EntityString} was banned by {chan.BannedBy} on {chan.BanDate} for reason: {chan.BanReason}", "Banned Channel", ModuleName ) );
                        }
                    }
                }
            }
            return toReturn;
        }
        /// <summary>
        /// Authenticate to 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 to identify a user.</param>
        /// <returns></returns>
        public static YouTubeService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            string[] scopes = new string[] { YouTubeService.Scope.Youtube,  // view and manage your YouTube account
                                             YouTubeService.Scope.YoutubeForceSsl,
                                             YouTubeService.Scope.Youtubepartner,
                                             YouTubeService.Scope.YoutubepartnerChannelAudit,
                                             YouTubeService.Scope.YoutubeReadonly,
                                             YouTubeService.Scope.YoutubeUpload};

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously 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;

            }

        }
Beispiel #12
0
        public List<YouTubeModel> GetYTResults(string searchString)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
               {
               ApiKey = "AIzaSyD9pT1ig_V3DrzF-9xTUENXyS3Nf7reWAk",
               ApplicationName = "Movie Search",
               });

            var searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q = searchString;
            searchListRequest.MaxResults = 50;

            var searchListResponse = searchListRequest.Execute();  // instead of Aync Call, i used Sync call
            List<YouTubeModel> videos = new List<YouTubeModel>();

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            foreach (var searchResult in searchListResponse.Items)
            {
                switch (searchResult.Id.Kind)
                {
                    case "youtube#video":
                        videos.Add(new YouTubeModel { Title = searchResult.Snippet.Title, Description = searchResult.Snippet.Description, VideoId = searchResult.Id.VideoId, Thumbnal = new Uri(searchResult.Snippet.Thumbnails.Medium.Url) });
                        break;

                }
            }
            return videos;
        }
        private async Task Run(SteamID toID, string[] query, bool room)
        {
            YouTubeService ys = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = Options.ChatCommandApi.ApiKey,
                ApplicationName = "Steam Chat Bot"
            });

            SearchResource.ListRequest search = ys.Search.List("snippet");
            string q = "";
            for (int i = 1; i < query.Length; i++)
            {
                q += query[i] + " ";
            }
            q = q.Trim();
            search.Q = q;
            search.MaxResults = 1;
            
            SearchListResponse response = await search.ExecuteAsync();
            
            foreach (SearchResult result in response.Items)
            {
                if (result.Id.Kind == "youtube#video")
                {
                    SendMessageAfterDelay(toID, "https://youtube.com/watch?v=" + result.Id.VideoId, room);
                }
                else if(result.Id.Kind == "youtube#channel")
                {
                    SendMessageAfterDelay(toID, "https://youtube.com/channel/" + result.Id.ChannelId, room);
                }
            }
        }
Beispiel #14
0
		private async Task<YouTubeResult> Run(string searchTerm) {
			var youtubeService = new YouTubeService(new BaseClientService.Initializer() {
				ApiKey = ConfigurationManager.AppSettings["YouTubeApiKey"],
				ApplicationName = this.GetType().ToString()
			});

			var searchListRequest = youtubeService.Search.List("snippet");
			searchListRequest.Q = searchTerm; // Replace with your search term.
			searchListRequest.MaxResults = 50;

			// Call the search.list method to retrieve results matching the specified query term.
			var searchListResponse = await searchListRequest.ExecuteAsync();

			List<string> videos = new List<string>();
			List<string> channels = new List<string>();
			List<string> playlists = new List<string>();

			// Add each result to the appropriate list, and then display the lists of
			// matching videos, channels, and playlists.
			YouTubeResult videoRes = searchListResponse.Items
				.Where(x => x.Id.Kind == "youtube#video")
				.Select(x => new YouTubeResult {
					Title = x.Snippet.Title,
					VideoId = x.Id.VideoId
				}).FirstOrDefault();

			return videoRes;
		}
Beispiel #15
0
        public YouTubeUtilities(String refresh_token, String client_secret, String client_id)
        {
            CLIENT_ID = client_id;
            CLIENT_SECRET = client_secret;
            REFRESH_TOKEN = refresh_token;

            youtube = BuildService();
        }
 static YoutubeViewModel()
 {
     Youtube = new YouTubeService(new BaseClientService.Initializer()
     {
         ApiKey = YoutubeApiKey.ApiKey,
         ApplicationName = "MediaViewer"
     });
 }
Beispiel #17
0
 public Service()
 {
     _youtube = new YouTubeService(new BaseClientService.Initializer
     {
         ApplicationName = "mutube-1090",
         ApiKey = "AIzaSyBeU5QR5N0qOphQkp816JUDOqLpmxIMqSU",
     });
 }
 public YouTubeTrackProvider()
 {
     youtubeService = new YouTubeService(new BaseClientService.Initializer
     {
         ApiKey = Constants.YouTubeApiKey(),
         ApplicationName = Constants.YoutubeApplicationName
     });
 }
 public ProcessDownload(string apiKey, string applicationName)
 {
     youtubeService = new YouTubeService(new BaseClientService.Initializer()
         {
             ApiKey = apiKey,
             ApplicationName = applicationName
         });
     _youtubeService = this.youtubeService;
 }
 public YouMixServiceContainer()
 {
     AssemblyHandler.RedirectAssembly("System.Net.Http.Primitives", new Version(4, 2, 28, 0), "b03f5f7f11d50a3a");
     Service = new YouTubeService(new BaseClientService.Initializer
     {
         ApiKey = "AIzaSyD8ZsvvMyOSftpldDtxeRmDkjGYmyzhnAQ",
         ApplicationName = "YouMixVS"
     });
 }
        public async Task<ActionResult> YouTubeViewUploads(CancellationToken cancellationToken)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var youTubeChannels = new List<YouTubeChannel>();

                var service = new YouTubeService(new BaseClientService.Initializer 
                { 
                    HttpClientInitializer = result.Credential,
                    ApplicationName = this.ApplicationName
                });

                // Grab users owned channels
                var channelListRequest = service.Channels.List("snippet,contentDetails");
                channelListRequest.Mine = true;

                var channelListResponse = await channelListRequest.ExecuteAsync();
                
                foreach(var channel in channelListResponse.Items)
                {
                    var youTubeChannel = new YouTubeChannel(channel);

                    // Grab the ID of the Upload List from the channel
                    var uploadListId = channel.ContentDetails.RelatedPlaylists.Uploads;

                    // Fetch the videos belonging to the Upload List - We'll have to use paging here
                    var nextPageToken = string.Empty;
                    while(nextPageToken != null)
                    {
                        var playlistItemsListRequest = service.PlaylistItems.List("snippet");
                        playlistItemsListRequest.PlaylistId = uploadListId;
                        playlistItemsListRequest.MaxResults = 50;
                        playlistItemsListRequest.PageToken = nextPageToken;

                        var playlistItemsResponse = await playlistItemsListRequest.ExecuteAsync();

                        foreach(var playlistItem in playlistItemsResponse.Items)
                        {
                            youTubeChannel.Videos.Add(new YouTubeVideo(playlistItem));
                        }

                        nextPageToken = playlistItemsResponse.NextPageToken;
                    }

                    youTubeChannels.Add(youTubeChannel);
                }

                return View(youTubeChannels);
            }
            else
            {
                return new RedirectResult(result.RedirectUri);
            }
        }
Beispiel #22
0
        public static async Task<List<YouTubeDTO>> SearchYouTube(string searchTerm) {
            List<YouTubeDTO> DTOs = null;

            try {
                var youtubeService = new YouTubeService(new BaseClientService.Initializer() {
                    ApiKey = "<ApiKey goes here>",
                    ApplicationName = "YouTube.Utils.YouTubeUtils"
                });

                string youTubeSearchTerm = searchTerm;
                int maxResults = 25;
                var searchListRequest = youtubeService.Search.List("snippet");
                searchListRequest.Q = youTubeSearchTerm;
                searchListRequest.MaxResults = maxResults;

                // Call the search.list method to retrieve results matching the specified query term.
                var searchListResponse = await searchListRequest.ExecuteAsync();

                YouTubeDTO y = new VideoDTO();

                DTOs = new List<YouTubeDTO>();

                // Add each result to the appropriate list, and then display the lists of
                // matching videos, channels, and playlists.
                foreach (var searchResult in searchListResponse.Items) {
                    if (searchResult.Id.Kind == "youtube#video") {
                        switch (searchResult.Id.Kind) {
                            case "youtube#video":
                                DTOs.Add(new VideoDTO { Title = searchResult.Snippet.Title, Id = searchResult.Id.VideoId });
                                break;

                            case "youtube#channel":
                                DTOs.Add(new ChannelDTO { Title = searchResult.Snippet.Title, Id = searchResult.Id.ChannelId });
                                break;

                            case "youtube#playlist":
                                DTOs.Add(new PlayListDTO { Title = searchResult.Snippet.Title, Id = searchResult.Id.PlaylistId });
                                break;
                        }
                    }

                }

                // http://stackoverflow.com/questions/3163922/sort-a-custom-class-listt
                //DTOs.Sort((a, b) => a.Title.CompareTo(b.Title));
                //videoDTOs.Sort(delegate(VideoDTO v1, VideoDTO v2) { return v1.Title.CompareTo(v2.Title); });

            }
            catch (Exception x) {
                string msg = x.Message;
            }

            return DTOs;
        }
Beispiel #23
0
        public static YouTubeService CreateService(string applicationName)
        {
            // Create the service.
            var service = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "AIzaSyAAgEriOPPuK_eVLn-RGaOsFw8SHjVl0tg",
                ApplicationName = applicationName
            });

            return service;
        }
Beispiel #24
0
        private async Task Run()
        {

            var ics = new BaseClientService.Initializer
            {
                ApiKey = "AIzaSyD9pT1ig_V3DrzF-9xTUENXyS3Nf7reWAk",
                ApplicationName = "Test",
            };
           
            var youtubeService = new YouTubeService(ics);


      /*      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "AIzaSyB5VEzoWa9suKGKl6NNW6Hc_M-og0Wn2Xw",
                ApplicationName = this.GetType().ToString()
            });
       * */

            var searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q = "Jurasic Park"; // Replace with your search term.
            searchListRequest.MaxResults = 5;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = await searchListRequest.ExecuteAsync();

            List<string> videos = new List<string>();
            List<string> channels = new List<string>();
            List<string> playlists = new List<string>();

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            foreach (var searchResult in searchListResponse.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;
                }
            }

            Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
            Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
            Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
        }
Beispiel #25
0
 public static async Task<PlaylistItem> AddVideoToPlaylist(YouTubeService service,  string playlistId, string videoId)
 {
     // Add a video to the newly created playlist.
     var newPlaylistItem = new PlaylistItem();
     newPlaylistItem.Snippet = new PlaylistItemSnippet();
     newPlaylistItem.Snippet.PlaylistId = playlistId;
     newPlaylistItem.Snippet.ResourceId = new ResourceId();
     newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video";
     newPlaylistItem.Snippet.ResourceId.VideoId = videoId;
     var playlistItemInsertReq = service.PlaylistItems.Insert(newPlaylistItem, "snippet");
     var item = await playlistItemInsertReq.ExecuteAsync();
     return item;
 }
        public GoogleApiService()
        {
            var bcs = new BaseClientService.Initializer
            {
                ApplicationName = "Nadeko Bot",
                ApiKey = NadekoBot.Credentials.GoogleApiKey
            };

            _log = LogManager.GetCurrentClassLogger();

            yt = new YouTubeService(bcs);
            sh = new UrlshortenerService(bcs);
        }
Beispiel #27
0
 public static async Task<string> CreatePlaylist(YouTubeService service, string title, string description)
 {
     // Create a new, public playlist in the authorized user's channel.
     var newPlaylist = new Playlist();
     newPlaylist.Snippet = new PlaylistSnippet();
     newPlaylist.Snippet.Title = title;
     newPlaylist.Snippet.Description = description;
     newPlaylist.Status = new PlaylistStatus();
     newPlaylist.Status.PrivacyStatus = "public";
     var playlistInsertReq = service.Playlists.Insert(newPlaylist, "snippet,status");
     newPlaylist = await playlistInsertReq.ExecuteAsync();
     return newPlaylist.Id;
 }
Beispiel #28
0
        public PrintingBox()
        {
            InitializeComponent();
            
            ReloadConfig();
            button_download.Enabled = false;

            _youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "AIzaSyDzqeoR5mWrtJJ1Qt1SL_DLRDJvVKStdSo",
                ApplicationName = this.GetType().ToString()
            });
        }
        public async Task<List<WebSong>> SearchYoutube(string title, string artist, string album = null, int limit = 5, bool includeAudioTag = true)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = ApiKeys.YoutubeId,
                ApplicationName = "Audiotica"
            });
            youtubeService.HttpClient.DefaultRequestHeaders.Referrer = new Uri("http://audiotica.fm");

            var searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q = CreateQuery(title, artist, album, false) + (includeAudioTag ? " (Audio)" : "");
            searchListRequest.MaxResults = limit;
            searchListRequest.SafeSearch = SearchResource.ListRequest.SafeSearchEnum.None;

            try
            {
                // Call the search.list method to retrieve results matching the specified query term.
                var searchListResponse = await searchListRequest.ExecuteAsync();

                var songs = new List<WebSong>();

                foreach (var vid in from searchResult in searchListResponse.Items
                    where searchResult.Id.Kind == "youtube#video"
                    select new WebSong(searchResult))
                {
                    try
                    {
                        vid.AudioUrl = await GetYoutubeUrl(vid.Id);
                    }
                    catch
                    {
                        // ignored
                    }

                    if (!string.IsNullOrEmpty(vid.AudioUrl))
                        songs.Add(vid);
                }
                var results = await IdentifyMatches(songs, title, artist, false);

                // try redoing the search without "(audio)"
                if (!results.Any(p => p.IsMatch) && includeAudioTag)
                    return await SearchYoutube(title, artist, album, limit, false);

                return results;
            }
            catch
            {
                return null;
            }
        }
Beispiel #30
0
        public async Task UploadVideoAsync(string youtubeChannel, string title, string description, string[] tags, string videoFilePath)
        {
            if (youtubeChannel == null || title == null || description == null || tags == null || videoFilePath == null)
            {
                throw new ArgumentNullException();
            }

            Console.WriteLine($"Uploading youtube video \"{title}\"" +
                              $" from path \"{videoFilePath}\" to youtube channel \"{youtubeChannel}\"");

            YouTubeService youtubeService = await GetYouTubeService(youtubeChannel);

            Video video = new Video
            {
                Snippet = new VideoSnippet
                {
                    Title       = title,
                    Description = description,
                    Tags        = tags,
                    CategoryId  = "20" // gaming, see https://developers.google.com/youtube/v3/docs/videoCategories/list
                },
                Status = new VideoStatus
                {
                    PrivacyStatus = "public" // "unlisted", "private" or "public"
                }
            };

            using (FileStream fileStream = new FileStream(videoFilePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged  += VideosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += VideosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }
        private async Task PerformYouTubeSearchAsync(YouTubeModel model)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyCTnrb4UFBFj3NknsqAKem6Chf1fbLdhT0",
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");

            searchListRequest.Q          = model.Keywords; // Replace with your search term.
            searchListRequest.MaxResults = 10;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = await searchListRequest.ExecuteAsync();

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            foreach (var searchResult in searchListResponse.Items)
            {
                switch (searchResult.Id.Kind)
                {
                case "youtube#video":
                    model.Videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                    break;

                case "youtube#channel":
                    model.Channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                    break;

                case "youtube#playlist":
                    model.Playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                    break;
                }
            }
        }
        public async Task GetPlaylistVideosAsyncWithProgressTest()
        {
            var progressCalled    = 0;
            var progressIndicator = new Progress <int>(i => Interlocked.Increment(ref progressCalled));

            // Mock
            var httpMock       = new Mock <ISafeHttpClient>(MockBehavior.Strict);
            var youTubeService = new YouTubeService(httpMock.Object, config);

            httpMock.SetupSequence(x => x.GetAsync <YouTube.OnlyIdResponse>(It.Is <string>(s => checkApiCall(s, "playlistItems", null))))
            .ReturnsAsync(_mockOnlyIdResponse)
            .ReturnsAsync(_mockOnlyIdResponseSecondPage);
            httpMock.Setup(x => x.GetAsync <YouTube.VideoResponse>(It.Is <string>(s => checkApiCall(s, "videos", null))))
            .ReturnsAsync(new YouTube.VideoResponse
            {
                Items = new List <YouTube.Video> {
                    _mockVideoResponse.Items[0],
                    _mockVideoResponse.Items[1],
                    _mockVideoResponse.Items[2],
                    _mockVideoResponseSecondPage.Items[0]
                }
            });

            // Run
            var videos = await youTubeService.GetPlaylistVideosAsync("1", progressIndicator);

            // Wait for progress
            Thread.Sleep(10);

            // Assert
            Assert.AreEqual(4, videos.Count);
            Assert.Greater(progressCalled, 0);

            // Verify
            httpMock.VerifyAll();
        }
Beispiel #33
0
        public async Task <IEnumerable <Show> > GetShows(int numberOfShows = 25)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = YouTubeApiKey,
                ApplicationName = YouTubeAppName
            });

            //var shows = new List<Show>(numberOfShows);


            var request = youtubeService.PlaylistItems.List("snippet");

            request.PlaylistId = YouTubePlaylistId;
            request.MaxResults = numberOfShows;
            //playlistItemsListRequest.PageToken = nextPageToken;

            // Retrieve the list of videos uploaded to the authenticated user's channel.
            var response = await request.ExecuteAsync();



            var shows = response.Items.Select(item => new Show
            {
                Id           = item.Snippet.ResourceId.VideoId,
                Title        = item.Snippet.Title,
                Description  = item.Snippet.Description,
                ThumbnailUrl = item.Snippet.Thumbnails.Medium.Url,
                Url          = GetVideoUrl(item.Snippet.ResourceId.VideoId,
                                           YouTubePlaylistId, item.Snippet.Position.GetValueOrDefault())
            }).ToList();

            await UpdateLiveStreamingDetails(youtubeService, shows);

            return(shows.OrderByDescending(s => s.ScheduledStartTime));
        }
Beispiel #34
0
        public async Task <IList <SearchResult> > byQuery(string query, type type = type.All)
        {
            string stype = "";

            switch (type)
            {
            case type.Video:
                stype = "video";
                break;

            case type.Channel:
                stype = "channel";
                break;

            case type.Playlist:
                stype = "playlist";
                break;
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyBSFxNBKeB-vPSUz7yZFONWZq6_fHsXUHM",
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");

            searchListRequest.Q          = query; // Replace with your search term.
            searchListRequest.MaxResults = 50;
            searchListRequest.Type       = stype;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = await searchListRequest.ExecuteAsync();

            return(searchListResponse.Items);
        }
Beispiel #35
0
        private async Task Run(string[] args)
        {
            UserCredential credential;

            using (var stream = new FileStream(this.clientSecretFilePath, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                    );
            }


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

            var video = this.GetYtVideoObject(args);

            string filePath = @"C:\Projects\YouTube\sample1.mp4"; // Replace with path two 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();
            }
        }
Beispiel #36
0
        /// <summary>
        /// Manage play list with given youtube service
        ///  required scope : Youtube
        /// </summary>
        /// <param name="youtubeService"></param>
        public static async void ManagePlaylist(YouTubeService youtubeService)
        {
            // Create a new, private playlist in the authorized user's channel.
            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 = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync();

            // Add a video to the newly created playlist.
            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 = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync();

            Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id);
        }
Beispiel #37
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            var service = new YouTubeService("iSpy", MainForm.Conf.YouTubeKey);

            service.setUserCredentials(txtYouTubeUsername.Text, txtYouTubePassword.Text);
            string token = "";

            try
            {
                token = service.QueryClientLoginToken();
            }
            catch (InvalidCredentialsException)
            {
                MessageBox.Show(this, "Login Failed");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (token != "")
            {
                MessageBox.Show(this, "Login OK");
            }
        }
Beispiel #38
0
        public async void Login()
        {
            //https://developers.google.com/youtube/v3/code_samples/dotnet
            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for full read/write access to the
                    // authenticated user's account.
                    new[] { YouTubeService.Scope.Youtube },
                    "user",
                    CancellationToken.None,
                    new FileDataStore("Webplayer")
                    );
            }
            //https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = this.GetType().ToString()
            });
        }
Beispiel #39
0
        public override async Task Initialize()
        {
            string appName = GetType().Assembly.GetName().Name;

            Service = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = await GoogleWebAuthorizationBroker.AuthorizeAsync(UploaderSettings.GoogleSecrets,
                                                                                          new [] {
                    YouTubeService.Scope.Youtube
                },
                                                                                          "youtube",
                                                                                          CancellationToken.None,
                                                                                          UploaderSettings.GoogleDataStore
                                                                                          ),
                ApplicationName = appName,
                GZipEnabled     = true,
            });
            Service.HttpClient.Timeout = TimeSpan.FromMinutes(2);

            if (!Directory.Exists(Path.Combine(Path.GetTempPath(), "MatchUploader")))
            {
                Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "MatchUploader"));
            }
        }
Beispiel #40
0
        async Task Init()
        {
            WebRequest.DefaultWebProxy = _proxySettings.GetWebProxy();

            var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync
                             (
                new ClientSecrets
            {
                ClientId     = _apiKeys.YouTubeClientId,
                ClientSecret = _apiKeys.YouTubeClientSecret
            },
                // This OAuth 2.0 access scope allows an application to upload files to the
                // authenticated user's YouTube channel, but doesn't allow other types of access.
                new[] { YouTubeService.Scope.YoutubeUpload },
                "user",
                CancellationToken.None
                             );

            _youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = nameof(Captura)
            });
        }
        private async Task <ShowList> GetShowsList()
        {
            using (var client = new YouTubeService(new BaseClientService.Initializer
            {
                ApplicationName = _appSettings.YouTubeApplicationName,
                ApiKey = _appSettings.YouTubeApiKey
            }))
            {
                var listRequest = client.PlaylistItems.List("snippet");
                listRequest.PlaylistId = _appSettings.YouTubePlaylistId;
                listRequest.MaxResults = 5 * 3; // 5 rows of 3 episodes

                var playlistItems = await listRequest.ExecuteAsync();

                var result = new ShowList
                {
                    PreviousShows = playlistItems.Items.Select(item => new Show
                    {
                        Provider     = "YouTube",
                        ProviderId   = item.Snippet.ResourceId.VideoId,
                        Title        = GetUsefulBitsFromTitle(item.Snippet.Title),
                        Description  = item.Snippet.Description,
                        ShowDate     = DateTimeOffset.Parse(item.Snippet.PublishedAtRaw, null, DateTimeStyles.RoundtripKind),
                        ThumbnailUrl = item.Snippet.Thumbnails.High.Url,
                        Url          = GetVideoUrl(item.Snippet.ResourceId.VideoId, item.Snippet.PlaylistId, item.Snippet.Position ?? 0)
                    }).ToList()
                };

                if (!string.IsNullOrEmpty(playlistItems.NextPageToken))
                {
                    result.MoreShowsUrl = GetPlaylistUrl(_appSettings.YouTubePlaylistId);
                }

                return(result);
            }
        }
Beispiel #42
0
        /// <summary>
        /// Uploads a custom video thumbnail to YouTube and sets it for a video. 
        /// Documentation https://developers.google.com/youtube/v3/reference/thumbnails/set
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated YouTube service.</param>  
        /// <param name="videoId">The videoId parameter specifies a YouTube video ID for which the custom video thumbnail is being provided.</param>
        /// <param name="optional">Optional paramaters.</param>        /// <returns>ThumbnailSetResponseResponse</returns>
        public static ThumbnailSetResponse Set(YouTubeService service, string videoId, ThumbnailsSetOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (videoId == null)
                    throw new ArgumentNullException(videoId);

                // Building the initial request.
                var request = service.Thumbnails.Set(videoId);

                // Applying optional parameters to the request.                
                request = (ThumbnailsResource.SetRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Thumbnails.Set failed.", ex);
            }
        }
Beispiel #43
0
        public Youtube GetYouTube(Imdb imdb)
        {
            Youtube youtube = new Youtube();

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyDPdiKDpjnwevDYtAMuMiFI0Zhdadl5QzY",
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");
            var titleDescription  = RetrieveTitleDescriptionForSearch(imdb.TitleDescription);

            searchListRequest.Q          = string.Format("{0} {1} trailer", imdb.Title, titleDescription);
            searchListRequest.MaxResults = 1;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = searchListRequest.Execute();

            youtube.Id        = searchListResponse.Items.FirstOrDefault().Id.VideoId;
            youtube.Thumbnail = searchListResponse.Items.FirstOrDefault().Snippet.Thumbnails.Default__.Url;

            return(youtube);
        }
Beispiel #44
0
        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddUserSecrets(Assembly.GetEntryAssembly())
                                .Build();

            var service = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = configuration["YouTubeApiKey"]
            });

            var playlistId = service.GetUploadPlaylist("CaseyNeistat");

            var items = service.GetAllItems(playlistId);

            File.WriteAllText($"{playlistId}.json", JsonConvert.SerializeObject(items.Select(i => new
            {
                title       = i.Snippet.Title,
                videoId     = i.Snippet.ResourceId.VideoId,
                publishedAt = i.Snippet.PublishedAt
            })));

            Console.WriteLine($"Downloaded {playlistId}");
        }
Beispiel #45
0
        private async Task LoadDataCollection()
        {
            var youtubeService = new YouTubeService(
                new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyBws9qCw7wjp-jsYeUWNX_MImMGjFl3e1Y",
                ApplicationName = this.GetType().ToString()
            });

            var request = youtubeService.Search.List("snippet");

            request.Q          = (string)LblMovieName.Content; // {영화이름} 예고편
            request.MaxResults = 10;                           // 사이즈가 크면 멈춰버림

            var response = await request.ExecuteAsync();       // 검색시작(Youtube OpenApi 호출)


            foreach (var item in response.Items)
            {
                if (item.Id.Kind == "youtube#video")
                {
                    YoutubeItem youtube = new YoutubeItem()
                    {
                        Title  = item.Snippet.Title,
                        Author = item.Snippet.ChannelTitle,
                        URL    = $"https://www.youtube.com/watch?v={item.Id.VideoId}"
                    };

                    // 썸네일 이미지
                    youtube.Thumbnail = new BitmapImage(new Uri(item.Snippet.Thumbnails.Default__.Url, UriKind.RelativeOrAbsolute));


                    Youtubes.Add(youtube);
                }
            }
        }
        public void FillInViews(List <YoutubeItemDataType> collection, YouTubeService service)
        {
            if (collection.Count <= 0)
            {
                return;
            }

            for (int i = 0; i <= (collection.Count - 1) / 50; i++)
            {
                string VideoIDs = "";
                int    j        = 0;
                foreach (var video in collection)
                {
                    if (video == null)
                    {
                        collection.RemoveAt(j); break;
                    }
                    VideoIDs += video.Id + ",";
                    j++;
                }
                var getViewsRequest = service.Videos.List("statistics, contentDetails");
                getViewsRequest.Id = VideoIDs.Remove(VideoIDs.Length - 1);

                var videoListResponse = getViewsRequest.Execute();

                for (int k = 0; k < collection.Count; k++)
                {
                    try
                    {
                        collection[k + i * 50].Length       = ISO8601Converter(videoListResponse.Items[k].ContentDetails.Duration);
                        collection[k + i * 50].ViewsAndDate = YoutubeMethodsStatic.ViewCountShortner(videoListResponse.Items[k].Statistics.ViewCount) + collection[k + i * 50].ViewsAndDate;
                    }
                    catch { collection[k + i * 50].ViewsAndDate = "Unknown" + collection[k + i * 50].ViewsAndDate; }
                }
            }
        }
Beispiel #47
0
        public async Task Startup()
        {
            var disclaimer = "This is a note to those looking either in the source code or decompiled. Please do not use my secret :( This is a client-only" +
                             "application so i have to leave my secret in here.";

            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
            {
                ClientId     = "632529535771-jfhmk689ql38k5cc4bg7clplvhorfi4i.apps.googleusercontent.com",
                ClientSecret = "DawckKBXVnuC32bCqL_ZIQkY"
            },
                new[] { YouTubeService.Scope.Youtube },
                "user",
                CancellationToken.None,
                new FileDataStore("Youtube.SuperChatter"));

            Service = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName       = "SuperChatter"
            });

            await GetSuperChats();
        }
Beispiel #48
0
        static public async Task GetLiveChatMessage(string liveChatId, YouTubeService youtubeService, string nextPageToken)
        {
            var liveChatRequest = youtubeService.LiveChatMessages.List(liveChatId, "snippet,authorDetails");

            liveChatRequest.PageToken = nextPageToken;

            System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true);
            var liveChatResponse      = await liveChatRequest.ExecuteAsync();

            foreach (var liveChat in liveChatResponse.Items)
            {
                try
                {
                    Console.WriteLine($"{liveChat.Snippet.DisplayMessage},{liveChat.AuthorDetails.DisplayName}");
                    sw.WriteLine(liveChat.Snippet.DisplayMessage);
                }
                catch { }
            }
            sw.Close();
            await Task.Delay((int)liveChatResponse.PollingIntervalMillis);


            await GetLiveChatMessage(liveChatId, youtubeService, liveChatResponse.NextPageToken);
        }
Beispiel #49
0
        public void YouTubeUploaderTest()
        {
            Tracing.TraceMsg("Entering YouTubeUploaderTest");

            YouTubeQuery query = new YouTubeQuery();

            query.Uri = new Uri(CreateUri(Path.Combine(this.resourcePath, "uploaderyt.xml")));

            YouTubeService service = new YouTubeService("NETUnittests", this.ytDevKey);

            if (!string.IsNullOrEmpty(this.ytUser))
            {
                service.Credentials = new GDataCredentials(this.ytUser, this.ytPwd);
            }

            YouTubeFeed  feed  = service.Query(query);
            YouTubeEntry entry = feed.Entries[0] as YouTubeEntry;

            YouTube.MediaCredit uploader = entry.Uploader;
            Assert.IsTrue(uploader != null);
            Assert.IsTrue(uploader.Role == "uploader");
            Assert.IsTrue(uploader.Scheme == "urn:youtube");
            Assert.IsTrue(uploader.Value == "GoogleDevelopers");
        }
        /// <summary>
        /// Get access and refresh tokens from user's account
        /// </summary>
        /// <param name="youTubeClientId"></param>
        /// <param name="youTubeClientSecret"></param>
        public override async Task <bool> GetAuthAsync(string youTubeClientId, string youTubeClientSecret)
        {
            try
            {
                string clientSecrets = @"{ 'installed': {'client_id': '" + youTubeClientId + "', 'client_secret': '" + youTubeClientSecret + "'} }";

                UserCredential credential;
                using (Stream stream = clientSecrets.ToStream())
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { YouTubeService.Scope.Youtube },
                        "user",
                        CancellationToken.None,
                        new FileDataStore("Twitch Bot")
                        );
                }

                YouTubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "Twitch Bot"
                });

                return(true);
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("access_denied")) // record unknown error
                {
                    await _errHndlrInstance.LogError(ex, "YouTubeClient", "GetAuth(string, string)", false);
                }

                return(false);
            }
        }
Beispiel #51
0
        // Sending comment
        private static async Task <string> SendComment(string url)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = key,
                HttpClientInitializer = credential,
                ApplicationName       = "YoutubeApp"
            });

            // Making a comment
            var commentThread              = new CommentThread();
            CommentThreadSnippet snippet   = new CommentThreadSnippet();
            Comment        topLevelComment = new Comment();
            CommentSnippet commentSnippet  = new CommentSnippet();

            commentSnippet.TextOriginal = GetRandomComment();
            topLevelComment.Snippet     = commentSnippet;
            snippet.TopLevelComment     = topLevelComment;
            snippet.VideoId             = url;
            commentThread.Snippet       = snippet;
            // Sending a query
            var query = youtubeService.CommentThreads.Insert(commentThread, "snippet");

            try
            {
                var resp = await query.ExecuteAsync();

                Console.WriteLine("Комментарий отправлен");
                return(resp.Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(string.Empty);
        }
        /// <param name="optional">Optional paramaters.</param>        /// <returns>SubscriptionListResponseResponse</returns>
        public static SubscriptionListResponse List(YouTubeService service, string part, SubscriptionsListOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (part == null)
                    throw new ArgumentNullException(part);

                // Building the initial request.
                var request = service.Subscriptions.List(part);

                // Applying optional parameters to the request.                
                request = (SubscriptionsResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Subscriptions.List failed.", ex);
            }
        }
        private async Task <YouTubeService> AuthenticateUserServiceAsync()
        {
            var            folder = System.IO.Path.GetFullPath(@"..\..\");
            UserCredential credential;

            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.Youtube },
                    Environment.UserName,
                    CancellationToken.None,
                    new FileDataStore(folder)
                    );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Music App"
            });

            return(youtubeService);
        }
Beispiel #54
0
        private async Task Run(string searchString)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = API_KEY,
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");

            searchListRequest.Q          = searchString;
            searchListRequest.MaxResults = numberSearchResult;

            var searchListResponse = searchListRequest.Execute();


            foreach (var searchResult in searchListResponse.Items)
            {
                if (searchResult.Id.Kind == "youtube#video")
                {
                    video.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                }
            }
        }
Beispiel #55
0
        public List <SearchResult> GetVidsForNewsEntity(string channelId)
        {
            List <SearchResult> newVids = new List <SearchResult>();

            var youtTubeApiKey = Configuration["IntegrationSettings:YouTube:ApiKey"];

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = youtTubeApiKey,
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("snippet");


            searchListRequest.MaxResults = 20;
            searchListRequest.ChannelId  = channelId;
            searchListRequest.Order      = 0;


            try
            {
                var searchLasistResponse = searchListRequest.Execute();
            }
            catch (Exception ex)
            {
                var test = ex.Message;
            }


            var searchListResponse = searchListRequest.Execute();

            newVids = new List <SearchResult>(searchListResponse.Items);

            return(newVids);
        }
Beispiel #56
0
        /// Guts of the program that actually calls service and retrieves our video result
        private async Task Run(string searchParams)
        {
            // Instantiate the service and set ApiKey
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = this.ApiKey,
                ApplicationName = this.GetType().ToString()
            });

            // Instantiate the search request and set the params and num of results
            var searchListRequest = youtubeService.Search.List("snippet");

            searchListRequest.Q          = searchParams; // Replace with your search term.
            searchListRequest.MaxResults = 1;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = await searchListRequest.ExecuteAsync();

            // Grab the first video ID from the search.list respons
            var vidurl = searchListResponse.Items[0].Id.VideoId;

            // Propagate the video ID
            yturl = vidurl;
        }
        private async Task <VideoDto> GetCurrentLiveStream()
        {
            YouTubeService t = new YouTubeService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                ApiKey          = ApiKey,
                ApplicationName = "TimeStampBot"
            });

            SearchResource.ListRequest request = t.Search.List("id");
            request.ChannelId  = "UC_a1ZYZ8ZTXpjg9xUY9sj8w";
            request.EventType  = SearchResource.ListRequest.EventTypeEnum.Live;
            request.MaxResults = 1;
            request.Type       = "video";
            request.Fields     = "items(id(videoId))";
            SearchListResponse result = await request.ExecuteAsync();

            SearchResult livestream = result.Items.FirstOrDefault();

            return(new VideoDto()
            {
                VideoId = livestream?.Id.VideoId,
                StartTime = TimeZoneInfo.ConvertTimeToUtc(DateTime.Parse(livestream.Snippet.PublishedAt))
            });
        }
Beispiel #58
0
        public async Task <bool> Authorization()
        {
            UserCredential credential;

            GetAPIKeyAndClientSecret(out string apiKey, out Stream stream);

            using ( stream )
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load ( stream ).Secrets,
                    new [] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                    );
            }

            if (credential == null)
            {
                return(false);
            }

            YouTubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey                = apiKey,
                ApplicationName       = "DaramYouTubeUploader",
                GZipEnabled           = true,
                HttpClientInitializer = credential,
                HttpClientFactory     = new MyHttpClientFactory(),
            });
            YouTubeService.HttpClient.Timeout = TimeSpan.FromMinutes(5);

            PC(nameof(IsAuthorized));
            PC(nameof(IsAlreadyAuthorized));

            return(true);
        }
Beispiel #59
0
        public async Task CommunityVideosCommand(string url, [Remainder] string desc = "")
        {
            bool validUser = false;
            var  channelId = "";

            using (var communityVideoIds = new StreamReader($"Resources{Path.DirectorySeparatorChar}CommunityVideoIds.csv"))
            {
                while (!communityVideoIds.EndOfStream && !validUser)
                {
                    var person = (await communityVideoIds.ReadLineAsync()) !.Split(',');
                    if (Context.User.Id == Convert.ToUInt64(person[0]))
                    {
                        validUser = true;
                        channelId = person[1];
                    }
                }
            }

            if (!validUser)
            {
                await ReplyAsync(new StringBuilder("It doesn't look like you're allowed to post in <#442474624417005589>.\n\n")
                                 .Append("If you have more than 25 subs, post reasonable Algodoo-related content and are in good standing with the rules, sign up here: https://goo.gl/forms/opPSzUg30BECNku13 \n\n")
                                 .Append("If you're an accepted user, please notify Doc671.")
                                 .ToString());

                return;
            }

            using var youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = _botCredentials.GoogleApiKey,
                ApplicationName = GetType().ToString()
            });

            string videoId = url.Contains("https://www.youtube.com/watch?v=")
                ? url[32..]  // removes "https://www.youtube.com/watch?v="
Beispiel #60
-1
        public static List<YoutubePlaylistObject> FeedRelatedVideo(string youtubeId)
        {
            List<YoutubePlaylistObject> ListVideo = new List<YoutubePlaylistObject>();
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = WebConfigurationManager.AppSettings["ApiKey"],
                ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
            });

            var searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.RelatedToVideoId = youtubeId;
            searchListRequest.MaxResults = 50;
            searchListRequest.Type = "video";

            //Call fist request
            // Call the search.list method to retrieve results matching the specified query term.
            Google.Apis.YouTube.v3.Data.SearchListResponse searchListResponse;
            searchListResponse = searchListRequest.Execute();//.ExecuteAsync();
            //Break if nothing to feed
            int Round = 0;
            do
            {
                searchListResponse = searchListRequest.Execute();//.ExecuteAsync();
                //Break if nothing to feed
                ListVideo.AddRange(ProcessResult(searchListResponse, null));
                searchListRequest.PageToken = searchListResponse.NextPageToken;
                Round++;

            } while (!string.IsNullOrEmpty(searchListResponse.NextPageToken) || Round > 10);

            return ListVideo;
        }