コード例 #1
0
        /// <summary>
        /// Adds a downloadItem to the panel
        /// </summary>
        /// <param name="item"></param>
        /// <param name="pnl"></param>
        public static DownloadItem AddDownloadItem(YoutubeExplode.Models.Video video, Panel pnl)
        {
            try
            {
                DownloadItem toAddItem = new DownloadItem(video);
                //Determines where to place the downloadItem
                int y = 0;
                if (downloadItems.Count > 0)
                {
                    y = downloadItems.Count * downloadItems.Where(itm => !itm.IsDisposed).ToList()[0].Height;
                }

                pnl.Invoke((MethodInvoker)(() =>
                {
                    pnl.Controls.Add(toAddItem);
                }));

                toAddItem.Invoke((MethodInvoker)(() =>
                {
                    toAddItem.Location = new Point(toAddItem.Location.X, y);
                }));

                downloadItems.Add(toAddItem);
                return(toAddItem);
            }
            catch (Exception)
            {
                MessageFormManager.MakeMessagePopup("Something went wrong!", "Could not find a video with that youtube url!\r\nPlease try again.", 5);
            }
            return(null);
        }
コード例 #2
0
        // GIANT HACK: This overload is very redundant, needed a quick bugfix...
        private Embed buildYtEmbed(YoutubeExplode.Models.Video ytMetadata, EmbedFieldBuilder additionalField)
        {
            var ytEmbed = new EmbedBuilder
            {
                Title  = String.Format(config["strings:video_embed_title"], Format.Sanitize(ytMetadata.Title)),
                Author = new EmbedAuthorBuilder
                {
                    Name    = String.Format(config["strings:video_embed_author"], Format.Sanitize(ytMetadata.Author)),
                    IconUrl = config["strings:video_embed_author_thumb_url"]
                },
                ThumbnailUrl = ytMetadata.Thumbnails.HighResUrl,
                Description  = String.Format(config["strings:video_embed_description"], Format.Sanitize(ytMetadata.Description)).Length <= 2048 ?
                               String.Format(config["strings:video_embed_description"], Format.Sanitize(ytMetadata.Description)) :
                               $"{String.Format(config["strings:video_embed_description"], Format.Sanitize(ytMetadata.Description)).Substring(0, 2045)}...",
                Footer = new EmbedFooterBuilder().WithText(
                    String.Format(config["strings:video_embed_footer"], ytMetadata.Duration.ToString(), ytMetadata.Statistics.ViewCount)
                    )
            }
            .WithFields(
                new EmbedFieldBuilder()
                .WithName(config["strings:video_embed_likes_title"])
                .WithValue(String.Format(config["strings:video_embed_likes_description"], ytMetadata.Statistics.LikeCount))
                .WithIsInline(true),
                new EmbedFieldBuilder()
                .WithName(config["strings:video_embed_dislikes_title"])
                .WithValue(String.Format(config["strings:video_embed_dislikes_description"], ytMetadata.Statistics.DislikeCount))
                .WithIsInline(true),
                additionalField
                );

            return(ytEmbed.Build());
        }
コード例 #3
0
ファイル: YtService.cs プロジェクト: DonElPadre/the-godfather
        private async Task <SongInfo> GetSongInfoViaYtExplodeAsync(string url)
        {
            if (!YoutubeClient.TryParseVideoId(url, out string id))
            {
                return(null);
            }

            YoutubeExplode.Models.Video video = await this.ytExplode.GetVideoAsync(id).ConfigureAwait(false);

            if (video is null)
            {
                return(null);
            }

            YoutubeExplode.Models.MediaStreams.MediaStreamInfoSet streamInfo = await this.ytExplode.GetVideoMediaStreamInfosAsync(video.Id).ConfigureAwait(false);

            YoutubeExplode.Models.MediaStreams.AudioStreamInfo stream = streamInfo.Audio
                                                                        .OrderByDescending(x => x.Bitrate)
                                                                        .FirstOrDefault();
            if (stream is null)
            {
                return(null);
            }

            return(new SongInfo {
                Provider = "YouTube",
                Query = $"{_ytUrl}/watch?v={video.Id}",
                Thumbnail = video.Thumbnails.MediumResUrl,
                TotalTime = video.Duration,
                Uri = stream.Url,
                VideoId = video.Id,
                Title = video.Title,
            });
        }
コード例 #4
0
        public DownloadItem(DownloadHistory history)
        {
            //When a new instance of DownloadItem is created with this constructor, it is being used to show it as history. There will not be a download button
            InitializeComponent();
            isHistory     = true;
            historyRecord = history;



            new Thread(async() =>
            {
                try
                {
                    //Because for some reason assigning 5 to a property that already is 5 makes it work. ? It doesn't show the elipse radius without this.
                    bunifuElipse1.ElipseRadius = 5;

                    pbYoutubeThumbnail.Load(history.ThumbnailLink);
                    theVideo = await client.GetVideoAsync(history.VideoId);
                }
                catch { }
            }).Start();



            lblStatus.Location  = pbLoad.Location;
            lblStatus.Text      = history.DownloadDate;
            btnDownload.Enabled = true;
            pbLoad.Visible      = false;
            lblExit.Enabled     = true;
            string completeString = "";
            string subAuthor      = "";
            string subTitle       = "";

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


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



            completeString += history.Duration;
            lblTitle.Text   = completeString;
        }
コード例 #5
0
 private static async Task <byte[]> GetThumbnail(HttpClient httpclient, YoutubeExplode.Models.Video mediainfo)
 {
     try { return(await httpclient.GetByteArrayAsync(mediainfo.Thumbnails.MaxResUrl)); } catch (Exception) { }
     try { return(await httpclient.GetByteArrayAsync(mediainfo.Thumbnails.StandardResUrl)); } catch (Exception) { }
     try { return(await httpclient.GetByteArrayAsync(mediainfo.Thumbnails.HighResUrl)); } catch (Exception) { }
     try { return(await httpclient.GetByteArrayAsync(mediainfo.Thumbnails.MediumResUrl)); } catch (Exception) { }
     return(await httpclient.GetByteArrayAsync(mediainfo.Thumbnails.LowResUrl));
 }
コード例 #6
0
        // Asynchronous method for obtaining video information
        private async Task LoadInfoVideoAsync()
        {
            try
            {
                string idVideo = YoutubeClient.ParseVideoId(this.url);

                var client = new YoutubeClient();
                this.info = await client.GetVideoAsync(idVideo);
            }
            catch
            {
                this.info = null;
            }
        }
コード例 #7
0
        public async void Download(YoutubeExplode.Models.Video video)
        {
            try
            {
                if (!canDownload)
                {
                    return;
                }

                isDownloading = true;

                //Set the image to zzz - enqueue'd. Then, if it can download(if there aren't already a few threads downloading) it will change to downloading...
                pbLoad.BackgroundImage = Properties.Resources.zzz;
                lblStatus.Visible      = true;
                lblStatus.Text         = "Enqueued.";
                pbLoad.Image           = null;


                var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(video.Id); //recursive?

                var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();


                pbLoad.BackgroundImage = null;
                pbLoad.Image           = Properties.Resources.load25x25;

                lblStatus.Text = "Downloading...";


                pathToVideo = GetValidFilePath(BLIO.rootFolder + "\\Video\\", video.Title, "." + BLSettings.VideoType);

                Task task = Task.Run(async() =>
                {
                    ctsDownload.Token.ThrowIfCancellationRequested();
                    await client.DownloadMediaStreamAsync(streamInfo, pathToVideo + RemoveIllegalCharacters(video.Title) + "." + BLSettings.VideoType, new Progress <double>(d => setProgressbarValue(pbDownload, (int)Math.Round(Convert.ToDouble(d.ToString()) * 100))), ctsDownload.Token);
                }, ctsDownload.Token);
                await task;

                pbLoad.Image           = null;
                pbLoad.BackgroundImage = Properties.Resources.load25x25;
                lblStatus.Text         = "Preparing...";
                ConvertToMp3(video.Title);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                //Probably a timeout! multiple other threads downloading. gotta wait for them to finish, re-try this one.
                Download(video);
            }
        }
コード例 #8
0
        public static async Task <string> DownloadAndConvertVideoAsync(string id, YoutubeExplode.Models.Video video)
        {
            Console.WriteLine($"Working on video [{id}]...");
            var set = await YoutubeClient.GetVideoMediaStreamInfosAsync(id);

            var cleanTitle = video.Title.Replace(Path.GetInvalidFileNameChars(), '_');
            var streamInfo = GetBestAudioStreamInfo(set);

            Directory.CreateDirectory(OutputDirectoryPath);
            var streamFileExt  = streamInfo.Container.GetFileExtension();
            var filename       = $"{cleanTitle}.{streamFileExt}";
            var streamFilePath = Path.Combine(OutputDirectoryPath, filename);
            await YoutubeClient.DownloadMediaStreamAsync(streamInfo, streamFilePath);

            return(filename);
        }
コード例 #9
0
ファイル: Bot.cs プロジェクト: developer-86/Rebot
        public async Task SendLocalVideoAsync(YVideo video, VideoStreamInfo videoStream, string path)
        {
            if (video == null)
            {
                throw new ArgumentNullException("video");
            }

            if (videoStream == null)
            {
                throw new ArgumentNullException("videoStream");
            }

            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            FileInfo file = new FileInfo(path);

            if (!file.Exists)
            {
                throw new Exception(string.Format("Файл по адресу {0} не найден",
                                                  path));
            }

            TLAbsInputFile           fileResult = this.UploadLocalFileToTelegram(path, video.Title);
            string                   mimeType   = "video/mp4";
            TLDocumentAttributeVideo attr1      = new TLDocumentAttributeVideo()
            {
                Duration = (int)video.Duration.TotalSeconds + 1,
                H        = videoStream.Resolution.Height,
                W        = videoStream.Resolution.Width,
            };

            TLVector <TLAbsDocumentAttribute> attrs = new TLVector <TLAbsDocumentAttribute>();

            attrs.Add(attr1);

            TLInputPeerUser peer = new TLInputPeerUser()
            {
                UserId = this.CurrentAuthUser.Id
            };
            var sendTask = this.TClient.SendUploadedDocument(
                peer, fileResult, video.Title, mimeType, attrs);

            sendTask.Wait();
        }
コード例 #10
0
        public static YoutubeSource GetYoutubeSource(string link)
        {
            string id = link.ParseVideoId();

            var client = new YoutubeClient();

            YoutubeExplode.Models.Video video = client.GetVideoAsync(id).Result;

            var youtubeSource = new YoutubeSource
            {
                ThumbnailUri = video.Thumbnails.MediumResUrl,
                Title        = video.Title,
                Id           = id
            };

            return(youtubeSource);
        }
コード例 #11
0
        private async Task _fetchYoutubeInfo(string youtubeVideoId)
        {
            var client = new YoutubeExplode.YoutubeClient();

            YoutubeExplode.Models.Video video = null;
            try
            {
                video = await client.GetVideoAsync(youtubeVideoId);

                this.Video.VideoInfo = YoutubeVideoInfo.FromVideoObject(video);
            }
            catch (Exception e)
            {
                _mediaInfoBeingFetched = false;
                YTrackLogger.Log("Cannot Fetch Video info for " + youtubeVideoId + " : \n\n" + e.Message);
            }
        }
コード例 #12
0
        private static async Task GetPlaylistAsync(string directory, int maxPage, string playlistId = "", bool audio = false, bool youtubeMusic = false)
        {
            var playlist = await Client.GetPlaylistAsync(playlistId);

            directory = string.IsNullOrEmpty(directory) ? playlist.Title : directory;
            Directory.CreateDirectory(directory);
            Console.WriteLine($"Playlist: {playlist.Title}");
            var playlistTitle = playlist.Title;

            if (youtubeMusic)
            {
                playlistTitle = playlist.Title.Split('-').Last().Trim();
            }

            for (int i = 0; i < playlist.Videos.Count; i++)
            {
                YoutubeExplode.Models.Video upload = playlist.Videos[i];
                Console.WriteLine($"{System.Environment.NewLine}Video {i + 1} of {playlist.Videos.Count}: {upload.Title}");
                await Download(upload, directory, audio, youtubeMusic, playlistTitle, i + 1, playlist.Videos.Count);
            }
        }
コード例 #13
0
        private static async Task GetChannelAsync(string directory, int maxPage, string username = "", string channelId = "", bool audio = false, bool youtubeMusic = false)
        {
            if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(channelId))
            {
                Console.WriteLine("Required Fields: --channel-id [YouTube Channel Id] OR --username [YouTube Username]");
                Console.WriteLine("Optional Fields: --directory [Output Directory For Videos] --ffmpeg-path [Path to FFMpeg] --max-page [Max Number of Video Pages to Download]");
                return;
            }

            if (string.IsNullOrEmpty(channelId))
            {
                channelId = await Client.GetChannelIdAsync(username);
            }

            if (string.IsNullOrEmpty(directory))
            {
                directory = channelId;
            }

            Directory.CreateDirectory(directory);
            var channel = await Client.GetChannelAsync(channelId);

            Console.WriteLine($"Channel: {channel.Title}");
            System.Collections.Generic.IReadOnlyList <YoutubeExplode.Models.Video> channelUploads;
            if (maxPage > 0)
            {
                channelUploads = await Client.GetChannelUploadsAsync(channelId, maxPage);
            }
            else
            {
                channelUploads = await Client.GetChannelUploadsAsync(channelId);
            }

            for (int i = 0; i < channelUploads.Count; i++)
            {
                YoutubeExplode.Models.Video upload = channelUploads[i];
                Console.WriteLine($"{System.Environment.NewLine}Video {i + 1} of {channelUploads.Count}: {upload.Title}");
                await Download(upload, directory, audio, youtubeMusic);
            }
        }
コード例 #14
0
        public SongInQueue DownloadSong(string link)
        {
            string      guid         = Guid.NewGuid().ToString();
            SongInQueue result       = new SongInQueue();
            string      fullFilePath = _musicStorage + guid;

            YoutubeClient client = new YoutubeClient();

            try
            {
                _log.Debug($"Started processing { link }");
                string             parsedYoutubeId = YoutubeClient.ParseVideoId(link);
                MediaStreamInfoSet streamInfoSet   = client.GetVideoMediaStreamInfosAsync(parsedYoutubeId).Result;

                YoutubeExplode.Models.Video video = client.GetVideoAsync(parsedYoutubeId).Result;
                result.Name = video.Title;
                AudioStreamInfo streamInfo = streamInfoSet.Audio.FirstOrDefault();

                string ext = streamInfo.Container.GetFileExtension();
                fullFilePath += $".{ ext }";

                IProgress <double> progress = new YoutubeExtractorClientProgress($"{result.Name} - { guid }");


                client.DownloadMediaStreamAsync(streamInfo, fullFilePath, progress).Wait();
                var inputFile = new MediaFile(fullFilePath);

                result.FilePath = fullFilePath;

                _log.Debug("Finished processing file " + link);
                return(result);
            }
            catch (Exception ex)
            {
                _log.Error($"Error while downloading youtube song", ex);
                throw ex;
            }
        }
コード例 #15
0
ファイル: Bot.cs プロジェクト: developer-86/Rebot
        private async Task TransferVideoAsync(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            DirectoryInfo dir     = null;
            string        dirPath = this.Configuration.GetParameterStringValue("DownloadFolder");

            if (!Directory.Exists(dirPath))
            {
                dir = Directory.CreateDirectory(dirPath);
            }
            else
            {
                dir = new DirectoryInfo(dirPath);
            }

            string tmpFile = string.Format("{0}\\{1}.mp4",
                                           dir.FullName,
                                           Guid.NewGuid());

            var videoID     = YoutubeClient.ParseVideoId(url);
            var streamInfos = await this.YoutubeClient.GetVideoMediaStreamInfosAsync(videoID);

            VideoStreamInfo videoStream = streamInfos.Video[0];
            YVideo          video       = await this.YoutubeClient.GetVideoAsync(videoID);

            await this.SendMessageAsync("Начало локальной загрузки файла");

            await this.YoutubeClient.DownloadMediaStreamAsync(videoStream, tmpFile);

            await this.SendLocalVideoAsync(video, videoStream, tmpFile);

            await this.SendMessageAsync("Окончание передачи файла");
        }
コード例 #16
0
        private static async Task Download(YoutubeExplode.Models.Video upload, string directory, bool audio, bool youtubeMusic, string playlistTitle = "", int playlistNum = 0, int playlistCount = 0)
        {
            var mediaStreamInfoSet = await Client.GetVideoMediaStreamInfosAsync(upload.Id);

            var audioStreamInfo = mediaStreamInfoSet.Audio.WithHighestBitrate();
            var videoStreamInfo = mediaStreamInfoSet.Video.WithHighestVideoQuality();

            if (!audio)
            {
                var mediaStreamInfos = new MediaStreamInfo[] { audioStreamInfo, videoStreamInfo };
                await Converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, $"{directory}\\{upload.Id}.mp4", "mp4", ProgressBar);
            }
            else
            {
                var mediaStreamInfos = new MediaStreamInfo[] { audioStreamInfo };
                await Converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, $"{directory}\\{upload.Id}.mp3", "mp3", ProgressBar);

                if (!youtubeMusic)
                {
                    return;
                }
                var tfile      = TagLib.File.Create($"{directory}\\{upload.Id}.mp3");
                var artistSong = upload.Author.Split('-');
                tfile.Tag.AlbumArtists = new string[1] {
                    artistSong[0]
                };
                tfile.Tag.Performers = new string[1] {
                    artistSong[0]
                };
                tfile.Tag.Album      = playlistTitle;
                tfile.Tag.Title      = upload.Title;
                tfile.Tag.Track      = (uint)playlistNum;
                tfile.Tag.TrackCount = (uint)playlistCount;
                tfile.Save();
                //tfile.Tag.Pictures = new TagLib.IPicture[1] { new TagLib.Picture() };
            }
        }
コード例 #17
0
        /* getter & setters */

        private void Erase()
        {
            this.url       = "";
            this.dstFolder = "";
            this.info      = null;
        }
コード例 #18
0
        private static async Task GetCaptionsAsync(string directory, int maxPage, string username = "", string channelId = "", string playlistId = "")
        {
            List <YoutubeExplode.Models.Video> videos = new List <YoutubeExplode.Models.Video>();
            var captionsId = "";

            if (!string.IsNullOrEmpty(playlistId))
            {
                var playlist = await Client.GetPlaylistAsync(playlistId);

                videos.AddRange(playlist.Videos);
                captionsId = playlist.Id;
            }
            else if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(channelId))
            {
                if (!string.IsNullOrEmpty(username))
                {
                    channelId = await Client.GetChannelIdAsync(username);
                }
                System.Collections.Generic.IReadOnlyList <YoutubeExplode.Models.Video> channelUploads;
                if (maxPage > 0)
                {
                    channelUploads = await Client.GetChannelUploadsAsync(channelId, maxPage);
                }
                else
                {
                    channelUploads = await Client.GetChannelUploadsAsync(channelId);
                }
                videos.AddRange(channelUploads);
                captionsId = channelId;
            }

            List <CaptionVideo> captionVideos = new List <CaptionVideo>();

            for (int i = 0; i < videos.Count; i++)
            {
                YoutubeExplode.Models.Video upload = videos[i];
                var trackInfos = await Client.GetVideoClosedCaptionTrackInfosAsync(upload.Id);

                var captionVid = new CaptionVideo()
                {
                    VideoId =
                        upload.Id, VideoTitle = upload.Title,
                    UploadDate    = upload.UploadDate,
                    VideoDuration = upload.Duration,
                    DislikeCount  = upload.Statistics.DislikeCount,
                    LikeCount     = upload.Statistics.LikeCount,
                    AverageRating = upload.Statistics.AverageRating,
                    ViewCount     = upload.Statistics.ViewCount,
                };
                Console.WriteLine($"{i}: {upload.Title} ({upload.Id})");
                foreach (var trackInfo in trackInfos)
                {
                    Console.WriteLine($"{trackInfo.Language}");
                    var track = await Client.GetClosedCaptionTrackAsync(trackInfo);

                    captionVid.Tracks.Add(track);
                }

                captionVideos.Add(captionVid);
            }
            Console.WriteLine($"Total Videos: {videos.Count}");
            Console.WriteLine($"Captions Missing: {videos.Count - captionVideos.Count}");
            File.WriteAllText($"{captionsId}-captions.txt", JsonConvert.SerializeObject(captionVideos, Formatting.Indented));
        }
コード例 #19
0
ファイル: AudioService.cs プロジェクト: ydobrov/arkasha
 private async Task SendAudio(AudioStreamInfo streamInfo, YoutubeExplode.Models.Video video)
 {
     using (var audioStream = await _youtubeClient.GetMediaStreamAsync(streamInfo))
         await TelegramClient.SendAudioAsync(ChatId, audioStream, video.Title, ParseMode.Default,
                                             (int)video.Duration.TotalSeconds, video.Author, title : video.Title);
 }
コード例 #20
0
 public DownloadItem(YoutubeExplode.Models.Video theVideo)
 {
     InitializeComponent();
     this.theVideo = theVideo;
 }
コード例 #21
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;
            }
        }
コード例 #22
0
ファイル: MusicDownloader.cs プロジェクト: jesst3r/Pootis-Bot
        private string DownloadAudio(Video youTubeVideo)
        {
            try
            {
                //Make sure we haven't been canceled yet
                if (cancellationSource.IsCancellationRequested)
                {
                    return(null);
                }

                string videoTitle = youTubeVideo.Title.RemoveIllegalChars();

                MessageUtils.ModifyMessage(message,
                                           $":musical_note: Give me a sec. Downloading **{videoTitle}** from **{youTubeVideo.Author}**...")
                .GetAwaiter().GetResult();

                //Get our video stream info
                MediaStreamInfoSet videoMediaInfo =
                    client.GetVideoMediaStreamInfosAsync(youTubeVideo.Id).GetAwaiter().GetResult();
                AudioStreamInfo streamInfo           = videoMediaInfo.Audio.WithHighestBitrate();
                string          songDownloadLocation = $"{downloadLocation}{videoTitle}.{streamInfo.Container.GetFileExtension()}";

                //Download the audio file
                client.DownloadMediaStreamAsync(streamInfo, songDownloadLocation, null, downloadCancellationToken)
                .GetAwaiter().GetResult();

                //Do another check to make sure our video hasn't been canceled
                if (cancellationSource.IsCancellationRequested)
                {
                    return(null);
                }

                Logger.Log($"The downloaded video file extension is '{streamInfo.Container.GetFileExtension()}'.",
                           LogVerbosity.Debug);
                if (streamInfo.Container.GetFileExtension() != downloadFileContainer.GetFormatExtension())
                {
                    if (cancellationSource.IsCancellationRequested)
                    {
                        return(null);
                    }

                    if (!ConvertAudioFileToMp3(songDownloadLocation,
                                               $"{this.downloadLocation}{videoTitle}.{downloadFileContainer.GetFormatExtension()}"))
                    {
                        if (!disposed)
                        {
                            MessageUtils.ModifyMessage(message,
                                                       "Sorry, but there was an issue downloading the song! Try again later.").GetAwaiter()
                            .GetResult();
                        }
                        return(null);
                    }
                }

                songDownloadLocation   = $"{this.downloadLocation}{videoTitle}.{downloadFileContainer.GetFormatExtension()}";
                hasFinishedDownloading = true;

                //We have finished downloading
                return(songDownloadLocation);
            }
            catch (Exception ex)
            {
#if DEBUG
                Logger.Log(ex.ToString(), LogVerbosity.Error);
#else
                Logger.Log(ex.Message, LogVerbosity.Error);
#endif

                MessageUtils
                .ModifyMessage(message, "Sorry, but there was an issue downloading the song! Try again later.")
                .GetAwaiter().GetResult();

                //Log out an error to the owner if they have it enabled
                if (Config.bot.ReportErrorsToOwner)
                {
                    Global.BotOwner.SendMessageAsync(
                        $"ERROR: {ex.Message}\nError occured while trying to search or download a video from YouTube on guild `{guild.Id}`.");
                }

                //Mark this as true so our error doesn't get deleted
                hasFinishedDownloading = true;

                return(null);
            }
        }
コード例 #23
0
        public override async Task SetURLAsync(string url)
        {
            try
            {
                id = YoutubeClient.ParseVideoId(url);
                var client = new YoutubeClient();
                Controller?.UpdateMessage(this, KEY_YOUTUBE,
                                          new PlainTextMessage(AppResources.GetString("YouTubeLinkDetectedButWaiting")));
                video = await client.GetVideoAsync(id);

                infos = await client.GetVideoMediaStreamInfosAsync(id);

                if (infos.Muxed.Count > 0)
                {
                    Controller?.SetComboBoxLayoutVisibility(this, true);
                }
                else
                {
                    throw new Exception();
                }

                Controller?.UpdateMessage(this, KEY_YOUTUBE,
                                          new PlainTextMessage(
                                              AppResources.GetString("YouTubeLinkDetectedButWaiting")
                                              + " - " +
                                              video.Title
                                              ));

                foreach (var info in infos.Muxed)
                {
                    PlainTextComboBoxData data = new PlainTextComboBoxData();
                    data.Text = info.VideoQuality.ToString() + " - " + info.VideoEncoding.ToString();
                    Controller?.AddComboBoxItem(this, data);
                }

                Controller?.SetComboBoxSelectionChangedListener(this,
                                                                async(item) => {
                    innerAnalyser?.Dispose();
                    string target = GetURLFromInfos(item.Text);
                    if (target != null)
                    {
                        innerAnalyser = Converters.UrlConverter.GetAnalyser(target);
                        if (innerAnalyser != null)
                        {
                            URL = target;
                            innerAnalyser.BindVisualController(Controller);
                            Controller?.RegistAnalyser(this, innerAnalyser);
                            await innerAnalyser.SetURLAsync(target);
                        }
                    }
                }
                                                                );
            }
            catch (Exception)
            {
                Controller?.UpdateMessage(this, KEY_YOUTUBE,
                                          new PlainTextMessage(
                                              AppResources.GetString("YouTubeLinkDetectedButFailed")
                                              ));
                Controller?.SetComboBoxLayoutVisibility(this, false);
            }
        }
コード例 #24
0
        getshit(string videoid, string path, bool onlyunlisted, string authormatchup)
        {
            var client = new YoutubeClient();

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

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

            var WClient = new WebClient();

            Console.WriteLine(video);
            int retry = 10;

            if (Bretry == false && video != null)
            {
                if (authormatchup == null)
                {
                    authormatchup = video.Author; Console.WriteLine(authormatchup);
                }
                if (onlyunlisted && video.Author != authormatchup)
                {
                    Console.WriteLine("External channel, skipping");
                    return;
                }
                while (retry > 0)
                {
                    try
                    {
                        WClient.DownloadFile("http://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=" + videoid, videoid);
                        while (WClient.IsBusy)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    catch (Exception e)
                    {
                        retry--;

                        if (retry == 0)
                        {
                            Console.WriteLine(e);
                            return;
                        }
                        else
                        {
                            Thread.Sleep(1000);
                            Console.WriteLine("Downloading failed, retrying " + video.Title);
                        }


                        //   Console.ReadLine();
                    }

                    if (File.Exists(videoid))
                    {
                        break;
                    }
                }
                try
                {
                    if (vetforformatting(videoid))
                    {
                        string titletest = title(path, videoid, video.Title, video.Author);
                        if (!File.Exists(titletest))
                        {
                            File.Copy(videoid, titletest);
                            Console.WriteLine("Downloaded annotations for video: " + video.Title);
                            Scanforid(videoid, path, authormatchup);
                            try
                            {
                                if (File.Exists(videoid))
                                {
                                    File.Delete(videoid);
                                }
                            }
                            catch
                            {
                                Console.WriteLine("Failed Delete");
                            }
                            //     break;
                        }
                        else
                        {
                            Console.WriteLine("Annotations file exists already: " + video.Title);
                            try
                            {
                                if (File.Exists(videoid))
                                {
                                    File.Delete(videoid);
                                }
                            }
                            catch
                            {
                                Console.WriteLine("Failed Delete");
                            }
                            //   break;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Video doesn't contain old youtube annotations:  " + video.Title);
                        try
                        {
                            if (File.Exists(videoid))
                            {
                                File.Delete(videoid);
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Failed Delete");
                        }
                        // break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            else
            {
                Console.WriteLine("Cannot retrieve metadata with YoutubeExplode, abandoning download");
                return;
            }
        }
コード例 #25
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message != null)
            {
                Telegram.Bot.Types.Message message = e.Message;
                Console.WriteLine($"Received a message from {message.Chat.FirstName} at {message.Date}. It says: \"{e.Message.Text}\"");

                switch (message.Text)
                {
                case "/stop":
                    step = -1;
                    break;

                case "/start":

                    await bot.SendTextMessageAsync(
                        chatId : message.Chat,
                        text : "Send link",
                        replyToMessageId : message.MessageId
                        );

                    step = 0;
                    break;

                default:
                    if (step == 0)
                    {
                        link = message.Text;

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send title",
                            replyToMessageId : message.MessageId
                            );

                        step = 1;

                        try
                        {
                            string id = YoutubeClient.ParseVideoId(link);

                            MediaStreamInfoSet streamInfoSet = await clientYT.GetVideoMediaStreamInfosAsync(id);     //So54Khf7bB8

                            video = await clientYT.GetVideoAsync(id);

                            duration = video.Duration;     // 00:07:14
                            AudioStreamInfo streamInfo = streamInfoSet.Audio.OrderBy(s => s.Bitrate).First();
                            string          ext        = streamInfo.Container.GetFileExtension();

                            Console.WriteLine("Downloading audio");

                            await clientYT.DownloadMediaStreamAsync(streamInfo, $"Audio\\audio.{ext}");

                            Console.WriteLine("Audio has been downloaded. Converting audio");

                            FFMpegConverter convertAudio = new NReco.VideoConverter.FFMpegConverter();
                            convertAudio.ConvertMedia($"Audio\\audio.{ext}", null, "Audio\\audio.ogg", null, new ConvertSettings()
                            {
                                //CustomOutputArgs = $"-b:a {streamInfo.Bitrate}"
                                CustomOutputArgs = $"-c:a libopus -b:a {streamInfo.Bitrate}"
                            });

                            Console.WriteLine("Converting has been completed.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : "The link that you have sent is not valid or the file size is too big. Please, send it again",
                                replyToMessageId : message.MessageId
                                );

                            step = 0;
                        }
                    }
                    else if (step == 1)
                    {
                        title    = message.Text.ToUpper();
                        titleLen = title.Length - 27;

                        output = $"<b>{message.Text}</b>\n";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send author",
                            replyToMessageId : message.MessageId
                            );

                        step = 2;
                    }
                    else if (step == 2)
                    {
                        author    = message.Text.ToUpper();
                        authorLen = author.Length - 14;

                        output += $"{message.Text}\n\n";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send desription",
                            replyToMessageId : message.MessageId
                            );

                        step = 3;
                    }
                    else if (step == 3)
                    {
                        output += $"{message.Text}\n\n";

                        ReplyKeyboardMarkup replyKeyboardMarkup = new[]
                        {
                            new[] { "Бизнес", "Биография", "Психология", "Саморазвитие" },
                            new[] { "Философия", "Наука", "История", "Финансы" }
                        };

                        replyKeyboardMarkup.OneTimeKeyboard = true;

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send genre",
                            replyToMessageId : message.MessageId,
                            replyMarkup : replyKeyboardMarkup
                            );

                        output += $"🔈 <b>Продолжительность ≈</b> {Math.Round(duration.TotalMinutes, MidpointRounding.AwayFromZero)} минут\n";

                        step = 4;
                    }
                    else if (step == 4)
                    {
                        genre   = message.Text.ToUpper();
                        output += $"📝 <b>Жанр:</b> #{message.Text}";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send image",
                            replyToMessageId : message.MessageId
                            );

                        step = 5;
                    }
                    else if (step == 5)
                    {
                        if (message.Type == MessageType.Photo)
                        {
                            FileStream fs = System.IO.File.OpenWrite("Image\\cover.png");
                            await bot.GetInfoAndDownloadFileAsync(message.Photo.Last().FileId, fs);

                            fs.Close();

                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : "Cover image received",
                                replyToMessageId : message.MessageId
                                );

                            FileStream pltrFile = File.OpenRead("Image\\palitre.png");

                            await bot.SendPhotoAsync(
                                chatId : message.Chat,
                                photo : pltrFile,
                                caption : "Choose your colors. First, send me primary color",
                                replyMarkup : replyKeyboardMarkupColor
                                );

                            pltrFile.Close();
                            step = 6;
                        }
                        else
                        {
                            await bot.SendTextMessageAsync(message.Chat, "I implores you to send photo and not anything else, capish?");

                            step = 5;
                        }
                    }
                    else if (step == 6)
                    {
                        if (message.Text[0] == '#')
                        {
                            primColor = message.Text;
                        }
                        else
                        {
                            primColor = '#' + message.Text;
                        }
                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got primary color. Now, send me secondary color"
                            );

                        step = 7;
                    }
                    else if (step == 7)
                    {
                        if (message.Text[0] == '#')
                        {
                            secColor = message.Text;
                        }
                        else
                        {
                            secColor = '#' + message.Text;
                        }

                        replyKeyboardMarkupColor.OneTimeKeyboard = true;
                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got secondary color. Now, send me background color",
                            replyMarkup : replyKeyboardMarkupColor
                            );

                        step = 8;
                    }
                    else if (step == 8)
                    {
                        if (message.Text[0] == '#')
                        {
                            backColor = message.Text;
                        }
                        else
                        {
                            backColor = '#' + message.Text;
                        }



                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got background color. Now, I will send you a final post"
                            );

                        if (authorLen > 0)
                        {
                            authorFontSize -= authorLen * 8;
                        }
                        if (titleLen > 0)
                        {
                            titleFontSize -= titleLen * 5;
                        }

                        using (MagickImage form = new MagickImage(MagickColors.White, 1920, 1080))
                        {
                            new Drawables()

                            //Draw rectangle
                            .FillColor(new MagickColor(backColor))
                            .Rectangle(0, 0, 840, 1080)

                            //Draw hashtag
                            .FontPointSize(100)
                            .Font("Font\\nrwstr.otf")
                            .FillColor(new MagickColor(secColor))
                            .Text(30, 124, "#")

                            //Draw genre
                            .Font("Font\\amcap.ttf")
                            .Text(124, 124, genre)

                            //Draw title
                            .FontPointSize(titleFontSize)
                            .FillColor(new MagickColor(primColor))
                            .Text(30, 520, title)

                            //Draw name of the author
                            .FontPointSize(authorFontSize)
                            .FillColor(new MagickColor(secColor))
                            .Text(30, 650, author)

                            //Draw name of the channel
                            .FillColor(new MagickColor(primColor))
                            .FontPointSize(50)
                            .Text(150, 960, "THINK! - АУДИОПОДКАСТЫ")

                            //Draw link of the channel
                            .Font("Font\\nrwstr.otf")
                            .FillColor(new MagickColor(secColor))
                            .FontPointSize(40)
                            .Text(150, 1010, "T.ME/THINKAUDIO")

                            .Draw(form);

                            using MagickImage cover = new MagickImage("Image\\cover.png");
                            cover.Resize(1280, 1280);
                            form.Composite(cover, 840, 0, CompositeOperator.Over);

                            //Draw logo of the channel
                            using MagickImage logo = new MagickImage("Image\\logo.png");
                            logo.Alpha(AlphaOption.Set);
                            logo.ColorFuzz = new Percentage(0);
                            logo.Settings.BackgroundColor = MagickColors.Transparent;
                            //logo.Settings.FillColor = MagickColors.White;
                            logo.Opaque(MagickColors.White, new MagickColor(primColor));
                            form.Composite(logo, 30, 920, CompositeOperator.Over);

                            form.Write("Image\\template.png");
                        }

                        await bot.SendTextMessageAsync(message.Chat, "Template has been created. Sending it to you");

                        using (var stream = new FileStream("Image\\template.png", FileMode.Open))
                        {
                            InputOnlineFile inputOnlineFile = new InputOnlineFile(stream, "template.png");
                            await bot.SendDocumentAsync(message.Chat, inputOnlineFile);
                        }


                        try
                        {
                            ImgurClient   client   = new ImgurClient("", "");
                            ImageEndpoint endpoint = new ImageEndpoint(client);
                            IImage        image;
                            using (FileStream fs = new FileStream("Image\\template.png", FileMode.Open))
                            {
                                await bot.SendTextMessageAsync(message.Chat, "Uploading Image to Imgur");

                                image = await endpoint.UploadImageStreamAsync(fs);
                            }
                            picLink = image.Link;
                            Console.WriteLine("Image uploaded. Image Url: " + image.Link);

                            output += $"<a href=\"{picLink}\">&#8205;</a>";

                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : output,
                                parseMode : ParseMode.Html
                                );
                        }
                        catch (ImgurException imgurEx)
                        {
                            Debug.Write("An error occurred uploading an image to Imgur.");
                            Debug.Write(imgurEx.Message);
                        }

                        using (var stream = new FileStream("Audio\\audio.ogg", FileMode.Open))
                        {
                            await bot.SendVoiceAsync(
                                chatId : message.Chat,
                                voice : stream

                                );
                        }
                        step = -1;
                    }
                    break;
                }
            }
        }