Example #1
0
        private async Task descargarListaReproduccionHDAsync(string id)
        {
            // Get playlist info
            updateProgressBar(7, "Recogiendo informacion de lista de reproducción...");
            var playlist = await YoutubeClient.GetPlaylistAsync(id);

            updateProgressBar(9, "Información de lista de reproducción recogida.");
            // Work on the videos
            int numVideo = 1;

            foreach (var video in playlist.Videos)
            {
                updateProgressBar(10, "Empezando con el video Nº: " + numVideo);
                numVideo++;
                if ((bool)rb_normal.IsChecked)
                {
                    await descargarVideoHDAsync(video.Id);
                }
                else if ((bool)rb_audio.IsChecked)
                {
                    await DescargarSoloAudioMP3(video.Id);
                }
                else if ((bool)rb_video.IsChecked)
                {
                    await DescargarVideoSinAudioAsync(video.Id);
                }
            }
        }
        private async void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (YoutubeClient.TryParsePlaylistId(PlaylistLinkTextBox.Text, out string playlistId))
                {
                    _ = Task.Run(async() =>
                    {
                        list = await client.GetPlaylistAsync(playlistId).ConfigureAwait(false);
                        VideoList.Clear();
                        await UpdatePlaylistInfo(Visibility.Visible, list.Title, list.Author, list.Statistics.ViewCount.ToString(), list.Videos.Count.ToString(), $"https://img.youtube.com/vi/{list?.Videos?.FirstOrDefault()?.Id}/0.jpg", true, true);
                    }).ConfigureAwait(false);
                }
                else if (YoutubeClient.TryParseChannelId(PlaylistLinkTextBox.Text, out string channelId))
                {
                    _ = Task.Run(async() =>
                    {
                        channel = await client.GetChannelAsync(channelId).ConfigureAwait(false);
                        list    = await client.GetPlaylistAsync(channel.GetChannelVideosPlaylistId());
                        VideoList.Clear();
                        await UpdatePlaylistInfo(Visibility.Visible, channel.Title, list.Author, list.Statistics.ViewCount.ToString(), list.Videos.Count.ToString(), channel.LogoUrl, true, true);
                    }).ConfigureAwait(false);
                }
                else if (YoutubeClient.TryParseUsername(PlaylistLinkTextBox.Text, out string username))
                {
                    _ = Task.Run(async() =>
                    {
                        string channelID = await client.GetChannelIdAsync(username).ConfigureAwait(false);
                        var channel      = await client.GetChannelAsync(channelID).ConfigureAwait(false);
                        list             = await client.GetPlaylistAsync(channel.GetChannelVideosPlaylistId()).ConfigureAwait(false);
                        VideoList.Clear();
                        await UpdatePlaylistInfo(Visibility.Visible, channel.Title, list.Author, list.Statistics.ViewCount.ToString(), list.Videos.Count.ToString(), channel.LogoUrl, true, true);
                    }).ConfigureAwait(false);
                }
                else if (YoutubeClient.TryParseVideoId(PlaylistLinkTextBox.Text, out string videoId))
                {
                    _ = Task.Run(async() =>
                    {
                        var video = await client.GetVideoAsync(videoId);
                        VideoList.Clear();
                        VideoList.Add(video);
                        list = null;
                        await UpdatePlaylistInfo(Visibility.Visible, video.Title, video.Author, video.Statistics.ViewCount.ToString(), string.Empty, $"https://img.youtube.com/vi/{video.Id}/0.jpg", true, false);
                    }).ConfigureAwait(false);
                }
                else
                {
                    await UpdatePlaylistInfo().ConfigureAwait(false);
                }
            }

            catch (Exception ex)
            {
                await GlobalConsts.Log(ex.ToString(), "MainPage TextBox_TextChanged");

                await GlobalConsts.ShowMessage((string)FindResource("Error"), ex.Message);
            }
        }
Example #3
0
        private async Task ParsePlaylist(GuildInfo guild, IMessageChannel channel, IUser user, string path, YoutubeClient youtube, string id)
        {
            var playlist = await youtube.GetPlaylistAsync(id);

            int added      = 0;
            int couldntAdd = 0;
            var maxSongs   = int.Parse(guild.Config["MaxSongsPerUser"].ToString());

            foreach (Video video in playlist.Videos)
            {
                var songs = guild.Songs;
                if (video.Duration.TotalMinutes > _maxMinutesForVideo || (int)video.Duration.TotalMinutes == 0 ||
                    (!((IGuildUser)user).GuildPermissions.BanMembers && songs.ToArray().Count(x => x.AuthorId == user.Id) == maxSongs))
                {
                    couldntAdd++;
                    continue;
                }

                AddVideo(guild, channel, user, video, false);
                added++;
            }

            string message = "";

            message += $"Added {added} video(s) to the Queue.";
            if (couldntAdd > 0)
            {
                message += $"\nCould not add {couldntAdd} video(s) to the Queue.";
            }

            await channel.SendMessageAsync(message);
        }
Example #4
0
        private static async void AddDownloadItems(string url, Panel pnl)
        {
            try
            {
                YoutubeClient client = new YoutubeClient();

                //Get the playlist object from the id
                YoutubeExplode.Models.Playlist playList = await client.GetPlaylistAsync(url);

                //We now have a playlist with every video from that playlist. (.Videos)
                foreach (YoutubeExplode.Models.Video video in playList.Videos)
                {
                    DownloadItem item = new DownloadItem(video);
                    //Determines where to place the downloadItem
                    int y = 0;
                    if (downloadItems.Count > 0)
                    {
                        y = downloadItems[downloadItems.Count - 1].Location.Y + item.Height;
                    }


                    pnl.Controls.Add(item);
                    item.Location = new Point(item.Location.X, y);
                    downloadItems.Add(item);
                }
            }
            catch (Exception)
            {
                MessageFormManager.MakeMessagePopup("Something went wrong!", "Could not find a video with that youtube url!\r\nPlease try again.", 5);
            }
        }
Example #5
0
        /// <summary>
        /// Gets the playlists videos.
        /// </summary>
        /// <param name="id">The id of the playlist.</param>
        /// <returns>The video info.</returns>
        public async Task <List <VideoInfo> > GetYoutubePlayList(string id)
        {
            var client   = new YoutubeClient();
            var playlist = await client.GetPlaylistAsync(id);

            return(playlist.Videos.Select(v => new VideoInfo(v)).ToList());
        }
Example #6
0
        private static async Task <IEnumerable <string> > ParseRequest(HttpRequestMessage req)
        {
            var param = req.GetQueryNameValuePairs().FirstOrDefault(kvp => kvp.Key == "v");
            var v     = param.Value;

            if (string.IsNullOrEmpty(v))
            {
                v = await req.Content.ReadAsStringAsync();
            }
            var result = new HashSet <string>();

            foreach (var p in v.Split(Environment.NewLine, ",", " "))
            {
                var playlistId = GetPlaylistId(p);
                if (string.IsNullOrEmpty(playlistId))
                {
                    var videoId = GetVideoId(p);
                    if (!string.IsNullOrEmpty(videoId))
                    {
                        result.Add(videoId);
                    }
                }
                else
                {
                    var playlist = await YoutubeClient.GetPlaylistAsync(playlistId);

                    result.AddRange(playlist.Videos.Select(video => video.Id));
                }
            }
            return(result);
        }
Example #7
0
        private static Playlist GetPlaylist(string playlistId)
        {
            Console.WriteLine($"Getting playlist {playlistId}");
            var client = new YoutubeClient();

            return(client.GetPlaylistAsync(playlistId).Result);
        }
Example #8
0
        public async Task PobierzAsync()
        {
            try
            {
                var client = new YoutubeClient();
                var url    = textBox1.Text;
                var id     = YoutubeClient.ParsePlaylistId(url);

                var playlist = await client.GetPlaylistAsync(id);

                foreach (var vid in playlist.Videos)
                {
                    var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(vid.Id);

                    var streamInfo = streamInfoSet.Audio.WithHighestBitrate();
                    var ext        = streamInfo.Container.GetFileExtension();
                    var video      = await client.GetVideoAsync(vid.Id);

                    string sourcePath = $"C:/YTMP3/{video.Title}.{ext}";
                    string outputPath = $"C:/YTMP3/{video.Title}.mp3";
                    await client.DownloadMediaStreamAsync(streamInfo, sourcePath);

                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                    ffMpeg.ConvertMedia(sourcePath, outputPath, Format.mp4);

                    File.Delete(sourcePath);
                }
                MessageBox.Show("Pobrałem.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Coś poszło nie tak." + Environment.NewLine + ex.Message);
            }
        }
        public async Task <IActionResult> GetPlaylistMetadata(string url)
        {
            var client   = new YoutubeClient();
            var id       = YoutubeClient.ParsePlaylistId(WebUtility.UrlDecode(url));
            var playlist = await client.GetPlaylistAsync(id);

            return(Ok(playlist));
        }
Example #10
0
        public async Task <IList <FileInformation> > PlaylistFileInformation(string url)
        {
            if (YoutubeClient.TryParsePlaylistId(url, out var id))
            {
                var playlisInfo = await YoutubeClient.GetPlaylistAsync(id);

                return(playlisInfo.Videos.Select(v => new FileInformation
                {
                    Tittle = v.Title,
                    Id = v.Id,
                    Thumbnails = v.Thumbnails
                }).ToList());
            }
            else
            {
                return(new List <FileInformation>());
            }
        }
        public async Task YoutubeClient_GetPlaylistAsync_Test(string playlistId)
        {
            // TODO: this should somehow verify video count

            var client = new YoutubeClient();

            var playlist = await client.GetPlaylistAsync(playlistId);

            Assert.That(playlist.Id, Is.EqualTo(playlistId));
        }
        public async Task YoutubeClient_GetPlaylistAsync_Truncated_Test(string playlistId)
        {
            const int pageLimit = 1;
            var       client    = new YoutubeClient();

            var playlist = await client.GetPlaylistAsync(playlistId, pageLimit);

            Assert.That(playlist.Id, Is.EqualTo(playlistId));
            Assert.That(playlist.Videos.Count, Is.LessThanOrEqualTo(200 * pageLimit));
        }
Example #13
0
        public async Task <Playlist> GetPlayList(string Url)
        {
            if (YoutubeClient.TryParsePlaylistId(Url, out string Id))
            {
                var client   = new YoutubeClient();
                var PlayList = await client.GetPlaylistAsync(Id);

                return(PlayList);
            }
            return(default);
Example #14
0
        private async Task GetPlaylistAsync(string id)
        {
            var client   = new YoutubeClient();
            var playlist = await client.GetPlaylistAsync(id);

            var title  = playlist.Title;  // "Igorrr - Hallelujah"
            var author = playlist.Author; // "randomusername604"

            var video       = playlist.Videos.First();
            var videoTitle  = video.Title;  // "Igorrr - Tout Petit Moineau"
            var videoAuthor = video.Author; // "Igorrr Official"
        }
Example #15
0
        public async void DownloadAndQueue()
        {
            YoutubeClient client = new YoutubeClient();

            while (true)
            {
                if (PreQueue.Count > 0)
                {
                    for (int c = 0; c < PreQueue.Count; c++)
                    {
                        if (PreQueue.ToList()[c].Contains("index") && PreQueue.ToList()[c].Contains("list"))
                        {
                            Console.WriteLine("Playlist");
                            List <Video> playlist = new List <Video>();
                            int          index    = 0;
                            for (int i = 0; i < PreQueue.Count; i++)
                            {
                                if (PreQueue.ToList()[i].Contains("index") && PreQueue.ToList()[i].Contains("list"))
                                {
                                    index = i;
                                    break;
                                }
                            }
                            var templist = await client.GetPlaylistAsync(YoutubeClient.ParsePlaylistId(PreQueue.ToList()[index]));

                            playlist = templist.Videos.ToList();
                            List <string> tempholder = PreQueue.ToList();
                            tempholder.RemoveAt(index);
                            PreQueue = new Queue <string>(tempholder);
                            for (int x = 0; x < playlist.Count; x++)
                            {
                                PreQueue.Enqueue(playlist[x].GetUrl());
                            }
                        }
                    }
                }

                if (PlayList.Count < 5 && PreQueue.Count > 0)
                {
                    if (PreQueue.Peek().Contains("www"))
                    {
                        SongInfo songInfo = new SongInfo();
                        await songInfo.AddVideoInfoAudio(PreQueue.Dequeue());

                        PlayList.Enqueue(songInfo);
                    }
                    else
                    {
                        //seach youtube
                    }
                }
            }
        }
Example #16
0
        static async Task getplaylist(string channelid, string path)
        {
            var client = new YoutubeClient();

            YoutubeExplode.Models.Playlist video = null;
            int  retry2 = 10;
            bool Bretry = false;

            Console.WriteLine("Downloading playlist started " + channelid);
            while (video == null)
            {
                if (retry2 == 0)
                {
                    Bretry = true;
                    break;
                }
                try
                {
                    video = await client.GetPlaylistAsync(channelid);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Retrying playlist download " + (11 - retry2) + " attempt");
                }
                retry2--;
                if (video == null)
                {
                    Thread.Sleep(1000);
                }
                else
                {
                    break;
                }
            }

            //  var video = await client.GetChannelUploadsAsync(channelid);
            if (video != null)
            {
                try
                {
                    foreach (var x in video.Videos)
                    {
                        await getshit(x.Id, path, false, null);
                    }
                }
                catch (Exception x)
                {
                    Console.WriteLine(x);
                }
                // Console.WriteLine("Downloading channel finished " + channelid);
            }
        }
Example #17
0
        public async Task DownloadPlayList(string url, string Path)
        {
            var id       = YoutubeClient.ParsePlaylistId(url);
            var client   = new YoutubeClient();
            var PlayList = await client.GetPlaylistAsync(id);

            Path += $"//{PlayList.Title.ValidNameForWindows()}";
            Path.EnsureExsit();
            foreach (var video in PlayList.Videos)
            {
                await DownloadVideoAsync(video, Path);
                await GenrateSubTitleAsync(video.Id, Path, video.Title.ValidNameForWindows());
            }
        }
Example #18
0
        public async Task Create_joblistAsync(string url)
        {
            string id     = YoutubeClient.ParsePlaylistId(url);
            var    client = new YoutubeClient();

            Playlist playlist = await client.GetPlaylistAsync(id);

            var videos = playlist.Videos;

            foreach (Video item in videos)
            {
                _jobs.Add(item);
            }
        }
 public static async Task <Playlist> GetPlaylistAsync(string playlistUrl)
 {
     try
     {
         var id     = YoutubeClient.ParsePlaylistId(playlistUrl);
         var client = new YoutubeClient();
         return(await client.GetPlaylistAsync(id));
     }
     catch (FormatException ex)
     {
         Debug.WriteLine(ex.StackTrace);
         return(null);
     }
 }
        //PL9v11TvMGKeIjVqzftXkpABp3aTsQ9WTk

        async void GetVideos(string link)
        {
            var client = new YoutubeClient();

            var playlist = await client.GetPlaylistAsync(link);

            var video = playlist.Videos.ToArray();

            Console.Clear();
            WriteOut("Liczba video w playliscie: " + video.Length);

            int ilosc = video.Length;
            int i     = 0;

            foreach (var v in video)
            {
                i++;

                try
                {
                    var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(v.Id);

                    var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
                    var ext        = streamInfo.Container.GetFileExtension();

                    if (!File.Exists(Directory.GetCurrentDirectory() + @"\Video\" + v.Title + "." + ext))
                    {
                        int istnieje = 0;

                        using (var progress = new ProgressBar())
                        {
                            WriteOut(v.Title, v.Id, i, ilosc, istnieje, NormalizeFileSize(streamInfo.Size));
                            await client.DownloadMediaStreamAsync(streamInfo, Directory.GetCurrentDirectory() + @"\Video\" + v.Title + "." + ext, progress);
                        }
                    }
                    else
                    {
                        int istnieje = 1;
                        WriteOut(v.Title, v.Id, i, ilosc, istnieje, NormalizeFileSize(streamInfo.Size));
                    }
                }
                catch
                {
                    string message = Environment.NewLine + i + " z " + ilosc + "  --- TYTUL: " + v.Title + "  --- URL: " + v.Id + "\nBlad podczas pobierania video";
                    WriteOut(message);
                }
            }
        }
        private static async Task DownloadAndConvertPlaylistAsync(string id)
        {
            Console.WriteLine($"Working on playlist [{id}]...");

            // Get playlist info
            var playlist = await YoutubeClient.GetPlaylistAsync(id);

            Console.WriteLine($"{playlist.Title} ({playlist.Videos.Count} videos)");

            // Work on the videos
            Console.WriteLine();
            foreach (var video in playlist.Videos)
            {
                await DownloadAndConvertVideoAsync(video.Id);

                Console.WriteLine();
            }
        }
Example #22
0
        public async Task PlaylistCmd([Remainder] string PlaylistLink)
        {
            await this._Service.LeaveAudio(this.Context.Guild);

            await this._Service.JoinAudio(this.Context.Guild, (this.Context.User as IVoiceState).VoiceChannel);

            var YTC = new YoutubeClient();

            var PlayListInfo = await YTC.GetPlaylistAsync(YoutubeClient.ParsePlaylistId(PlaylistLink));

            var IDArray = PlayListInfo.Videos.ToArray();

            foreach (var ID in IDArray)
            {
                await this._Service.SendAudioAsync(this.Context.Guild, ID);
            }
            await this._Service.LeaveAudio(this.Context.Guild);
        }
Example #23
0
        public async void AddYoutubeVideo(string url)
        {
            try
            {
                string id = url.Replace("https://www.youtube.com/watch?v=", "");
                if (id.Contains("&t="))
                {
                    id = id.Remove(id.IndexOf("&t="));
                }
                if (id.Contains("&start_radio="))
                {
                    id = id.Remove(id.IndexOf("&start_radio="));
                }

                if (!id.Contains("&list="))
                {
                    Video video = await client.GetVideoAsync(id);

                    AddSong(video);
                }
                else
                {
                    id = id.Remove(0, id.IndexOf("&list=") + 6);
                    if (id.Contains("&index="))
                    {
                        id = id.Remove(id.IndexOf("&index="));
                    }
                    Playlist playlist = await client.GetPlaylistAsync(id);

                    int i = 1;
                    foreach (Video v in playlist.Videos)
                    {
                        AddSong(v, i++);
                    }
                    ClearHeader();
                }
                AddLyrics();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private async Task <bool> GetAllLinks()
        {
            try
            {
                var cliente          = new YoutubeClient();
                var playlistCompleta = await cliente.GetPlaylistAsync(_linkDaPlaylist);

                foreach (var video in playlistCompleta.Videos)
                {
                    _listaDeVideosPlaylist.Add(video.Id);
                    _listaDeNomesVideos.Add(FormatTitle(video.Title));
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        protected override void ProcessLinks(string[] links, string format)
        {
            var  tasksToWait     = new List <Task>();
            long playListCounter = 0;

            foreach (var link in links)
            {
                playListCounter++;
                var client = new YoutubeClient();
                uiService.WriteHeader($@"[{playListCounter}] Processing link ""{link}""");

                try
                {
                    var id       = YoutubeClient.ParsePlaylistId(link);
                    var playlist = client.GetPlaylistAsync(id).GetAwaiter().GetResult();

                    long videoCounter = 0;

                    foreach (var video in playlist.Videos)
                    {
                        videoCounter++;
                        var directoryToSaveVideo = $"../{_downloadFolderName}/{_downloadSubFolderName} - {playlist.Title}";
                        var logPrefix            = $"{playListCounter}.{videoCounter}";

                        ProcessVideo(format, video.Id, client, logPrefix, ref tasksToWait, directoryToSaveVideo);
                    }
                }
                catch (Exception ex)
                {
                    uiService.WriteOutput($"[{playListCounter}] {ex.Message}", true);
                }
            }

            if (tasksToWait.Any())
            {
                uiService.WriteOutput($"Converting files, please wait...");
                Task.WaitAll(tasksToWait.ToArray());
                uiService.WriteOutput($"Converting files done.");
            }
        }
Example #26
0
        public async void InitPlayListFromUrl(string playListUrl, YoutubeClient client)
        {
            try
            {
                var playlist = await client.GetPlaylistAsync(YoutubeClient.ParsePlaylistId(playListUrl));

                this.PlaylistAuthor.Content = playlist.Author;
                this.PlaylistTitle.Content  = playlist.Title;
                for (int i = 0; i < playlist.Videos.Count; i++)
                {
                    ListBoxItem         item     = new ListBoxItem();
                    PlayListItemControl playItem = new PlayListItemControl();
                    playItem.NumberLabel.Content = i + 1;
                    playItem.VideoTitle.Content  = playlist.Videos[i].Title;

                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(playlist.Videos[i].Thumbnails.MediumResUrl, UriKind.Absolute);
                    bitmap.EndInit();
                    playItem.VideoThumbnail.Source = bitmap;
                    if (playlist.Videos[i].Author.Equals(""))
                    {
                        playItem.VideoAuthor.Content = "Youtube";
                    }
                    else
                    {
                        playItem.VideoAuthor.Content = playlist.Videos[i].Author;
                    }
                    playItem.VideoDuration.Content = playlist.Videos[i].Duration;
                    item.Content = playItem;
                    PlayListBox.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                // ignored
            }
        }
Example #27
0
    public async Task <bool> AddYoutubeVideo(string videoURL)
    {
        string videoId = "";

        if (!GetVideoId(videoURL, out videoId))
        {
            return(false);
        }

        if (videoURL.Contains("list="))
        {
            // get entire playlist
            string playlistID = videoURL.Substring(videoURL.IndexOf("list=") + 5);
            int    videoIndex = 1;
            if (playlistID.Contains("&index"))
            {
                videoIndex = int.Parse(playlistID.Substring(playlistID.IndexOf("&index") + 7));
                playlistID = playlistID.Substring(0, playlistID.IndexOf("&index"));
            }

            YoutubeExplode.Models.Playlist playlist = await client.GetPlaylistAsync(playlistID);

            if (playlist != null)
            {
                for (int i = videoIndex - 1; i < playlist.Videos.Count; i++)
                {
                    data.Enqueue(await YoutubeVideoStuff(playlist.Videos[i].Id));
                }
            }
        }
        VideoData newVideo = await YoutubeVideoStuff(videoId);

        if (newVideo != null)
        {
            data.Enqueue(newVideo);
        }
        return(newVideo != null);
    }
Example #28
0
        private async Task SavePlaylist(string id)
        {
            // Get playlist info
            var playlist = await YoutubeClient.GetPlaylistAsync(id);

            // Clear error list on new playlist
            errorList.Clear();

            // Work on the videos
            int index = 1;

            foreach (var video in playlist.Videos)
            {
                try
                {
                    await SaveTrackAudioAsync(video.Id, index, playlist.Videos.Count, playlist.Title, true);
                }
                catch
                {
                    //MessageBox.Show($"Niestety wystąpił błąd :( Z utworu: {video.Title} nic nie będzie :(");//tutaj sie nie udalo
                    errorList.Add(video.Title);
                }
                index++;
            }

            MessageBox.Show("Zakończono pobieranie playlisty", "Zakończono");
            if (errorList.Count != 0)
            {
                string titles = "";
                foreach (var title in errorList)
                {
                    titles += title + "\n";
                }
                titles = titles.Trim();
                MessageBox.Show("Niestety nie udało się pobrać następujących tytułów: \n" + titles, "Błąd w pobieraniu");
            }
        }
Example #29
0
        private void DownloadItem_Load(object sender, EventArgs e)
        {
            try
            {
                downloadTask = new Task(Download); //just so it isn't null and we can check on IsCanceled
                convertTask  = new Task(Download); //just so it isn't null and we can check on IsCanceled

                YoutubeClient client = new YoutubeClient();
                pbLoad.Image = Properties.Resources.load25x25;

                //Attempt to get the single video id
                string singleVideoId = "";
                if (theVideo != null)
                {
                    singleVideoId = theVideo.Id;
                }
                else
                {
                    YoutubeClient.TryParseVideoId(youtubeUrl, out singleVideoId);
                }


                //Attempt to get the playlist id
                string playlistId = "";
                if (thePlaylist != null)
                {
                    playlistId = thePlaylist.Id;
                }
                else
                {
                    YoutubeClient.TryParsePlaylistId(youtubeUrl, out playlistId);
                }



                //Thread that handles playlists loading data
                Thread playlistThread = null;
                playlistThread = new Thread(async() =>
                {
                    if (!string.IsNullOrEmpty(playlistId))
                    {
                        if (thePlaylist == null)
                        {
                            thePlaylist = await client.GetPlaylistAsync(playlistId);
                        }
                    }
                });
                playlistThread.IsBackground = true;
                playlistThread.Start();



                //Thread that handles loading single video data
                Thread singleVideoThread = new Thread(async() =>
                {
                    if (!string.IsNullOrEmpty(singleVideoId))
                    {
                        try
                        {
                            //Put the thumbnail into the picturebox
                            pbYoutubeThumbnail.Load("http://img.youtube.com/vi/" + singleVideoId + "/0.jpg");
                            //Get the video
                            try
                            {
                                if (theVideo == null)
                                {
                                    theVideo = await client.GetVideoAsync(singleVideoId);
                                }
                            }
                            catch (Exception ex)
                            {
                                SetVideoUnavailableErrorText(ex);
                                return;
                            }



                            string title      = theVideo.Title;
                            string author     = theVideo.Author;
                            TimeSpan duration = theVideo.Duration;

                            string subTitle  = "";
                            string subAuthor = "";

                            string completeString = ""; //The complete string containing title + author + duration


                            if (title.Length > 33)
                            {
                                subTitle        = title.Substring(0, 33) + "...";
                                completeString += subTitle + "   ";
                            }
                            else
                            {
                                completeString += title + "   ";
                            }


                            if (author.Length > 23)
                            {
                                subAuthor       = author.Substring(0, 23) + "...";
                                completeString += subAuthor + "   ";
                            }
                            else
                            {
                                completeString += author + "   ";
                            }

                            completeString += duration;

                            lblTitle.Invoke((MethodInvoker)(() =>
                            {
                                lblTitle.Text = completeString;
                                lblExit.Invoke((MethodInvoker)(() =>
                                {
                                    lblExit.Enabled = true;
                                }));
                                btnDownload.Invoke((MethodInvoker)(() =>
                                {
                                    btnDownload.Enabled = true;
                                }));
                                pbLoad.Invoke((MethodInvoker)(() =>
                                {
                                    pbLoad.Image = null;
                                    pbLoad.BackgroundImage = Properties.Resources.Check;
                                }));
                                lblStatus.Invoke((MethodInvoker)(() =>
                                {
                                    if (!isHistory)
                                    {
                                        lblStatus.Text = "Ready.";
                                    }
                                    isReady = true;
                                }));
                            }));
                        }
                        catch (System.Net.WebException ex)
                        {
                            SetVideoUnavailableErrorText(ex);
                        }
                    }
                });
                singleVideoThread.IsBackground = true;
                singleVideoThread.Start();
            }
            catch (Exception)
            {
                lblTitle.Text  = "An error occured - Could not load this entry";
                lblStatus.Text = "Error.";
                canDownload    = false;
            }
        }
Example #30
0
 /// <summary>
 /// Get the playList videos
 /// </summary>
 /// <param name="playlistId">comma seperated ids</param>
 /// <returns></returns>
 public async Task <IEnumerable <VideoWrapper> > GetPlaylistVideosAsync(string playlistId, int pageNumber = 1, int pageSize = 30)
 {
     return((await dataContext.GetPlaylistAsync(playlistId, pageNumber, pageSize))?.Videos?.Select(x => Create(x)));
 }