Example #1
0
        public async Task TestMethod()
        {
            var youtubeService = new YoutubeService();
            var searchResults  = await youtubeService.GetVideosAsync("Corey Taylor");

            Debug.WriteLine(searchResults.ElementAt(0).Title);
        }
Example #2
0
        public async void Start()
        {
            try
            {
                if (_timer == null)
                {
                    Logger.Info("Server has been started");

                    Logger.Info("Enter Api key (30 seconds waiting): ");

                    if (LoadSettingsFromFile())
                    {
                        _youtubeService = new YoutubeService(_settings.Token);

                        await InitChannelsFromFile();

                        _timer = new Timer(HandlerRepostMessage, null, _settings.Timeout,
                                           _settings.Timeout);
                        Logger.Info("Repost handler started!");
                    }
                    else
                    {
                        throw new Exception(
                                  "Fatal Error. Settings (/Resources/settings.json) not found! You should add settings.json and restart service!");
                    }
                }
            }
            catch (Exception ex)
            {
                var mes = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                Logger.Warn($"{DateTime.UtcNow.AddHours(3).ToShortTimeString()} Repost error: {ex.GetType()} {mes}");
                Logger.Error($"{DateTime.UtcNow.AddHours(3).ToShortTimeString()} Repost error: {ex.ToString()}");
                Logger.Info($"{DateTime.UtcNow.AddHours(3).ToShortTimeString()} Repost error {ex.GetType()} {mes}");
            }
        }
        /// <summary>
        /// Uploads a watermark image to YouTube and sets it for a channel.
        /// Documentation https://developers.google.com/youtube/v3/reference/watermarks/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="channelId">The channelId parameter specifies the YouTube channel ID for which the watermark is being provided.</param>
        /// <param name="body">A valid Youtube v3 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        public static void Set(YoutubeService service, string channelId, InvideoBranding body, WatermarksSetOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (channelId == null)
                {
                    throw new ArgumentNullException(channelId);
                }

                // Building the initial request.
                var request = service.Watermarks.Set(body, channelId);

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

                // Requesting data.
                request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Watermarks.Set failed.", ex);
            }
        }
Example #4
0
        public VideoTitleParseResult GetTitle(string id)
        {
            var service = new YoutubeService(AppConfig.YoutubeApiKey);

            YoutubeVideoResponse result;

            try {
                result = service.Video(id);
            } catch (WebException x) {
                return(VideoTitleParseResult.CreateError(x.Message));
            }

            if (!result.Items.Any())
            {
                return(VideoTitleParseResult.Empty);
            }

            var video       = result.Items.First();
            var thumbUrl    = video.Snippet.Thumbnails.Default != null ? video.Snippet.Thumbnails.Default.Url : string.Empty;
            var length      = GetLength(video);
            var author      = video.Snippet.ChannelTitle;
            var publishDate = GetPublishDate(video);

            return(VideoTitleParseResult.CreateSuccess(video.Snippet.Title, author, thumbUrl, length, uploadDate: publishDate));
        }
        public void LoadData()
        {
            IsBusy = true;

            // Load data with services
            Items  = FeedService.GetAll();
            Videos = YoutubeService.GetAll();

            // Check if user enabled the Twitter feature.
            if (Preferences.Get(ENABLE_TWITTER_FEED_PREF_KEY, false))
            {
                // Update binded Tweets member with service-based tweets.
                Tweets = TwitterService.GetAll();
            }
            else
            {
                // Else return dummy tweet entry with helpful text that the
                // feature is disabled by the user.
                Tweets = new List <Tweet> {
                    CreateFeatureInfoTweet()
                };
            }

            IsBusy = false;
        }
Example #6
0
        private static async Task ThreadForYoutube()
        {
            YoutubeService SearchTime = new YoutubeService(youtubekey);

            while (true)
            {
                await semaphore.WaitAsync();

                try {
                    try {
                        var VID = SearchTime.Search().Result;
                        if (VID != null)
                        {
                            await Tweet1("Checkout Blunder's New VID https://www.youtube.com/watch?v=" + VID.VidID);
                        }
                    }
                    catch (AggregateException ex)
                    {
                        //Incase youtube throws an error for going over the quota
                        foreach (var e in ex.InnerExceptions)
                        {
                            Console.WriteLine("Error: " + e.Message);
                        }
                    }
                }
                finally
                {
                    semaphore.Release();
                }

                Thread.Sleep(15 * 60 * 1000); //Since you're only allowed 100 searches per day for the youtube API, floor(100/24)=4, so 4 searches per hour.
            }
        }
        /// <summary>
        /// Sets the moderation status of one or more comments. The API request must be authorized by the owner of the channel or video associated with the comments.
        /// Documentation https://developers.google.com/youtube/v3/reference/comments/setModerationStatus
        /// 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="id">The id parameter specifies a comma-separated list of IDs that identify the comments for which you are updating the moderation status.</param>
        /// <param name="moderationStatus">Identifies the new moderation status of the specified comments.</param>
        /// <param name="optional">Optional paramaters.</param>
        public static void SetModerationStatus(YoutubeService service, string id, string moderationStatus, CommentsSetModerationStatusOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (id == null)
                {
                    throw new ArgumentNullException(id);
                }
                if (moderationStatus == null)
                {
                    throw new ArgumentNullException(moderationStatus);
                }

                // Building the initial request.
                var request = service.Comments.SetModerationStatus(id, moderationStatus);

                // Applying optional parameters to the request.
                request = (CommentsResource.SetModerationStatusRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Comments.SetModerationStatus failed.", ex);
            }
        }
        //default argument
        public static YoutubeResults NormalSearch(string searchString)
        {
            YoutubeService youtube = new YoutubeService();
            youtube.Key = ConfigurationManager.AppSettings["GoogleAPIKey"]; //Gets the API key from app settings at azure

            SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
            listRequest.Q = searchString;
            listRequest.Order = SearchResource.Order.Relevance;

            SearchListResponse searchResponse = listRequest.Fetch();

            YoutubeResults searchResults = new YoutubeResults();
            searchResults.titles = new List<string>();
            searchResults.videoIDs = new List<string>();
            searchResults.thumbnailURLs = new List<string>();
            searchResults.descriptions = new List<string>();

            foreach (SearchResult searchResult in searchResponse.Items)
            {
                if (searchResult.Id.Kind == "youtube#video")
                {
                    searchResults.titles.Add(searchResult.Snippet.Title);

                    searchResults.thumbnailURLs.Add(searchResult.Snippet.Thumbnails[searchResult.Snippet.Thumbnails.Keys.ToArray()[0]].Url);
                    searchResults.videoIDs.Add(searchResult.Id.VideoId);

                    searchResults.descriptions.Add(searchResult.Snippet.Description);
                }
            }

            return searchResults;
        }
        /// <summary>
        /// Adds a new ban to the chat.
        /// Documentation https://developers.google.com/youtube/v3/reference/liveChatBans/insert
        /// 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="part">The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response returns. Set the parameter value to snippet.</param>
        /// <param name="body">A valid Youtube v3 body.</param>
        /// <returns>LiveChatBanResponse</returns>
        public static LiveChatBan Insert(YoutubeService service, string part, LiveChatBan body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Make the request.
                return(service.LiveChatBans.Insert(body, part).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request LiveChatBans.Insert failed.", ex);
            }
        }
        /// <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);
            }
        }
Example #11
0
 public MusicCommands(MusicService music, Bot bot, YoutubeService youtube, DatabaseContext db)
 {
     this.Music    = music;
     this.Bot      = bot;
     this.Youtube  = youtube;
     this.Database = db;
 }
        /// <summary>
        /// Modifies the top-level comment in a comment thread.
        /// Documentation https://developers.google.com/youtube/v3/reference/commentThreads/update
        /// 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="part">The part parameter specifies a comma-separated list of commentThread resource properties that the API response will include. You must at least include the snippet part in the parameter value since that part contains all of the properties that the API request can update.</param>
        /// <param name="body">A valid Youtube v3 body.</param>
        /// <returns>CommentThreadResponse</returns>
        public static CommentThread Update(YoutubeService service, string part, CommentThread body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Make the request.
                return(service.CommentThreads.Update(body, part).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request CommentThreads.Update failed.", ex);
            }
        }
Example #13
0
        private static async Task Main(string[] args)
        {
            Directory.CreateDirectory(OutputFolderPath);

            var youtubeService = new YoutubeService();

            Console.Write("Playlist Link:");
            var playlist = await youtubeService.GetPlaylistAsync(Console.ReadLine());

            foreach (var video in playlist.Videos)
            {
                var stream = (await youtubeService.GetMediaStreamsAsync($"youtu.be/{video.EncryptedId}"))
                             .OfType <MixedStream>().FirstOrDefault();
                if (stream == null)
                {
                    var oldForegroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"No mixed streams found for video \"{video.Title}\"");
                    Console.ForegroundColor = oldForegroundColor;
                    continue;
                }

                Console.WriteLine($"Downloading {video.Title}");
                await youtubeService.DownloadMediaStreamAsync(stream,
                                                              Path.Combine(OutputFolderPath, $"{InvalidCharactersRegex.Replace(video.Title, string.Empty)}.mp3"));

                Console.WriteLine("\t--> Done");
            }

            Console.ReadKey();
        }
Example #14
0
 public YoutubeController(
     AccountService accountService,
     YoutubeService youtubeService)
 {
     _youtubeService = youtubeService;
     _accountService = accountService;
 }
        /// <summary>
        /// Returns a list of videos that match the API request parameters.
        /// Documentation https://developers.google.com/youtube/v3/reference/videos/list
        /// 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="part">The part parameter specifies a comma-separated list of one or more video resource properties that the API response will include.If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a video resource, the snippet property contains the channelId, title, description, tags, and categoryId properties. As such, if you set part=snippet, the API response will contain all of those properties.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>VideoListResponseResponse</returns>
        public static VideoListResponse List(YoutubeService service, string part, VideosListOptionalParms 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.Videos.List(part);

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

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Videos.List failed.", ex);
            }
        }
        /// <summary>
        /// Uploads a channel banner image to YouTube. This method represents the first two steps in a three-step process to update the banner image for a channel:- Call the channelBanners.insert method to upload the binary image data to YouTube. The image must have a 16:9 aspect ratio and be at least 2120x1192 pixels.- Extract the url property's value from the response that the API returns for step 1.- Call the channels.update method to update the channel's branding settings. Set the brandingSettings.image.bannerExternalUrl property's value to the URL obtained in step 2.
        /// Documentation https://developers.google.com/youtube/v3/reference/channelBanners/insert
        /// 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="body">A valid Youtube v3 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>ChannelBannerResourceResponse</returns>
        public static ChannelBannerResource Insert(YoutubeService service, ChannelBannerResource body, ChannelBannersInsertOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }

                // Building the initial request.
                var request = service.ChannelBanners.Insert(body);

                // Applying optional parameters to the request.
                request = (ChannelBannersResource.InsertRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request ChannelBanners.Insert failed.", ex);
            }
        }
        /// <summary>
        /// Add a like or dislike rating to a video or remove a rating from a video.
        /// Documentation https://developers.google.com/youtube/v3/reference/videos/rate
        /// 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="id">The id parameter specifies the YouTube video ID of the video that is being rated or having its rating removed.</param>
        /// <param name="rating">Specifies the rating to record.</param>
        public static void Rate(YoutubeService service, string id, string rating)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (id == null)
                {
                    throw new ArgumentNullException(id);
                }
                if (rating == null)
                {
                    throw new ArgumentNullException(rating);
                }

                // Make the request.
                service.Videos.Rate(id, rating).Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Videos.Rate failed.", ex);
            }
        }
Example #18
0
        public async Task <ActionResult> FormTwo(Models.SocialMedia model)
        {
            ViewBag.Collection = null;
            if (ModelState.IsValid)
            {
                if (model.Type.ToString() == "Youtube")
                {
                    var    instance   = new YoutubeService();
                    string playListID = "PLrQMMjaEqBpNTb40EHXeD_3r5Q2UyMjC2";

                    Array testOutput = await instance.getPlayList(playListID);

                    ViewBag.Collection = testOutput;
                }

                if (model.Type.ToString() == "Spotify")
                {
                    var             instanceSpot  = new SpotifyService();
                    SpotifyPlaylist testOutput123 = await instanceSpot.GetPlayList();

                    //System.Diagnostics.Debug.WriteLine(testOutput123.Tracks.Items[0].Track.Name);

                    ViewBag.Collection = testOutput123;
                }
            }
            return(View("index", model));
        }
        /// <summary>
        /// Deletes a YouTube video.
        /// Documentation https://developers.google.com/youtube/v3/reference/videos/delete
        /// 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="id">The id parameter specifies the YouTube video ID for the resource that is being deleted. In a video resource, the id property specifies the video's ID.</param>
        /// <param name="optional">Optional paramaters.</param>
        public static void Delete(YoutubeService service, string id, VideosDeleteOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (id == null)
                {
                    throw new ArgumentNullException(id);
                }

                // Building the initial request.
                var request = service.Videos.Delete(id);

                // Applying optional parameters to the request.
                request = (VideosResource.DeleteRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Videos.Delete failed.", ex);
            }
        }
        /// <summary>
        /// Binds a YouTube broadcast to a stream or removes an existing binding between a broadcast and a stream. A broadcast can only be bound to one video stream, though a video stream may be bound to more than one broadcast.
        /// Documentation https://developers.google.com/youtube/v3/reference/liveBroadcasts/bind
        /// 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="id">The id parameter specifies the unique ID of the broadcast that is being bound to a video stream.</param>
        /// <param name="part">The part parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>LiveBroadcastResponse</returns>
        public static LiveBroadcast Bind(YoutubeService service, string id, string part, LiveBroadcastsBindOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (id == null)
                {
                    throw new ArgumentNullException(id);
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Building the initial request.
                var request = service.LiveBroadcasts.Bind(id, part);

                // Applying optional parameters to the request.
                request = (LiveBroadcastsResource.BindRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request LiveBroadcasts.Bind failed.", ex);
            }
        }
        /// <summary>
        /// Updates a channel's metadata. Note that this method currently only supports updates to the channel resource's brandingSettings and invideoPromotion objects and their child properties.
        /// Documentation https://developers.google.com/youtube/v3/reference/channels/update
        /// 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="part">The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.The API currently only allows the parameter value to be set to either brandingSettings or invideoPromotion. (You cannot update both of those parts with a single request.)Note that this method overrides the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies.</param>
        /// <param name="body">A valid Youtube v3 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>ChannelResponse</returns>
        public static Channel Update(YoutubeService service, string part, Channel body, ChannelsUpdateOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Building the initial request.
                var request = service.Channels.Update(body, part);

                // Applying optional parameters to the request.
                request = (ChannelsResource.UpdateRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Channels.Update failed.", ex);
            }
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var button = FindViewById <Button>(Resource.Id.MyButton);

            button.Click += async(s, e) =>
            {
                var text = FindViewById <TextView>(Resource.Id.MyText);

                try
                {
                    text.Text = "Please wait";
                    var service = new YoutubeService();
                    text.Text = await service.Refresh();
                }
                catch (Exception ex)
                {
                    text.Text = ex.Message;
                }
            };
        }
Example #23
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (string.IsNullOrWhiteSpace(ConfigurationService.UserName) ||
                string.IsNullOrWhiteSpace(ConfigurationService.DeviceId) ||
                string.IsNullOrWhiteSpace(ConfigurationService.DeviceKey))
            {
                var dialog = new UserNameDialog();
                ContentDialogResult result;
                do
                {
                    result = await dialog.ShowAsync();
                } while (result != ContentDialogResult.Primary);
            }

            MotionConfig.Text             = ConfigurationService.Motion;
            ConfigurationService.Playlist = await YoutubeService.GetYoutubeURI();

            NavigateToList(0);

            UserName.Text = ConfigurationService.UserName;
            DeviceId.Text = ConfigurationService.DeviceId;

            await Init();

            GetEmotions(null, null);
            dispatcherTimer.Tick += GetEmotions;
            dispatcherTimer.Start();
        }
        /// <summary>
        /// Creates a video stream. The stream enables you to send your video to YouTube, which can then broadcast the video to your audience.
        /// Documentation https://developers.google.com/youtube/v3/reference/liveStreams/insert
        /// 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="part">The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.The part properties that you can include in the parameter value are id, snippet, cdn, and status.</param>
        /// <param name="body">A valid Youtube v3 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>LiveStreamResponse</returns>
        public static LiveStream Insert(YoutubeService service, string part, LiveStream body, LiveStreamsInsertOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Building the initial request.
                var request = service.LiveStreams.Insert(body, part);

                // Applying optional parameters to the request.
                request = (LiveStreamsResource.InsertRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request LiveStreams.Insert failed.", ex);
            }
        }
Example #25
0
 public Music(MusicPlayerService music, MultichannelAudioService audio, YoutubeService youtube, MusicRatingService ratings, Random random)
 {
     _music   = music;
     _audio   = audio;
     _youtube = youtube;
     _ratings = ratings;
     _random  = random;
 }
Example #26
0
 public YoutubeController(IConfiguration configuration, IHubContext <ChatHub> chatHubContext,
                          YoutubeService youtubeService, UserService userService, ConfigurationService configurationService)
 {
     this.chatHubContext       = chatHubContext;
     this.youtubeService       = youtubeService;
     this.userService          = userService;
     this.configurationService = configurationService;
 }
Example #27
0
 public IntegrationController(IntegrationService integrationService, YoutubeService youtubeService,
                              TwitchService twitchService, DiscordService discordService)
 {
     this.integrationService = integrationService;
     this.youtubeService     = youtubeService;
     this.twitchService      = twitchService;
     this.discordService     = discordService;
 }
 public DefaultController(YoutubeService youtubeService, ApplicationDbContext db, EmotionServiceClient emotionService, IHostingEnvironment hostingEnvironment, AzureStorageService storageService, FFMpegLocator ffmpegLocator)
 {
     this.youtubeService     = youtubeService;
     this.db                 = db;
     this.emotionService     = emotionService;
     this.hostingEnvironment = hostingEnvironment;
     this._StorageService    = storageService;
     this._FFMpegLocator     = ffmpegLocator;
 }
Example #29
0
        private void InitClass()
        {
            _mqttService         = new MqttService(this);
            _youtubeService      = new YoutubeService();
            _textService         = new SpeechToTextService();
            _cloudStorageService = new CloudStorageService();

            _textService.OnStatusChanged  += _textService_OnStatusChanged;
            _textService.OnTranscribeDone += _textService_OnTranscribeDone;
        }
        private async void LoadVideos()
        {
            var service = new YoutubeService();

            var channelId = await service.GetYoutubeId("paint");

            var items = await service.GetVideosAsync(channelId);

            this.listView.ItemsSource = items;
        }
Example #31
0
        public MainPage()
        {
            this.InitializeComponent();

            RefreshButton.Click += async(s, e) =>
            {
                var service = new YoutubeService();
                MyText.Text = await service.Refresh();
            };
        }
Example #32
0
        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();
        }
Example #33
0
        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();
        }
Example #34
0
        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();
        }
        public static YoutubeResults getResultsForList(List<SongStruct> songs)
        {
            YoutubeService youtube = new YoutubeService();
            youtube.Key = ConfigurationManager.AppSettings["GoogleAPIKey"]; //Gets the API key from app settings at azure

            YoutubeResults searchResults = new YoutubeResults();
            searchResults.titles = new List<string>();
            searchResults.videoIDs = new List<string>();
            searchResults.thumbnailURLs = new List<string>();
            searchResults.descriptions = new List<string>();

            for (int i = 0; i < songs.Count; i++)
            {
                string artist = songs[i].artist;
                string song = songs[i].title;
                //int duration = songs[i].duration;

                string searchString = artist + " " + song;

                SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
                listRequest.Q = searchString;
                listRequest.Order = SearchResource.Order.Relevance;
                listRequest.MaxResults = 1;
                listRequest.Type = "video";

                SearchListResponse searchResponse = listRequest.Fetch();

                SearchResult searchResult = searchResponse.Items[0];

                searchResults.titles.Add(searchResult.Snippet.Title);

                searchResults.thumbnailURLs.Add(searchResult.Snippet.Thumbnails[searchResult.Snippet.Thumbnails.Keys.ToArray()[0]].Url);
                searchResults.videoIDs.Add(searchResult.Id.VideoId);
                searchResults.descriptions.Add(searchResult.Snippet.Description);
            }

            return searchResults;
        }
    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();
    }